From 15590d127c7923afdd71fa3c7e7ff58458cec1f0 Mon Sep 17 00:00:00 2001 From: shira Date: Sat, 10 Oct 2026 03:01:36 +0300 Subject: [PATCH] feat(frontend): redesign the employer cabinet with step-by-step need and invitation forms --- frontend/README.en.md | 23 +- frontend/README.md | 23 +- frontend/e2e/invitation-compose.spec.ts | 36 +- frontend/e2e/need-management.spec.ts | 47 +- frontend/src/entities/match/index.ts | 1 + frontend/src/entities/match/model/labels.ts | 17 + .../ui/candidate-card-details.module.css | 4 +- .../entities/match/ui/match-card.module.css | 169 ++- frontend/src/entities/match/ui/match-card.tsx | 219 ++- .../match/ui/match-explanation.module.css | 4 + .../edit-company/ui/company-editor.module.css | 69 +- .../edit-company/ui/company-editor.tsx | 58 +- .../features/edit-need/model/steps.test.ts | 67 + .../src/features/edit-need/model/steps.ts | 105 ++ .../edit-need/ui/need-editor-parts.tsx | 262 ++++ .../edit-need/ui/need-editor.module.css | 479 ++++-- .../edit-need/ui/need-editor.test.tsx | 38 +- .../src/features/edit-need/ui/need-editor.tsx | 1347 +++++++++-------- .../features/edit-need/ui/need-summary.tsx | 107 ++ .../ui/match-filter-form.module.css | 137 +- .../filter-matches/ui/match-filter-form.tsx | 82 +- ...organization-notification-inbox.module.css | 14 +- .../send-invitation/model/steps.test.ts | 21 + .../features/send-invitation/model/steps.ts | 53 + .../ui/invitation-form.module.css | 332 ++-- .../send-invitation/ui/invitation-form.tsx | 992 ++++++------ .../pages/company/ui/company-page.module.css | 27 +- .../src/pages/company/ui/company-page.tsx | 25 +- .../ui/invitation-compose-page.module.css | 58 +- .../ui/invitation-compose-page.test.tsx | 13 +- .../ui/invitation-compose-page.tsx | 147 +- .../jury-guide/ui/jury-guide-page.module.css | 20 +- .../pages/jury-guide/ui/jury-guide-page.tsx | 10 +- .../pages/matches/ui/matches-page.module.css | 75 +- .../src/pages/matches/ui/matches-page.tsx | 47 +- .../ui/need-editor-page.module.css | 17 +- .../pages/need-editor/ui/need-editor-page.tsx | 5 +- .../pages/needs/ui/need-list-page.module.css | 43 +- .../src/pages/needs/ui/need-list-page.tsx | 41 +- .../ui/placeholder-page.module.css | 38 +- .../pages/placeholder/ui/placeholder-page.tsx | 25 +- .../ui/invitation-preview.module.css | 7 +- .../match-list/ui/match-list.module.css | 102 +- .../widgets/match-list/ui/match-list.test.tsx | 30 +- .../src/widgets/match-list/ui/match-list.tsx | 147 +- 45 files changed, 3600 insertions(+), 1983 deletions(-) create mode 100644 frontend/src/features/edit-need/model/steps.test.ts create mode 100644 frontend/src/features/edit-need/model/steps.ts create mode 100644 frontend/src/features/edit-need/ui/need-editor-parts.tsx create mode 100644 frontend/src/features/edit-need/ui/need-summary.tsx create mode 100644 frontend/src/features/send-invitation/model/steps.test.ts create mode 100644 frontend/src/features/send-invitation/model/steps.ts diff --git a/frontend/README.en.md b/frontend/README.en.md index e97a581..d2ccff8 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -39,6 +39,8 @@ Generated Orval hooks call the shared same-origin `apiRequest` client, so the `Q `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. +The form goes in steps (`Stepper`): contacts, roles with the self-assessment and the confirmed categories, experience with the confirmation of parallel periods, 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 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. 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. @@ -47,6 +49,8 @@ After saving, the form reloads the session and shows the account step returned b `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. +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 @@ -55,12 +59,16 @@ A 412 conflict retains the draft and offers explicit reload or replacement again 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. +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. `demo_express` is labeled as a demonstration and does not award a qualification score or confirmed category. The attempt screen displays the server result with the same component as the result page and links to it (see [Candidate results](#candidate-results)). Only the server assigns a category; the client calculates neither scores nor grades. +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 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 listeners are passive, block nothing, and show nothing. 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. @@ -106,6 +114,8 @@ Creation uses one idempotency key for retries of the same body after a lost resp 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`. @@ -132,7 +142,7 @@ The tests take their fixtures from the named contract examples in `api/core/open - The explanation opens with a button that carries `aria-expanded`. It is built only from the components of the response: Fit, Cov, Dom, Sem, the percentile, V, Fr, Rsp, and the final score S appear exactly as they arrived, with no rounding beyond six decimals. A neutral value (`unknown_flags`) is labelled "Нейтральное значение, не измерено" with its reason (`ml_unavailable`, `cohort_below_30`, `percentile_not_computed`, and others). A `null` percentile is printed as "Нет значения" and no number is invented. A zero competition value is called "не штраф". An entry without a confirmed grade has only Fit and Cov: the server computes no S, percentile, or category for it, and the screen draws none. Unknowns outside the scores (experience, formats, expectations, the assessment result) are listed under "Что неизвестно" with a note that they are not an absence of ability. - Opening a card. The "Открыть карточку" button reads `GET /organizations/{org_id}/candidate-cards/{handle}` and, when the card has categories, the evidence section as well; the server refuses the section for a card without categories, so the request is not sent. Reads are neither retried automatically nor cached after the panel leaves the screen (`gcTime: 0`, no refetch on focus), because every read is an entry in the candidate's access history. A closed panel stays mounted, and opening it again does not read the card again. A 429 shows "Квота просмотров карточек исчерпана" and the time from `Retry-After`; when the server named none, no time is invented. A 404 replaces every hidden case with one text and names no reason. - Invitation. Every entry has a "Пригласить" button, an unconfirmed one included. It leads to `/employer/invitations/new` with `organization_id`, `candidate_handle`, `specialization`, and, for a need search, `need_id` (see [Invitation to a candidate](#invitation-to-a-candidate)). The alias is scoped to the organization and is not a candidate identifier. -- Layout. At 1280 px the form is on the left and the result on the right; below 1024 px the form sits above the result; at 360 px the entry actions stack and the facts and the explanation fold into one column. Every action works from the keyboard, focus is visible, and status is carried by text and shape, not by color. +- 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. @@ -144,11 +154,12 @@ Checks. Unit tests cover parsing and labels (`entities/match`), the request buil - Form (`features/send-invitation`). The fields follow `InvitationTerms` and nothing more: the role, the specialization (from the search entry), the grade, the offer type, the tasks (one per line), the team, the technologies, the work formats and the place of work, the channel with an optional note, the range in rubles with an explicit basis (net or gross), the four package conditions, and a response period of 3, 7, or 14 days. Each package condition is chosen explicitly: "Предусмотрено" with a description or "Не предусмотрено"; nothing is preselected. For a need search the form is prefilled only with the confirmed requirements of the need, and the draft refers to its `requirements_version`. - Checks before a request. The client repeats the contract rules: required fields and lengths, a range in whole rubles with a step of 1000, a lower bound below the upper one, and a width from 10% to 40% of the midpoint (`entities/invitation/model/salary-range.ts`), a place of work for office and hybrid, and a technology repeated in another letter case. With an incomplete range, no communication method, or an unanswered package condition nothing is sent. Issues are listed in a focused summary at the top of the form and bound to their fields with `aria-invalid` and `aria-describedby`. - The server decides. RFC 9457 errors from `errors[].pointer` are mapped to form fields (`fieldOfPointer`, for example `/terms/salary/salary_to`, `/terms/communication_method`, `/terms/package/training`); server text is not shown. `/candidate_handle` and `/need` give a general message without the reason. -- Preview (`widgets/invitation-preview`). "Показать предпросмотр" checks the form and shows the company card from `candidate_card` (`GET /organizations/{org_id}`) and every term as the candidate will see them; focus moves to the preview. The preview sends nothing and creates no draft. When the form changes, a note says the preview is out of date. +- 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, and checks the preview against every term; without the communication method a field error shows, no request is sent, and the candidates' inboxes stay empty. Then the send is slowed down and its first response lost, a second click during the request starts nothing, and the retry uses the same key; the result is one invitation in one inbox (`GET /me/invitations`) with the deadline the screen shows, also after a reload. A 403 for a recruiter is not checked in the browser, since the stand cannot grant that role; the screen for a non-owner role is covered by a unit test. +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. ## Candidate incoming invitations @@ -256,7 +267,9 @@ The interface has no FSP logo. `Wordmark` is the text mark "Lincodex" with a ter - `TrustLevel`: an empty mark, ring, partial fill, or full mark with a visible label. - `CircuitTrace`, `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`. -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 (phone first): below 700px the sections form a scrolling bottom tab bar and the current tab scrolls to the middle; from 700px the tabs sit in the plate. 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. +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 (phone first): below 700px the sections form a scrolling bottom tab bar and the current tab scrolls to the middle; from 700px the tabs sit in the plate. When the tabs do not fit, the strip fades at the edge that hides more of them. 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`. diff --git a/frontend/README.md b/frontend/README.md index 4f57cc9..e52218e 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -39,6 +39,8 @@ SPA на React и TypeScript со сборкой Vite и структурой FS `entities/candidate` хранит модель полного черновика профиля и переводит ее в `CandidateProfileUpdate`. `features/edit-profile` отвечает за поля и сохранение, `pages/profile` - за страницу. Серверные данные остаются в React Query; контакты и черновик не записываются в localStorage или sessionStorage. +Форма идет по шагам (`Stepper`): контакты, роли с самооценкой и подтвержденными категориями, опыт с подтверждением параллельных периодов, навыки, условия, проверка и сохранение. Сервер принимает профиль целиком с `expected_version`, поэтому сохранение есть только на последнем шаге. «Далее» проверяет поля текущего шага; ошибка клиента или сервера при сохранении открывает шаг, которому принадлежит поле. Неактивные шаги остаются в дереве со скрытым атрибутом: «Назад» сохраняет введенное, а связи полей с подсказками и ошибками остаются. При смене шага фокус переходит на его заголовок. У сохраненного профиля есть переход «К проверке и сохранению», а шаг проверки ведет к любому шагу кнопкой «Изменить». Перезагрузка открывает первый шаг с серверной записью; несохраненный черновик не восстанавливается. + Форма сохраняет происхождение нетронутых предложений, показывает пересекающиеся периоды работы и требует явного подтверждения параллельной работы. Подтверждение связано с текущими индексами и датами; перестановка или изменение периодов требует проверки заново. Подтвержденные категории отображаются отдельно и не входят в тело сохранения. Ошибка версии 412 оставляет черновик и предлагает явно заменить его актуальными данными. После сохранения форма перечитывает сессию и показывает шаг аккаунта, который вернул сервер. Сохранение профиля само по себе не завершает шаг согласий; переход от него пока не реализован. Независимое редактирование профиля доступно без ML, файла и ФСП. @@ -47,6 +49,8 @@ SPA на React и TypeScript со сборкой Vite и структурой FS `pages/questionnaire` получает каталог специализаций и приватные ответы текущего кандидата через Orval. Черновик остается в состоянии компонента, сохраненные ответы принадлежат React Query, а reload восстанавливает серверную запись. Форма предлагает одну или две специализации, самооценку грейда, доступные языки заданий, стек, опыт и форматы работы. Специализация без опубликованного банка отмечена как находящаяся в разработке; ее можно сохранить без ФСП. +Анкета идет по шагам: направления (одна или две специализации и доступность проверки по каталогу), уровень и опыт для каждой выбранной специализации (самооценка, язык заданий, стек, опыт), формат работы, проверка и сохранение. Правила шагов те же, что у профиля: сохранение целиком на последнем шаге с `expected_version`, проверка текущего шага кнопкой «Далее», переход к шагу с ошибкой сервера, скрытые, но смонтированные шаги, фокус на заголовке шага, первый шаг после перезагрузки. + Конфликт 412 сохраняет черновик и предлагает явное перечитывание или замену по последней прочитанной версии. Ошибки сессии скрывают приватные ответы; ответ прежнего аккаунта не заполняет кеш заново. Переходы onboarding следуют шагу, возвращенному сервером. Сохраненный шаг анкеты открывает `/candidate/questionnaire`. ## Главная кандидата @@ -55,12 +59,16 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Заявленный уровень и подтвержденная категория всегда показаны раздельно, по специализациям: заявленный берется из `self_assessed_grade` анкеты и помечен как самооценка, подтвержденный - только из `confirmed_grade` доступности проверки. Клиент не выводит категорию из баллов, порогов или целевого грейда. Страница также показывает последний результат (`GET /me/assessment-results?limit=1`, пересказ через `assessmentResultSummary`, ссылки на разбор и историю) и видимость профиля (`GET /me/privacy`: карточка открыта или закрыта с причиной, показывается ли категория, статус поиска) со ссылкой на `/candidate/privacy`. -Состояния загрузки, ошибки с повтором, "нет доступа" (401 и 403 без повтора) и пусто есть у каждого блока. Три чтения, от которых зависит следующий шаг, образуют одно состояние: если любое из них не удалось, показывается ошибка с повтором, а не шаг, угаданный по неполным данным. Результат и видимость независимы, поэтому их сбой не скрывает следующий шаг. Ключи запросов содержат идентификатор аккаунта, данные не живут после ухода с экрана (`gcTime: 0`) и читаются заново при каждом открытии и возврате на вкладку, так что обновление страницы показывает актуальное состояние API. Вход после выхода по-прежнему ведет на страницу сохраненного шага (`getOnboardingDestination`), а не на главную. +Состояния загрузки, ошибки с повтором, "нет доступа" (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 ничего не запускает. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным. Во время реальной попытки `features/assessment-signals` собирает отправляемые сигналы: потерю фокуса с длительностью, копирование, вставку и вырезание только с размером, выход из полноэкранного режима. Слушатели пассивные, ничего не блокируют и не показывают; события уходят пакетами (по таймеру в 10 секунд, при скрытии вкладки или накоплении 20 событий), у каждого пакета свой `Idempotency-Key`, который сохраняется при повторах. При закрытии страницы (`pagehide`) и при размонтировании оставшиеся события отправляются последним запросом с `keepalive`, поэтому закрытие вкладки не теряет накопленное за последние секунды; результат такого запроса не ожидается и не повторяется. Сбой сети никогда не мешает отправке ответа: неудачный пакет повторяется с тем же ключом и телом с нарастающей паузой, а после лимита попыток отбрасывается. Ответ сервера об отказе (нет C3, попытка завершена) останавливает сбор. Демонстрационный запуск сигналы не собирает. @@ -106,6 +114,8 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Черновик редактора хранится в памяти. Извлеченные из описания поля и навыки остаются предложениями с происхождением, пока пользователь не подтвердит, не изменит или не удалит их. Неизвестные значения не подменяются дефолтами. Вопросы готовности показываются рядом с незаполненными полями; статус рекомендаций и категории берутся из 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`. @@ -132,7 +142,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS - Объяснение раскрывается кнопкой с `aria-expanded`. Оно строится только из компонентов ответа: Fit, Cov, Dom, Sem, перцентиль, V, Fr, Rsp и итоговый балл S показаны ровно так, как пришли, без округления сверх шести знаков. Нейтральное значение (`unknown_flags`) подписано "Нейтральное значение, не измерено" с причиной (`ml_unavailable`, `cohort_below_30`, `percentile_not_computed` и другие). Перцентиль `null` выводится как "Нет значения", число не выдумывается. Нулевой соревновательный вклад назван "не штрафом". У записи без подтвержденного грейда есть только Fit и Cov: балла S, перцентиля и категории для нее не считают, и экран их не рисует. Неизвестное вне баллов (опыт, форматы, ожидания, результат проверки) перечислено в блоке "Что неизвестно" с пометкой, что это не отсутствие способности. - Открытие карточки. Кнопка "Открыть карточку" читает `GET /organizations/{org_id}/candidate-cards/{handle}`, а при наличии категорий - и раздел доказательств; без категорий сервер раздел не отдает, поэтому запрос не отправляется. Чтения не повторяются автоматически и не кешируются после ухода с экрана (`gcTime: 0`, без обновления при фокусе): каждое чтение попадает в журнал доступа кандидата. Закрытая панель остается в дереве, повторное открытие не читает карточку снова. Ответ 429 показывает "Квота просмотров карточек исчерпана" и время из `Retry-After`; если сервер его не назвал, время не выдумывается. Ответ 404 одним текстом заменяет все скрытые случаи и не называет причину. - Приглашение. Кнопка "Пригласить" есть у каждой записи, в том числе у неподтвержденной. Она ведет на `/employer/invitations/new` с параметрами `organization_id`, `candidate_handle`, `specialization` и, для поиска по потребности, `need_id` (см. [приглашение кандидату](#приглашение-кандидату)). Псевдоним привязан к организации и не является идентификатором кандидата. -- Раскладка. На 1280 px форма слева, выдача справа; ниже 1024 px форма стоит над выдачей; на 360 px действия записи идут в столбец, а факты и объяснение складываются в один столбец. Все действия доступны с клавиатуры, фокус виден, статус кодируется текстом и формой, а не цветом. +- Раскладка. Форма стоит над выдачей на всех ширинах: основание поиска (сегментный переключатель "По потребности" и "По всем профилям"), выборы, ряд фильтр-чипов (технологии, формат, совместимость ожиданий; примененный чип синий и с галочкой) и действие; выдача идет на всю ширину. Запись на 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 из браузера работодателя тоже не проверены. @@ -144,11 +154,12 @@ SPA на React и TypeScript со сборкой Vite и структурой FS - Форма (`features/send-invitation`). Поля повторяют `InvitationTerms` и ничего сверх: роль, специализация (из записи поиска), грейд, тип предложения, задачи (по одной в строке), команда, технологии, форматы и место работы, канал связи с необязательным комментарием, вилка в рублях с явной базой (net или gross), четыре условия пакета и срок ответа 3, 7 или 14 дней. Каждое условие пакета выбирается явно: "Предусмотрено" с описанием или "Не предусмотрено"; по умолчанию не выбрано ничего. При поиске по потребности форма заполняется только подтвержденными требованиями потребности, а в черновик уходит ссылка на ее `requirements_version`. - Проверка до запроса. Клиент повторяет правила контракта: обязательные поля и длины, вилка из целых рублей с шагом 1 000, нижняя граница меньше верхней, ширина от 10% до 40% середины (`entities/invitation/model/salary-range.ts`), место работы для офиса и гибрида, повтор технологии без учета регистра. С неполной вилкой, без способа связи или без выбора в пакете запрос не отправляется. Ошибки собираются в список с фокусом в начале формы и привязаны к полям через `aria-invalid` и `aria-describedby`. - Ответ сервера главнее. Ошибки RFC 9457 из `errors[].pointer` переводятся в поля формы (`fieldOfPointer`, например `/terms/salary/salary_to`, `/terms/communication_method`, `/terms/package/training`); текст сервера не показывается. `/candidate_handle` и `/need` дают общее сообщение без причины. -- Предпросмотр (`widgets/invitation-preview`). "Показать предпросмотр" проверяет форму и показывает карточку компании из `candidate_card` (`GET /organizations/{org_id}`) и все условия так, как их увидит кандидат; фокус переходит на предпросмотр. Предпросмотр ничего не отправляет и не создает черновик. Если форма изменилась, над ним появляется пометка, что он устарел. +- Шаги. Форма идет в четыре шага (`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 для рекрутера в браузере не проверен: на стенде нет способа выдать такую роль; поведение экрана для неглавной роли покрыто модульным тестом. +Проверки. Модульные тесты: правила вилки (`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 для рекрутера в браузере не проверен: на стенде нет способа выдать такую роль; поведение экрана для неглавной роли покрыто модульным тестом. ## Входящие приглашения кандидата @@ -256,7 +267,9 @@ SPA на React и TypeScript со сборкой Vite и структурой FS - `TrustLevel` - пустая метка, кольцо, частичная или полная заливка с видимой подписью. - `CircuitTrace`, `Mono`, `VisuallyHidden`, `SkipLink`, `MainRegion`. -Оболочки. Публичная: плавающая плашка со словесным знаком и ссылками, ниже 700px ссылки открываются кнопкой "Меню"; подвал со ссылкой на технический статус. Кандидат (сначала телефон): ниже 700px разделы образуют нижнюю панель вкладок с прокруткой, текущая вкладка прокручивается в середину; с 700px вкладки стоят в плашке. Навигация в документе идет до `main`, поэтому порядок клавиатуры одинаков на любой ширине. Работодатель (сначала компьютер): с 1024px плавающая боковая панель 240px, ниже - плашка с кнопкой "Меню". +Шаги длинной формы (`form-steps.tsx`, `use-form-steps.ts`: панель шага с заголовком, получающим фокус, навигация «Назад» и «Далее», блок проверки с кнопкой «Изменить») пока лежат одинаковыми копиями в `features/edit-profile` и `features/fill-questionnaire`; общий вариант стоит перенести в `shared/ui`. + +Оболочки. Публичная: плавающая плашка со словесным знаком и ссылками, ниже 700px ссылки открываются кнопкой "Меню"; подвал со ссылкой на технический статус. Кандидат (сначала телефон): ниже 700px разделы образуют нижнюю панель вкладок с прокруткой, текущая вкладка прокручивается в середину; с 700px вкладки стоят в плашке. Если вкладки не помещаются, полоса затухает у того края, за которым они остались. Навигация в документе идет до `main`, поэтому порядок клавиатуры одинаков на любой ширине. Работодатель (сначала компьютер): с 1024px плавающая боковая панель 240px, ниже - плашка с кнопкой "Меню". Доступность: каждая оболочка начинается со ссылки пропуска к `main`, содержит ориентиры и видимое кольцо фокуса (2px `#9A92FF` с отступом 2px) и переводит фокус на `main` после перехода. Анимации учитывают `prefers-reduced-motion`. diff --git a/frontend/e2e/invitation-compose.spec.ts b/frontend/e2e/invitation-compose.spec.ts index 461d543..b000f60 100644 --- a/frontend/e2e/invitation-compose.spec.ts +++ b/frontend/e2e/invitation-compose.spec.ts @@ -250,10 +250,13 @@ test.describe("organization invitation with the real backend", () => { if (isInvitationCommand(request)) commands.push(request); }); + // The form has four steps: terms, package, preview, send. + await expect(page.getByText("Шаг 1 из 4")).toBeVisible(); + // Step 1: the terms with [100000; 140000] net and a package. await page.getByLabel("Название роли", { exact: true }).fill("Аналитик SOC, стажировка"); - await page.getByLabel("Грейд", { exact: true }).selectOption("intern"); - await page.getByLabel("Тип предложения", { exact: true }).selectOption("internship"); + await page.getByRole("radio", { name: "Стажер", exact: true }).check(); + await page.getByRole("radio", { name: "Стажировка", exact: true }).check(); await page .getByLabel("Задачи", { exact: true }) .fill("Разбирать события SIEM\nГотовить отчеты об инцидентах"); @@ -270,7 +273,11 @@ test.describe("organization invitation with the real backend", () => { .fill("Созвон с руководителем смены в течение трех рабочих дней"); await page.getByLabel("От, ₽", { exact: true }).fill("100000"); await page.getByLabel("До, ₽", { exact: true }).fill("140000"); - await page.getByLabel("База суммы", { exact: true }).selectOption("net"); + await page.getByRole("radio", { name: "После налога (net)", exact: true }).check(); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect( + page.getByRole("heading", { level: 2, name: "Пакет и срок ответа" }), + ).toBeFocused(); const bonus = page.getByRole("group", { name: "Премии и бонусы" }); await bonus.getByRole("radio", { name: "Предусмотрено", exact: true }).check(); await page.getByLabel("Премии и бонусы: описание").fill("Квартальная премия до 10%"); @@ -286,9 +293,10 @@ test.describe("organization invitation with the real backend", () => { .getByRole("radio", { name: "Не предусмотрено", exact: true }) .check(); - await page.getByRole("button", { name: "Показать предпросмотр" }).click(); + await page.getByRole("button", { name: "К предпросмотру" }).click(); + await expect(page.getByRole("heading", { level: 2, name: "Предпросмотр" })).toBeFocused(); const preview = page.getByRole("region", { name: "Предпросмотр приглашения" }); - await expect(preview).toBeFocused(); + await expect(preview).toBeVisible(); await expect(preview.getByRole("heading", { name: organizationName })).toBeVisible(); const terms = preview.getByRole("article", { name: "Условия приглашения" }); for (const value of [ @@ -319,17 +327,25 @@ test.describe("organization invitation with the real backend", () => { expect(commands).toEqual([]); expect(await inboxItems(candidates)).toEqual([]); - // Step 2: without the communication method the form refuses to send. + // Step 2: without the communication method the form does not leave the + // terms. The send step is only reachable through a valid preview, so + // the employer walks back to the terms and clears the channel. + await page.getByRole("button", { name: "К отправке" }).click(); + await expect(page.getByRole("heading", { level: 2, name: "Отправка" })).toBeFocused(); + for (let index = 0; index < 3; index += 1) { + await page.getByRole("button", { name: "Назад", exact: true }).click(); + } + await expect(page.getByText("Шаг 1 из 4")).toBeVisible(); const channel = page.getByLabel("Канал связи", { exact: true }); await channel.selectOption({ index: 0 }); - await page.getByRole("button", { name: "Отправить приглашение" }).click(); + await page.getByRole("button", { name: "Далее", exact: true }).click(); const summary = page.getByRole("alert").filter({ hasText: "Проверьте условия приглашения" }); await expect(summary).toBeFocused(); await expect(channel).toHaveAttribute("aria-invalid", "true"); await expect(channel).toHaveAccessibleDescription( "Выберите способ связи после принятия приглашения.", ); - await expect(page.getByText("Условия изменены после предпросмотра")).toBeVisible(); + await expect(page.getByText("Шаг 1 из 4")).toBeVisible(); expect(commands).toEqual([]); expect(await inboxItems(candidates)).toEqual([]); @@ -337,6 +353,10 @@ test.describe("organization invitation with the real backend", () => { // then retried. The browser keeps the key until the command completes. await channel.selectOption("video_call"); await expect(channel).toHaveAttribute("aria-invalid", "false"); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await page.getByRole("button", { name: "К предпросмотру" }).click(); + await expect(preview).toBeVisible(); + await page.getByRole("button", { name: "К отправке" }).click(); let sendAttempts = 0; let delivered: SentInvitation | null = null; await page.route("**/api/v1/organizations/*/invitations/*/send", async (route) => { diff --git a/frontend/e2e/need-management.spec.ts b/frontend/e2e/need-management.spec.ts index 1f99996..85f0484 100644 --- a/frontend/e2e/need-management.spec.ts +++ b/frontend/e2e/need-management.spec.ts @@ -214,6 +214,13 @@ async function findSkillRow(section: Locator, name: string): Promise { throw new Error(`The parsed need did not contain the expected skill ${name}.`); } +// The need form has five steps and saves only on the last one; "Далее" moves one step on. +async function nextStep(page: Page, times = 1): Promise { + for (let index = 0; index < times; index += 1) { + await page.getByRole("button", { name: "Далее", exact: true }).click(); + } +} + function isResponse(response: Response, method: string, path: string, status: number): boolean { return ( response.request().method() === method && @@ -262,15 +269,32 @@ test.describe("employer needs", () => { await page.getByRole("link", { name: "Создать потребность" }).first().click(); await expect(page.getByLabel("Название потребности")).toBeVisible(); await expect(page.getByText("Вакансия для сохранения потребности не требуется.")).toBeVisible(); - await expect(page.getByLabel("Грейд")).toHaveValue(""); - await expect(page.getByLabel("База суммы")).toHaveValue(""); - await expect( - page.getByText("Укажите обе суммы и выберите базу. Без явной базы диапазон не сохранится."), - ).toBeVisible(); + await expect(page.getByText("Шаг 1 из 5")).toBeVisible(); + // A step that needs a title does not let the employer leave it blank. + await nextStep(page); + await expect(page.getByLabel("Название потребности")).toHaveAttribute("aria-invalid", "true"); + await expect(page.getByLabel("Название потребности")).toBeFocused(); await page.getByLabel("Название потребности").fill(`Payments backend ${suffix}`); + // An unknown grade stays unknown: no grade radio is preselected. + await expect(page.getByRole("radio", { name: "Не указан", exact: true })).toBeChecked(); expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]); await page.getByLabel("Описание работы").fill(sourceText); expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]); + // Focus follows the employer to the heading of each step, and back keeps the draft. + await nextStep(page); + await expect( + page.getByRole("heading", { level: 2, name: "Навыки", exact: true }), + ).toBeFocused(); + await page.getByRole("button", { name: "Назад", exact: true }).click(); + await expect(page.getByRole("heading", { level: 2, name: "Роль и грейд" })).toBeFocused(); + await expect(page.getByLabel("Описание работы")).toHaveValue(sourceText); + await nextStep(page, 3); + await expect(page.getByRole("radio", { name: /После налога/ })).not.toBeChecked(); + await expect(page.getByRole("radio", { name: /До налога/ })).not.toBeChecked(); + await expect( + page.getByText("Укажите обе суммы и выберите базу. Без явной базы диапазон не сохранится."), + ).toBeVisible(); + await nextStep(page); const organizationNeedsPath = needCollectionPath(organization.id); const createResponsePromise = page.waitForResponse((response) => @@ -289,6 +313,7 @@ test.describe("employer needs", () => { expect(created.readiness.missing_fields.map((field) => field.field)).toContain("salary"); expect(created.recommendations.status).toBe("not_available"); + await nextStep(page); const requiredSkills = page .getByRole("heading", { name: "Обязательные навыки" }) .locator("xpath=.."); @@ -302,6 +327,7 @@ test.describe("employer needs", () => { const needId = created.id; const itemPath = needPath(organization.id, needId); + await nextStep(page, 3); const firstSavePromise = page.waitForResponse((response) => isResponse(response, "PATCH", itemPath, 200), ); @@ -342,6 +368,8 @@ test.describe("employer needs", () => { const firstWindowTitle = `Payments backend first ${suffix}`; await page.getByLabel("Название потребности").fill(firstWindowTitle); + // An existing need can jump straight to the review step. + await page.getByRole("button", { name: "К проверке и сохранению" }).click(); const firstWindowSave = page.waitForResponse((response) => isResponse(response, "PATCH", itemPath, 200), ); @@ -353,6 +381,7 @@ test.describe("employer needs", () => { const secondWindowDraft = `Payments backend second ${suffix}`; await secondPage.getByLabel("Название потребности").fill(secondWindowDraft); + await secondPage.getByRole("button", { name: "К проверке и сохранению" }).click(); const conflictResponsePromise = secondPage.waitForResponse((response) => isResponse(response, "PATCH", itemPath, 412), ); @@ -486,19 +515,23 @@ test.describe("employer needs", () => { await page.getByLabel("Название потребности").fill(`Manual Go developer ${suffix}`); await expect(page.getByLabel("Описание работы")).toHaveValue(""); await page.getByLabel("Специализация").selectOption("backend"); - await page.getByLabel("Грейд").selectOption("junior"); + await page.getByRole("radio", { name: "Junior", exact: true }).check(); + await nextStep(page); const requiredSkills = page .getByRole("heading", { name: "Обязательные навыки" }) .locator("xpath=.."); await requiredSkills.getByLabel("Добавить навык").fill("Go"); await requiredSkills.getByRole("button", { name: "Добавить", exact: true }).click(); + await nextStep(page); const tasks = page.getByRole("heading", { name: "Задачи команды" }).locator("xpath=.."); await tasks.getByLabel("Добавить задачу").fill("Развивать сервис уведомлений"); await tasks.getByRole("button", { name: "Добавить", exact: true }).click(); + await nextStep(page); await page.getByLabel("От, рублей в месяц").fill("100000"); await page.getByLabel("До, рублей в месяц").fill("130000"); - await page.getByLabel("База суммы").selectOption("net"); + await page.getByRole("radio", { name: /После налога/ }).check(); + await nextStep(page); const createResponsePromise = page.waitForResponse((response) => isResponse(response, "POST", collectionPath, 201), diff --git a/frontend/src/entities/match/index.ts b/frontend/src/entities/match/index.ts index 2174d60..2a54a75 100644 --- a/frontend/src/entities/match/index.ts +++ b/frontend/src/entities/match/index.ts @@ -48,6 +48,7 @@ export { matchGroupOrder, specializationCodes, specializationLabels, + specializationShortLabels, stackCodes, stackLabels, workFormatCodes, diff --git a/frontend/src/entities/match/model/labels.ts b/frontend/src/entities/match/model/labels.ts index 9bee6c7..f3a2663 100644 --- a/frontend/src/entities/match/model/labels.ts +++ b/frontend/src/entities/match/model/labels.ts @@ -29,6 +29,23 @@ export const specializationLabels: Readonly> export const specializationCodes = Object.keys(specializationLabels) as SpecializationCode[]; +/** + * Short names for the grade tag, for example BACKEND · MIDDLE. The tag is set + * in capitals and never wraps, so a long specialization name would not fit a + * phone; the full name stays in the heading of the card. + */ +export const specializationShortLabels: Readonly> = { + backend: "Backend", + frontend: "Frontend", + mobile: "Mobile", + network_engineer: "Network", + devops_sre: "DevOps", + data_analyst: "Data", + ds_ml: "DS/ML", + information_security: "InfoSec", + qa: "QA", +}; + export const gradeLabels: Readonly> = { intern: "Стажер", junior: "Junior", diff --git a/frontend/src/entities/match/ui/candidate-card-details.module.css b/frontend/src/entities/match/ui/candidate-card-details.module.css index 239ed5a..f20b3e7 100644 --- a/frontend/src/entities/match/ui/candidate-card-details.module.css +++ b/frontend/src/entities/match/ui/candidate-card-details.module.css @@ -3,9 +3,9 @@ gap: var(--space-4); min-width: 0; padding: var(--space-4); - border: var(--line-thin) solid var(--color-border-strong); + border: var(--line-thin) solid var(--color-divider); border-radius: var(--radius-s); - background: var(--color-surface); + background: var(--color-canvas); } .panel[hidden] { diff --git a/frontend/src/entities/match/ui/match-card.module.css b/frontend/src/entities/match/ui/match-card.module.css index 43da78e..271ca81 100644 --- a/frontend/src/entities/match/ui/match-card.module.css +++ b/frontend/src/entities/match/ui/match-card.module.css @@ -1,24 +1,43 @@ +/* A result card: the content column and, from 768px, a column of actions. + * Hover brightens the hairline; there is no shadow. */ .card { display: grid; gap: var(--space-4); min-width: 0; padding: var(--space-4); border: var(--line-thin) solid var(--color-divider); - border-inline-start: var(--space-1) solid var(--color-border-strong); border-radius: var(--radius-m); background: var(--color-surface); + transition: border-color var(--duration-fast) var(--easing-standard); } -/* The confirmed and the unconfirmed state differ in the edge style and the - * text of the badge, so the difference never relies on color alone. */ -.card[data-confirmed="false"] { - border-inline-start-style: dashed; +.card:hover { + border-color: var(--color-border-hover); +} + +@media (width >= 48rem) { + .card { + grid-template-columns: minmax(0, 1fr) 13rem; + column-gap: var(--space-5); + padding: var(--space-5); + } + + .panels { + grid-column: 1 / -1; + } +} + +.main { + display: grid; + gap: var(--space-3); + align-content: start; + min-width: 0; } .header { display: flex; flex-wrap: wrap; - gap: var(--space-2) var(--space-4); + gap: var(--space-1) var(--space-4); align-items: baseline; justify-content: space-between; min-width: 0; @@ -26,33 +45,67 @@ .specialization { margin: 0; - overflow-wrap: anywhere; + color: var(--color-text-strong); font-size: var(--font-size-l); - font-weight: var(--font-weight-bold); + overflow-wrap: anywhere; } .handle { color: var(--color-text-secondary); - font-size: var(--font-size-s); + font-size: var(--font-size-xs); overflow-wrap: anywhere; } .status { display: flex; flex-wrap: wrap; - gap: var(--space-1) var(--space-4); + gap: var(--space-2) var(--space-4); align-items: center; } +.caption { + color: var(--color-text-secondary); + font-size: var(--font-size-xs); +} + +.salary, +.stack { + display: flex; + flex-wrap: wrap; + gap: var(--space-1) var(--space-3); + align-items: baseline; + min-width: 0; +} + +/* Salary is mono 600 as in the design system; the word, not the hue, says + * whether the expectations fit. Green 8.7:1 on the surface. */ +.salary > span:last-child { + font-size: var(--font-size-m); +} + +.salary[data-fit="compatible"] > span:last-child { + color: var(--color-success); +} + +.chips { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + margin: 0; + padding: 0; + list-style: none; +} + .facts { display: grid; - grid-template-columns: minmax(9rem, max-content) minmax(0, 1fr); - gap: var(--space-2) var(--space-4); + grid-template-columns: repeat(auto-fit, minmax(min(100%, 11rem), 1fr)); + gap: var(--space-3) var(--space-4); margin: 0; } .facts dt { color: var(--color-text-secondary); + font-size: var(--font-size-xs); } .facts dd { @@ -65,42 +118,94 @@ color: var(--color-text-secondary); } -.sources { - display: grid; +/* "Why in the selection": the server's sources and gaps in mono on a nested + * surface. The sign repeats the state; the words carry it. */ +.why { gap: var(--space-2); - min-width: 0; + font-family: var(--font-mono); + font-size: var(--font-size-xs); + line-height: 1.55; } -.sources-title { +.why-title { margin: 0; - font-size: var(--font-size-s); - font-weight: var(--font-weight-bold); + color: var(--color-text-secondary); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-medium); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; } -.sources ul { +.why-list { display: grid; - gap: var(--space-2); + gap: var(--space-1); margin: 0; padding: 0; list-style: none; } -.sources li { - display: flex; - flex-wrap: wrap; - gap: var(--space-1) var(--space-3); - align-items: center; +.why-list li { + display: grid; + grid-template-columns: 1rem minmax(0, 1fr); + column-gap: var(--space-2); min-width: 0; } -.source-label { - font-weight: var(--font-weight-medium); +.sign { + font-weight: var(--font-weight-bold); +} + +.why-label { + color: var(--color-text); + overflow-wrap: anywhere; +} + +.why-text { + display: flex; + flex-wrap: wrap; + gap: 0 var(--space-3); + min-width: 0; +} + +.why-state { + color: var(--color-text-secondary); + overflow-wrap: anywhere; +} + +.why-list li[data-state="supports"] .sign, +.why-list li[data-state="supports"] .why-state { + color: var(--color-success); +} + +.why-list li[data-state="gap"] .sign, +.why-list li[data-state="gap"] .why-state { + color: var(--color-danger); +} + +.why-list li[data-state="partial"] .sign, +.why-list li[data-state="partial"] .why-state { + color: var(--color-accent); } .actions { display: flex; flex-wrap: wrap; - gap: var(--space-2) var(--space-3); + gap: var(--space-2); + align-content: start; +} + +.actions > * { + flex: 1 1 auto; +} + +@media (width >= 48rem) { + .actions { + flex-flow: column nowrap; + } + + .actions > * { + flex: none; + } } .panels { @@ -114,14 +219,6 @@ padding: var(--space-3); } - .facts { - grid-template-columns: minmax(0, 1fr); - } - - .facts dd + dt { - padding-block-start: var(--space-2); - } - .actions > * { flex: 1 1 100%; } diff --git a/frontend/src/entities/match/ui/match-card.tsx b/frontend/src/entities/match/ui/match-card.tsx index 3bc6d8d..4352568 100644 --- a/frontend/src/entities/match/ui/match-card.tsx +++ b/frontend/src/entities/match/ui/match-card.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from "react"; -import { Mono, TrustLevel, type TrustLevelValue } from "../../../shared/ui"; +import type { MatchSearchStackTag } from "../../../shared/api/schemas"; +import { Card, Mono, Tag, TrustLevel, VisuallyHidden } from "../../../shared/ui"; import type { MatchCardModel } from "../model/adapter"; import { evidenceRows, type EvidenceRow } from "../model/explanation"; import { @@ -8,17 +9,20 @@ import { salaryCompatibilityLabels, confirmationLabel, specializationLabels, + specializationShortLabels, stackLabels, workFormatLabels, } from "../model/labels"; import { shortHandle } from "../model/views"; import styles from "./match-card.module.css"; -const stateLevels: Readonly> = { - supports: "confirmed", - partial: "partial", - declared_only: "claimed", - gap: "none", +// A row of the "why in the selection" block: a mono sign and the state in +// words. The sign repeats the state; the words carry it. +const stateSigns: Readonly> = { + supports: "+", + partial: "±", + declared_only: "?", + gap: "−", }; const noValue = "Нет значения в карточке"; @@ -31,100 +35,153 @@ type MatchCardViewProps = { card: MatchCardModel; /** Id of the heading, so the surrounding group can label the article. */ headingId: string; - /** Buttons and links under the card facts. */ + /** Technologies that the search asked for; a matching chip gets a dot. */ + matchedStack?: readonly MatchSearchStackTag[]; + /** Buttons and links in the action column. */ actions?: ReactNode; - /** Expandable panels under the actions. */ + /** Expandable panels under the card. */ children?: ReactNode; }; /** - * One search result: a candidate under one specialization. It prints the - * confirmed category and the declared grade on separate lines, the safe card - * context, and the server's templated sources and gaps. Nothing here is - * calculated: the status comes from the group and the fields of the entry. + * One search result: a candidate under one specialization. The grade tag and + * the confirmed category and the declared grade are printed on separate + * lines, so a claim never reads as a confirmation. Below sit the safe card + * context, the technology chips, and the server's templated sources and gaps + * in a "why in the selection" block. Nothing here is calculated: the status + * comes from the group and the fields of the entry. */ -export function MatchCardView({ card, headingId, actions, children }: MatchCardViewProps) { +export function MatchCardView({ + card, + headingId, + matchedStack = [], + actions, + children, +}: MatchCardViewProps) { const confirmed = card.confirmationStatus === "confirmed"; const context = card.publicContext; const sources = evidenceRows(card); + const shortSpecialization = specializationShortLabels[card.specialization]; + const compatibility = context.salaryCompatibility; return (
-
-

- {specializationLabels[card.specialization]} -

-

- Кандидат {shortHandle(card.candidateHandle)} -

-
-
- {card.category && card.strength ? ( - - ) : ( - - )} -
-
-
Подтвержденная категория
-
- {card.category && card.strength - ? `${specializationLabels[card.category.specialization]}, ${gradeLabels[card.category.grade]}. ${confirmationLabel(card.category.basis, card.strength)}` - : "Нет"} -
-
Заявленный кандидатом грейд
-
{card.declaredGrade ? gradeLabels[card.declaredGrade] : "Не указан"}
-
Технологии
-
+
+
+

+ {specializationLabels[card.specialization]} +

+

+ Кандидат {shortHandle(card.candidateHandle)} +

+
+
+ {card.category && card.strength ? ( + <> + {`${shortSpecialization} · ${gradeLabels[card.category.grade]}`} + + + ) : ( + <> + + {card.declaredGrade + ? `Заявлено: ${gradeLabels[card.declaredGrade]}` + : "Грейд не заявлен"} + + + + )} +
+
+ Зарплатные ожидания + {compatibility ? ( + {salaryCompatibilityLabels[compatibility]} + ) : ( + + )} +
+
+ Технологии {context.stack === null ? ( ) : context.stack.length === 0 ? ( - "Не названы" + Не названы ) : ( - context.stack.map((tag) => stackLabels[tag]).join(", ") +
    + {context.stack.map((tag) => { + const matched = matchedStack.includes(tag); + return ( +
  • + + {stackLabels[tag]} + {matched ? ( + , совпадает с условием поиска + ) : null} + +
  • + ); + })} +
)} -
-
Общий опыт
-
- {context.experienceBand ? experienceBandLabels[context.experienceBand] : } -
-
Форматы работы
-
- {context.workFormats === null ? ( - - ) : context.workFormats.length === 0 ? ( - "Не названы" + +
+
+
Подтвержденная категория
+
+ {card.category && card.strength + ? `${specializationLabels[card.category.specialization]}, ${gradeLabels[card.category.grade]}. ${confirmationLabel(card.category.basis, card.strength)}` + : "Нет"} +
+
+
+
Заявленный кандидатом грейд
+
{card.declaredGrade ? gradeLabels[card.declaredGrade] : "Не указан"}
+
+
+
Общий опыт
+
+ {context.experienceBand ? experienceBandLabels[context.experienceBand] : } +
+
+
+
Форматы работы
+
+ {context.workFormats === null ? ( + + ) : context.workFormats.length === 0 ? ( + "Не названы" + ) : ( + context.workFormats.map((format) => workFormatLabels[format]).join(", ") + )} +
+
+
+ +
+ Почему в подборке +
+ {sources.length > 0 ? ( +
    + {sources.map((item) => ( +
  • + + + {item.label} + {item.stateLabel} + +
  • + ))} +
) : ( - context.workFormats.map((format) => workFormatLabels[format]).join(", ") +

Сервер не вернул пояснений по источникам.

)} -
-
Зарплатные ожидания
-
- {context.salaryCompatibility ? ( - salaryCompatibilityLabels[context.salaryCompatibility] - ) : ( - - )} -
-
-
-
Источники подтверждения и пробелы
- {sources.length > 0 ? ( -
    - {sources.map((item) => ( -
  • - {item.label} - -
  • - ))} -
- ) : ( -

Сервер не вернул пояснений по источникам.

- )} -
+ + {actions ?
{actions}
: null} {children ?
{children}
: null}
diff --git a/frontend/src/entities/match/ui/match-explanation.module.css b/frontend/src/entities/match/ui/match-explanation.module.css index 2e62d9e..10c1307 100644 --- a/frontend/src/entities/match/ui/match-explanation.module.css +++ b/frontend/src/entities/match/ui/match-explanation.module.css @@ -8,6 +8,10 @@ background: var(--color-canvas); } +.panel:focus-visible { + outline-offset: 2px; +} + .title { margin: 0; font-size: var(--font-size-m); diff --git a/frontend/src/features/edit-company/ui/company-editor.module.css b/frontend/src/features/edit-company/ui/company-editor.module.css index 383ccdc..9ed6e0c 100644 --- a/frontend/src/features/edit-company/ui/company-editor.module.css +++ b/frontend/src/features/edit-company/ui/company-editor.module.css @@ -1,16 +1,15 @@ .form { display: grid; - gap: var(--space-4); + gap: var(--space-5); min-width: 0; } .title { + color: var(--color-text-strong); font-size: var(--font-size-l); - font-weight: var(--font-weight-bold); } -.field, -.group { +.field { display: grid; gap: var(--space-2); min-width: 0; @@ -18,6 +17,8 @@ .field label, .group legend { + color: var(--color-text); + font-size: var(--font-size-s); font-weight: var(--font-weight-bold); } @@ -25,12 +26,7 @@ .field textarea { width: 100%; min-width: 0; - padding: var(--space-3); border: var(--line-thin) solid var(--color-border-strong); - border-radius: var(--radius-s); - color: var(--color-text); - background: var(--color-surface); - font: inherit; line-height: var(--line-height-body); } @@ -38,25 +34,33 @@ resize: vertical; } -.field input:focus-visible, -.field textarea:focus-visible { - outline: var(--line-strong) solid var(--color-accent); - outline-offset: 2px; -} - .field input[aria-invalid="true"], .field textarea[aria-invalid="true"] { border-color: var(--color-danger); } +/* A group of related fields: a mono legend over a hairline, no frame. */ .group { - padding: var(--space-4); - border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-m); + display: grid; + gap: var(--space-4); + min-width: 0; + margin: 0; + padding: var(--space-5) 0 0; + border: 0; + border-top: var(--line-thin) solid var(--color-divider); +} + +.group legend { + padding: 0; + color: var(--color-text-strong); + font-family: var(--font-mono); + font-size: var(--font-size-m); + font-weight: var(--font-weight-medium); } .hint { color: var(--color-text-secondary); + font-size: var(--font-size-s); } .representative { @@ -68,26 +72,11 @@ border-bottom: var(--line-thin) solid var(--color-divider); } -.field-error, -.action-error { +.field-error { + margin: 0; color: var(--color-danger); -} - -.action-error, -.notice, -.conflict { - padding: var(--space-3); - border-left: var(--line-strong) solid var(--color-accent); - background: var(--color-canvas); -} - -.conflict { - display: grid; - gap: var(--space-2); -} - -.conflict h3 { - font-weight: var(--font-weight-bold); + font-size: var(--font-size-s); + font-weight: var(--font-weight-medium); } .actions { @@ -102,9 +91,3 @@ grid-template-columns: minmax(0, 1fr); } } - -@media (width < 30rem) { - .group { - padding: var(--space-3); - } -} diff --git a/frontend/src/features/edit-company/ui/company-editor.tsx b/frontend/src/features/edit-company/ui/company-editor.tsx index d5a89cc..42297b6 100644 --- a/frontend/src/features/edit-company/ui/company-editor.tsx +++ b/frontend/src/features/edit-company/ui/company-editor.tsx @@ -12,7 +12,7 @@ import { } from "../../../shared/api/endpoints/identity/identity"; import { ApiRequestError } from "../../../shared/api"; import type { Organization, OrganizationCreate, Session } from "../../../shared/api/schemas"; -import { Button, SavingStatus } from "../../../shared/ui"; +import { Button, Notice, SavingStatus } from "../../../shared/ui"; import { buildCompanyCreateBody, buildCompanyUpdateBody, @@ -359,10 +359,10 @@ export function CompanyEditor({ organization, onSaved, onAccessLost }: CompanyEd
{creating ?

Основные данные компании

: null} {createRequestIsFrozen ? ( -

+ Запрос создания хранится только на этой странице. Не меняйте данные до подтверждения ответа. -

+ ) : null}
@@ -521,32 +521,42 @@ export function CompanyEditor({ organization, onSaved, onAccessLost }: CompanyEd {conflict ? ( -
-

Компания изменилась

-

- Черновик оставлен. Прочитайте текущие данные, проверьте изменения и подтвердите - повторное сохранение. -

- -
+ void reloadCurrentVersion()} + > + Прочитать текущую версию + + } + > + Черновик оставлен. Прочитайте текущие данные, проверьте изменения и подтвердите повторное + сохранение. + ) : null} {reviewRequired ? ( -
-

- Текущая версия загружена. Ваши измененные поля сохранены в черновике; проверьте их перед - повторной отправкой. -

- -
+ setReviewRequired(false)}> + Я проверил черновик + + } + > + Текущая версия загружена. Ваши измененные поля сохранены в черновике; проверьте их перед + повторной отправкой. + ) : null} {errorMessage ? ( -

+ {errorMessage} -

+ ) : null}
+ ) : null} + + +
+ + ))} + +
+ + { + if (event.key === "Enter") { + event.preventDefault(); + onAdd(list, event.currentTarget); + } + }} + /> + +
+ {error ? {error} : null} + + ); +} + +type TaskListProps = { + id: string; + items: NeedFormValues["tasks"]; + error: string | undefined; + disabled: boolean; + onConfirm: (index: number) => void; + onEdit: (index: number, text: string) => void; + onRemove: (index: number) => void; + onAdd: (input: HTMLInputElement) => void; +}; + +/** The tasks of the team, editable in the same way as a skill list. */ +export function TaskList({ + id, + items, + error, + disabled, + onConfirm, + onEdit, + onRemove, + onAdd, +}: TaskListProps) { + return ( +
+

+ Задачи команды +

+ {items.length === 0 ?

Задачи не указаны.

: null} +
    + {items.map((item, index) => ( + +
    + + onEdit(index, event.currentTarget.value)} + /> + + {item.status === "extracted" ? "Предложено" : "Подтверждено"} + +
    + {item.stored?.source.quote ? ( +
    {item.stored.source.quote}
    + ) : null} +
    + {item.status === "extracted" ? ( + + ) : null} + +
    +
    + ))} +
+
+ + { + if (event.key === "Enter") { + event.preventDefault(); + onAdd(event.currentTarget); + } + }} + /> + +
+ {error ? {error} : null} +
+ ); +} diff --git a/frontend/src/features/edit-need/ui/need-editor.module.css b/frontend/src/features/edit-need/ui/need-editor.module.css index ba98429..bbad93b 100644 --- a/frontend/src/features/edit-need/ui/need-editor.module.css +++ b/frontend/src/features/edit-need/ui/need-editor.module.css @@ -4,155 +4,172 @@ min-width: 0; } -.intro, -.hint, -.meta, -.provenance, -.question { +.intro { + display: grid; + gap: var(--space-1); + max-width: 46rem; color: var(--color-text-secondary); } .hint, -.provenance, -.question, -.field-error, -.action-error, .meta { margin: 0; + color: var(--color-text-secondary); + font-size: var(--font-size-s); } -.group, -.salary, -.conflict, -.recommendations, -.list { +/* The form and a sticky summary side by side once the work area is wide + * enough; below that the summary follows the form. */ +.layout { + display: grid; + gap: var(--space-5); + align-items: start; + min-width: 0; +} + +.main, +.aside { display: grid; gap: var(--space-4); min-width: 0; - padding: var(--space-4); - border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-m); } -.group legend, -.work-formats legend { - padding: 0 var(--space-2); - font-weight: var(--font-weight-bold); +@media (width >= 75rem) { + .layout { + grid-template-columns: minmax(0, 1fr) 19rem; + } + + .aside { + position: sticky; + top: var(--space-5); + } +} + +.panels { + gap: var(--space-5); + padding: var(--space-4); +} + +@media (width >= 48rem) { + .panels { + padding: var(--space-5); + } +} + +.panel { + display: grid; + gap: var(--space-5); + min-width: 0; +} + +.panel[hidden] { + display: none; +} + +.panel-head { + display: grid; + gap: var(--space-2); + padding-bottom: var(--space-4); + border-bottom: var(--line-thin) solid var(--color-divider); +} + +.panel-title { + color: var(--color-text-strong); + font-size: var(--font-size-xl); +} + +.lead { + max-width: 42rem; + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} + +.fields { + display: grid; + gap: var(--space-5); + min-width: 0; + margin: 0; + padding: 0; + border: 0; } .field { display: grid; gap: var(--space-2); + align-content: start; min-width: 0; } -.field label, -.add-row label, -.skill-label { +.field > label, +.add-row > label, +.chip-group > legend { + color: var(--color-text); + font-size: var(--font-size-s); font-weight: var(--font-weight-bold); } -.field input, -.field select, -.field textarea, -.item input, +.field :is(input, select, textarea), .add-row input { width: 100%; min-width: 0; - padding: var(--space-3); border: var(--line-thin) solid var(--color-border-strong); - border-radius: var(--radius-s); - color: var(--color-text); - background: var(--color-surface); - font: inherit; -} - -.add-row input { - flex: 1 1 14rem; } .field textarea { resize: vertical; } -.field :is(input, select, textarea):focus-visible, -.item input:focus-visible, -.add-row input:focus-visible { - outline: var(--line-strong) solid var(--color-accent); - outline-offset: 2px; -} - -.field [aria-invalid="true"] { +.field [aria-invalid="true"], +.add-row [aria-invalid="true"] { border-color: var(--color-danger); } +.field-error { + margin: 0; + color: var(--color-danger); + font-size: var(--font-size-s); + font-weight: var(--font-weight-medium); +} + +.confirm-field { + justify-self: start; +} + +.notice-title { + color: var(--color-text-strong); + font-size: 0.9375rem; +} + +/* Provenance of a stored value: a status tag and, when the server tied one, + * the excerpt of the need text. */ .provenance { display: grid; - gap: var(--space-1); - font-size: var(--font-size-s); + gap: var(--space-2); + justify-items: start; + min-width: 0; } -.provenance p, -.provenance blockquote, -.item blockquote { +.quote { margin: 0; -} - -.provenance blockquote, -.item blockquote { padding-inline-start: var(--space-3); - border-inline-start: var(--line-strong) solid var(--color-divider); + border-inline-start: var(--line-strong) solid var(--color-accent); color: var(--color-text-secondary); + font-size: var(--font-size-s); overflow-wrap: anywhere; } -.question { - padding: var(--space-3); - border-inline-start: var(--line-strong) solid var(--color-accent); - background: var(--color-canvas); -} - -.field-error, -.action-error { - color: var(--color-danger); -} - -.work-formats { - display: flex; - flex-wrap: wrap; +.list { + display: grid; gap: var(--space-3); min-width: 0; - padding: var(--space-3); - border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-s); } -.work-formats label { - display: inline-flex; - gap: var(--space-2); - align-items: center; +.list-title { + color: var(--color-text-strong); + font-size: var(--font-size-m); } -.work-formats .provenance, -.work-formats .question { - flex-basis: 100%; -} - -.salary-grid { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: var(--space-3); -} - -.actions, -.add-row { - display: flex; - flex-wrap: wrap; - gap: var(--space-2); - align-items: center; -} - -.list ul { +.items { display: grid; gap: var(--space-3); margin: 0; @@ -161,42 +178,272 @@ } .item { + gap: var(--space-2); +} + +.item-main { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: var(--space-3); + align-items: center; +} + +.item-input { + width: 100%; + min-width: 0; + border: var(--line-thin) solid var(--color-border-strong); +} + +.item-actions { + display: flex; + flex-wrap: wrap; + gap: 0 var(--space-3); +} + +.add-row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: var(--space-2); + align-items: center; +} + +.add-row > label { + grid-column: 1 / -1; +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +/* Work format as filter chips: a native checkbox under a capsule. A checked + * chip is blue with a check mark, so the state is not carried by color alone. */ +.chip-group { display: grid; gap: var(--space-2); min-width: 0; - padding: var(--space-3); - border: var(--line-thin) solid var(--color-divider); - border-radius: var(--radius-s); + margin: 0; + padding: 0; + border: 0; } -.badge { - width: fit-content; - padding: var(--space-1) var(--space-2); - border-radius: var(--radius-s); +.chip-group > legend { + padding: 0; + margin-bottom: var(--space-2); +} + +.chip-row { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.chip { + position: relative; + display: inline-flex; +} + +.chip input[type="checkbox"] { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + margin: 0; + opacity: 0; + cursor: pointer; +} + +.chip span { + display: inline-flex; + gap: 0.375rem; + align-items: center; + min-height: 2.5rem; + padding: 0 var(--space-4); + border: var(--line-thin) solid var(--color-border-strong); + border-radius: var(--radius-pill); + color: var(--color-text); + font-family: var(--font-mono); + font-size: var(--font-size-s); + font-weight: var(--font-weight-medium); + background: var(--color-surface); + transition: + background-color var(--duration-fast) var(--easing-standard), + border-color var(--duration-fast) var(--easing-standard); +} + +.chip span::before { + content: "+"; color: var(--color-text-secondary); - background: var(--color-canvas); - font-size: var(--font-size-s); } -.conflict { - border-color: var(--color-accent); - background: var(--color-canvas); +.chip input:checked + span { + border-color: var(--color-action); + color: var(--color-on-action); + background: var(--color-action); } -.meta { - font-size: var(--font-size-s); +.chip input:checked + span::before { + content: "✓"; + color: inherit; +} + +.chip input:focus-visible + span { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.chip:hover input:not(:checked, :focus-visible) + span { + background: var(--color-surface-tint-hover); +} + +.salary-box { + gap: var(--space-3); +} + +.salary-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: var(--space-3); } @media (width < 42rem) { .salary-grid { grid-template-columns: minmax(0, 1fr); } +} - .group, - .salary, - .conflict, - .recommendations, - .list { - padding: var(--space-3); +.salary-line { + color: var(--color-text-strong); + font-size: var(--font-size-l); +} + +.summary-salary { + color: var(--color-text-strong); + font-size: var(--font-size-m); +} + +.chips { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + align-items: center; + justify-content: space-between; +} + +.actions-side { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + align-items: center; +} + +.eyebrow { + color: var(--color-text-secondary); + font-family: var(--font-mono); + font-size: var(--font-size-xs); + font-weight: var(--font-weight-medium); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; +} + +.summary-title { + color: var(--color-text-strong); + font-size: var(--font-size-l); + overflow-wrap: anywhere; +} + +.summary-title[data-empty] { + color: var(--color-text-secondary); +} + +.summary-facts { + display: grid; + gap: var(--space-3); + margin: 0; +} + +.summary-facts dt { + margin-bottom: var(--space-1); + color: var(--color-text-secondary); + font-size: var(--font-size-xs); +} + +.summary-facts dd { + margin: 0; +} + +.category-list { + display: grid; + gap: var(--space-2); + margin: 0; + padding: 0; + list-style: none; +} + +.category-list li { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-3); + align-items: center; +} + +.review { + display: grid; + margin: 0; +} + +.review-row { + display: grid; + grid-template-columns: 8rem minmax(0, 1fr); + gap: var(--space-1) var(--space-4); + align-items: start; + padding: var(--space-3) 0; + border-bottom: var(--line-thin) solid var(--color-divider); +} + +.review-row > dt { + padding-top: var(--space-2); + color: var(--color-text-secondary); + font-size: var(--font-size-s); +} + +.review-row > dd { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: var(--space-1) var(--space-3); + align-items: start; + min-width: 0; + margin: 0; +} + +.review-value { + min-width: 0; + overflow-wrap: anywhere; +} + +.review-list { + display: grid; + gap: var(--space-1); + margin: 0; + padding-inline-start: var(--space-4); +} + +@media (width < 30rem) { + .review-row { + grid-template-columns: minmax(0, 1fr); + } + + .review-row > dt { + padding-top: 0; } } diff --git a/frontend/src/features/edit-need/ui/need-editor.test.tsx b/frontend/src/features/edit-need/ui/need-editor.test.tsx index 1113675..8a934b0 100644 --- a/frontend/src/features/edit-need/ui/need-editor.test.tsx +++ b/frontend/src/features/edit-need/ui/need-editor.test.tsx @@ -65,11 +65,45 @@ describe("NeedEditor", () => { expect(markup).toContain("Какой грейд нужен"); expect(markup).toContain("в какой базе"); expect(markup).toContain("Вакансия для сохранения потребности не требуется."); - expect(markup).toMatch( - / { - const title = event.currentTarget.value; - changeDraft((current) => ({ ...current, title })); - }} - /> - {fieldErrors.title ? ( -

- {fieldErrors.title} -

+
+
+ + +
+
+ + { + const title = event.currentTarget.value; + changeDraft((current) => ({ ...current, title })); + }} + /> + {fieldErrors.title ? ( + {fieldErrors.title} + ) : null} +
+
+ +