diff --git a/api/README.en.md b/api/README.en.md index c251a2d..2df7fe0 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -180,7 +180,7 @@ Questionnaire: ### Candidate profile -The `candidate` tag includes implemented `GetMyProfile` and `SaveMyProfile` operations for the private manual profile. A verified candidate reads and edits only their own profile; an employer receives 403 and a guest receives 401. PUT requires the session CSRF token and exact Origin. Data, version, overlap confirmations, history, and the step transition commit in one transaction. Without DATABASE_URL, the operations retain their 501 fallback. +The `candidate` tag includes implemented `GetMyProfile` and `SaveMyProfile` operations for the private manual profile. A verified candidate reads and edits only their own profile; an employer receives 403 and a guest receives 401. PUT requires the session CSRF token and exact Origin. Data, version, overlap confirmations, history, and the step transition commit in one transaction. Without DATABASE_URL, the operations retain their 501 fallback. `confirmed_categories` is read-only: one category per specialization in catalog order, from assessment results, with `basis` (`synthetic_demo` for a demonstration category), `confirmed_at`, and `attempt_id`; no request carries it. | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -288,6 +288,7 @@ Attempt lifecycle, with the commands each state accepts: - Limits: `expires_at` and `sessions` (`used`, `max`, `idle_timeout_seconds`, null when the policy defines no session limit) come from the policy version; PRD FR04 allows two sessions within 72 hours. Creation starts session 1. After an idle timeout the candidate explicitly calls `StartMyAssessmentAttemptSession` with the latest `expected_version`; it starts the next session only if quota and deadline allow. Calling it during an active session is a no-op. Session start does not extend `expires_at` or `chain_deadline`. - At the limits: a practice already `pending` is graded first. A command or background transition then finalizes `ready_to_finalize` as `completed`, declines an unsubmitted additional practice (`completed`, `not_confirmed`), or moves `in_progress` and `practice_pending` to `expired`. GET never commits these transitions. `GetMyAssessmentResult` answers 409 while a due transition has not yet been stored. - Insufficient bank is a distinct state in two places. Before a root attempt starts, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or enough unseen families, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating an attempt or reserving a root slot. A correction with an expired chain deadline or insufficient safe bank is also refused; it does not create a new chain. During an existing attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families. +- Confirmed grade. `confirmed_grade` and `confirmed_basis` of each questionnaire specialization are read together from the current category, in one snapshot. `confirmed_basis` is `synthetic_demo` for a demonstration grade and null exactly when no grade is confirmed. An attempt does not set them directly: only a category upgrade changes them. - No new problem code is added, so attempt creation gets 409 `state_conflict` plus the availability status instead of a `bank_unavailable` code. The `ProblemCode` enum is copied byte-for-byte into the ML contract (`test_contract_copies.py`), so a new code would also change the ML contract and its generated models. The availability read also tells the client why an attempt cannot start and, for `cooldown`, from when, which a fixed problem detail cannot carry. - Availability shows the limits of each grade before the start: `time_limit_seconds`, `max_sessions`, `max_items`, and `practice_required`, null when unknown. - Root-attempt quota and retry timers are separate. Only root creation reserves one of the three root slots per 180 days; corrections in that chain do not reserve another. `insufficient_bank` or an unavailable sandbox does not create a new attempt or open a free chain. After a failure, including the first test, a strictly lower grade can be tested through the same chain; lower-grade corrections do not reset the 30-day same-grade or 90-day promotion timers. @@ -318,7 +319,7 @@ Result: - `next_steps` come from the server: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (the command is planned), and `take_higher_grade`. A first confirmation is not a promotion, so `take_higher_grade` after it has a null `available_at`; after a promotion the next one waits for the 90-day promotion interval. - The result never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. - Category from a `demo_basic` result. A real result carries `category_decision`: `status` (`not_eligible`, `not_confirmed`, `assigned`, `unchanged`), the grade in force before and after the attempt, `method` (`demo_basic_pass_mark`), `source` (`synthetic_demo`), and `calibration_status`. The threshold comes from the accepted policy version pinned to the attempt: reaching it counts, and no request parameter sets it. A category is assigned only when `ASSESSMENT_DEMO_CATEGORIES_ENABLED` is on, the policy version is a complete demonstration policy with `demo_basic` (its threshold is its own `basic_pass_mark_bp`), and an operator attestation exists for the opening, its manifest, and the policy version; otherwise `status` is `not_eligible` and `confirmed_grade` is null even though `outcome` may be `confirmed`. `confirmed_grade` is set only when a reviewed source accepted the confirmation (`assigned` or `unchanged`). A failure, an equal grade, or a lower grade neither lowers nor changes the current category. `demo_express` never gets a `category_decision` and never creates a category. A result stored before category decisions existed has no `category_decision`: its current grade is not reconstructed afterwards. -- `GET /api/v1/me/assessment-results` returns the history of the candidate only: completed `root` and `corrective` results, newest first by `decided_at` and `attempt_id`. The cursor is opaque, bound to the candidate, and uses only `[A-Za-z0-9_-]`; a foreign, altered, or malformed cursor answers 400 `validation_failed` with pointer `/cursor`. An employer account gets 403. A later change of the current policy, bank, or category changes no stored record. An employer receives only the current category (specialization, grade, and the coarse strength `standard`) through the anonymous card when the candidate published the `categories` field; the projection holds no attempt, score, version, or reason for a missing confirmation. +- `GET /api/v1/me/assessment-results` returns the history of the candidate only: completed `root` and `corrective` results, newest first by `decided_at` and `attempt_id`. The cursor is opaque, bound to the candidate, and uses only `[A-Za-z0-9_-]`; a foreign, altered, or malformed cursor answers 400 `validation_failed` with pointer `/cursor`. An employer account gets 403. A later change of the current policy, bank, or category changes no stored record. An employer receives only the current category (specialization, grade, the coarse strength `standard`, and the basis `basis`) through the anonymous card when the candidate published the `categories` field; the projection holds no attempt, score, version, or reason for a missing confirmation. Planned, additive: a short approach description of up to 1500 characters next to the practice, which never decides the grade (PRD FR05); the debug run operation of the practice; the server signals of the anti-cheat layer (answer time, parallel sessions, address changes), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05). @@ -733,6 +734,7 @@ The operation changes nothing and needs no Idempotency-Key; `POST` carries the b - Access. The organization comes from the path and the active owner membership of the session account. A missing session answers 401, a candidate account, a member who is not the owner, a missing CSRF token, and a foreign `Origin` answer 403, and an unknown organization, an organization without an active membership, a need of another organization, an unknown need, or a `requirements_version` that no change of the confirmed requirements created answer 404. Hidden profiles, a revoked or missing C2 publication, the organization's own hiding, and the minimum cohort of the card are applied before any entry exists: a handle in the result is a handle that `GetOrganizationCandidateCard` opens at that moment. - Basis. `MatchSearchByNeed` searches the immutable `requirements_version` snapshot (not the general `version`), and its optional `filters` narrow it; `MatchSearchByBank` searches all organization-visible entries with explicit filters. The response `source` repeats the basis: the need reference, or the bank filters with every key present and null for a filter that was not sent (the stack is sorted). - Entries. Every entry is one candidate specialization under the organization-scoped `candidate_handle`. `main` and `near` hold confirmed categories (`near` when a required skill of the request earns less than 0.25), `unconfirmed` holds the declared specializations, sorted by Fit, then Coverage, then an internal identifier that is never returned. An unconfirmed entry has `category: null`, `strength: null`, and only `fit` and `coverage`. The groups are not one scale, and one handle can be confirmed in one specialization and unconfirmed in another. +- Category basis. Each confirmed category of an entry carries `basis` (`synthetic_demo` for a demonstration category). The organization sees a demonstration as such, not as a standard confirmation; the field is required in `MatchCategory`. - Neutral and unknown values. The semantics component is 0.5 for every entry with `ml_unavailable`; `percentile` is null with `cohort_below_30` and T is 0.5 (no comparable real cohort exists, and demonstration results never form one); domain, freshness, and responsiveness are 0.5 with their flags; competition is 0 and is neither a penalty nor an unknown; a card value that is not published is `null` in `public_context` with `not_in_public_card`. - A search is charged like card reads, because an entry carries card content. The whole visible bank is ranked, and each group returns at most `max_results_per_group` entries of the policy version (demo 10, so at most 30 reveals for one search, below the 50 views per day of tier E0); no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate counts as one distinct card view of the organization (the same reservation as `GetOrganizationCandidateCard`, so a candidate already viewed inside the window costs nothing again, and repeating the search or opening the card afterwards does not charge twice) and gets one `card_viewed` entry in the access history per search with the fields actually returned. When the allowance ends, the entries already paid for are returned with `truncated: true`, nothing is written for the rest, and no error and no new problem code is returned. `truncated` is also true when a group exceeded its limit and never carries a count. The response `truncated` is required. - No contact, candidate location, salary amount or minimum, raw answer, failed attempt, or reason for withheld data is in any entry; the explanation uses the bounded `MatchEvidenceCode` and `MatchEvidenceState` values only. A deployment whose effective policy has no `matching` section answers an internal error and never ranks with defaults. diff --git a/api/README.md b/api/README.md index 81979e5..4986c13 100644 --- a/api/README.md +++ b/api/README.md @@ -180,7 +180,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Профиль кандидата -Тег `candidate` включает реализованные `GetMyProfile` и `SaveMyProfile` для приватного ручного профиля. Подтвержденный кандидат читает и меняет только свой профиль; работодатель получает 403, гость - 401. PUT требует CSRF-токен сессии и точный Origin. Данные, версия, подтверждения пересечений, история и переход шага сохраняются одной транзакцией. Без DATABASE_URL остается ответ 501. +Тег `candidate` включает реализованные `GetMyProfile` и `SaveMyProfile` для приватного ручного профиля. Подтвержденный кандидат читает и меняет только свой профиль; работодатель получает 403, гость - 401. PUT требует CSRF-токен сессии и точный Origin. Данные, версия, подтверждения пересечений, история и переход шага сохраняются одной транзакцией. Без DATABASE_URL остается ответ 501. `confirmed_categories` только читается: одна категория на специализацию в порядке каталога из результатов оценки, с `basis` (`synthetic_demo` для демонстрационной категории), `confirmed_at` и `attempt_id`; ни один запрос ее не принимает. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -288,6 +288,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Лимиты: `expires_at` и `sessions` (`used`, `max`, `idle_timeout_seconds`; null, если политика не задает лимит сессий) берутся из версии политики; FR04 в PRD допускает две сессии в пределах 72 часов. Создание начинает сессию 1. После простоя кандидат явно вызывает `StartMyAssessmentAttemptSession` с последним `expected_version`; следующая сессия начинается только если позволяют квота и срок. Вызов во время активной сессии ничего не меняет. Начало сессии не продлевает `expires_at` или `chain_deadline`. - При достижении лимитов практика, уже имеющая статус `pending`, сначала оценивается. Затем команда или фоновый переход завершает `ready_to_finalize` как `completed`, отклоняет неотправленную дополнительную практику (`completed`, `not_confirmed`) или переводит `in_progress` и `practice_pending` в `expired`. GET не фиксирует эти переходы. `GetMyAssessmentResult` отвечает 409, пока назревший переход не сохранен. - Недостаточный банк - отдельное состояние в двух местах. До старта корневой попытки `GetMyAssessmentAvailability` показывает `insufficient_bank` для грейда без опубликованного банка или достаточного числа невиденных семейств, а `CreateMyAssessmentAttempt` отвечает 409 `state_conflict`, не создавая попытку и не резервируя корневой слот. Корректировка также отклоняется, если срок цепочки истек или безопасного банка недостаточно; новая цепочка не создается. Во время существующей попытки терминальное состояние `insufficient_bank` завершает ее без подтвержденного грейда вместо повтора семейств. +- Подтвержденный грейд. `confirmed_grade` и `confirmed_basis` каждой специализации анкеты читаются из текущей категории вместе, в одном снимке. `confirmed_basis` равен `synthetic_demo` для демонстрационного грейда и null ровно тогда, когда грейд не подтвержден. Попытка напрямую их не задает: меняет их только повышение категории. - Новый код проблемы не добавлен, поэтому создание попытки получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может. - Доступность показывает лимиты каждого грейда до старта: `time_limit_seconds`, `max_sessions`, `max_items` и `practice_required`; null, если значение неизвестно. - Корневая квота и таймеры повторов разделены. Только запуск корневой попытки резервирует один из трех слотов на 180 дней; корректировки этой цепочки не резервируют дополнительные слоты. `insufficient_bank` или недоступность песочницы не создают новую попытку и не открывают бесплатную цепочку. После неудачи, включая первый тест, строго меньший грейд можно проверить в той же цепочке; корректировки не сбрасывают 30-дневный таймер повтора того же грейда или 90-дневный таймер повышения. @@ -318,7 +319,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - `next_steps` приходят с сервера: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (команда запланирована) и `take_higher_grade`. Первое подтверждение - не повышение, поэтому `take_higher_grade` после него имеет null в `available_at`; после повышения следующее ждет 90-дневный интервал повышения. - Результат никогда не содержит ответы, правильность отдельных заданий, ключи, seed, скрытые проверки или античит-сигналы. - Категория по результату `demo_basic`. Результат реальной попытки содержит `category_decision`: `status` (`not_eligible`, `not_confirmed`, `assigned`, `unchanged`), грейд, действовавший до попытки и после нее, `method` (`demo_basic_pass_mark`), `source` (`synthetic_demo`) и `calibration_status`. Порог берется из принятой версии политики, закрепленной за попыткой: достижение порога засчитывается, параметр запроса его не задает. Категория присваивается, только если включен `ASSESSMENT_DEMO_CATEGORIES_ENABLED`, версия политики является полной демонстрационной политикой с `demo_basic` (порог - ее собственный `basic_pass_mark_bp`), а для открытия, манифеста и версии политики есть аттестация оператора; иначе `status` равен `not_eligible`, `confirmed_grade` равен null, хотя `outcome` может быть `confirmed`. `confirmed_grade` заполнен, только когда подтверждение принято проверенным источником (`assigned` или `unchanged`). Неудача, равный или более низкий грейд не понижают и не меняют текущую категорию. `demo_express` никогда не получает `category_decision` и не создает категорию. Результат, сохраненный до появления решений о категориях, не содержит `category_decision`: его текущий грейд не восстанавливается задним числом. -- `GET /api/v1/me/assessment-results` возвращает историю только самого кандидата: завершенные `root` и `corrective` результаты от новых к старым по `decided_at` и `attempt_id`. Курсор непрозрачен, привязан к кандидату и содержит только символы `[A-Za-z0-9_-]`; чужой, измененный или некорректный курсор дает 400 `validation_failed` с pointer `/cursor`. Аккаунт работодателя получает 403. Смена текущей политики, банка или категории не меняет ни одну сохраненную запись. Работодатель получает только текущую категорию (специализация, грейд и грубая сила `standard`) через анонимную карточку, если кандидат опубликовал поле `categories`; ни попытки, ни баллы, ни версии, ни причины неподтверждения в этой проекции нет. +- `GET /api/v1/me/assessment-results` возвращает историю только самого кандидата: завершенные `root` и `corrective` результаты от новых к старым по `decided_at` и `attempt_id`. Курсор непрозрачен, привязан к кандидату и содержит только символы `[A-Za-z0-9_-]`; чужой, измененный или некорректный курсор дает 400 `validation_failed` с pointer `/cursor`. Аккаунт работодателя получает 403. Смена текущей политики, банка или категории не меняет ни одну сохраненную запись. Работодатель получает только текущую категорию (специализация, грейд, грубая сила `standard` и основание `basis`) через анонимную карточку, если кандидат опубликовал поле `categories`; ни попытки, ни баллы, ни версии, ни причины неподтверждения в этой проекции нет. Запланировано, добавляется без ломающих изменений: краткое описание подхода до 1500 знаков рядом с практикой, которое не определяет грейд (FR05 в PRD); операция отладочных запусков практики; серверные сигналы античит-слоя (время ответа, параллельные сессии, смена адреса); сигналы ведут к перепроверке и апелляции, а не к публичному ярлыку, и работодателю не показываются (FR05 в PRD). @@ -733,6 +734,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Доступ. Организация берется из пути и действующего членства владельца аккаунта сессии. Отсутствие сессии дает 401; аккаунт кандидата, участник не владелец, отсутствие CSRF-токена и чужой `Origin` дают 403; неизвестная организация, организация без действующего членства, потребность другой организации, неизвестная потребность и `requirements_version`, которую не создавало изменение подтвержденных требований, дают 404. Скрытые профили, отозванная или отсутствующая публикация C2, скрытие именно этой организации и минимальная когорта карточки применяются до появления любой записи: handle в результате - это handle, который `GetOrganizationCandidateCard` открывает в тот же момент. - Основание. `MatchSearchByNeed` ищет по неизменяемому снимку `requirements_version` (не по общей `version`), необязательные `filters` сужают его; `MatchSearchByBank` ищет по всем записям, видимым организации, с явными фильтрами. `source` в ответе повторяет основание: ссылку на потребность либо фильтры банка, где присутствует каждый ключ, а неотправленный фильтр равен null (стек отсортирован). - Записи. Каждая запись - одна специализация кандидата под организационным `candidate_handle`. В `main` и `near` лежат подтвержденные категории (`near`, если обязательный навык запроса дает меньше 0.25), в `unconfirmed` - заявленные специализации, отсортированные по Fit, затем Coverage, затем по внутреннему идентификатору, который не возвращается. У неподтвержденной записи `category: null`, `strength: null` и только `fit` и `coverage`. Группы - не одна шкала, и один handle может быть подтвержден по одной специализации и не подтвержден по другой. +- Основание категории. Каждая подтвержденная категория записи несет `basis` (`synthetic_demo` для демонстрационной категории). Организация видит демонстрацию как таковую, а не как стандартное подтверждение; поле обязательно в `MatchCategory`. - Нейтральные и неизвестные значения. Семантика равна 0.5 для каждой записи с `ml_unavailable`; `percentile` равен null с `cohort_below_30`, а T равен 0.5 (сопоставимой реальной когорты нет, демонстрационные результаты ее не образуют); домен, свежесть и своевременность равны 0.5 со своими признаками; соревновательный вклад равен 0 и не является ни штрафом, ни неизвестностью; неопубликованное значение карточки - `null` в `public_context` с `not_in_public_card`. - Поиск оплачивается как чтение карточек, потому что запись несет содержимое карточки. Ранжируется весь видимый банк, а каждая группа возвращает не более `max_results_per_group` записей версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 просмотров в сутки для уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат считается одним уникальным просмотром карточки организации (то же резервирование, что у `GetOrganizationCandidateCard`: кандидат, уже просмотренный в окне, второй раз ничего не стоит, и повтор поиска или последующее открытие карточки не списывает дважды) и получает по одной записи `card_viewed` в истории доступа за поиск с фактически возвращенными полями. Когда лимит заканчивается, возвращаются уже оплаченные записи с `truncated: true`, для остальных ничего не пишется, ошибка и новый код проблемы не возвращаются. `truncated` также истинно, когда группа превысила предел, и никогда не несет число. В ответе `truncated` обязателен. - Ни в одной записи нет контакта, локации кандидата, суммы или минимума зарплаты, сырого ответа, проваленной попытки и причины скрытых данных; объяснение использует только ограниченные значения `MatchEvidenceCode` и `MatchEvidenceState`. Развертывание, действующая политика которого не содержит раздела `matching`, отвечает внутренней ошибкой и не ранжирует по умолчаниям. diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index a720590..74b1aca 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -436,6 +436,7 @@ AssessmentAvailability: specializations: - specialization: backend confirmed_grade: null + confirmed_basis: null active_attempt_id: null grades: - grade: intern @@ -472,6 +473,7 @@ AssessmentAvailability: practice_required: null - specialization: network_engineer confirmed_grade: null + confirmed_basis: null active_attempt_id: null grades: - grade: intern @@ -4139,6 +4141,7 @@ BackendCandidateProfile: confirmed_categories: - specialization: backend grade: junior + basis: synthetic_demo confirmed_at: "2026-10-04T18:10:00Z" attempt_id: 0192b3c4-d5e6-7f80-9a1b-2c3d4e5f6a7b updated_at: "2026-10-05T09:30:00Z" @@ -4378,6 +4381,7 @@ PublishedCardPreview: - specialization: backend grade: middle strength: standard + basis: synthetic_demo stack: - postgresql - kafka @@ -4403,6 +4407,7 @@ OrganizationAnonymousCandidateCard: - specialization: backend grade: middle strength: standard + basis: synthetic_demo stack: - postgresql - kafka diff --git a/api/core/components/examples/matches.yml b/api/core/components/examples/matches.yml index cfffb6d..0ee943a 100644 --- a/api/core/components/examples/matches.yml +++ b/api/core/components/examples/matches.yml @@ -52,6 +52,7 @@ ThreeGroups: category: specialization: backend grade: middle + basis: synthetic_demo strength: standard public_context: stack: @@ -87,6 +88,7 @@ ThreeGroups: category: specialization: frontend grade: junior + basis: synthetic_demo strength: standard public_context: stack: @@ -183,6 +185,7 @@ MLUnavailable: category: specialization: backend grade: middle + basis: synthetic_demo strength: strong public_context: stack: @@ -234,6 +237,7 @@ CohortBelow30: category: specialization: backend grade: middle + basis: synthetic_demo strength: standard public_context: stack: @@ -287,6 +291,7 @@ Truncated: category: specialization: backend grade: junior + basis: synthetic_demo strength: standard public_context: stack: null diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index c517ee1..ad20bb2 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -1682,6 +1682,7 @@ AssessmentSpecializationAvailability: required: - specialization - confirmed_grade + - confirmed_basis - active_attempt_id - grades properties: @@ -1692,6 +1693,11 @@ AssessmentSpecializationAvailability: oneOf: - $ref: '#/GradeCode' - type: 'null' + confirmed_basis: + description: What the confirmed grade rests on, or null exactly when `confirmed_grade` is null. `synthetic_demo` marks a demonstration category, which is not a validated measurement and must not be shown as a real confirmation. + oneOf: + - $ref: '#/EvidenceBasis' + - type: 'null' active_attempt_id: type: - string @@ -2325,11 +2331,12 @@ ProfileParallelPeriodConfirmation: $ref: '#/ProfileExperiencePeriod' ProfileConfirmedCategory: type: object - description: 'A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`.' + description: 'A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category that is not a validated measurement.' additionalProperties: false required: - specialization - grade + - basis - confirmed_at - attempt_id properties: @@ -2337,6 +2344,8 @@ ProfileConfirmedCategory: $ref: '#/SpecializationCode' grade: $ref: '#/GradeCode' + basis: + $ref: '#/EvidenceBasis' confirmed_at: $ref: '#/Timestamp' attempt_id: @@ -4808,16 +4817,19 @@ MatchStrength: - strong MatchCategory: type: object - description: A confirmed category. Its specialization must equal the enclosing match entry's specialization. + description: A confirmed category. Its specialization must equal the enclosing match entry's specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation. additionalProperties: false required: - specialization - grade + - basis properties: specialization: $ref: '#/SpecializationCode' grade: $ref: '#/GradeCode' + basis: + $ref: '#/EvidenceBasis' MatchScore: type: number format: double @@ -6783,12 +6795,13 @@ PrivacySettings: description: Number of organizations that the candidate hides the profile from. The list is read with `ListMyHiddenOrganizations`. CardCategory: type: object - description: A category confirmed by assessment results, as the card shows it. + description: A category confirmed by assessment results, as the card shows it. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which is never a standard confirmation. additionalProperties: false required: - specialization - grade - strength + - basis properties: specialization: $ref: '#/SpecializationCode' @@ -6800,6 +6813,8 @@ CardCategory: - standard - strong description: Coarse strength of the authoritative confirmation. + basis: + $ref: '#/EvidenceBasis' CardSelfAssessment: type: object description: Candidate-declared specialization and optional grade. This is never an assessment result. diff --git a/api/core/components/schemas/assessment_schemas.yml b/api/core/components/schemas/assessment_schemas.yml index 1371cfe..8a3cc22 100644 --- a/api/core/components/schemas/assessment_schemas.yml +++ b/api/core/components/schemas/assessment_schemas.yml @@ -1845,6 +1845,7 @@ schemas: required: - specialization - confirmed_grade + - confirmed_basis - active_attempt_id - grades properties: @@ -1855,6 +1856,15 @@ schemas: oneOf: - $ref: "./catalog_schemas.yml#/schemas/GradeCode" - type: "null" + confirmed_basis: + description: >- + What the confirmed grade rests on, or null exactly when + `confirmed_grade` is null. `synthetic_demo` marks a demonstration + category, which is not a validated measurement and must not be shown + as a real confirmation. + oneOf: + - $ref: "./evidence_schemas.yml#/schemas/EvidenceBasis" + - type: "null" active_attempt_id: type: - string diff --git a/api/core/components/schemas/candidate_schemas.yml b/api/core/components/schemas/candidate_schemas.yml index 6e963b2..a8a2ede 100644 --- a/api/core/components/schemas/candidate_schemas.yml +++ b/api/core/components/schemas/candidate_schemas.yml @@ -593,11 +593,14 @@ schemas: from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of - the profile and from the self-assessed grades in `roles`. + the profile and from the self-assessed grades in `roles`. `basis` says + what the grade rests on; `synthetic_demo` marks a demonstration category + that is not a validated measurement. additionalProperties: false required: - specialization - grade + - basis - confirmed_at - attempt_id properties: @@ -605,6 +608,8 @@ schemas: $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" grade: $ref: "./catalog_schemas.yml#/schemas/GradeCode" + basis: + $ref: "./evidence_schemas.yml#/schemas/EvidenceBasis" confirmed_at: $ref: "./common_schemas.yml#/schemas/Timestamp" attempt_id: diff --git a/api/core/components/schemas/match_schemas.yml b/api/core/components/schemas/match_schemas.yml index 7a83a4e..8c3f5da 100644 --- a/api/core/components/schemas/match_schemas.yml +++ b/api/core/components/schemas/match_schemas.yml @@ -236,16 +236,21 @@ schemas: type: object description: >- A confirmed category. Its specialization must equal the enclosing - match entry's specialization. + match entry's specialization. `basis` says what the grade rests on; + `synthetic_demo` marks a demonstration category, which an organization + must read as one and never as a standard confirmation. additionalProperties: false required: - specialization - grade + - basis properties: specialization: $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" grade: $ref: "./catalog_schemas.yml#/schemas/GradeCode" + basis: + $ref: "./evidence_schemas.yml#/schemas/EvidenceBasis" MatchScore: type: number format: double diff --git a/api/core/components/schemas/privacy_schemas.yml b/api/core/components/schemas/privacy_schemas.yml index 434d8c7..b2e6423 100644 --- a/api/core/components/schemas/privacy_schemas.yml +++ b/api/core/components/schemas/privacy_schemas.yml @@ -315,12 +315,16 @@ schemas: The list is read with `ListMyHiddenOrganizations`. CardCategory: type: object - description: A category confirmed by assessment results, as the card shows it. + description: >- + A category confirmed by assessment results, as the card shows it. + `basis` says what the grade rests on; `synthetic_demo` marks a + demonstration category, which is never a standard confirmation. additionalProperties: false required: - specialization - grade - strength + - basis properties: specialization: $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" @@ -332,6 +336,8 @@ schemas: - standard - strong description: Coarse strength of the authoritative confirmation. + basis: + $ref: "./evidence_schemas.yml#/schemas/EvidenceBasis" CardSelfAssessment: type: object description: Candidate-declared specialization and optional grade. This is never an assessment result. diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 72e380a..fdb9649 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -4672,11 +4672,12 @@ components: $ref: '#/components/schemas/ProfileExperiencePeriod' ProfileConfirmedCategory: type: object - description: 'A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`.' + description: 'A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category that is not a validated measurement.' additionalProperties: false required: - specialization - grade + - basis - confirmed_at - attempt_id properties: @@ -4684,6 +4685,8 @@ components: $ref: '#/components/schemas/SpecializationCode' grade: $ref: '#/components/schemas/GradeCode' + basis: + $ref: '#/components/schemas/EvidenceBasis' confirmed_at: $ref: '#/components/schemas/Timestamp' attempt_id: @@ -6163,6 +6166,7 @@ components: required: - specialization - confirmed_grade + - confirmed_basis - active_attempt_id - grades properties: @@ -6173,6 +6177,11 @@ components: oneOf: - $ref: '#/components/schemas/GradeCode' - type: 'null' + confirmed_basis: + description: What the confirmed grade rests on, or null exactly when `confirmed_grade` is null. `synthetic_demo` marks a demonstration category, which is not a validated measurement and must not be shown as a real confirmation. + oneOf: + - $ref: '#/components/schemas/EvidenceBasis' + - type: 'null' active_attempt_id: type: - string @@ -9436,12 +9445,13 @@ components: description: Number of organizations that the candidate hides the profile from. The list is read with `ListMyHiddenOrganizations`. CardCategory: type: object - description: A category confirmed by assessment results, as the card shows it. + description: A category confirmed by assessment results, as the card shows it. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which is never a standard confirmation. additionalProperties: false required: - specialization - grade - strength + - basis properties: specialization: $ref: '#/components/schemas/SpecializationCode' @@ -9453,6 +9463,8 @@ components: - standard - strong description: Coarse strength of the authoritative confirmation. + basis: + $ref: '#/components/schemas/EvidenceBasis' AnonymousCardContent: type: object description: The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content. @@ -10835,16 +10847,19 @@ components: description: Search basis echoed with the response so the displayed result remains tied to its need requirements version or bank filters. MatchCategory: type: object - description: A confirmed category. Its specialization must equal the enclosing match entry's specialization. + description: A confirmed category. Its specialization must equal the enclosing match entry's specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation. additionalProperties: false required: - specialization - grade + - basis properties: specialization: $ref: '#/components/schemas/SpecializationCode' grade: $ref: '#/components/schemas/GradeCode' + basis: + $ref: '#/components/schemas/EvidenceBasis' MatchStrength: type: string description: Coarse strength of a confirmed assessment for this specialization. @@ -12441,6 +12456,7 @@ components: confirmed_categories: - specialization: backend grade: junior + basis: synthetic_demo confirmed_at: '2026-10-04T18:10:00Z' attempt_id: 0192b3c4-d5e6-7f80-9a1b-2c3d4e5f6a7b updated_at: '2026-10-05T09:30:00Z' @@ -12554,6 +12570,7 @@ components: specializations: - specialization: backend confirmed_grade: null + confirmed_basis: null active_attempt_id: null grades: - grade: intern @@ -12590,6 +12607,7 @@ components: practice_required: null - specialization: network_engineer confirmed_grade: null + confirmed_basis: null active_attempt_id: null grades: - grade: intern @@ -14552,6 +14570,7 @@ components: category: specialization: backend grade: middle + basis: synthetic_demo strength: standard public_context: stack: @@ -14587,6 +14606,7 @@ components: category: specialization: frontend grade: junior + basis: synthetic_demo strength: standard public_context: stack: @@ -14681,6 +14701,7 @@ components: category: specialization: backend grade: middle + basis: synthetic_demo strength: strong public_context: stack: @@ -14731,6 +14752,7 @@ components: category: specialization: backend grade: middle + basis: synthetic_demo strength: standard public_context: stack: @@ -14781,6 +14803,7 @@ components: category: specialization: backend grade: junior + basis: synthetic_demo strength: standard public_context: stack: null @@ -14817,6 +14840,7 @@ components: - specialization: backend grade: middle strength: standard + basis: synthetic_demo stack: - postgresql - kafka @@ -16265,6 +16289,7 @@ components: - specialization: backend grade: middle strength: standard + basis: synthetic_demo stack: - postgresql - kafka diff --git a/backend/db/queries/assessment_results.sql b/backend/db/queries/assessment_results.sql index 1e82ece..b28f5a9 100644 --- a/backend/db/queries/assessment_results.sql +++ b/backend/db/queries/assessment_results.sql @@ -55,6 +55,14 @@ SELECT candidate_id, specialization, grade, source_attempt_id, source_review_id, FROM candidate_assessment_categories WHERE candidate_id = sqlc.arg(candidate_id) AND specialization = sqlc.arg(specialization); +-- name: ListCandidateAssessmentCategories :many +SELECT candidate_id, specialization, grade, source_attempt_id, source_review_id, + product_policy_version_id, product_policy_version, grading_policy_version_id, + opening_id, opening_manifest_sha256, source, calibration_status, assigned_at +FROM candidate_assessment_categories +WHERE candidate_id = sqlc.arg(candidate_id) +ORDER BY specialization; + -- name: GetSyntheticCategoryReview :one SELECT review.id, review.opening_id, review.category, review.source, review.opening_manifest_sha256, review.product_policy_version_id, diff --git a/backend/db/queries/privacy_cohort.sql b/backend/db/queries/privacy_cohort.sql index 2d3b07d..b34e16b 100644 --- a/backend/db/queries/privacy_cohort.sql +++ b/backend/db/queries/privacy_cohort.sql @@ -53,7 +53,11 @@ SELECT COALESCE( ( SELECT jsonb_agg( - jsonb_build_object('specialization', category.specialization, 'grade', category.grade) + jsonb_build_object( + 'specialization', category.specialization, + 'grade', category.grade, + 'source', category.source + ) ORDER BY category.specialization )::text FROM candidate_assessment_categories AS category @@ -187,7 +191,11 @@ SELECT COALESCE( ( SELECT jsonb_agg( - jsonb_build_object('specialization', category.specialization, 'grade', category.grade) + jsonb_build_object( + 'specialization', category.specialization, + 'grade', category.grade, + 'source', category.source + ) ORDER BY category.specialization )::text FROM candidate_assessment_categories AS category diff --git a/backend/integration_test/assessment_category_http_test.go b/backend/integration_test/assessment_category_http_test.go index 5267f07..cc97c41 100644 --- a/backend/integration_test/assessment_category_http_test.go +++ b/backend/integration_test/assessment_category_http_test.go @@ -710,6 +710,7 @@ func TestAssessmentCategoryAssignmentOverHTTP(t *testing.T) { } wantHigh := []domain.CandidateViewConfirmedCategoryInput{{ Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard, + Basis: domain.AssessmentCategorySourceSyntheticDemo, }} if len(sources) != 2 || fmt.Sprint(categories[high.id]) != fmt.Sprint(wantHigh) || len(categories[low.id]) != 0 { t.Fatalf("organization projection = %v, want only the current intern category of the confirmed candidate", categories) diff --git a/backend/integration_test/assessment_category_read_http_test.go b/backend/integration_test/assessment_category_read_http_test.go new file mode 100644 index 0000000..45c17b0 --- /dev/null +++ b/backend/integration_test/assessment_category_read_http_test.go @@ -0,0 +1,166 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" + profileusecase "lincodex/backend/internal/usecase/profile" +) + +// TestConfirmedCategoryReadsOverHTTP checks the two candidate reads that show +// the confirmed category, with its basis: the availability and the profile. A +// candidate without a category gets null and an empty list. A higher passing +// result replaces the category, and a lower passing result leaves it as it is. +func TestConfirmedCategoryReadsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), 2*assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, &isolatedEnv, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}, + func(parts assessmentHarnessParts) []v1.HandlerOption { + return []v1.HandlerOption{v1.WithProfile(v1.NewProfileHandler(profileusecase.NewService(parts.transactor, parts.clock.Now)))} + }) + bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV2(), true) + threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark)) + client := &categoryHTTPClient{harness: harness, ctx: ctx} + + none := client.candidate(t, "category-read-none@example.test") + failed := client.candidate(t, "category-read-failed@example.test") + held := client.candidate(t, "category-read-held@example.test") + + t.Run("a candidate without any result sees no confirmed category in either read", func(t *testing.T) { + assertAvailabilityConfirmation(t, client, none, "backend", nil, nil) + assertProfileConfirmedCategoriesEmpty(t, client, none) + }) + + t.Run("a candidate whose attempt confirmed nothing still sees no category", func(t *testing.T) { + run := client.run(t, failed, "backend", "intern", func(int) int { return threshold - 1 }) + if run.result["outcome"] != "not_confirmed" { + t.Fatalf("failing run outcome = %v, want not_confirmed", run.result["outcome"]) + } + assertAvailabilityConfirmation(t, client, failed, "backend", nil, nil) + assertProfileConfirmedCategoriesEmpty(t, client, failed) + }) + + var intern, junior attemptRun + t.Run("an assigned category is shown with its basis and attempt in both reads", func(t *testing.T) { + intern = client.run(t, held, "backend", "intern", func(int) int { return threshold }) + assertAvailabilityConfirmation(t, client, held, "backend", "intern", "synthetic_demo") + assertAvailabilityConfirmation(t, client, held, "frontend", nil, nil) + assertProfileBackendCategory(t, client, held, "intern", "synthetic_demo", intern) + }) + + t.Run("a higher passing result replaces the category and a lower one never lowers it", func(t *testing.T) { + // The promotion interval counts on database time, so the finished intern + // attempt is moved past it instead of waiting for days. + moveFinishedAttemptBack(t, ctx, harness.pool, intern.id, categoryHTTPPromotionGap) + junior = client.run(t, held, "backend", "junior", func(int) int { return threshold }) + if decision := decisionOf(t, junior.result); decision["status"] != "assigned" { + t.Fatalf("junior decision = %v, want assigned", decision) + } + assertAvailabilityConfirmation(t, client, held, "backend", "junior", "synthetic_demo") + assertProfileBackendCategory(t, client, held, "junior", "synthetic_demo", junior) + + lower := client.run(t, held, "backend", "intern", func(int) int { return threshold }) + if decision := decisionOf(t, lower.result); decision["status"] != "unchanged" || decision["current_confirmed_grade"] != "junior" { + t.Fatalf("lower passing decision = %v, want unchanged at junior", decision) + } + assertAvailabilityConfirmation(t, client, held, "backend", "junior", "synthetic_demo") + assertProfileBackendCategory(t, client, held, "junior", "synthetic_demo", junior) + }) +} + +// assertAvailabilityConfirmation checks the confirmed grade and basis of one +// specialization in the availability read. A nil argument stands for JSON null. +func assertAvailabilityConfirmation(t *testing.T, client *categoryHTTPClient, who categoryHTTPCandidate, specialization string, grade, basis any) { + t.Helper() + status, body := client.call(t, who, http.MethodGet, "/api/v1/me/assessment-availability", "", "") + if status != http.StatusOK { + t.Fatalf("read availability = %d %s", status, body) + } + var read struct { + Specializations []map[string]any `json:"specializations"` + } + if err := json.Unmarshal(body, &read); err != nil { + t.Fatalf("decode availability: %v", err) + } + for _, item := range read.Specializations { + if item["specialization"] != specialization { + continue + } + if item["confirmed_grade"] != grade || item["confirmed_basis"] != basis { + t.Fatalf("availability %s = grade %v basis %v, want grade %v basis %v", specialization, item["confirmed_grade"], item["confirmed_basis"], grade, basis) + } + return + } + t.Fatalf("availability lists no %s specialization: %s", specialization, body) +} + +func readProfileBody(t *testing.T, client *categoryHTTPClient, who categoryHTTPCandidate) []byte { + t.Helper() + status, body := client.call(t, who, http.MethodGet, "/api/v1/me/profile", "", "") + if status != http.StatusOK { + t.Fatalf("read profile = %d %s", status, body) + } + return body +} + +func assertProfileConfirmedCategoriesEmpty(t *testing.T, client *categoryHTTPClient, who categoryHTTPCandidate) { + t.Helper() + if body := readProfileBody(t, client, who); !strings.Contains(string(body), `"confirmed_categories":[]`) { + t.Fatalf("profile = %s, want an empty confirmed_categories list", body) + } +} + +// assertProfileBackendCategory checks that the profile holds exactly one +// confirmed category, the backend one, with its grade, basis, and the attempt +// whose result assigned it. The assignment time is the decision time of that +// result. +func assertProfileBackendCategory(t *testing.T, client *categoryHTTPClient, who categoryHTTPCandidate, grade, basis string, attempt attemptRun) { + t.Helper() + var profile struct { + ConfirmedCategories []map[string]any `json:"confirmed_categories"` + } + if err := json.Unmarshal(readProfileBody(t, client, who), &profile); err != nil { + t.Fatalf("decode profile: %v", err) + } + if len(profile.ConfirmedCategories) != 1 { + t.Fatalf("confirmed_categories = %v, want exactly the backend category", profile.ConfirmedCategories) + } + category := profile.ConfirmedCategories[0] + if len(category) != 5 { + t.Fatalf("confirmed category has %d properties, want exactly specialization, grade, basis, confirmed_at, attempt_id: %v", len(category), category) + } + if category["specialization"] != "backend" || category["grade"] != grade || category["basis"] != basis || + category["attempt_id"] != attempt.id.String() { + t.Fatalf("confirmed category = %v, want backend %s with basis %s from attempt %s", category, grade, basis, attempt.id) + } + confirmedAt, ok := category["confirmed_at"].(string) + if !ok { + t.Fatalf("confirmed_at = %v, want a timestamp", category["confirmed_at"]) + } + assignedAt, err := time.Parse(time.RFC3339Nano, confirmedAt) + if err != nil { + t.Fatalf("parse confirmed_at %q: %v", confirmedAt, err) + } + decidedAt, err := time.Parse(time.RFC3339Nano, attempt.result["decided_at"].(string)) + if err != nil { + t.Fatalf("parse decided_at: %v", err) + } + if !assignedAt.Equal(decidedAt) { + t.Fatalf("confirmed_at = %s, want the decision time %s of the attempt", assignedAt, decidedAt) + } +} diff --git a/backend/integration_test/match_search_http_test.go b/backend/integration_test/match_search_http_test.go index f3b7346..60a0799 100644 --- a/backend/integration_test/match_search_http_test.go +++ b/backend/integration_test/match_search_http_test.go @@ -130,6 +130,7 @@ type matchEntryBody struct { Category *struct { Specialization string `json:"specialization"` Grade string `json:"grade"` + Basis string `json:"basis"` } `json:"category"` Strength *string `json:"strength"` PublicContext struct { @@ -545,6 +546,13 @@ func TestMatchSearchOverHTTP(t *testing.T) { t.Fatalf("organization A confirmed bank = %d main, %d near, %d unconfirmed; want exactly the eleven visible confirmed candidates", len(bankA.Groups.Main), len(bankA.Groups.Near), len(bankA.Groups.Unconfirmed)) } + // Every confirmed category names its basis, so a demonstration grade is + // never presented as a standard confirmation. + for _, entry := range bankA.Groups.Main { + if entry.Category == nil || entry.Category.Basis != "synthetic_demo" { + t.Fatalf("confirmed entry %s category = %+v, want the synthetic_demo basis", entry.CandidateHandle, entry.Category) + } + } if slices.Contains(handlesOf(bankA.Groups.Main), aliasIn(orgA.ID(), hiddenFromA.id)) { t.Fatal("organization A received a candidate that hides it") } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index 68ca674..d751cc6 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -10300,6 +10300,10 @@ func (s *AssessmentSpecializationAvailability) encodeFields(e *jx.Encoder) { e.FieldStart("confirmed_grade") s.ConfirmedGrade.Encode(e) } + { + e.FieldStart("confirmed_basis") + s.ConfirmedBasis.Encode(e) + } { e.FieldStart("active_attempt_id") s.ActiveAttemptID.Encode(e) @@ -10314,11 +10318,12 @@ func (s *AssessmentSpecializationAvailability) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAssessmentSpecializationAvailability = [4]string{ +var jsonFieldsNameOfAssessmentSpecializationAvailability = [5]string{ 0: "specialization", 1: "confirmed_grade", - 2: "active_attempt_id", - 3: "grades", + 2: "confirmed_basis", + 3: "active_attempt_id", + 4: "grades", } // Decode decodes AssessmentSpecializationAvailability from json. @@ -10350,8 +10355,18 @@ func (s *AssessmentSpecializationAvailability) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"confirmed_grade\"") } - case "active_attempt_id": + case "confirmed_basis": requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.ConfirmedBasis.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmed_basis\"") + } + case "active_attempt_id": + requiredBitSet[0] |= 1 << 3 if err := func() error { if err := s.ActiveAttemptID.Decode(d); err != nil { return err @@ -10361,7 +10376,7 @@ func (s *AssessmentSpecializationAvailability) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"active_attempt_id\"") } case "grades": - requiredBitSet[0] |= 1 << 3 + requiredBitSet[0] |= 1 << 4 if err := func() error { s.Grades = make([]AssessmentGradeAvailability, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -10388,7 +10403,7 @@ func (s *AssessmentSpecializationAvailability) Decode(d *jx.Decoder) error { // Validate required fields. var failures []validate.FieldError for i, mask := range [1]uint8{ - 0b00001111, + 0b00011111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -13612,12 +13627,17 @@ func (s *CardCategory) encodeFields(e *jx.Encoder) { e.FieldStart("strength") s.Strength.Encode(e) } + { + e.FieldStart("basis") + s.Basis.Encode(e) + } } -var jsonFieldsNameOfCardCategory = [3]string{ +var jsonFieldsNameOfCardCategory = [4]string{ 0: "specialization", 1: "grade", 2: "strength", + 3: "basis", } // Decode decodes CardCategory from json. @@ -13659,6 +13679,16 @@ func (s *CardCategory) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"strength\"") } + case "basis": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Basis.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"basis\"") + } default: return errors.Errorf("unexpected field %q", k) } @@ -13669,7 +13699,7 @@ func (s *CardCategory) Decode(d *jx.Decoder) error { // Validate required fields. var failures []validate.FieldError for i, mask := range [1]uint8{ - 0b00000111, + 0b00001111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -29198,11 +29228,16 @@ func (s *MatchCategory) encodeFields(e *jx.Encoder) { e.FieldStart("grade") s.Grade.Encode(e) } + { + e.FieldStart("basis") + s.Basis.Encode(e) + } } -var jsonFieldsNameOfMatchCategory = [2]string{ +var jsonFieldsNameOfMatchCategory = [3]string{ 0: "specialization", 1: "grade", + 2: "basis", } // Decode decodes MatchCategory from json. @@ -29234,6 +29269,16 @@ func (s *MatchCategory) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"grade\"") } + case "basis": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Basis.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"basis\"") + } default: return errors.Errorf("unexpected field %q", k) } @@ -29244,7 +29289,7 @@ func (s *MatchCategory) Decode(d *jx.Decoder) error { // Validate required fields. var failures []validate.FieldError for i, mask := range [1]uint8{ - 0b00000011, + 0b00000111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -39018,6 +39063,50 @@ func (s *NilEmailAddress) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes EvidenceBasis as json. +func (o NilEvidenceBasis) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes EvidenceBasis from json. +func (o *NilEvidenceBasis) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilEvidenceBasis to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v EvidenceBasis + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilEvidenceBasis) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilEvidenceBasis) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes float64 as json. func (o NilFloat64) Encode(e *jx.Encoder) { if o.Null { @@ -49486,6 +49575,10 @@ func (s *ProfileConfirmedCategory) encodeFields(e *jx.Encoder) { e.FieldStart("grade") s.Grade.Encode(e) } + { + e.FieldStart("basis") + s.Basis.Encode(e) + } { e.FieldStart("confirmed_at") s.ConfirmedAt.Encode(e) @@ -49496,11 +49589,12 @@ func (s *ProfileConfirmedCategory) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfProfileConfirmedCategory = [4]string{ +var jsonFieldsNameOfProfileConfirmedCategory = [5]string{ 0: "specialization", 1: "grade", - 2: "confirmed_at", - 3: "attempt_id", + 2: "basis", + 3: "confirmed_at", + 4: "attempt_id", } // Decode decodes ProfileConfirmedCategory from json. @@ -49532,8 +49626,18 @@ func (s *ProfileConfirmedCategory) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"grade\"") } - case "confirmed_at": + case "basis": requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Basis.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"basis\"") + } + case "confirmed_at": + requiredBitSet[0] |= 1 << 3 if err := func() error { if err := s.ConfirmedAt.Decode(d); err != nil { return err @@ -49543,7 +49647,7 @@ func (s *ProfileConfirmedCategory) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"confirmed_at\"") } case "attempt_id": - requiredBitSet[0] |= 1 << 3 + requiredBitSet[0] |= 1 << 4 if err := func() error { v, err := json.DecodeUUID(d) s.AttemptID = v @@ -49564,7 +49668,7 @@ func (s *ProfileConfirmedCategory) Decode(d *jx.Decoder) error { // Validate required fields. var failures []validate.FieldError for i, mask := range [1]uint8{ - 0b00001111, + 0b00011111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index ba86802..847e415 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -5395,6 +5395,10 @@ type AssessmentSpecializationAvailability struct { Specialization SpecializationCode `json:"specialization"` // Currently confirmed grade of the specialization, or null. ConfirmedGrade NilGradeCode `json:"confirmed_grade"` + // What the confirmed grade rests on, or null exactly when `confirmed_grade` is null. `synthetic_demo` + // marks a demonstration category, which is not a validated measurement and must not be shown as a real + // confirmation. + ConfirmedBasis NilEvidenceBasis `json:"confirmed_basis"` // Identifier of the active attempt of the specialization, or null. ActiveAttemptID NilUUID `json:"active_attempt_id"` // Every grade of the scale in ascending order. @@ -5411,6 +5415,11 @@ func (s *AssessmentSpecializationAvailability) GetConfirmedGrade() NilGradeCode return s.ConfirmedGrade } +// GetConfirmedBasis returns the value of ConfirmedBasis. +func (s *AssessmentSpecializationAvailability) GetConfirmedBasis() NilEvidenceBasis { + return s.ConfirmedBasis +} + // GetActiveAttemptID returns the value of ActiveAttemptID. func (s *AssessmentSpecializationAvailability) GetActiveAttemptID() NilUUID { return s.ActiveAttemptID @@ -5431,6 +5440,11 @@ func (s *AssessmentSpecializationAvailability) SetConfirmedGrade(val NilGradeCod s.ConfirmedGrade = val } +// SetConfirmedBasis sets the value of ConfirmedBasis. +func (s *AssessmentSpecializationAvailability) SetConfirmedBasis(val NilEvidenceBasis) { + s.ConfirmedBasis = val +} + // SetActiveAttemptID sets the value of ActiveAttemptID. func (s *AssessmentSpecializationAvailability) SetActiveAttemptID(val NilUUID) { s.ActiveAttemptID = val @@ -7030,13 +7044,15 @@ func (s *CardAccessListHeaders) SetResponse(val CardAccessList) { func (*CardAccessListHeaders) listMyCardAccessHistoryRes() {} -// A category confirmed by assessment results, as the card shows it. +// A category confirmed by assessment results, as the card shows it. `basis` says what the grade rests +// on; `synthetic_demo` marks a demonstration category, which is never a standard confirmation. // Ref: #/components/schemas/CardCategory type CardCategory struct { Specialization SpecializationCode `json:"specialization"` Grade GradeCode `json:"grade"` // Coarse strength of the authoritative confirmation. Strength CardCategoryStrength `json:"strength"` + Basis EvidenceBasis `json:"basis"` } // GetSpecialization returns the value of Specialization. @@ -7054,6 +7070,11 @@ func (s *CardCategory) GetStrength() CardCategoryStrength { return s.Strength } +// GetBasis returns the value of Basis. +func (s *CardCategory) GetBasis() EvidenceBasis { + return s.Basis +} + // SetSpecialization sets the value of Specialization. func (s *CardCategory) SetSpecialization(val SpecializationCode) { s.Specialization = val @@ -7069,6 +7090,11 @@ func (s *CardCategory) SetStrength(val CardCategoryStrength) { s.Strength = val } +// SetBasis sets the value of Basis. +func (s *CardCategory) SetBasis(val EvidenceBasis) { + s.Basis = val +} + // Coarse strength of the authoritative confirmation. type CardCategoryStrength string @@ -12918,10 +12944,13 @@ func (s *MatchAppliedFilters) SetConditions(val NilMatchAppliedConditions) { } // A confirmed category. Its specialization must equal the enclosing match entry's specialization. +// `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an +// organization must read as one and never as a standard confirmation. // Ref: #/components/schemas/MatchCategory type MatchCategory struct { Specialization SpecializationCode `json:"specialization"` Grade GradeCode `json:"grade"` + Basis EvidenceBasis `json:"basis"` } // GetSpecialization returns the value of Specialization. @@ -12934,6 +12963,11 @@ func (s *MatchCategory) GetGrade() GradeCode { return s.Grade } +// GetBasis returns the value of Basis. +func (s *MatchCategory) GetBasis() EvidenceBasis { + return s.Basis +} + // SetSpecialization sets the value of Specialization. func (s *MatchCategory) SetSpecialization(val SpecializationCode) { s.Specialization = val @@ -12944,6 +12978,11 @@ func (s *MatchCategory) SetGrade(val GradeCode) { s.Grade = val } +// SetBasis sets the value of Basis. +func (s *MatchCategory) SetBasis(val EvidenceBasis) { + s.Basis = val +} + // Confirmation state for this specialization only. A result for one specialization never changes the // state of another specialization. // Ref: #/components/schemas/MatchConfirmationStatus @@ -18060,6 +18099,51 @@ func (o NilEmailAddress) Or(d EmailAddress) EmailAddress { return d } +// NewNilEvidenceBasis returns new NilEvidenceBasis with value set to v. +func NewNilEvidenceBasis(v EvidenceBasis) NilEvidenceBasis { + return NilEvidenceBasis{ + Value: v, + } +} + +// NilEvidenceBasis is nullable EvidenceBasis. +type NilEvidenceBasis struct { + Value EvidenceBasis + Null bool +} + +// SetTo sets value to v. +func (o *NilEvidenceBasis) SetTo(v EvidenceBasis) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilEvidenceBasis) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilEvidenceBasis) SetToNull() { + o.Null = true + var v EvidenceBasis + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilEvidenceBasis) Get() (v EvidenceBasis, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilEvidenceBasis) Or(d EvidenceBasis) EvidenceBasis { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilFloat64 returns new NilFloat64 with value set to v. func NewNilFloat64(v float64) NilFloat64 { return NilFloat64{ @@ -26050,11 +26134,13 @@ type ProfileClaimTrustLevel int32 // read-only and derived by the server from the assessment results of the candidate; no request carries // it and the profile storage holds no such column, so neither a form nor an import can write a // confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in -// `roles`. +// `roles`. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category that +// is not a validated measurement. // Ref: #/components/schemas/ProfileConfirmedCategory type ProfileConfirmedCategory struct { Specialization SpecializationCode `json:"specialization"` Grade GradeCode `json:"grade"` + Basis EvidenceBasis `json:"basis"` ConfirmedAt Timestamp `json:"confirmed_at"` // Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate. AttemptID uuid.UUID `json:"attempt_id"` @@ -26070,6 +26156,11 @@ func (s *ProfileConfirmedCategory) GetGrade() GradeCode { return s.Grade } +// GetBasis returns the value of Basis. +func (s *ProfileConfirmedCategory) GetBasis() EvidenceBasis { + return s.Basis +} + // GetConfirmedAt returns the value of ConfirmedAt. func (s *ProfileConfirmedCategory) GetConfirmedAt() Timestamp { return s.ConfirmedAt @@ -26090,6 +26181,11 @@ func (s *ProfileConfirmedCategory) SetGrade(val GradeCode) { s.Grade = val } +// SetBasis sets the value of Basis. +func (s *ProfileConfirmedCategory) SetBasis(val EvidenceBasis) { + s.Basis = val +} + // SetConfirmedAt sets the value of ConfirmedAt. func (s *ProfileConfirmedCategory) SetConfirmedAt(val Timestamp) { s.ConfirmedAt = val diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index 99b8a04..fa5d156 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -4477,6 +4477,24 @@ func (s *AssessmentSpecializationAvailability) Validate() error { Error: err, }) } + if err := func() error { + if value, ok := s.ConfirmedBasis.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "confirmed_basis", + Error: err, + }) + } if err := func() error { if s.Grades == nil { return errors.New("nil is invalid value") @@ -6388,6 +6406,17 @@ func (s *CardCategory) Validate() error { Error: err, }) } + if err := func() error { + if err := s.Basis.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "basis", + Error: err, + }) + } if len(failures) > 0 { return &validate.Error{Fields: failures} } @@ -12044,6 +12073,17 @@ func (s *MatchCategory) Validate() error { Error: err, }) } + if err := func() error { + if err := s.Basis.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "basis", + Error: err, + }) + } if len(failures) > 0 { return &validate.Error{Fields: failures} } @@ -19717,6 +19757,17 @@ func (s *ProfileConfirmedCategory) Validate() error { Error: err, }) } + if err := func() error { + if err := s.Basis.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "basis", + Error: err, + }) + } if len(failures) > 0 { return &validate.Error{Fields: failures} } diff --git a/backend/internal/adapter/primary/http/v1/assessment_availability.go b/backend/internal/adapter/primary/http/v1/assessment_availability.go index ca39050..58b82a8 100644 --- a/backend/internal/adapter/primary/http/v1/assessment_availability.go +++ b/backend/internal/adapter/primary/http/v1/assessment_availability.go @@ -49,11 +49,19 @@ func assessmentAvailabilityResponse( Grades: make([]api.AssessmentGradeAvailability, 0, len(item.Grades)), } specialization.ConfirmedGrade.SetToNull() + specialization.ConfirmedBasis.SetToNull() + if (item.ConfirmedGrade == nil) != (item.ConfirmedBasis == nil) { + return api.AssessmentAvailability{}, errors.New("assessment availability pairs a confirmed grade with its basis inconsistently") + } if item.ConfirmedGrade != nil { if !item.ConfirmedGrade.IsKnown() { return api.AssessmentAvailability{}, errors.New("assessment availability has an unknown confirmed grade") } + if !item.ConfirmedBasis.IsKnown() { + return api.AssessmentAvailability{}, errors.New("assessment availability has an unknown confirmed basis") + } specialization.ConfirmedGrade.SetTo(api.GradeCode(*item.ConfirmedGrade)) + specialization.ConfirmedBasis.SetTo(api.EvidenceBasis(*item.ConfirmedBasis)) } specialization.ActiveAttemptID.SetToNull() if item.ActiveAttemptID != nil { diff --git a/backend/internal/adapter/primary/http/v1/assessment_availability_test.go b/backend/internal/adapter/primary/http/v1/assessment_availability_test.go index 80226f9..0ff3686 100644 --- a/backend/internal/adapter/primary/http/v1/assessment_availability_test.go +++ b/backend/internal/adapter/primary/http/v1/assessment_availability_test.go @@ -97,3 +97,46 @@ func TestGetMyAssessmentAvailabilityMapsAuthAndUnavailableMode(t *testing.T) { } func noPrincipalContext() context.Context { return context.Background() } + +// A confirmed grade is never returned without the basis that says whether it +// is a demonstration, and a basis never arrives without its grade. +func TestAssessmentAvailabilityResponseCarriesTheBasisOfTheConfirmedGrade(t *testing.T) { + basis := domain.AssessmentCategorySourceSyntheticDemo + grade := domain.GradeJunior + confirmed, err := assessmentAvailabilityResponse(assessmentusecase.AssessmentAvailability{ + Specializations: []assessmentusecase.SpecializationAvailability{{ + Specialization: domain.SpecializationBackend, ConfirmedGrade: &grade, ConfirmedBasis: &basis, + }}, + }) + if err != nil { + t.Fatalf("assessmentAvailabilityResponse(confirmed) error = %v", err) + } + item := confirmed.Specializations[0] + if grade, found := item.ConfirmedGrade.Get(); !found || grade != api.GradeCodeJunior { + t.Fatalf("confirmed_grade = %+v, want junior", item.ConfirmedGrade) + } + if got, found := item.ConfirmedBasis.Get(); !found || got != api.EvidenceBasisSyntheticDemo { + t.Fatalf("confirmed_basis = %+v, want synthetic_demo", item.ConfirmedBasis) + } + + unconfirmed, err := assessmentAvailabilityResponse(assessmentusecase.AssessmentAvailability{ + Specializations: []assessmentusecase.SpecializationAvailability{{Specialization: domain.SpecializationBackend}}, + }) + if err != nil { + t.Fatalf("assessmentAvailabilityResponse(unconfirmed) error = %v", err) + } + if !unconfirmed.Specializations[0].ConfirmedGrade.IsNull() || !unconfirmed.Specializations[0].ConfirmedBasis.IsNull() { + t.Fatalf("unconfirmed specialization = %+v, want null grade and basis", unconfirmed.Specializations[0]) + } + + for _, orphan := range []assessmentusecase.SpecializationAvailability{ + {Specialization: domain.SpecializationBackend, ConfirmedGrade: &grade}, + {Specialization: domain.SpecializationBackend, ConfirmedBasis: &basis}, + } { + if _, err := assessmentAvailabilityResponse(assessmentusecase.AssessmentAvailability{ + Specializations: []assessmentusecase.SpecializationAvailability{orphan}, + }); err == nil { + t.Fatalf("assessmentAvailabilityResponse(%+v) error = nil, want an inconsistent pair to fail", orphan) + } + } +} diff --git a/backend/internal/adapter/primary/http/v1/matches.go b/backend/internal/adapter/primary/http/v1/matches.go index d0a370d..5d088b0 100644 --- a/backend/internal/adapter/primary/http/v1/matches.go +++ b/backend/internal/adapter/primary/http/v1/matches.go @@ -225,6 +225,7 @@ func matchConfirmedCandidate(entry matching.Entry) api.MatchConfirmedCandidate { if entry.Category != nil { candidate.Category = api.MatchCategory{ Specialization: api.SpecializationCode(entry.Category.Specialization), Grade: api.GradeCode(entry.Category.Grade), + Basis: api.EvidenceBasis(entry.Category.Basis), } candidate.Strength = api.MatchStrength(entry.Category.Strength) } diff --git a/backend/internal/adapter/primary/http/v1/matches_test.go b/backend/internal/adapter/primary/http/v1/matches_test.go index 3cc5fed..5b745ab 100644 --- a/backend/internal/adapter/primary/http/v1/matches_test.go +++ b/backend/internal/adapter/primary/http/v1/matches_test.go @@ -128,7 +128,10 @@ func TestSearchOrganizationMatchesMapsAConfirmedEntryWithANullPercentile(t *test handle := "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" stub := &matchOperationsStub{result: matching.Result{Main: []matching.Entry{{ CandidateHandle: handle, Specialization: domain.SpecializationBackend, - Category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, Strength: domain.CandidateViewStrengthStrong}, + Category: &domain.CandidateViewCategory{ + Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, Strength: domain.CandidateViewStrengthStrong, + Basis: domain.AssessmentCategorySourceSyntheticDemo, + }, Components: matching.Components{ Fit: 0.5, Coverage: 0.5, Domain: 0.5, Semantics: 0.5, Freshness: 0.5, Responsiveness: 0.5, RankScore: 0.45125, }, @@ -147,7 +150,8 @@ func TestSearchOrganizationMatchesMapsAConfirmedEntryWithANullPercentile(t *test t.Fatalf("encode response: %v", err) } for _, want := range []string{ - `"confirmation_status":"confirmed"`, `"declared_grade":null`, `"category":{"specialization":"backend","grade":"middle"}`, `"strength":"strong"`, + `"confirmation_status":"confirmed"`, `"declared_grade":null`, + `"category":{"specialization":"backend","grade":"middle","basis":"synthetic_demo"}`, `"strength":"strong"`, `"percentile":null`, `"competition":0`, `"rank_score":0.45125`, } { if !strings.Contains(string(encoded), want) { diff --git a/backend/internal/adapter/primary/http/v1/privacy.go b/backend/internal/adapter/primary/http/v1/privacy.go index affd2bc..929c07b 100644 --- a/backend/internal/adapter/primary/http/v1/privacy.go +++ b/backend/internal/adapter/primary/http/v1/privacy.go @@ -535,7 +535,7 @@ func anonymousCardResponse(view domain.AnonymousCandidateViewDTO) api.AnonymousC for _, category := range view.Categories { content.Categories = append(content.Categories, api.CardCategory{ Specialization: api.SpecializationCode(category.Specialization), Grade: api.GradeCode(category.Grade), - Strength: api.CardCategoryStrength(category.Strength), + Strength: api.CardCategoryStrength(category.Strength), Basis: api.EvidenceBasis(category.Basis), }) } for _, skill := range view.Skills { diff --git a/backend/internal/adapter/primary/http/v1/privacy_test.go b/backend/internal/adapter/primary/http/v1/privacy_test.go index 2ee5130..dfe39fb 100644 --- a/backend/internal/adapter/primary/http/v1/privacy_test.go +++ b/backend/internal/adapter/primary/http/v1/privacy_test.go @@ -23,6 +23,7 @@ func TestPrivacyGetOrganizationCandidateCardMapsClosedProjection(t *testing.T) { Pseudonym: "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Categories: []domain.CandidateViewCategory{{ Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStrong, + Basis: domain.AssessmentCategorySourceSyntheticDemo, }}, Skills: []domain.CandidateViewSkillCode{"go"}, SelfAssessment: []domain.CandidateViewSelfAssessment{{ @@ -45,6 +46,7 @@ func TestPrivacyGetOrganizationCandidateCardMapsClosedProjection(t *testing.T) { } if body.CacheControl != api.CacheControlNoStoreNoStore || body.Response.Pseudonym != view.Pseudonym || len(body.Response.Categories) != 1 || body.Response.Categories[0].Strength != api.CardCategoryStrengthStrong || + body.Response.Categories[0].Basis != api.EvidenceBasisSyntheticDemo || len(body.Response.Stack) != 1 || body.Response.Stack[0] != "go" || len(body.Response.SelfAssessment) != 1 || body.Response.SelfAssessment[0].ConfirmationStatus != api.CardSelfAssessmentConfirmationStatusUnconfirmed { t.Fatalf("anonymous content mapping = %+v", body) diff --git a/backend/internal/adapter/primary/http/v1/profile.go b/backend/internal/adapter/primary/http/v1/profile.go index 1633f0b..6faab34 100644 --- a/backend/internal/adapter/primary/http/v1/profile.go +++ b/backend/internal/adapter/primary/http/v1/profile.go @@ -16,8 +16,8 @@ import ( // ProfileOperations reads and version-saves the authenticated candidate's // private manual profile. type ProfileOperations interface { - GetMyProfile(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error) - SaveMyProfile(ctx context.Context, userID uuid.UUID, expectedVersion int64, input domain.CandidateProfileInput) (domain.CandidateProfile, error) + GetMyProfile(ctx context.Context, userID uuid.UUID) (profile.View, error) + SaveMyProfile(ctx context.Context, userID uuid.UUID, expectedVersion int64, input domain.CandidateProfileInput) (profile.View, error) } // ProfileHandler serves the candidate's own profile operations. @@ -51,13 +51,13 @@ func (handler *ProfileHandler) GetMyProfile(ctx context.Context) (api.GetMyProfi if !ok { return (*api.GetMyProfileUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil } - profile, err := handler.operations.GetMyProfile(ctx, principal.UserID) + view, err := handler.operations.GetMyProfile(ctx, principal.UserID) if err != nil { return profileReadFailure(ctx, err) } return &api.CandidateProfileHeaders{ CacheControl: api.CacheControlNoStoreNoStore, - Response: candidateProfileResponse(profile), + Response: candidateProfileResponse(view), }, nil } @@ -69,13 +69,13 @@ func (handler *ProfileHandler) SaveMyProfile(ctx context.Context, request *api.C if request == nil { return (*api.SaveMyProfileBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil } - profile, err := handler.operations.SaveMyProfile(ctx, principal.UserID, int64(request.ExpectedVersion), candidateProfileInput(request)) + view, err := handler.operations.SaveMyProfile(ctx, principal.UserID, int64(request.ExpectedVersion), candidateProfileInput(request)) if err != nil { return profileSaveFailure(ctx, err) } return &api.CandidateProfileHeaders{ CacheControl: api.CacheControlNoStoreNoStore, - Response: candidateProfileResponse(profile), + Response: candidateProfileResponse(view), }, nil } @@ -194,16 +194,16 @@ func profileYearMonth(value api.NilProfileYearMonth) string { return string(month) } -func candidateProfileResponse(profile domain.CandidateProfile) api.CandidateProfile { - content := profile.Content() +func candidateProfileResponse(view profile.View) api.CandidateProfile { + saved := view.Profile + content := saved.Content() response := api.CandidateProfile{ - Version: api.ProfileVersion(profile.Version()), - ExperienceOverlaps: make([]api.ProfileExperienceOverlap, 0), - Stack: make([]api.ProfileStackItem, 0), - Roles: make([]api.ProfileRoleItem, 0), - Experience: make([]api.ProfileExperienceItem, 0), - SoftSkills: make([]api.ProfileSoftSkillItem, 0), - ConfirmedCategories: make([]api.ProfileConfirmedCategory, 0), + Version: api.ProfileVersion(saved.Version()), + ExperienceOverlaps: make([]api.ProfileExperienceOverlap, 0), + Stack: make([]api.ProfileStackItem, 0), + Roles: make([]api.ProfileRoleItem, 0), + Experience: make([]api.ProfileExperienceItem, 0), + SoftSkills: make([]api.ProfileSoftSkillItem, 0), } if name, ok := content.FullName(); ok { response.FullName = profileFullNameClaim(name) @@ -279,15 +279,39 @@ func candidateProfileResponse(profile domain.CandidateProfile) api.CandidateProf } response.Terms = candidateProfileTerms(content) updatedAt := api.NilTimestamp{} - if profile.UpdatedAt().IsZero() { + if saved.UpdatedAt().IsZero() { updatedAt.SetToNull() } else { - updatedAt.SetTo(api.Timestamp(profile.UpdatedAt())) + updatedAt.SetTo(api.Timestamp(saved.UpdatedAt())) } response.UpdatedAt = updatedAt + response.ConfirmedCategories = confirmedCategoriesResponse(view.ConfirmedCategories) return response } +// confirmedCategoriesResponse maps the categories in their stored order. The +// result is never nil, so a profile without categories encodes as an empty list. +func confirmedCategoriesResponse(categories []domain.CandidateAssessmentCategory) []api.ProfileConfirmedCategory { + response := make([]api.ProfileConfirmedCategory, 0, len(categories)) + for _, category := range categories { + response = append(response, confirmedCategoryResponse(category)) + } + return response +} + +// confirmedCategoryResponse maps a stored category, including its basis, so a +// demonstration grade is never returned as if an assessment had measured it. +func confirmedCategoryResponse(category domain.CandidateAssessmentCategory) api.ProfileConfirmedCategory { + snapshot := category.Snapshot() + return api.ProfileConfirmedCategory{ + Specialization: api.SpecializationCode(snapshot.Specialization), + Grade: api.GradeCode(snapshot.Grade), + Basis: api.EvidenceBasis(snapshot.Source), + ConfirmedAt: api.Timestamp(snapshot.AssignedAt), + AttemptID: snapshot.SourceAttemptID.UUID(), + } +} + func candidateProfileTerms(content domain.CandidateProfileContent) api.ProfileTerms { terms := api.ProfileTerms{} if location, ok := content.Location(); ok { diff --git a/backend/internal/adapter/primary/http/v1/profile_test.go b/backend/internal/adapter/primary/http/v1/profile_test.go new file mode 100644 index 0000000..91e1b5f --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/profile_test.go @@ -0,0 +1,48 @@ +package v1 + +import ( + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/profile" +) + +func TestCandidateProfileResponseCarriesConfirmedCategoriesWithTheirBasis(t *testing.T) { + userID := uuid.New() + saved, err := domain.EmptyCandidateProfile(userID) + if err != nil { + t.Fatalf("EmptyCandidateProfile() error = %v", err) + } + assignedAt := time.Date(2026, time.October, 8, 10, 30, 0, 0, time.UTC) + attemptID := uuid.New() + category, err := domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{ + CandidateID: userID, Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, + SourceAttemptID: domain.AssessmentAttemptID(attemptID), SourceReviewID: uuid.New(), + ProductPolicyVersionID: domain.PolicyVersionID(uuid.New()), ProductPolicyVersion: 1, + OpeningID: uuid.New(), OpeningManifestHash: [32]byte{1}, + Source: domain.AssessmentCategorySourceSyntheticDemo, CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, + AssignedAt: assignedAt, + }) + if err != nil { + t.Fatalf("RestoreCandidateAssessmentCategory() error = %v", err) + } + + response := candidateProfileResponse(profile.View{Profile: saved, ConfirmedCategories: []domain.CandidateAssessmentCategory{category}}) + if len(response.ConfirmedCategories) != 1 { + t.Fatalf("confirmed_categories = %+v, want one category", response.ConfirmedCategories) + } + got := response.ConfirmedCategories[0] + if got.Specialization != api.SpecializationCodeBackend || got.Grade != api.GradeCodeJunior || + got.Basis != api.EvidenceBasisSyntheticDemo || got.AttemptID != attemptID || time.Time(got.ConfirmedAt) != assignedAt { + t.Fatalf("confirmed category = %+v, want backend junior from attempt %s with basis synthetic_demo", got, attemptID) + } + + empty := candidateProfileResponse(profile.View{Profile: saved}) + if empty.ConfirmedCategories == nil || len(empty.ConfirmedCategories) != 0 { + t.Fatalf("confirmed_categories of an empty view = %#v, want an empty list", empty.ConfirmedCategories) + } +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_attempt_category.go b/backend/internal/adapter/secondary/postgres/assessment_attempt_category.go index ded234a..6c3e04e 100644 --- a/backend/internal/adapter/secondary/postgres/assessment_attempt_category.go +++ b/backend/internal/adapter/secondary/postgres/assessment_attempt_category.go @@ -339,6 +339,29 @@ func (repository assessmentAttemptRepository) GetCandidateCategory( return category, true, nil } +func (repository assessmentAttemptRepository) ListCandidateCategories( + ctx context.Context, + candidateID uuid.UUID, +) ([]domain.CandidateAssessmentCategory, error) { + const location = "assessmentAttemptRepository.ListCandidateCategories" + if candidateID == uuid.Nil { + return nil, fmt.Errorf("%s - candidate scope is invalid: %w", location, domain.ErrInvalidAssessmentCategory) + } + rows, err := repository.queries.ListCandidateAssessmentCategories(ctx, pgUUID(candidateID)) + if err != nil { + return nil, fmt.Errorf("%s - select current categories: %w", location, mapAssessmentAttemptError(err)) + } + categories := make([]domain.CandidateAssessmentCategory, 0, len(rows)) + for _, row := range rows { + category, err := restoreCandidateAssessmentCategory(row) + if err != nil { + return nil, fmt.Errorf("%s - stored category is invalid: %w", location, err) + } + categories = append(categories, category) + } + return categories, nil +} + func restoreCandidateAssessmentCategory(row sqlc.CandidateAssessmentCategory) (domain.CandidateAssessmentCategory, error) { manifestHash, err := assessmentManifestHash(row.OpeningManifestSha256) if err != nil || !row.CandidateID.Valid || !row.SourceAttemptID.Valid || !row.SourceReviewID.Valid || diff --git a/backend/internal/adapter/secondary/postgres/privacy_cohort.go b/backend/internal/adapter/secondary/postgres/privacy_cohort.go index 588d16c..f9cb98d 100644 --- a/backend/internal/adapter/secondary/postgres/privacy_cohort.go +++ b/backend/internal/adapter/secondary/postgres/privacy_cohort.go @@ -154,16 +154,18 @@ func newPrivacyCohortCandidate( const privacyCohortCategoryStrength = domain.CandidateViewStrengthStandard // privacyCohortConfirmedCategories reads the current categories selected by -// the cohort query: only a specialization and a grade of each, never the -// attempt, score, policy, or review that produced it. +// the cohort query: a specialization, a grade, and the basis of each, never the +// attempt, score, policy, or review that produced it. A category without a +// known basis is rejected rather than shown as a real confirmation. func privacyCohortConfirmedCategories(value any) ([]domain.CandidateViewConfirmedCategoryInput, error) { encoded, err := privacyCohortEncodedJSONBytes(value) if err != nil { return nil, fmt.Errorf("invalid confirmed categories: %w", domain.ErrInvalidCandidateViewSource) } var stored []struct { - Specialization domain.SpecializationCode `json:"specialization"` - Grade domain.GradeCode `json:"grade"` + Specialization domain.SpecializationCode `json:"specialization"` + Grade domain.GradeCode `json:"grade"` + Source domain.AssessmentCategorySource `json:"source"` } decoder := json.NewDecoder(bytes.NewReader(encoded)) decoder.DisallowUnknownFields() @@ -172,8 +174,12 @@ func privacyCohortConfirmedCategories(value any) ([]domain.CandidateViewConfirme } categories := make([]domain.CandidateViewConfirmedCategoryInput, 0, len(stored)) for _, category := range stored { + if !category.Source.IsKnown() { + return nil, fmt.Errorf("confirmed category has an unknown basis: %w", domain.ErrInvalidCandidateViewSource) + } categories = append(categories, domain.CandidateViewConfirmedCategoryInput{ - Specialization: category.Specialization, Grade: category.Grade, Strength: privacyCohortCategoryStrength, + Specialization: category.Specialization, Grade: category.Grade, + Strength: privacyCohortCategoryStrength, Basis: category.Source, }) } return categories, nil diff --git a/backend/internal/adapter/secondary/postgres/privacy_cohort_test.go b/backend/internal/adapter/secondary/postgres/privacy_cohort_test.go new file mode 100644 index 0000000..36f9e11 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/privacy_cohort_test.go @@ -0,0 +1,35 @@ +package postgres + +import ( + "errors" + "testing" + + "lincodex/backend/internal/domain" +) + +func TestPrivacyCohortConfirmedCategoriesCarryTheStoredBasis(t *testing.T) { + categories, err := privacyCohortConfirmedCategories(`[{"specialization":"backend","grade":"junior","source":"synthetic_demo"}]`) + if err != nil { + t.Fatalf("privacyCohortConfirmedCategories() error = %v", err) + } + if len(categories) != 1 || categories[0].Specialization != domain.SpecializationBackend || + categories[0].Grade != domain.GradeJunior || categories[0].Basis != domain.AssessmentCategorySourceSyntheticDemo { + t.Fatalf("categories = %+v, want the backend junior category with its synthetic basis", categories) + } +} + +// A category whose basis is missing or unknown must not reach a card as if it +// were a real confirmation, so the projection fails instead of guessing. +func TestPrivacyCohortConfirmedCategoriesRejectAnUnknownBasis(t *testing.T) { + for name, value := range map[string]string{ + "missing basis": `[{"specialization":"backend","grade":"junior"}]`, + "unknown basis": `[{"specialization":"backend","grade":"junior","source":"real"}]`, + "unknown property": `[{"specialization":"backend","grade":"junior","source":"synthetic_demo","score":9}]`, + } { + t.Run(name, func(t *testing.T) { + if _, err := privacyCohortConfirmedCategories(value); !errors.Is(err, domain.ErrInvalidCandidateViewSource) { + t.Fatalf("privacyCohortConfirmedCategories() error = %v, want invalid candidate view source", err) + } + }) + } +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_results.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_results.sql.go index 2c04a97..674dcd3 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/assessment_results.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_results.sql.go @@ -244,6 +244,49 @@ func (q *Queries) InsertSyntheticCategoryReview(ctx context.Context, arg InsertS return result.RowsAffected(), nil } +const listCandidateAssessmentCategories = `-- name: ListCandidateAssessmentCategories :many +SELECT candidate_id, specialization, grade, source_attempt_id, source_review_id, + product_policy_version_id, product_policy_version, grading_policy_version_id, + opening_id, opening_manifest_sha256, source, calibration_status, assigned_at +FROM candidate_assessment_categories +WHERE candidate_id = $1 +ORDER BY specialization +` + +func (q *Queries) ListCandidateAssessmentCategories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateAssessmentCategory, error) { + rows, err := q.db.Query(ctx, listCandidateAssessmentCategories, candidateID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []CandidateAssessmentCategory + for rows.Next() { + var i CandidateAssessmentCategory + if err := rows.Scan( + &i.CandidateID, + &i.Specialization, + &i.Grade, + &i.SourceAttemptID, + &i.SourceReviewID, + &i.ProductPolicyVersionID, + &i.ProductPolicyVersion, + &i.GradingPolicyVersionID, + &i.OpeningID, + &i.OpeningManifestSha256, + &i.Source, + &i.CalibrationStatus, + &i.AssignedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const listCandidateAssessmentResults = `-- name: ListCandidateAssessmentResults :many SELECT attempt_id, user_id, schema_version, result_snapshot::text, COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade, decided_at diff --git a/backend/internal/adapter/secondary/postgres/sqlc/privacy_cohort.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/privacy_cohort.sql.go index 8403ff8..7fd572e 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/privacy_cohort.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/privacy_cohort.sql.go @@ -57,7 +57,11 @@ SELECT COALESCE( ( SELECT jsonb_agg( - jsonb_build_object('specialization', category.specialization, 'grade', category.grade) + jsonb_build_object( + 'specialization', category.specialization, + 'grade', category.grade, + 'source', category.source + ) ORDER BY category.specialization )::text FROM candidate_assessment_categories AS category @@ -286,7 +290,11 @@ SELECT COALESCE( ( SELECT jsonb_agg( - jsonb_build_object('specialization', category.specialization, 'grade', category.grade) + jsonb_build_object( + 'specialization', category.specialization, + 'grade', category.grade, + 'source', category.source + ) ORDER BY category.specialization )::text FROM candidate_assessment_categories AS category diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 421578d..7e6e16f 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -656,6 +656,7 @@ type Querier interface { ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error) // Reads the exact family membership pinned by a training binding. ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error) + ListCandidateAssessmentCategories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateAssessmentCategory, error) // The caller validates and signs an opaque owner-bound cursor. This query // applies the keyset to the same stable order and fetches one extra row. ListCandidateAssessmentResults(ctx context.Context, arg ListCandidateAssessmentResultsParams) ([]ListCandidateAssessmentResultsRow, error) diff --git a/backend/internal/domain/assessment_category.go b/backend/internal/domain/assessment_category.go index e87167c..93e55e6 100644 --- a/backend/internal/domain/assessment_category.go +++ b/backend/internal/domain/assessment_category.go @@ -37,6 +37,11 @@ type AssessmentCategorySource string const AssessmentCategorySourceSyntheticDemo AssessmentCategorySource = "synthetic_demo" +// IsKnown reports whether source is a value that the category contract names. +func (source AssessmentCategorySource) IsKnown() bool { + return source == AssessmentCategorySourceSyntheticDemo +} + // AssessmentSyntheticCategoryReviewSnapshot pins the reviewed synthetic bank // opening to the exact product policy under which demo categories may be assigned. type AssessmentSyntheticCategoryReviewSnapshot struct { diff --git a/backend/internal/domain/candidate.go b/backend/internal/domain/candidate.go index e30a3b5..cbb8663 100644 --- a/backend/internal/domain/candidate.go +++ b/backend/internal/domain/candidate.go @@ -119,6 +119,10 @@ var specializationCodes = []SpecializationCode{ // IsKnown reports whether code is a specialization of the catalog. func (code SpecializationCode) IsKnown() bool { return slices.Contains(specializationCodes, code) } +// SpecializationCatalog returns the specializations in catalog order. The +// result is a copy that the caller may change. +func SpecializationCatalog() []SpecializationCode { return slices.Clone(specializationCodes) } + // GradeCode is a grade of the MVP scale. The same codes describe a // self-assessed grade, which the candidate states, and a confirmed grade, // which only an assessment result establishes; a profile stores only the diff --git a/backend/internal/domain/candidate_view.go b/backend/internal/domain/candidate_view.go index 1dde518..7be65c4 100644 --- a/backend/internal/domain/candidate_view.go +++ b/backend/internal/domain/candidate_view.go @@ -176,6 +176,9 @@ type CandidateViewConfirmedCategoryInput struct { Specialization SpecializationCode Grade GradeCode Strength CandidateViewConfirmationStrength + // Basis says what the grade rests on. It is required: a category without + // a basis would read as a real confirmation. + Basis AssessmentCategorySource } type candidateViewStackClaim struct { @@ -228,12 +231,15 @@ func CandidateViewProfileFromContent(content CandidateProfileContent) CandidateV return profile } -// CandidateViewCategory is the category and coarse strength shown only when -// categories were explicitly included in the publication. +// CandidateViewCategory is the category, its coarse strength, and its basis, +// shown only when categories were explicitly included in the publication. +// The field order matches CandidateViewConfirmedCategoryInput so that the two +// convert into each other. type CandidateViewCategory struct { Specialization SpecializationCode `json:"specialization"` Grade GradeCode `json:"grade"` Strength CandidateViewConfirmationStrength `json:"strength"` + Basis AssessmentCategorySource `json:"basis"` } // CandidateViewSelfAssessment is a candidate-declared specialization and @@ -381,7 +387,8 @@ func IsCandidateViewPseudonym(value string) bool { func validateCandidateViewConfirmations(confirmations []CandidateViewConfirmedCategoryInput) error { seen := make(map[SpecializationCode]struct{}, len(confirmations)) for _, confirmation := range confirmations { - if !confirmation.Specialization.IsKnown() || !confirmation.Grade.IsKnown() || !confirmation.Strength.IsKnown() { + if !confirmation.Specialization.IsKnown() || !confirmation.Grade.IsKnown() || !confirmation.Strength.IsKnown() || + !confirmation.Basis.IsKnown() { return ErrInvalidAnonymousCandidateView } if _, duplicate := seen[confirmation.Specialization]; duplicate { diff --git a/backend/internal/domain/candidate_view_test.go b/backend/internal/domain/candidate_view_test.go index 72a8cdf..b52ce71 100644 --- a/backend/internal/domain/candidate_view_test.go +++ b/backend/internal/domain/candidate_view_test.go @@ -144,6 +144,7 @@ func TestAnonymousCandidateViewUsesPublishedAllowlist(t *testing.T) { AsOf: time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC), ConfirmedCategories: []CandidateViewConfirmedCategoryInput{{ Specialization: SpecializationBackend, Grade: GradeMiddle, Strength: CandidateViewStrengthStrong, + Basis: AssessmentCategorySourceSyntheticDemo, }}, WorkFormats: []QuestionnaireWorkFormat{QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatHybrid}, }) @@ -250,6 +251,7 @@ func TestAnonymousCandidateViewKeepsCategoriesSeparateFromSelfAssessment(t *test } category := CandidateViewConfirmedCategoryInput{ Specialization: SpecializationBackend, Grade: GradeMiddle, Strength: CandidateViewStrengthStandard, + Basis: AssessmentCategorySourceSyntheticDemo, } newView := func(field CardField) AnonymousCandidateViewDTO { t.Helper() @@ -417,3 +419,24 @@ func containsCandidateViewSkill(skills []CandidateViewSkillCode, wanted Candidat } return false } + +// A category without a known basis would read as a real confirmation, so the +// anonymous view refuses it instead of defaulting the basis. +func TestAnonymousCandidateViewRequiresTheBasisOfEveryCategory(t *testing.T) { + fields, err := NewCardFieldSet([]CardField{CardFieldCategories}) + if err != nil { + t.Fatalf("NewCardFieldSet() error = %v", err) + } + for _, basis := range []AssessmentCategorySource{"", "real"} { + _, err := NewAnonymousCandidateView(CandidateViewInput{ + Pseudonym: candidateViewTestPseudonym(t, uuid.New(), uuid.New()), PublishedFields: fields, + AsOf: time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC), + ConfirmedCategories: []CandidateViewConfirmedCategoryInput{{ + Specialization: SpecializationBackend, Grade: GradeJunior, Strength: CandidateViewStrengthStandard, Basis: basis, + }}, + }) + if err == nil { + t.Fatalf("NewAnonymousCandidateView(basis %q) error = nil, want rejection", basis) + } + } +} diff --git a/backend/internal/port/outbound/assessment_attempt.go b/backend/internal/port/outbound/assessment_attempt.go index 555d342..6603dcb 100644 --- a/backend/internal/port/outbound/assessment_attempt.go +++ b/backend/internal/port/outbound/assessment_attempt.go @@ -273,6 +273,11 @@ type AssessmentAttemptRepository interface { specialization domain.SpecializationCode, ) (domain.CandidateAssessmentCategory, bool, error) + // ListCandidateCategories returns the current category of each + // specialization the candidate holds, ordered by specialization code. + // Callers that need catalog order sort the result themselves. It is a read. + ListCandidateCategories(ctx context.Context, candidateID uuid.UUID) ([]domain.CandidateAssessmentCategory, error) + // GetSyntheticCategoryReview requires the complete immutable opening and // product-policy pins; gradingPolicyID must match the opening's policy. GetSyntheticCategoryReview( diff --git a/backend/internal/usecase/assessment/availability.go b/backend/internal/usecase/assessment/availability.go index 9687c5a..00a888b 100644 --- a/backend/internal/usecase/assessment/availability.go +++ b/backend/internal/usecase/assessment/availability.go @@ -29,8 +29,12 @@ type AssessmentAvailability struct { } type SpecializationAvailability struct { - Specialization domain.SpecializationCode + Specialization domain.SpecializationCode + // ConfirmedGrade and ConfirmedBasis are set together from the current + // category of the specialization, or both are nil. The basis keeps a + // demonstration grade from reading as a real confirmation. ConfirmedGrade *domain.GradeCode + ConfirmedBasis *domain.AssessmentCategorySource ActiveAttemptID *domain.AssessmentAttemptID Grades []GradeAvailability } @@ -108,6 +112,7 @@ type assessmentAvailabilityReads struct { selections []outbound.AssessmentAvailabilitySelection active map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary rootHistory map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary + categories map[domain.SpecializationCode]domain.CandidateAssessmentCategory quota outbound.AssessmentRootQuotaSnapshot seen map[domain.AssessmentFamilyKey]struct{} } @@ -164,6 +169,14 @@ func readAssessmentAvailability( if err != nil { return assessmentAvailabilityReads{}, fmt.Errorf("%s - read active attempts: %w", location, err) } + categories, err := unit.AssessmentAttempts().ListCandidateCategories(ctx, userID) + if err != nil { + return assessmentAvailabilityReads{}, fmt.Errorf("%s - read confirmed categories: %w", location, err) + } + reads.categories = make(map[domain.SpecializationCode]domain.CandidateAssessmentCategory, len(categories)) + for _, category := range categories { + reads.categories[category.Snapshot().Specialization] = category + } window := policy.AttemptWindow.Duration() reads.quota, err = unit.AssessmentAttempts().GetRootQuotaSnapshot( ctx, userID, now.Add(-window), now, window, policy.MaxAttemptsPerWindow, @@ -245,6 +258,12 @@ func buildSpecializationAvailability( id := active.ID result.ActiveAttemptID = &id } + if category, confirmed := reads.categories[answer.Specialization]; confirmed { + snapshot := category.Snapshot() + grade, basis := snapshot.Grade, snapshot.Source + result.ConfirmedGrade = &grade + result.ConfirmedBasis = &basis + } for _, grade := range availabilityGrades { result.Grades = append(result.Grades, buildGradeAvailability( answer, grade, reads, policy, now, seconds, itemCount, hasActive, diff --git a/backend/internal/usecase/assessment/availability_test.go b/backend/internal/usecase/assessment/availability_test.go index 2901959..63350ef 100644 --- a/backend/internal/usecase/assessment/availability_test.go +++ b/backend/internal/usecase/assessment/availability_test.go @@ -4,6 +4,8 @@ import ( "testing" "time" + "github.com/google/uuid" + "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) @@ -98,3 +100,39 @@ func TestPlatformFailureDoesNotAddPromotionCooldown(t *testing.T) { }) } } + +// The confirmed grade of a specialization and its basis come from the same +// stored category, so a demonstration grade is never returned without its basis. +func TestAvailabilityCarriesTheConfirmedGradeWithItsBasis(t *testing.T) { + now := time.Date(2026, time.October, 9, 12, 0, 0, 0, time.UTC) + policy := domain.AssessmentPolicy{Attempt: &domain.AssessmentAttemptPolicy{RealMode: domain.AssessmentRealModeDemoBasic}} + category, err := domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{ + CandidateID: uuid.New(), Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, + SourceAttemptID: domain.AssessmentAttemptID(uuid.New()), SourceReviewID: uuid.New(), + ProductPolicyVersionID: domain.PolicyVersionID(uuid.New()), ProductPolicyVersion: 1, + OpeningID: uuid.New(), OpeningManifestHash: [32]byte{1}, + Source: domain.AssessmentCategorySourceSyntheticDemo, CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, + AssignedAt: now, + }) + if err != nil { + t.Fatalf("RestoreCandidateAssessmentCategory() error = %v", err) + } + reads := assessmentAvailabilityReads{categories: map[domain.SpecializationCode]domain.CandidateAssessmentCategory{ + domain.SpecializationBackend: category, + }} + + confirmed := buildSpecializationAvailability( + domain.QuestionnaireSpecialization{Specialization: domain.SpecializationBackend}, reads, policy, now, 60, 12) + if confirmed.ConfirmedGrade == nil || *confirmed.ConfirmedGrade != domain.GradeJunior { + t.Fatalf("ConfirmedGrade = %v, want junior", confirmed.ConfirmedGrade) + } + if confirmed.ConfirmedBasis == nil || *confirmed.ConfirmedBasis != domain.AssessmentCategorySourceSyntheticDemo { + t.Fatalf("ConfirmedBasis = %v, want synthetic_demo", confirmed.ConfirmedBasis) + } + + unconfirmed := buildSpecializationAvailability( + domain.QuestionnaireSpecialization{Specialization: domain.SpecializationFrontend}, reads, policy, now, 60, 12) + if unconfirmed.ConfirmedGrade != nil || unconfirmed.ConfirmedBasis != nil { + t.Fatalf("unconfirmed specialization reports grade %v and basis %v, want none", unconfirmed.ConfirmedGrade, unconfirmed.ConfirmedBasis) + } +} diff --git a/backend/internal/usecase/demoseed/seeder.go b/backend/internal/usecase/demoseed/seeder.go index c3143b7..bb95ae9 100644 --- a/backend/internal/usecase/demoseed/seeder.go +++ b/backend/internal/usecase/demoseed/seeder.go @@ -639,10 +639,10 @@ func (seeder *Seeder) ensureProfile(ctx context.Context, spec accountSpec, userI if err != nil { return false, fmt.Errorf("read profile: %w", err) } - if current.Version() > 0 { + if current.Profile.Version() > 0 { return false, nil } - if _, err := seeder.deps.Profiles.SaveMyProfile(ctx, userID, current.Version(), profileInput(spec)); err != nil { + if _, err := seeder.deps.Profiles.SaveMyProfile(ctx, userID, current.Profile.Version(), profileInput(spec)); err != nil { return false, fmt.Errorf("save profile: %w", err) } return true, nil diff --git a/backend/internal/usecase/profile/service.go b/backend/internal/usecase/profile/service.go index e9f34d2..13ec162 100644 --- a/backend/internal/usecase/profile/service.go +++ b/backend/internal/usecase/profile/service.go @@ -2,9 +2,11 @@ package profile import ( + "cmp" "context" "errors" "fmt" + "slices" "time" "github.com/google/uuid" @@ -21,6 +23,16 @@ var ( ErrEmailNotVerified = errors.New("candidate profile requires a confirmed email") ) +// View is the profile as the candidate reads it: the saved document and the +// categories that assessment results confirmed. The categories are derived by +// the server, are read-only, and are never part of the saved document. +type View struct { + Profile domain.CandidateProfile + // ConfirmedCategories holds at most one category per specialization, in + // catalog order. + ConfirmedCategories []domain.CandidateAssessmentCategory +} + // Service is stateless between calls. Profile data, its history, and onboarding // movement are written through one transaction. type Service struct { @@ -40,27 +52,28 @@ func NewService(transactor outbound.Transactor, clock func() time.Time) *Service return &Service{transactor: transactor, clock: clock} } -// GetMyProfile reads only the profile owned by userID. Version zero means the +// GetMyProfile reads only the profile owned by userID, with the categories +// that the candidate's assessment results confirmed. Version zero means the // candidate has not saved a profile yet. -func (service *Service) GetMyProfile(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error) { +func (service *Service) GetMyProfile(ctx context.Context, userID uuid.UUID) (View, error) { const location = "Service.GetMyProfile" if userID == uuid.Nil { - return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile) + return View{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile) } - var result domain.CandidateProfile + var result View err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := requireCandidate(ctx, unit, userID, location); err != nil { return err } - var err error - result, err = unit.CandidateProfiles().Get(ctx, userID) + profile, err := unit.CandidateProfiles().Get(ctx, userID) if err != nil { return fmt.Errorf("%s - read profile: %w", location, err) } - return nil + result, err = readView(ctx, unit, userID, profile, location) + return err }) if err != nil { - return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err) + return View{}, fmt.Errorf("%s - transaction: %w", location, err) } return result, nil } @@ -73,16 +86,16 @@ func (service *Service) SaveMyProfile( userID uuid.UUID, expectedVersion int64, input domain.CandidateProfileInput, -) (domain.CandidateProfile, error) { +) (View, error) { const location = "Service.SaveMyProfile" if userID == uuid.Nil { - return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile) + return View{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile) } at := service.clock().UTC() if at.IsZero() { - return domain.CandidateProfile{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateProfile) + return View{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateProfile) } - var result domain.CandidateProfile + var result View err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := requireCandidate(ctx, unit, userID, location); err != nil { return err @@ -105,18 +118,56 @@ func (service *Service) SaveMyProfile( if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil { return fmt.Errorf("%s - advance onboarding: %w", location, err) } - result = updated - return nil + result, err = readView(ctx, unit, userID, updated, location) + return err }) if err != nil { if errors.Is(err, outbound.ErrCandidateProfileVersionConflict) || errors.Is(err, domain.ErrCandidateProfileVersionConflict) { - return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateProfileVersionConflict) + return View{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateProfileVersionConflict) } - return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err) + return View{}, fmt.Errorf("%s - transaction: %w", location, err) } return result, nil } +// readView attaches the confirmed categories of the candidate to a profile +// that was read or written in the same transaction. +func readView( + ctx context.Context, + unit outbound.UnitOfWork, + userID uuid.UUID, + profile domain.CandidateProfile, + location string, +) (View, error) { + categories, err := unit.AssessmentAttempts().ListCandidateCategories(ctx, userID) + if err != nil { + return View{}, fmt.Errorf("%s - read confirmed categories: %w", location, err) + } + return View{Profile: profile, ConfirmedCategories: inCatalogOrder(categories)}, nil +} + +// inCatalogOrder sorts the categories by their place in the catalog. A +// category outside the catalog cannot exist (the storage constraint and the +// domain both reject it), so it sorts last instead of being dropped silently. +func inCatalogOrder(categories []domain.CandidateAssessmentCategory) []domain.CandidateAssessmentCategory { + position := make(map[domain.SpecializationCode]int, len(domain.SpecializationCatalog())) + for index, code := range domain.SpecializationCatalog() { + position[code] = index + } + sorted := slices.Clone(categories) + slices.SortStableFunc(sorted, func(left, right domain.CandidateAssessmentCategory) int { + return cmp.Compare(catalogPosition(position, left), catalogPosition(position, right)) + }) + return sorted +} + +func catalogPosition(position map[domain.SpecializationCode]int, category domain.CandidateAssessmentCategory) int { + if index, known := position[category.Snapshot().Specialization]; known { + return index + } + return len(position) +} + func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error { user, err := unit.Users().GetByID(ctx, userID) if err != nil { diff --git a/backend/internal/usecase/profile/service_test.go b/backend/internal/usecase/profile/service_test.go index 007ebb5..208128d 100644 --- a/backend/internal/usecase/profile/service_test.go +++ b/backend/internal/usecase/profile/service_test.go @@ -3,6 +3,7 @@ package profile import ( "context" "errors" + "fmt" "testing" "time" @@ -28,6 +29,8 @@ type profileTestUnit struct { users outbound.UserRepository profiles outbound.CandidateProfileRepository + // attempts is the zero value by default: a candidate without categories. + attempts profileTestAttempts } func (unit profileTestUnit) Users() outbound.UserRepository { return unit.users } @@ -36,6 +39,48 @@ func (unit profileTestUnit) CandidateProfiles() outbound.CandidateProfileReposit return unit.profiles } +func (unit profileTestUnit) AssessmentAttempts() outbound.AssessmentAttemptRepository { + return unit.attempts +} + +type profileTestAttempts struct { + outbound.AssessmentAttemptRepository + + categories []domain.CandidateAssessmentCategory + err error +} + +func (attempts profileTestAttempts) ListCandidateCategories( + _ context.Context, + _ uuid.UUID, +) ([]domain.CandidateAssessmentCategory, error) { + return attempts.categories, attempts.err +} + +// profileTestCategory is a stored synthetic demonstration category of the +// candidate, as the assessment result that assigned it left it. +func profileTestCategory( + t *testing.T, + candidateID uuid.UUID, + specialization domain.SpecializationCode, + grade domain.GradeCode, + assignedAt time.Time, +) domain.CandidateAssessmentCategory { + t.Helper() + category, err := domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{ + CandidateID: candidateID, Specialization: specialization, Grade: grade, + SourceAttemptID: domain.AssessmentAttemptID(uuid.Must(uuid.NewV7())), SourceReviewID: uuid.Must(uuid.NewV7()), + ProductPolicyVersionID: domain.PolicyVersionID(uuid.Must(uuid.NewV7())), ProductPolicyVersion: 1, + OpeningID: uuid.Must(uuid.NewV7()), OpeningManifestHash: [32]byte{1}, + Source: domain.AssessmentCategorySourceSyntheticDemo, CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, + AssignedAt: assignedAt, + }) + if err != nil { + t.Fatalf("RestoreCandidateAssessmentCategory() error = %v", err) + } + return category +} + type profileTestUsers struct { outbound.UserRepository @@ -182,3 +227,93 @@ func TestSaveMyProfileDoesNotAdvanceAfterProfileWriteFailure(t *testing.T) { t.Fatalf("onboarding advances %d times after a failed write, want 0", profiles.advanceCalls) } } + +func TestGetMyProfileReturnsConfirmedCategoriesInCatalogOrder(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + id := uuid.Must(uuid.NewV7()) + user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now} + users := &profileTestUsers{user: user} + profiles := &profileTestRepository{} + profiles.profile, _ = domain.EmptyCandidateProfile(id) + // The storage returns codes in alphabetical order; the catalog starts with backend. + categories := []domain.CandidateAssessmentCategory{ + profileTestCategory(t, id, domain.SpecializationQA, domain.GradeIntern, now), + profileTestCategory(t, id, domain.SpecializationBackend, domain.GradeJunior, now), + profileTestCategory(t, id, domain.SpecializationFrontend, domain.GradeMiddle, now), + } + attempts := profileTestAttempts{categories: categories} + service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles, attempts: attempts}}, func() time.Time { return now }) + + view, err := service.GetMyProfile(context.Background(), id) + if err != nil { + t.Fatalf("GetMyProfile() error = %v", err) + } + got := make([]domain.SpecializationCode, 0, len(view.ConfirmedCategories)) + for _, category := range view.ConfirmedCategories { + got = append(got, category.Snapshot().Specialization) + } + want := []domain.SpecializationCode{domain.SpecializationBackend, domain.SpecializationFrontend, domain.SpecializationQA} + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("confirmed categories = %v, want catalog order %v", got, want) + } + if snapshot := view.ConfirmedCategories[0].Snapshot(); snapshot.Source != domain.AssessmentCategorySourceSyntheticDemo || snapshot.Grade != domain.GradeJunior { + t.Fatalf("first category = %+v, want the synthetic junior category", snapshot) + } + if view.Profile.UserID() != id { + t.Fatalf("profile owner = %s, want %s", view.Profile.UserID(), id) + } +} + +func TestGetMyProfileWithoutCategoriesReturnsAnEmptyList(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + id := uuid.Must(uuid.NewV7()) + users := &profileTestUsers{user: domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}} + profiles := &profileTestRepository{} + profiles.profile, _ = domain.EmptyCandidateProfile(id) + service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now }) + + view, err := service.GetMyProfile(context.Background(), id) + if err != nil { + t.Fatalf("GetMyProfile() error = %v", err) + } + if len(view.ConfirmedCategories) != 0 { + t.Fatalf("confirmed categories = %d, want none", len(view.ConfirmedCategories)) + } +} + +func TestGetMyProfileFailsWhenCategoriesCannotBeRead(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + id := uuid.Must(uuid.NewV7()) + users := &profileTestUsers{user: domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}} + profiles := &profileTestRepository{} + profiles.profile, _ = domain.EmptyCandidateProfile(id) + readErr := errors.New("categories unavailable") + attempts := profileTestAttempts{err: readErr} + service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles, attempts: attempts}}, func() time.Time { return now }) + + if _, err := service.GetMyProfile(context.Background(), id); !errors.Is(err, readErr) { + t.Fatalf("GetMyProfile() error = %v, want the category read failure", err) + } +} + +func TestSaveMyProfileReturnsTheConfirmedCategoriesAsWell(t *testing.T) { + now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + id := uuid.Must(uuid.NewV7()) + users := &profileTestUsers{user: domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}} + profiles := &profileTestRepository{} + profiles.profile, _ = domain.EmptyCandidateProfile(id) + attempts := profileTestAttempts{categories: []domain.CandidateAssessmentCategory{ + profileTestCategory(t, id, domain.SpecializationDSML, domain.GradeMiddle, now), + }} + service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles, attempts: attempts}}, func() time.Time { return now }) + input := domain.CandidateProfileInput{FullName: &domain.ProfileClaimInput[string]{Value: "Anna Sokolova", Status: domain.ProfileClaimConfirmed}} + + view, err := service.SaveMyProfile(context.Background(), id, 0, input) + if err != nil { + t.Fatalf("SaveMyProfile() error = %v", err) + } + if view.Profile.Version() != 1 || len(view.ConfirmedCategories) != 1 || + view.ConfirmedCategories[0].Snapshot().Specialization != domain.SpecializationDSML { + t.Fatalf("saved view = version %d with categories %v, want version 1 with the ds_ml category", view.Profile.Version(), view.ConfirmedCategories) + } +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 66298f9..b58e74d 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -702,14 +702,25 @@ Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries - Contract checks. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData`, and `TestEvidenceWalkReachesTheEvidenceFamily` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and the candidate list through all references and fail on an assessment, signal, or review schema, or on a raw answer, score, or failure property. - Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open. +### Assessment availability and the confirmed grade + +`GET /api/v1/me/assessment-availability` (`GetMyAssessmentAvailability`) only reads. The usecase `backend/internal/usecase/assessment/availability.go` reads the policy, the bank, the questionnaire, the attempts, the quota, and the current categories in one repeatable-read snapshot. For each questionnaire specialization, `confirmed_grade` and its basis `confirmed_basis` come from the current `candidate_assessment_categories` row through the `ListCandidateCategories` port, not from the results. The grade and its basis are therefore read together, and `confirmed_basis` is null exactly when no grade is confirmed. A category of a specialization that the questionnaire no longer lists does not appear in the availability, but the profile shows it. + +The profile (`GetMyProfile`, `SaveMyProfile`) reads the same rows in its own transaction. `confirmed_categories` holds one category per specialization in catalog order, with its `basis`, its assignment time (`confirmed_at`), and the `attempt_id` of the attempt whose result assigned it. An empty list means that no result has confirmed a category. + +A category changes only by a strict grade upgrade (the database trigger and the domain): a result with a higher pass replaces the row, a pass at an equal or lower grade leaves it as it is and the decision gets the status `unchanged`. A failed attempt does not change the category. The domain has no category revocation; the row leaves only through the cascade of an account deletion. + +`basis` is the same value as the `source` of the category decision. Today it is always `synthetic_demo`: the database accepts only the demonstration source and `calibration_status = uncalibrated`. The candidate card and the organization search therefore show such a category as a demonstration, not as a validated measurement. The basis is required in every category object, so a category without a basis cannot look like a standard confirmation. + ## Matching and explanations Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule. - Access before ranking. The search is one transaction. The owner role is checked under the membership lock before any card is read. `ListVisibleCards` then runs the checks of a card read: verified employer, then `ListVisibleCandidateViewSources`, which selects from `candidate_effective_publications` (published and backed by an unrevoked C2) and excludes the candidates that hide the reading organization with `NOT EXISTS` over `candidate_hidden_organizations`; then the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five. The list is therefore exactly the set of handles that `GetOrganizationCandidateCard` opens at that moment: a card that the cohort rules suppress is not searched, a revoked C2, a closed publication, or a hidden organization takes effect on the next request, and nothing is cached or stored. The permitted evidence is read only through the organization-safe batch query `ListOrganizationVisibleEvidenceBatch` (one statement for the whole candidate set, with the barriers of the single read: the effective publication view, `NOT EXISTS` over the hiding, the `categories` field, visible measurements), and only when the request names skills. The locks are those of the card read and nothing else is locked; the writes of the search are limited to the candidates it returns. - Owner only. For the MVP milestone the active owner of the organization searches. The HTTP boundary refuses every other role (`ownerCompanyOperations`), and the usecase repeats the role check under the membership lock, so a membership alone grants nothing. The full role and assignment matrix is later work and must not widen rights by one membership. -- Charged like card reads. A search returns card content (the confirmed category with its strength, the declared grade, the stack, the experience band, the work formats, and the explanation), so it passes through the same allowance as a card read. The whole visible bank is ranked, and then each group is cut to `max_results_per_group` of the policy version (demo value 10, so at most 30 reveals for one search, below the 50 distinct card views per day of tier E0); no total is returned. Walking the output in the order `main`, `near`, `unconfirmed`, each newly revealed candidate is reserved through the company quota port (`candidateview.SearchViews.Reserve`, the same `ReserveCardView` as a card read: idempotent per organization and candidate inside the window, so repeating the search or opening the card afterwards does not charge twice), and the candidate's access history gets one `card_viewed` entry per search with the fields actually returned (`SearchViews.Record`), all in the transaction of the search. When the allowance ends, the output stops at the first refusal: the entries already paid for are returned, `truncated` is true, nothing is written for the rest, and there is no error. `truncated` is also true when a group exceeded its limit; it carries no count. Opening a card is still the read for the full card. +- Charged like card reads. A search returns card content (the confirmed category with its strength and basis, the declared grade, the stack, the experience band, the work formats, and the explanation), so it passes through the same allowance as a card read. The whole visible bank is ranked, and then each group is cut to `max_results_per_group` of the policy version (demo value 10, so at most 30 reveals for one search, below the 50 distinct card views per day of tier E0); no total is returned. Walking the output in the order `main`, `near`, `unconfirmed`, each newly revealed candidate is reserved through the company quota port (`candidateview.SearchViews.Reserve`, the same `ReserveCardView` as a card read: idempotent per organization and candidate inside the window, so repeating the search or opening the card afterwards does not charge twice), and the candidate's access history gets one `card_viewed` entry per search with the fields actually returned (`SearchViews.Record`), all in the transaction of the search. When the allowance ends, the output stops at the first refusal: the entries already paid for are returned, `truncated` is true, nothing is written for the rest, and there is no error. `truncated` is also true when a group exceeded its limit; it carries no count. Opening a card is still the read for the full card. - One entry per candidate specialization, built from the card the organization is allowed to see. A specialization is confirmed only when the card shows its category (`categories` published and not generalized away); a role that the self-assessment lists as unconfirmed is an unconfirmed entry; a role marked confirmed whose category the card does not show gives no entry, because a result cannot claim a confirmation the candidate did not publish. The same handle can therefore be confirmed in Backend and unconfirmed in Networks, and a Backend confirmation never changes the Networks entry. The status of an entry follows the specialization of the request: a need with a confirmed specialization and a `specialization` filter both restrict it, and two different values leave nothing. A need without a confirmed specialization searches all of them and returns each specialization separately. +- Category basis. Each confirmed category of an entry carries `basis` from the same stored row as the card. Today it is `synthetic_demo`, a demonstration that is not a validated measurement. The organization reads it as a demonstration confirmation; the field is required in `MatchCategory`, so a category without a basis cannot exist. - Filters, all applied before scoring. `confirmed_grade`, `confirmed_category`, and `confirmation_status: confirmed` keep only confirmed entries; a declared grade never satisfies them. `declared_grade` is a separate claim. `stack` requires every named tag in the card and also counts as a required skill of the request. `conditions.work_formats` needs one common format, and `conditions.salary_compatibility` needs the same value; an unknown card value never satisfies a condition. An unconfirmed category alone hides nothing: without a confirmed filter the declared specializations are listed. - Requested skills. The skills of the Cov come from the confirmed required (weight 2) and desired (weight 1) skills of the need snapshot, with the tags of the `stack` filter as required. A code is counted once however often it is repeated. A skill without a taxonomy code has no reviewed mapping, matches nothing, and is a gap. An empty request uses the neutral Cov 0.5 instead of dividing by zero. The need is read by `requirements_version` (`GetVersion`); a general version that only changed the title is not a requirements snapshot and answers 404, and the snapshot of an older requirements version stays searchable and unchanged. - Evidence of a skill. Each requested skill takes the best product of the trust, attribution, and relation coefficients over the permitted evidence, not their sum. The evidence is the stated stack tags of the card (trust 0, a claim) and, for a confirmed entry, the one assessment fact that supports its category (trust 1, personal). The relation is exact for the same code, broader for a specialization over a technology, and narrower the other way, by the `skill_taxonomy` of the policy version (demo: `backend` over `docker`, `go`, `kafka`, `postgresql`; `devops_sre` over `docker`); a version without a taxonomy relates only equal codes, so the version fully determines the result. The taxonomy is a demonstration mapping, not a measured one. An online Backend result is worth 0.6 * 1.0 * 0.4 = 0.24 for a requested Go and a stated Go tag 0.25; the near threshold is 0.25, so a candidate whose only evidence for a required technology is a Backend assessment is always in `near` for it, and a stated tag alone is enough to be in `main`. That consequence of the PRD values is an owner question. Repeating a tag or a skill adds nothing. @@ -908,7 +919,7 @@ Own `GetMyProfile` and `SaveMyProfile` operations are implemented through `backe Migration `00020_create_candidate_profile_history.sql` adds overlapping-period confirmations and version history. `experience_overlaps` lists intersections of inclusive calendar months. An explicit confirmation binds two indices to their exact dates in the current request and its `expected_version`; an earlier confirmation carries forward only for the same indices and dates. Editing an employer or description alone does not invalidate the confirmed periods. A stored unconfirmed overlap permits only an exact no-op; a changed profile requires confirmation or corrected dates. -The changed version, complete claim set, period confirmations, and private history snapshot commit in one transaction. Each snapshot is bounded to 256 KiB; a trigger refuses history UPDATE, and deleting the profile cascades to its history. There is no automatic retention expiry. A no-op creates no history. A successful save, including a no-op, advances only `candidate_profile` to `candidate_questionnaire`, leaving later steps unchanged. Confirmed categories currently remain empty until assessment-result reading is implemented and are never written by the profile form. +The changed version, complete claim set, period confirmations, and private history snapshot commit in one transaction. Each snapshot is bounded to 256 KiB; a trigger refuses history UPDATE, and deleting the profile cascades to its history. There is no automatic retention expiry. A no-op creates no history. A successful save, including a no-op, advances only `candidate_profile` to `candidate_questionnaire`, leaving later steps unchanged. Confirmed categories are read in the same transaction as the profile (`GetMyProfile`, `SaveMyProfile`): one per specialization in catalog order, from `candidate_assessment_categories`. The profile form never writes them. Tables: @@ -919,7 +930,7 @@ Decisions: - Claims, not columns. Every value has a status, a source, and a confirmation time, so one claims table replaces fifty columns; jsonb holds the shape of the value (a string, a boolean, or an object), and each kind has its own CHECK for the format and bounds of the contract (E.164 for the phone, the `@` of a Telegram name, a multiple of 1000 for the salary, `YYYY-MM` and the order of the period for experience, the known specialization and grade codes). The domain validates a value in full before it is written, and `RestoreCandidateProfileContent` applies the same rules on read, so a row changed outside the application is rejected. - Trust level 0 in the schema. `trust_level` is stored in a column with `CHECK (trust_level = 0)`, and the insert statement supplies 0 itself and takes no level from the caller. A confirmed value requires `confirmed_at`, an unconfirmed suggestion does not and is always an import (`extraction_version` is not NULL); a manual value is always confirmed and carries no quote. Raising trust is a property of evidence, which is not stored here. -- No confirmed category. The tables have no column for a confirmed grade or a category, and the value of a role admits only the keys `specialization` and `self_assessed_grade`, so neither a form nor an import can write a confirmed category; it is derived from assessment results when read (`confirmed_categories`). +- No confirmed category. The tables have no column for a confirmed grade or a category, and the value of a role admits only the keys `specialization` and `self_assessed_grade`, so neither a form nor an import can write a confirmed category; it is read from the `candidate_assessment_categories` rows, which only an assessment result writes (`confirmed_categories`, with its `basis`). - No mandatory link to a file, ML, or FSP. The tables have no column or foreign key to a resume file, the object storage, ML, or an FSP account, and the only foreign keys point at `users` and `candidate_profiles`. A profile typed by hand is complete; a future import adds its own columns or tables additively (`TestCandidateProfileStorage` checks the set of columns and foreign keys). - Version. `AdvanceCandidateProfileVersion` is one statement that advances the version only when the stored one equals the one the caller read; for a stale version no row returns, and the caller answers 412 `version_conflict`. The update time is `GREATEST(stored, application clock)`, so an instance clock that runs behind never violates the CHECK `candidate_profiles_updated_after_creation` (which would be a 500). Version monotonicity is enforced by these queries only: there is no trigger, so no other code may write `version`. `InsertCandidateProfile` with `ON CONFLICT DO NOTHING` tells a lost first save apart (concurrent first saves: one wins, the rest get a version conflict). Replacing the set of claims (delete all, insert the new ones) runs in one transaction with the version advance. `domain.CandidateProfile.Replace(input, expectedVersion, at)` fixes the order: a version above the current one is a conflict; body rules are 400; a decision `extracted` that depends on the stored claims, against a stale version, is `ErrCandidateProfileVersionConflict` rather than 400; a body that changes nothing does not advance the version; any other change over a stale version is a conflict. - Consistent read. `ReadCandidateProfile` reads the profile row and every claim in one statement (a LEFT JOIN), that is, from one snapshot; two separate queries could return version N with the claims of N+1 when a save commits between them. The adapter must use only this query and never replace it with two; a write reads the profile in the same transaction as the replacement, and the version condition protects against a lost edit. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 2001933..bfcde8f 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -702,14 +702,25 @@ contact_grant относится к паре кандидат-компания - Проверки контракта. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData` и `TestEvidenceWalkReachesTheEvidenceFamily` (Go) и `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) обходят все организационные операции и список кандидата по всем ссылкам и падают на схеме оценки, сигнала или проверки, а также на свойстве с сырым ответом, баллом или провалом. - Не реализовано: операция скрыть или показать факт (колонка и охранник есть, HTTP-операции для изменения нет), заявления профиля как факты, факты из ФСП и других источников, отзыв источника, уровень доверия выше 1, использование доказательств в PDF "Паспорт навыков", срок хранения. Нужно ли доказательствам отдельное поле карточки вместо `categories`, остается открытым вопросом. +### Доступность оценки и подтвержденный грейд + +`GET /api/v1/me/assessment-availability` (`GetMyAssessmentAvailability`) только читает. Usecase `backend/internal/usecase/assessment/availability.go` читает политику, банк, анкету, попытки, квоту и текущие категории одним снимком repeatable read. Для каждой специализации анкеты `confirmed_grade` и основание `confirmed_basis` берутся из текущей строки `candidate_assessment_categories` через порт `ListCandidateCategories`, а не из результатов. Поэтому грейд и основание читаются вместе, а `confirmed_basis` равен null ровно тогда, когда грейда нет. Категория специализации, которой нет в анкете, в доступности не появляется, но профиль ее показывает. + +Профиль (`GetMyProfile`, `SaveMyProfile`) читает те же строки в своей транзакции. `confirmed_categories` содержит одну категорию на специализацию в порядке каталога с `basis`, временем назначения (`confirmed_at`) и `attempt_id` попытки, чей результат ее назначил. Пустой список означает, что ни один результат категорию не подтвердил. + +Замена категории - только строгое повышение грейда (триггер базы и домен): результат с более высоким проходом заменяет строку, а проход на равный или более низкий грейд оставляет ее прежней, и решение получает статус `unchanged`. Неудачная попытка категорию не меняет. Отзыва категории домен не предусматривает; строка уходит только каскадом при удалении аккаунта. + +`basis` - то же значение, что `source` решения о категории. Сейчас оно всегда `synthetic_demo`: база принимает только демонстрационный источник и `calibration_status = uncalibrated`. Поэтому карточки кандидата и подбор организаций показывают такую категорию как демонстрационную, а не как проверенное измерение. Основание обязательно в каждом объекте категории, поэтому категория без основания не может выглядеть стандартным подтверждением. + ## Подбор и объяснение Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре. - Доступ до ранжирования. Поиск выполняется в одной транзакции. Роль владельца проверяется под блокировкой членства до чтения любых карточек. Затем `ListVisibleCards` проводит проверки чтения карточки: подтвержденный работодатель, затем `ListVisibleCandidateViewSources`, который выбирает из `candidate_effective_publications` (опубликовано и подкреплено неотозванным C2) и исключает кандидатов, скрывших читающую организацию, через `NOT EXISTS` по `candidate_hidden_organizations`; затем блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти. Поэтому список - это ровно те handle, которые в этот момент открывает `GetOrganizationCandidateCard`: карточка, скрытая правилами когорты, не ищется, отзыв C2, закрытая публикация или скрытая организация действуют со следующего запроса, ничего не кешируется и не хранится. Разрешенные доказательства читаются только организационно безопасным пакетным запросом `ListOrganizationVisibleEvidenceBatch` (один запрос на весь набор кандидатов с барьерами одиночного чтения: представление действующих публикаций, `NOT EXISTS` по скрытию, поле `categories`, видимые измерения) и только если запрос называет навыки. Блокировки - те же, что у чтения карточки, ничего больше не блокируется; записи поиска ограничены кандидатами, которых он возвращает. - Только владелец. Для MVP ищет действующий владелец организации. HTTP-граница отклоняет любую другую роль (`ownerCompanyOperations`), а usecase повторяет проверку роли под блокировкой членства, поэтому само членство ничего не дает. Полная матрица ролей и назначений - более поздняя работа и не должна расширять права по одному членству. -- Оплата как чтение карточек. Поиск возвращает содержимое карточки (подтвержденную категорию с силой, заявленный грейд, стек, диапазон стажа, форматы работы и объяснение), поэтому проходит через тот же лимит, что чтение карточки. Ранжируется весь видимый банк, затем каждая группа обрезается до `max_results_per_group` версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 уникальных просмотров в сутки уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат резервируется через порт квоты компании (`candidateview.SearchViews.Reserve`, тот же `ReserveCardView`, что у чтения карточки: идемпотентно на организацию и кандидата внутри окна, поэтому повтор поиска или открытие карточки после него не списывает дважды), а в истории доступа кандидата появляется по одной записи `card_viewed` за поиск с фактически возвращенными полями (`SearchViews.Record`); все это в транзакции поиска. Когда лимит заканчивается, вывод останавливается на первом отказе: возвращаются уже оплаченные записи, `truncated` истинно, для остальных ничего не пишется, ошибки нет. `truncated` истинно и когда группа превысила предел; числа оно не несет. Полная карточка по-прежнему открывается своим чтением. +- Оплата как чтение карточек. Поиск возвращает содержимое карточки (подтвержденную категорию с силой и основанием, заявленный грейд, стек, диапазон стажа, форматы работы и объяснение), поэтому проходит через тот же лимит, что чтение карточки. Ранжируется весь видимый банк, затем каждая группа обрезается до `max_results_per_group` версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 уникальных просмотров в сутки уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат резервируется через порт квоты компании (`candidateview.SearchViews.Reserve`, тот же `ReserveCardView`, что у чтения карточки: идемпотентно на организацию и кандидата внутри окна, поэтому повтор поиска или открытие карточки после него не списывает дважды), а в истории доступа кандидата появляется по одной записи `card_viewed` за поиск с фактически возвращенными полями (`SearchViews.Record`); все это в транзакции поиска. Когда лимит заканчивается, вывод останавливается на первом отказе: возвращаются уже оплаченные записи, `truncated` истинно, для остальных ничего не пишется, ошибки нет. `truncated` истинно и когда группа превысила предел; числа оно не несет. Полная карточка по-прежнему открывается своим чтением. - Одна запись на специализацию кандидата, из карточки, которую организации разрешено видеть. Специализация подтверждена, только когда карточка показывает ее категорию (`categories` опубликованы и не обобщены до пустоты); роль, помеченная в самооценке как неподтвержденная, - неподтвержденная запись; роль, помеченная подтвержденной, чью категорию карточка не показывает, записи не дает, потому что результат не может заявлять подтверждение, которое кандидат не опубликовал. Один и тот же handle может быть подтвержден по Backend и не подтвержден по сетям, и подтверждение Backend никогда не меняет запись по сетям. Статус записи следует специализации запроса: подтвержденная специализация потребности и фильтр `specialization` оба ограничивают поиск, а два разных значения не оставляют ничего. Потребность без подтвержденной специализации ищет по всем и возвращает каждую специализацию отдельно. +- Основание категории. Каждая подтвержденная категория записи несет `basis` из той же строки, что и карточка. Сейчас это `synthetic_demo`: демонстрация, которая не является проверенным измерением. Организация видит ее как демонстрационное подтверждение; поле обязательно в `MatchCategory`, поэтому категория без основания невозможна. - Фильтры, все до расчета. `confirmed_grade`, `confirmed_category` и `confirmation_status: confirmed` оставляют только подтвержденные записи; заявленный грейд их не удовлетворяет. `declared_grade` - отдельное заявление. `stack` требует каждый названный тег в карточке и одновременно считается обязательным навыком запроса. `conditions.work_formats` требует один общий формат, `conditions.salary_compatibility` - то же значение; неизвестное значение карточки условие не удовлетворяет. Одна неподтвержденная категория ничего не скрывает: без подтвержденного фильтра заявленные специализации выводятся. - Запрошенные навыки. Навыки для Cov берутся из подтвержденных обязательных (вес 2) и желательных (вес 1) навыков снимка потребности, теги фильтра `stack` считаются обязательными. Код считается один раз, сколько бы раз он ни повторялся. Навык без таксономического кода не имеет проверенного соответствия, ничему не соответствует и остается пробелом. Пустой запрос использует нейтральное Cov 0.5 вместо деления на ноль. Потребность читается по `requirements_version` (`GetVersion`); общая версия, изменившая только название, не является снимком требований и дает 404, а снимок прежней версии требований остается доступным и неизменным. - Доказательство навыка. Для каждого запрошенного навыка берется лучшее произведение коэффициентов доверия, атрибуции и связи среди разрешенных доказательств, а не их сумма. Доказательства - заявленные теги стека карточки (доверие 0, заявление) и для подтвержденной записи единственный факт оценки, подтверждающий ее категорию (доверие 1, личный). Связь точная для того же кода, широкая для специализации над технологией и узкая в обратную сторону, по `skill_taxonomy` версии политики (демо: `backend` над `docker`, `go`, `kafka`, `postgresql`; `devops_sre` над `docker`); версия без таксономии связывает только равные коды, так что версия политики полностью определяет результат. Таксономия - демонстрационное соответствие, а не измеренное. Онлайн-результат Backend стоит 0.6 * 1.0 * 0.4 = 0.24 для запрошенного Go, заявленный тег Go - 0.25; порог близости 0.25, поэтому кандидат, у которого единственное доказательство обязательной технологии - оценка Backend, для нее всегда в `near`, а одного заявленного тега достаточно для `main`. Это следствие значений PRD - вопрос владельцу продукта. Повтор тега или навыка ничего не добавляет. @@ -908,7 +919,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове Миграция `00020_create_candidate_profile_history.sql` добавляет подтверждения пересекающихся периодов и историю версий. `experience_overlaps` перечисляет пересечения включительных календарных месяцев. Явное подтверждение связывает два индекса с точными датами в текущем запросе и его `expected_version`; прежнее подтверждение переносится только при тех же индексах и датах. Изменение работодателя или описания само по себе не меняет подтвержденные периоды. Сохраненный неподтвержденный overlap допускает только точный no-op; перед изменением профиля его надо подтвердить или исправить даты. -Измененная версия, полный набор заявлений, подтверждения периодов и закрытый снимок истории записываются одной транзакцией. Каждый снимок ограничен 256 KiB; UPDATE истории запрещен триггером, удаление профиля каскадно удаляет историю. Автоматического срока очистки нет. No-op не создает историю. Успешное сохранение, включая no-op, переводит только шаг `candidate_profile` в `candidate_questionnaire`; поздний шаг не меняется. Подтвержденные категории пока возвращаются пустыми до реализации чтения результатов оценки и никогда не записываются формой профиля. +Измененная версия, полный набор заявлений, подтверждения периодов и закрытый снимок истории записываются одной транзакцией. Каждый снимок ограничен 256 KiB; UPDATE истории запрещен триггером, удаление профиля каскадно удаляет историю. Автоматического срока очистки нет. No-op не создает историю. Успешное сохранение, включая no-op, переводит только шаг `candidate_profile` в `candidate_questionnaire`; поздний шаг не меняется. Подтвержденные категории читаются в той же транзакции, что и профиль (`GetMyProfile`, `SaveMyProfile`): по одной на специализацию в порядке каталога, из строк `candidate_assessment_categories`. Форма профиля их никогда не записывает. Таблицы: @@ -919,7 +930,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Заявления, а не столбцы. У каждого значения есть статус, источник и время подтверждения, поэтому одна таблица заявлений вместо пятидесяти столбцов; форму значения (строка, булево или объект) держит jsonb, а у каждого вида есть свой CHECK формата и границ контракта (E.164 для телефона, `@` у Telegram, кратность 1000 у зарплаты, `YYYY-MM` и порядок периода у опыта, известные коды специализации и грейда). Домен проверяет значение полностью до записи, а `RestoreCandidateProfileContent` повторяет те же правила при чтении, поэтому строка, измененная вне приложения, отклоняется. - Доверие 0 в схеме. `trust_level` хранится в столбце с `CHECK (trust_level = 0)`, а оператор вставки подставляет 0 сам и не принимает уровень от вызывающего. Подтвержденное значение требует `confirmed_at`, неподтвержденное предложение - нет и обязательно является импортом (`extraction_version` не NULL); ручное значение всегда подтверждено и не несет цитаты. Повышение доверия - свойство доказательств, которые хранятся не здесь. -- Нет подтвержденной категории. В таблицах нет столбца подтвержденного грейда или категории, а значение роли допускает только ключи `specialization` и `self_assessed_grade`, поэтому ни форма, ни импорт не могут записать подтвержденную категорию; она выводится из результатов оценки при чтении (`confirmed_categories`). +- Нет подтвержденной категории. В таблицах нет столбца подтвержденного грейда или категории, а значение роли допускает только ключи `specialization` и `self_assessed_grade`, поэтому ни форма, ни импорт не могут записать подтвержденную категорию; она читается из строк `candidate_assessment_categories`, которые пишет только результат оценки (`confirmed_categories`, вместе с основанием `basis`). - Нет обязательной связи с файлом, ML или ФСП. В таблицах нет столбцов и внешних ключей к файлу резюме, хранилищу объектов, ML или аккаунту ФСП, а единственные внешние ключи - на `users` и на `candidate_profiles`. Профиль, набранный вручную, полон; будущий импорт добавит свои столбцы или таблицы аддитивно (`TestCandidateProfileStorage` проверяет набор столбцов и внешних ключей). - Версия. `AdvanceCandidateProfileVersion` - один оператор, который увеличивает версию только когда сохраненная равна прочитанной вызывающим; для устаревшей версии строка не возвращается, и вызывающий отвечает 412 `version_conflict`. Время обновления считается как `GREATEST(сохраненное, текущее время приложения)`, поэтому отставшие часы экземпляра не нарушают CHECK `candidate_profiles_updated_after_creation` (иначе был бы 500). Монотонность версии обеспечивают только эти запросы: триггера нет, поэтому никакой другой код не должен писать `version`. `InsertCandidateProfile` с `ON CONFLICT DO NOTHING` отличает проигранное первое сохранение (параллельные первые сохранения: одно выигрывает, остальные - конфликт версии). Замена набора заявлений (удалить все и вставить новые) идет в одной транзакции вместе с продвижением версии. `domain.CandidateProfile.Replace(input, expectedVersion, at)` задает порядок: версия выше текущей - конфликт; правила тела - 400; решение `extracted`, зависящее от сохраненных заявлений, при устаревшей версии - `ErrCandidateProfileVersionConflict`, а не 400; тело без изменений - без продвижения версии; иное изменение по устаревшей версии - конфликт. - Согласованное чтение. `ReadCandidateProfile` читает строку профиля и все заявления одним оператором (LEFT JOIN), то есть из одного снимка; два отдельных запроса могли бы вернуть версию N с заявлениями N+1 при сохранении между ними. Адаптер обязан использовать только этот запрос и не заменять его двумя; запись читает профиль в той же транзакции, что и замена, а защиту от потерянной правки дает условие версии. diff --git a/frontend/e2e/candidate-home.spec.ts b/frontend/e2e/candidate-home.spec.ts index efffc0e..772352e 100644 --- a/frontend/e2e/candidate-home.spec.ts +++ b/frontend/e2e/candidate-home.spec.ts @@ -327,7 +327,10 @@ function scenarioAnswer(scenario: Scenario, pathname: string): Stub { }; case "/api/v1/me/profile": // The home reads only the version; the profile form is not opened here. - return { status: 200, body: { version: scenario.profileVersion ?? 0 } }; + return { + status: 200, + body: { version: scenario.profileVersion ?? 0, confirmed_categories: [] }, + }; case "/api/v1/me/questionnaire": return { status: 200, @@ -357,6 +360,7 @@ function scenarioAnswer(scenario: Scenario, pathname: string): Stub { { specialization: declared.specialization, confirmed_grade: scenario.confirmed ?? null, + confirmed_basis: scenario.confirmed ? "synthetic_demo" : null, active_attempt_id: null, grades: [ { @@ -438,13 +442,14 @@ test.describe("candidate home states with a stubbed API", () => { await captureReviewScreenshots(page, "candidate-home-category"); }); - test("states one confirmed category in every block when the availability read has none", async ({ + test("states one confirmed category in every block when the availability confirms it", async ({ page, }) => { await mockCandidateApi(page, { step: "candidate_consents", profileVersion: 1, declared: { specialization: "backend", grade: "junior" }, + confirmed: "junior", results: [realResult("confirmed")], }); await page.goto("/candidate"); diff --git a/frontend/e2e/match-search.spec.ts b/frontend/e2e/match-search.spec.ts index 26c4fa6..8058768 100644 --- a/frontend/e2e/match-search.spec.ts +++ b/frontend/e2e/match-search.spec.ts @@ -495,7 +495,7 @@ function confirmedEntry(handle: string, grade: string, coverage: number, overrid specialization: "backend", confirmation_status: "confirmed", declared_grade: "senior", - category: { specialization: "backend", grade }, + category: { specialization: "backend", grade, basis: "synthetic_demo" }, strength: "strong", public_context: { stack: ["go", "postgresql"], @@ -715,7 +715,14 @@ async function installFakeApi(page: Page, options: FakeOptions = {}): Promise { // The confirmed and the declared grade have separate lines. const confirmed = groupSection(page, "Подтвержденные").getByRole("article"); await expect(confirmed).toContainText("Грейд подтвержден: Middle"); - await expect(confirmed).toContainText("Backend, Middle. Сильное подтверждение"); + await expect(confirmed).toContainText("Backend, Middle. Демонстрационное подтверждение"); await expect(confirmed).toContainText("Заявленный кандидатом грейд"); await expect(confirmed).toContainText("Senior"); @@ -956,7 +963,7 @@ test.describe("employer candidate search with a stubbed API", () => { const open = confirmed.getByRole("button", { name: /карточку/ }); await open.click(); const panel = confirmed.getByRole("region", { name: "Карточка кандидата" }); - await expect(panel.getByText("Backend: Middle. Сильное подтверждение")).toBeVisible(); + await expect(panel.getByText("Backend: Middle. Демонстрационное подтверждение")).toBeVisible(); await expect(panel.getByText("Заявлено: Junior")).toBeVisible(); await expect(panel.getByText("Backend: Middle").first()).toBeVisible(); await expect(panel.getByText("Год оценки")).toBeVisible(); diff --git a/frontend/src/entities/candidate-view/model/presentation.test.ts b/frontend/src/entities/candidate-view/model/presentation.test.ts index 903e672..9236f12 100644 --- a/frontend/src/entities/candidate-view/model/presentation.test.ts +++ b/frontend/src/entities/candidate-view/model/presentation.test.ts @@ -24,7 +24,14 @@ describe("candidate card presentation", () => { const result = presentCandidatePreview( preview({ pseudonym: `cv1_${"a".repeat(43)}`, - categories: [{ specialization: "backend", grade: "junior", strength: "standard" }], + categories: [ + { + specialization: "backend", + grade: "junior", + strength: "standard", + basis: "synthetic_demo", + }, + ], stack: ["go"], self_assessment: [ { @@ -43,7 +50,7 @@ describe("candidate card presentation", () => { { specialization: "Backend", grade: "Junior", - strength: "Стандартное подтверждение", + strength: "Демонстрационное подтверждение", }, ]); expect(result?.selfAssessments).toEqual([ @@ -60,7 +67,14 @@ describe("candidate card presentation", () => { const result = presentCandidatePreview( preview({ pseudonym: `cv1_${"b".repeat(43)}`, - categories: [{ specialization: "backend", grade: "middle", strength: "strong" }], + categories: [ + { + specialization: "backend", + grade: "middle", + strength: "strong", + basis: "synthetic_demo", + }, + ], stack: null, self_assessment: [ { specialization: "backend", confirmation_status: "confirmed", declared_grade: "middle" }, @@ -95,7 +109,14 @@ describe("candidate card presentation", () => { const result = presentCandidatePreview({ ...preview({ pseudonym: `cv1_${"c".repeat(43)}`, - categories: [{ specialization: "backend", grade: "middle", strength: "standard" }], + categories: [ + { + specialization: "backend", + grade: "middle", + strength: "standard", + basis: "synthetic_demo", + }, + ], stack: null, self_assessment: null, experience_band: null, diff --git a/frontend/src/entities/candidate-view/model/presentation.ts b/frontend/src/entities/candidate-view/model/presentation.ts index 2a8b1fe..fedc115 100644 --- a/frontend/src/entities/candidate-view/model/presentation.ts +++ b/frontend/src/entities/candidate-view/model/presentation.ts @@ -232,12 +232,17 @@ export type CandidateViewPresentation = { evidence: readonly EvidencePresentation[] | null; }; +// A demonstration basis is named as one, never as a standard confirmation. +function confirmationLabelOf(category: CardCategory): string { + if (category.basis === "synthetic_demo") return "Демонстрационное подтверждение"; + return category.strength === "strong" ? "Сильное подтверждение" : "Стандартное подтверждение"; +} + function categoryPresentation(category: CardCategory): CategoryPresentation { return { specialization: specializationLabels[category.specialization], grade: gradeLabels[category.grade], - strength: - category.strength === "strong" ? "Сильное подтверждение" : "Стандартное подтверждение", + strength: confirmationLabelOf(category), }; } diff --git a/frontend/src/entities/candidate-view/ui/employer-card-preview.test.tsx b/frontend/src/entities/candidate-view/ui/employer-card-preview.test.tsx index 06601bf..7208952 100644 --- a/frontend/src/entities/candidate-view/ui/employer-card-preview.test.tsx +++ b/frontend/src/entities/candidate-view/ui/employer-card-preview.test.tsx @@ -11,7 +11,14 @@ function published(overrides: Partial = {}): CardPreview { fields: ["categories", "self_assessment"], card: { pseudonym, - categories: [{ specialization: "backend", grade: "middle", strength: "standard" }], + categories: [ + { + specialization: "backend", + grade: "middle", + strength: "standard", + basis: "synthetic_demo", + }, + ], stack: null, self_assessment: [ { specialization: "backend", confirmation_status: "confirmed", declared_grade: "middle" }, @@ -69,7 +76,7 @@ describe("employer card preview", () => { it("states the confirmation of each specialization separately", () => { const markup = render(published()); - expect(markup).toContain("Backend: Middle, стандартное подтверждение"); + expect(markup).toContain("Backend: Middle, демонстрационное подтверждение"); expect(markup.match(/Грейд подтвержден/g)).toHaveLength(1); expect(markup.match(/Грейд не подтвержден/g)).toHaveLength(2); expect(markup).toContain("Заявлено: Junior"); diff --git a/frontend/src/entities/candidate/api/home-queries.test.ts b/frontend/src/entities/candidate/api/home-queries.test.ts index d3fd22e..44bf54c 100644 --- a/frontend/src/entities/candidate/api/home-queries.test.ts +++ b/frontend/src/entities/candidate/api/home-queries.test.ts @@ -17,7 +17,9 @@ function read( return { status, data, error, isRefetching: false, refetch }; } -const profile = { version: 1 } as CandidateProfile; +// The home reads only the version and the confirmed categories of the profile. +type ProfileHome = Pick; +const profile: ProfileHome = { version: 1, confirmed_categories: [] }; const questionnaire = { version: 1, specializations: [ @@ -34,7 +36,13 @@ const questionnaire = { } as CandidateQuestionnaire; const availability = { specializations: [ - { specialization: "backend", confirmed_grade: null, active_attempt_id: null, grades: [] }, + { + specialization: "backend", + confirmed_grade: null, + confirmed_basis: null, + active_attempt_id: null, + grades: [], + }, ], } as AssessmentAvailability; const results = { @@ -75,6 +83,33 @@ describe("combineJourneyReads", () => { } }); + it("passes the profile categories into the journey", () => { + const state = combineJourneyReads( + "candidate_assessment", + read("success", { + version: 1, + confirmed_categories: [ + { + specialization: "qa", + grade: "junior", + basis: "synthetic_demo", + confirmed_at: "2026-10-08T10:00:00Z", + attempt_id: "0199b4f2-7c1e-7d3a-9f00-aabbccddee10", + }, + ], + }), + read("success", questionnaire), + read("success", availability), + read("success", results), + ); + + expect(state.status).toBe("success"); + if (state.status === "success") { + expect(state.journey.confirmed.map((standing) => standing.specialization)).toEqual(["qa"]); + expect(state.journey.nextStep).toEqual({ kind: "result" }); + } + }); + it("fails as a whole instead of guessing a step from partial data", () => { const failure = apiError(500); const state = combineJourneyReads( diff --git a/frontend/src/entities/candidate/api/home-queries.ts b/frontend/src/entities/candidate/api/home-queries.ts index 2f2f7bc..bf86406 100644 --- a/frontend/src/entities/candidate/api/home-queries.ts +++ b/frontend/src/entities/candidate/api/home-queries.ts @@ -21,10 +21,10 @@ import { } from "../../../shared/api/schemas"; import { buildCandidateJourney, type CandidateJourney } from "../model/home"; -// The home needs only the version of the profile: 0 means it was never saved. -// The profile form validates the rest of the document itself. -const profileVersionSchema = CandidateProfile.pick({ version: true }); -type CandidateProfileVersion = Pick; +// The home reads the version of the profile (0 means it was never saved) and +// its confirmed categories. The profile form validates the rest of the document. +const profileHomeSchema = CandidateProfile.pick({ version: true, confirmed_categories: true }); +type CandidateProfileHome = Pick; const homeQueryPrefix = ["candidate-home"] as const; @@ -94,11 +94,11 @@ function useHomeQuery( } export function useCandidateProfileRead(session: Session | undefined) { - return useHomeQuery( + return useHomeQuery( session, candidateHomeQueryKeys.profile, (signal) => getMyProfile({ signal }), - profileVersionSchema, + profileHomeSchema, ); } @@ -122,9 +122,10 @@ export function useCandidateAvailabilityRead(session: Session | undefined) { /** * The first page of real results, newest first. The home screen shows its - * first item as the last result and reads the current category of each - * specialization from the newest decision in the same page. The page size is - * the maximum of the list endpoint; the full history stays on the results page. + * first item as the last result and uses the page only to tell whether the + * candidate has a result; the confirmed categories come from the availability + * and profile reads. The page size is the maximum of the list endpoint; the + * full history stays on the results page. */ export function useCandidateLatestResultRead(session: Session | undefined) { return useHomeQuery( @@ -162,16 +163,16 @@ function isAccessError(error: unknown): boolean { } /** - * Joins the four reads that the next step depends on: the profile version, - * the questionnaire, the assessment availability, and the first page of - * results. One failed read fails the whole state, because a step chosen from - * partial data could send the candidate to a form they already completed, or - * hide a confirmed category. A denied read wins over other failures so that - * the forbidden state is shown instead of a retry. + * Joins the four reads that the next step depends on: the profile (its version + * and confirmed categories), the questionnaire, the assessment availability, + * and the first page of results. One failed read fails the whole state, because + * a step chosen from partial data could send the candidate to a form they + * already completed, or hide a confirmed category. A denied read wins over + * other failures so that the forbidden state is shown instead of a retry. */ export function combineJourneyReads( savedStep: CandidateJourney["savedStep"], - profile: ReadResult, + profile: ReadResult, questionnaire: ReadResult, availability: ReadResult, results: ReadResult, @@ -202,6 +203,7 @@ export function combineJourneyReads( journey: buildCandidateJourney({ savedStep, profileVersion: profile.data.version, + profileCategories: profile.data.confirmed_categories, questionnaire: questionnaire.data, availability: availability.data, results: results.data, diff --git a/frontend/src/entities/candidate/model/home.test.ts b/frontend/src/entities/candidate/model/home.test.ts index f0c78ad..98c82b0 100644 --- a/frontend/src/entities/candidate/model/home.test.ts +++ b/frontend/src/entities/candidate/model/home.test.ts @@ -7,6 +7,8 @@ import type { } from "../../../shared/api/schemas"; import { buildCandidateJourney, summarizeVisibility, type CandidateJourneyInput } from "./home"; +type ProfileCategory = CandidateJourneyInput["profileCategories"][number]; + type Availability = AssessmentAvailability["specializations"][number]; function gradeRows(status: "available" | "cooldown"): Availability["grades"] { @@ -33,6 +35,7 @@ function availabilityRow( return { specialization, confirmed_grade: options.confirmed ?? null, + confirmed_basis: options.confirmed ? "synthetic_demo" : null, active_attempt_id: options.attemptId ?? null, grades: gradeRows(options.status ?? "available"), }; @@ -57,27 +60,11 @@ function questionnaire( type ResultRow = CandidateJourneyInput["results"]["items"][number]; /** - * One real result as the results list returns it. A v2 result carries the - * category decision with the grade in force when the attempt ended; a legacy - * result carries none. + * One real result as the results list returns it, with the category decision + * that was in force when the attempt ended. The home screen reads the result + * list only to tell whether a result exists, so this row never sets a grade. */ -function resultRow( - specialization: SpecializationCode, - options: { grade?: GradeCode | null; decidedAt?: string; legacy?: boolean } = {}, -): ResultRow { - const grade = options.grade ?? null; - const decision = options.legacy - ? {} - : { - category_decision: { - status: grade ? "assigned" : "not_eligible", - previous_confirmed_grade: null, - current_confirmed_grade: grade, - method: grade ? "demo_basic_pass_mark" : null, - source: grade ? "synthetic_demo" : null, - calibration_status: "uncalibrated", - }, - }; +function resultRow(specialization: SpecializationCode, grade: GradeCode | null = null): ResultRow { return { kind: "root", attempt_id: "0199b4f2-7c1e-7d3a-9f00-aabbccddee10", @@ -85,15 +72,34 @@ function resultRow( outcome: grade ? "confirmed" : "not_confirmed", confirmed_grade: grade, previous_confirmed_grade: null, - decided_at: options.decidedAt ?? "2026-10-08T10:00:00Z", - ...decision, + decided_at: "2026-10-08T10:00:00Z", + category_decision: { + status: grade ? "assigned" : "not_eligible", + previous_confirmed_grade: null, + current_confirmed_grade: grade, + method: grade ? "demo_basic_pass_mark" : null, + source: grade ? "synthetic_demo" : null, + calibration_status: "uncalibrated", + }, } as unknown as ResultRow; } +/** One confirmed category of the profile read, as the server returns it. */ +function profileCategory(specialization: SpecializationCode, grade: GradeCode): ProfileCategory { + return { + specialization, + grade, + basis: "synthetic_demo", + confirmed_at: "2026-10-08T10:00:00Z", + attempt_id: "0199b4f2-7c1e-7d3a-9f00-aabbccddee10", + }; +} + function input(overrides: Partial = {}): CandidateJourneyInput { return { savedStep: "candidate_consents", profileVersion: 0, + profileCategories: [], questionnaire: questionnaire([]), availability: { specializations: [] }, results: { items: [] }, @@ -234,18 +240,18 @@ describe("buildCandidateJourney next step", () => { }); }); -// Regression: the availability read reported no confirmed grade for a candidate -// whose newest result confirmed Junior, so the next step said "take the test" -// while the result block said the category was confirmed. +// The confirmed category comes from the availability read and, for a +// specialization the questionnaire no longer lists, from the profile read. +// A result never sets a grade: the results list only tells whether one exists. describe("buildCandidateJourney confirmed category", () => { - it("confirms the category from the newest result when the availability read has none", () => { + it("confirms the category from the availability read", () => { const journey = buildCandidateJourney( input({ savedStep: "candidate_consents", profileVersion: 1, questionnaire: questionnaire([["backend", "junior"]]), - availability: { specializations: [availabilityRow("backend")] }, - results: { items: [resultRow("backend", { grade: "junior" })] }, + availability: { specializations: [availabilityRow("backend", { confirmed: "junior" })] }, + results: { items: [resultRow("backend", "junior")] }, }), ); @@ -258,61 +264,13 @@ describe("buildCandidateJourney confirmed category", () => { expect(journey.hasResults).toBe(true); }); - it("keeps the grade of the availability read when both sources name one", () => { - const journey = buildCandidateJourney( - input({ - profileVersion: 1, - questionnaire: questionnaire([["backend", "middle"]]), - availability: { specializations: [availabilityRow("backend", { confirmed: "middle" })] }, - results: { items: [resultRow("backend", { grade: "junior" })] }, - }), - ); - - expect(journey.standings[0]?.confirmedGrade).toBe("middle"); - }); - - it("takes the grade in force from the newest decision, whatever the order of the page", () => { - const journey = buildCandidateJourney( - input({ - profileVersion: 1, - questionnaire: questionnaire([["backend", "senior"]]), - results: { - items: [ - resultRow("backend", { grade: "junior", decidedAt: "2026-10-01T10:00:00Z" }), - resultRow("backend", { grade: "senior", decidedAt: "2026-10-08T10:00:00Z" }), - ], - }, - }), - ); - - expect(journey.standings[0]?.confirmedGrade).toBe("senior"); - }); - - it("does not revive an older grade behind a newer decision that confirms none", () => { - const journey = buildCandidateJourney( - input({ - profileVersion: 1, - questionnaire: questionnaire([["backend", "junior"]]), - results: { - items: [ - resultRow("backend", { grade: "junior", decidedAt: "2026-10-01T10:00:00Z" }), - resultRow("backend", { grade: null, decidedAt: "2026-10-08T10:00:00Z" }), - ], - }, - }), - ); - - expect(journey.confirmed).toEqual([]); - expect(journey.nextStep).toEqual({ kind: "assessment" }); - }); - - it("ignores legacy results that carry no category decision", () => { + it("takes no grade from a result when the availability read confirms none", () => { const journey = buildCandidateJourney( input({ profileVersion: 1, questionnaire: questionnaire([["backend", "junior"]]), availability: { specializations: [availabilityRow("backend")] }, - results: { items: [resultRow("backend", { grade: "junior", legacy: true })] }, + results: { items: [resultRow("backend", "junior")] }, }), ); @@ -321,12 +279,25 @@ describe("buildCandidateJourney confirmed category", () => { expect(journey.nextStep).toEqual({ kind: "assessment" }); }); + it("keeps the availability grade when the profile names another one", () => { + const journey = buildCandidateJourney( + input({ + profileVersion: 1, + questionnaire: questionnaire([["backend", "middle"]]), + availability: { specializations: [availabilityRow("backend", { confirmed: "middle" })] }, + profileCategories: [profileCategory("backend", "junior")], + }), + ); + + expect(journey.standings[0]?.confirmedGrade).toBe("middle"); + }); + it("keeps a confirmed category visible when the questionnaire no longer lists it", () => { const journey = buildCandidateJourney( input({ profileVersion: 1, questionnaire: questionnaire([]), - results: { items: [resultRow("qa", { grade: "junior" })] }, + profileCategories: [profileCategory("qa", "junior")], }), ); diff --git a/frontend/src/entities/candidate/model/home.ts b/frontend/src/entities/candidate/model/home.ts index 9456ec1..dbc9ffd 100644 --- a/frontend/src/entities/candidate/model/home.ts +++ b/frontend/src/entities/candidate/model/home.ts @@ -2,6 +2,7 @@ import type { Account, AssessmentAvailability, AssessmentResultHistoryPage, + CandidateProfile, CandidateQuestionnaire, GradeCode, PrivacySettings, @@ -49,6 +50,8 @@ export type CandidateJourneyInput = { savedStep: OnboardingStep; /** `version` of the profile read; 0 means it was never saved. */ profileVersion: number; + /** `confirmed_categories` of the profile read, in catalog order. */ + profileCategories: CandidateProfile["confirmed_categories"]; questionnaire: Pick; availability: Pick; /** The first page of the candidate's real results, newest first. */ @@ -67,48 +70,25 @@ export type CandidateJourney = { nextStep: CandidateNextStep; }; -type ResultItem = AssessmentResultHistoryPage["items"][number]; - /** - * Grade in force for each specialization, read from the newest result of that - * specialization. A v2 result records the grade in force when its attempt - * ended, so the newest decision is the current category. A legacy result has - * no decision and yields no grade; a result that confirms no grade leaves the - * specialization unconfirmed. Older results never override a newer decision. + * Standings of the questionnaire specializations and of the confirmed + * categories. The confirmed grade comes from the availability read, which + * answers for every questionnaire specialization. A category whose + * specialization the questionnaire no longer lists comes from the profile read, + * so a confirmed grade never disappears from the home screen. Results are not a + * source of the grade: the home takes the category from the server's current + * state only. */ -export function currentGradesFromResults( - results: readonly ResultItem[], -): Map { - // The server lists results newest first; sorting here keeps the rule local. - const newestFirst = [...results].sort((left, right) => - right.decided_at.localeCompare(left.decided_at), - ); - const grades = new Map(); - const decided = new Set(); - for (const result of newestFirst) { - if (decided.has(result.specialization)) continue; - decided.add(result.specialization); - const grade = result.category_decision?.current_confirmed_grade ?? null; - if (grade !== null) grades.set(result.specialization, grade); - } - return grades; -} - -function buildStandings( - input: CandidateJourneyInput, - resultGrades: ReadonlyMap, -): SpecializationStanding[] { +function buildStandings(input: CandidateJourneyInput): SpecializationStanding[] { const standings = new Map(); + const listedByAvailability = new Set(); - // The availability list is the server's view of the questionnaire - // specializations; the questionnaire adds the declared grade. The current - // confirmed grade comes from the availability read when it has one, and from - // the newest result of the specialization otherwise. for (const item of input.availability.specializations) { + listedByAvailability.add(item.specialization); standings.set(item.specialization, { specialization: item.specialization, declaredGrade: null, - confirmedGrade: item.confirmed_grade ?? resultGrades.get(item.specialization) ?? null, + confirmedGrade: item.confirmed_grade ?? null, activeAttemptId: item.active_attempt_id, canStartAttempt: item.grades.some((grade) => grade.status === "available"), }); @@ -118,21 +98,20 @@ function buildStandings( standings.set(item.specialization, { specialization: item.specialization, declaredGrade: item.self_assessed_grade, - confirmedGrade: existing?.confirmedGrade ?? resultGrades.get(item.specialization) ?? null, + confirmedGrade: existing?.confirmedGrade ?? null, activeAttemptId: existing?.activeAttemptId ?? null, canStartAttempt: existing?.canStartAttempt ?? false, }); } - // A result can name a specialization that the current questionnaire no - // longer lists. Its confirmed grade is still a fact, so it stays visible. - for (const [specialization, grade] of resultGrades) { - if (standings.has(specialization)) continue; - standings.set(specialization, { - specialization, - declaredGrade: null, - confirmedGrade: grade, - activeAttemptId: null, - canStartAttempt: false, + for (const category of input.profileCategories) { + if (listedByAvailability.has(category.specialization)) continue; + const existing = standings.get(category.specialization); + standings.set(category.specialization, { + specialization: category.specialization, + declaredGrade: existing?.declaredGrade ?? null, + confirmedGrade: category.grade, + activeAttemptId: existing?.activeAttemptId ?? null, + canStartAttempt: existing?.canStartAttempt ?? false, }); } return [...standings.values()]; @@ -145,14 +124,14 @@ function buildStandings( * questionnaire is saved from the matching step, so a saved profile can sit * behind an earlier stored step. Presence of saved data therefore decides * between the profile, the questionnaire, and the test. Facts about the - * category and the test come only from the availability and results reads. + * category and the test come only from the availability, profile, and results + * reads. * * The client invents no category, grade, or threshold: a category exists only - * when the availability read or the newest result returns a confirmed grade. + * when the availability read or the profile read returns a confirmed grade. */ export function buildCandidateJourney(input: CandidateJourneyInput): CandidateJourney { - const resultGrades = currentGradesFromResults(input.results.items); - const standings = buildStandings(input, resultGrades); + const standings = buildStandings(input); const confirmed = standings.filter((standing) => standing.confirmedGrade !== null); const profileSaved = input.profileVersion > 0; const questionnaireSaved = diff --git a/frontend/src/entities/match/model/adapter.test.ts b/frontend/src/entities/match/model/adapter.test.ts index d008049..20de906 100644 --- a/frontend/src/entities/match/model/adapter.test.ts +++ b/frontend/src/entities/match/model/adapter.test.ts @@ -34,7 +34,7 @@ function matchResponseFixture(): MatchSearchResponseOutput { specialization: "backend", confirmation_status: "confirmed", declared_grade: "middle", - category: { specialization: "backend", grade: "middle" }, + category: { specialization: "backend", grade: "middle", basis: "synthetic_demo" }, strength: "strong", public_context: { stack: ["go"], @@ -66,7 +66,7 @@ function matchResponseFixture(): MatchSearchResponseOutput { specialization: "frontend", confirmation_status: "confirmed", declared_grade: "junior", - category: { specialization: "frontend", grade: "junior" }, + category: { specialization: "frontend", grade: "junior", basis: "synthetic_demo" }, strength: "standard", public_context: { stack: null, @@ -184,7 +184,11 @@ describe("match response adapter", () => { if (!backend || !near || !network) throw new Error("Fixture match cards are missing."); expect(backend.candidateHandle).toBe(network.candidateHandle); - expect(backend.category).toEqual({ specialization: "backend", grade: "middle" }); + expect(backend.category).toEqual({ + specialization: "backend", + grade: "middle", + basis: "synthetic_demo", + }); expect(network.category).toBeNull(); expect(network.strength).toBeNull(); expect(network.components).toEqual({ fit: 0.51, coverage: 0.38 }); diff --git a/frontend/src/entities/match/model/card-presentation.ts b/frontend/src/entities/match/model/card-presentation.ts index 84e6d1f..b312078 100644 --- a/frontend/src/entities/match/model/card-presentation.ts +++ b/frontend/src/entities/match/model/card-presentation.ts @@ -5,12 +5,12 @@ import type { } from "../../../shared/api/schemas"; import type { TrustLevelValue } from "../../../shared/ui"; import { + confirmationLabel, experienceBandLabels, gradeLabels, salaryCompatibilityLabels, specializationLabels, stackLabels, - strengthLabels, workFormatLabels, } from "./labels"; @@ -40,7 +40,7 @@ export function presentCard(card: AnonymousCardContent): CardDetails { card.categories?.map((category) => ({ specialization: specializationLabels[category.specialization], grade: gradeLabels[category.grade], - strength: strengthLabels[category.strength], + strength: confirmationLabel(category.basis, category.strength), })) ?? null, selfAssessments: card.self_assessment?.map((item) => ({ diff --git a/frontend/src/entities/match/model/labels.ts b/frontend/src/entities/match/model/labels.ts index c05f25a..9bee6c7 100644 --- a/frontend/src/entities/match/model/labels.ts +++ b/frontend/src/entities/match/model/labels.ts @@ -1,6 +1,7 @@ import type { CandidateExperienceBand, CandidateSalaryCompatibility, + EvidenceBasis, GradeCode, MatchEvidenceCode, MatchEvidenceState, @@ -58,6 +59,16 @@ export const strengthLabels: Readonly> = { strong: "Сильное подтверждение", }; +/** + * Words for how a confirmed category was established. A demonstration basis is + * named as one, because it is not a measurement and never a standard + * confirmation; only a category with another basis gets its strength label. + */ +export function confirmationLabel(basis: EvidenceBasis, strength: MatchStrength): string { + if (basis === "synthetic_demo") return "Демонстрационное подтверждение"; + return strengthLabels[strength]; +} + export const stackLabels: Readonly> = { go: "Go", postgresql: "PostgreSQL", diff --git a/frontend/src/entities/match/model/match.fixtures.ts b/frontend/src/entities/match/model/match.fixtures.ts index fe6b35a..7643211 100644 --- a/frontend/src/entities/match/model/match.fixtures.ts +++ b/frontend/src/entities/match/model/match.fixtures.ts @@ -37,7 +37,7 @@ export function matchResponseFixture( specialization: "backend", confirmation_status: "confirmed", declared_grade: "senior", - category: { specialization: "backend", grade: "middle" }, + category: { specialization: "backend", grade: "middle", basis: "synthetic_demo" }, strength: "strong", public_context: { stack: ["go", "postgresql"], @@ -76,7 +76,7 @@ export function matchResponseFixture( specialization: "backend", confirmation_status: "confirmed", declared_grade: null, - category: { specialization: "backend", grade: "junior" }, + category: { specialization: "backend", grade: "junior", basis: "synthetic_demo" }, strength: "standard", public_context: { stack: null, diff --git a/frontend/src/entities/match/ui/match-card.tsx b/frontend/src/entities/match/ui/match-card.tsx index 0e20b77..3bc6d8d 100644 --- a/frontend/src/entities/match/ui/match-card.tsx +++ b/frontend/src/entities/match/ui/match-card.tsx @@ -6,9 +6,9 @@ import { experienceBandLabels, gradeLabels, salaryCompatibilityLabels, + confirmationLabel, specializationLabels, stackLabels, - strengthLabels, workFormatLabels, } from "../model/labels"; import { shortHandle } from "../model/views"; @@ -72,7 +72,7 @@ export function MatchCardView({ card, headingId, actions, children }: MatchCardV
Подтвержденная категория
{card.category && card.strength - ? `${specializationLabels[card.category.specialization]}, ${gradeLabels[card.category.grade]}. ${strengthLabels[card.strength]}` + ? `${specializationLabels[card.category.specialization]}, ${gradeLabels[card.category.grade]}. ${confirmationLabel(card.category.basis, card.strength)}` : "Нет"}
Заявленный кандидатом грейд
diff --git a/frontend/src/pages/candidate-home/ui/candidate-home-page.test.tsx b/frontend/src/pages/candidate-home/ui/candidate-home-page.test.tsx index 7f1ddf6..a0e2af0 100644 --- a/frontend/src/pages/candidate-home/ui/candidate-home-page.test.tsx +++ b/frontend/src/pages/candidate-home/ui/candidate-home-page.test.tsx @@ -59,6 +59,7 @@ function render(seed: Seed = {}): string { }); queryClient.setQueryData(candidateHomeQueryKeys.profile(accountId), { version: seed.profileVersion ?? 0, + confirmed_categories: [], }); queryClient.setQueryData(candidateHomeQueryKeys.questionnaire(accountId), { version: seed.declared ? 1 : 0, @@ -82,6 +83,7 @@ function render(seed: Seed = {}): string { { specialization: seed.declared.specialization, confirmed_grade: seed.confirmed ?? null, + confirmed_basis: seed.confirmed ? "synthetic_demo" : null, active_attempt_id: seed.activeAttempt ?? null, grades: [ { @@ -254,13 +256,14 @@ describe("candidate home", () => { expect(html).toContain("Пока не подтверждена"); }); - // Regression: the availability read had no confirmed grade while the newest - // result confirmed Junior. Every block must then state the same category. - it("states one confirmed category in every block when the availability read has none", () => { + // The availability read confirms the grade that the newest result also + // records. Every block must then state the same category. + it("states one confirmed category in every block from the availability read", () => { const html = render({ step: "candidate_consents", profileVersion: 1, declared: { specialization: "backend", grade: "junior" }, + confirmed: "junior", results: [ { attempt_id: attemptId, diff --git a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts index 923a7f1..d03a33e 100644 --- a/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts +++ b/frontend/src/shared/api/endpoints/assessment/assessment.msw.ts @@ -48,7 +48,7 @@ import type { } from '../../schemas'; -export const getGetMyAssessmentAvailabilityResponseMock = (overrideResponse: Partial> = {}): AssessmentAvailability => ({specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), active_attempt_id: faker.helpers.arrayElement([faker.string.uuid(), null]), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), status: faker.helpers.arrayElement(['available','active_attempt','cooldown','insufficient_bank'] as const), mode: faker.helpers.arrayElement([faker.helpers.arrayElement(['demo_basic','adaptive'] as const),null,]), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), time_limit_seconds: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), max_sessions: faker.helpers.arrayElement([faker.number.int({min: 1, max: 10}), null]), max_items: faker.helpers.arrayElement([faker.number.int({min: 1, max: 100}), null]), practice_required: faker.helpers.arrayElement([faker.datatype.boolean(), null])}))})), ...overrideResponse}) +export const getGetMyAssessmentAvailabilityResponseMock = (overrideResponse: Partial> = {}): AssessmentAvailability => ({specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), confirmed_basis: faker.helpers.arrayElement([faker.helpers.arrayElement(['synthetic_demo'] as const),null,]), active_attempt_id: faker.helpers.arrayElement([faker.string.uuid(), null]), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), status: faker.helpers.arrayElement(['available','active_attempt','cooldown','insufficient_bank'] as const), mode: faker.helpers.arrayElement([faker.helpers.arrayElement(['demo_basic','adaptive'] as const),null,]), available_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), time_limit_seconds: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), max_sessions: faker.helpers.arrayElement([faker.number.int({min: 1, max: 10}), null]), max_items: faker.helpers.arrayElement([faker.number.int({min: 1, max: 100}), null]), practice_required: faker.helpers.arrayElement([faker.datatype.boolean(), null])}))})), ...overrideResponse}) export const getListMyAssessmentResultsResponseAssessmentUncertaintyMock = (overrideResponse: Partial = {}): AssessmentUncertainty => ({...{theta: faker.number.float({fractionDigits: 2}), standard_error: faker.number.float({min: 0, fractionDigits: 2}), interval_95: {low: faker.number.float({fractionDigits: 2}), high: faker.number.float({fractionDigits: 2})}, p_grade: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, ...overrideResponse}); diff --git a/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts b/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts index 68541fb..63f222d 100644 --- a/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts +++ b/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts @@ -46,13 +46,13 @@ export const getGetMyProfileResponseProfileClaimSourceMock = (overrideResponse: export const getGetMyProfileResponseProfileSalaryMinimumMock = (overrideResponse: Partial = {}): ProfileSalaryMinimum => ({...{amount: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse}); -export const getGetMyProfileResponseMock = (overrideResponse: Partial> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience_overlaps: Array.from({ length: faker.number.int({min: 1, max: 190}) }, (_, i) => i + 1).map(() => ({first_index: faker.number.int({min: 0, max: 19}), second_index: faker.number.int({min: 1, max: 19}), status: faker.helpers.arrayElement(['needs_confirmation','confirmed'] as const)})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {location: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, relocation: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.datatype.boolean(), null]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, salary_minimum: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileSalaryMinimumMock()},null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}}, confirmed_categories: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), confirmed_at: faker.date.past().toISOString().slice(0, 19) + 'Z', attempt_id: faker.string.uuid()})), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) +export const getGetMyProfileResponseMock = (overrideResponse: Partial> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience_overlaps: Array.from({ length: faker.number.int({min: 1, max: 190}) }, (_, i) => i + 1).map(() => ({first_index: faker.number.int({min: 0, max: 19}), second_index: faker.number.int({min: 1, max: 19}), status: faker.helpers.arrayElement(['needs_confirmation','confirmed'] as const)})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {location: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, relocation: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.datatype.boolean(), null]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, salary_minimum: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileSalaryMinimumMock()},null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}}, confirmed_categories: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), basis: faker.helpers.arrayElement(['synthetic_demo'] as const), confirmed_at: faker.date.past().toISOString().slice(0, 19) + 'Z', attempt_id: faker.string.uuid()})), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) export const getSaveMyProfileResponseProfileClaimSourceMock = (overrideResponse: Partial = {}): ProfileClaimSource => ({...{origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}, ...overrideResponse}); export const getSaveMyProfileResponseProfileSalaryMinimumMock = (overrideResponse: Partial = {}): ProfileSalaryMinimum => ({...{amount: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse}); -export const getSaveMyProfileResponseMock = (overrideResponse: Partial> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience_overlaps: Array.from({ length: faker.number.int({min: 1, max: 190}) }, (_, i) => i + 1).map(() => ({first_index: faker.number.int({min: 0, max: 19}), second_index: faker.number.int({min: 1, max: 19}), status: faker.helpers.arrayElement(['needs_confirmation','confirmed'] as const)})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {location: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, relocation: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.datatype.boolean(), null]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, salary_minimum: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileSalaryMinimumMock()},null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}}, confirmed_categories: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), confirmed_at: faker.date.past().toISOString().slice(0, 19) + 'Z', attempt_id: faker.string.uuid()})), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) +export const getSaveMyProfileResponseMock = (overrideResponse: Partial> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience_overlaps: Array.from({ length: faker.number.int({min: 1, max: 190}) }, (_, i) => i + 1).map(() => ({first_index: faker.number.int({min: 0, max: 19}), second_index: faker.number.int({min: 1, max: 19}), status: faker.helpers.arrayElement(['needs_confirmation','confirmed'] as const)})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {location: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, relocation: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.datatype.boolean(), null]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, salary_minimum: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileSalaryMinimumMock()},null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}}, confirmed_categories: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), basis: faker.helpers.arrayElement(['synthetic_demo'] as const), confirmed_at: faker.date.past().toISOString().slice(0, 19) + 'Z', attempt_id: faker.string.uuid()})), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) export const getGetMyQuestionnaireMockHandler = (overrideResponse?: CandidateQuestionnaire | ((info: Parameters[1]>[0]) => Promise | CandidateQuestionnaire), options?: RequestHandlerOptions) => { diff --git a/frontend/src/shared/api/endpoints/organization/organization.msw.ts b/frontend/src/shared/api/endpoints/organization/organization.msw.ts index c43eb70..1e95183 100644 --- a/frontend/src/shared/api/endpoints/organization/organization.msw.ts +++ b/frontend/src/shared/api/endpoints/organization/organization.msw.ts @@ -47,7 +47,7 @@ export const getSearchOrganizationMatchesResponseMatchAppliedConditionsMock = (o export const getSearchOrganizationMatchesResponseMatchSearchBankSourceMock = (overrideResponse: Partial = {}): MatchSearchBankSource => ({...{kind: faker.helpers.arrayElement(['bank'] as const), filters: {specialization: faker.helpers.arrayElement([faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const),null,]), confirmed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), confirmed_category: faker.helpers.arrayElement([{...getSearchOrganizationMatchesResponseMatchGradeFilterMock()},null,]), confirmation_status: faker.helpers.arrayElement([faker.helpers.arrayElement(['confirmed','unconfirmed'] as const),null,]), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), conditions: faker.helpers.arrayElement([{...getSearchOrganizationMatchesResponseMatchAppliedConditionsMock()},null,])}}, ...overrideResponse}); -export const getSearchOrganizationMatchesResponseMock = (overrideResponse: Partial> = {}): MatchSearchResponse => ({source: faker.helpers.arrayElement([{...getSearchOrganizationMatchesResponseMatchSearchNeedSourceMock()},{...getSearchOrganizationMatchesResponseMatchSearchBankSourceMock()},]), groups: {main: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: {specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)}, strength: faker.helpers.arrayElement(['standard','strong'] as const), public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignment','task_alignment','work_conditions_match','salary_compatibility','declared_grade'] as const), state: faker.helpers.arrayElement(['supports','partial','gap','declared_only'] as const)})), components: {fit: faker.number.float({min: 0, max: 1, fractionDigits: 2}), coverage: faker.number.float({min: 0, max: 1, fractionDigits: 2}), domain: faker.number.float({min: 0, max: 1, fractionDigits: 2}), semantics: faker.number.float({min: 0, max: 1, fractionDigits: 2}), percentile: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}),null,]), competition: faker.number.float({min: 0, max: 1, fractionDigits: 2}), freshness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), responsiveness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), rank_score: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, unknown_flags: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({component: faker.helpers.arrayElement(['semantics','percentile','assessment','freshness','responsiveness','experience_band','work_formats','salary_compatibility','domain'] as const), reason: faker.helpers.arrayElement(['ml_unavailable','cohort_below_30','no_confirmation_for_specialization','not_in_public_card','need_field_unconfirmed','no_freshness_history','no_response_history','percentile_not_computed'] as const)}))})), near: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: {specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)}, strength: faker.helpers.arrayElement(['standard','strong'] as const), public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignment','task_alignment','work_conditions_match','salary_compatibility','declared_grade'] as const), state: faker.helpers.arrayElement(['supports','partial','gap','declared_only'] as const)})), components: {fit: faker.number.float({min: 0, max: 1, fractionDigits: 2}), coverage: faker.number.float({min: 0, max: 1, fractionDigits: 2}), domain: faker.number.float({min: 0, max: 1, fractionDigits: 2}), semantics: faker.number.float({min: 0, max: 1, fractionDigits: 2}), percentile: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}),null,]), competition: faker.number.float({min: 0, max: 1, fractionDigits: 2}), freshness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), responsiveness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), rank_score: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, unknown_flags: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({component: faker.helpers.arrayElement(['semantics','percentile','assessment','freshness','responsiveness','experience_band','work_formats','salary_compatibility','domain'] as const), reason: faker.helpers.arrayElement(['ml_unavailable','cohort_below_30','no_confirmation_for_specialization','not_in_public_card','need_field_unconfirmed','no_freshness_history','no_response_history','percentile_not_computed'] as const)}))})), unconfirmed: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: null, strength: null, public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignment','task_alignment','work_conditions_match','salary_compatibility','declared_grade'] as const), state: faker.helpers.arrayElement(['supports','partial','gap','declared_only'] as const)})), components: {fit: faker.number.float({min: 0, max: 1, fractionDigits: 2}), coverage: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, unknown_flags: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({component: faker.helpers.arrayElement(['semantics','percentile','assessment','freshness','responsiveness','experience_band','work_formats','salary_compatibility','domain'] as const), reason: faker.helpers.arrayElement(['ml_unavailable','cohort_below_30','no_confirmation_for_specialization','not_in_public_card','need_field_unconfirmed','no_freshness_history','no_response_history','percentile_not_computed'] as const)}))}))}, truncated: faker.datatype.boolean(), ...overrideResponse}) +export const getSearchOrganizationMatchesResponseMock = (overrideResponse: Partial> = {}): MatchSearchResponse => ({source: faker.helpers.arrayElement([{...getSearchOrganizationMatchesResponseMatchSearchNeedSourceMock()},{...getSearchOrganizationMatchesResponseMatchSearchBankSourceMock()},]), groups: {main: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: {specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), basis: faker.helpers.arrayElement(['synthetic_demo'] as const)}, strength: faker.helpers.arrayElement(['standard','strong'] as const), public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignment','task_alignment','work_conditions_match','salary_compatibility','declared_grade'] as const), state: faker.helpers.arrayElement(['supports','partial','gap','declared_only'] as const)})), components: {fit: faker.number.float({min: 0, max: 1, fractionDigits: 2}), coverage: faker.number.float({min: 0, max: 1, fractionDigits: 2}), domain: faker.number.float({min: 0, max: 1, fractionDigits: 2}), semantics: faker.number.float({min: 0, max: 1, fractionDigits: 2}), percentile: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}),null,]), competition: faker.number.float({min: 0, max: 1, fractionDigits: 2}), freshness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), responsiveness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), rank_score: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, unknown_flags: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({component: faker.helpers.arrayElement(['semantics','percentile','assessment','freshness','responsiveness','experience_band','work_formats','salary_compatibility','domain'] as const), reason: faker.helpers.arrayElement(['ml_unavailable','cohort_below_30','no_confirmation_for_specialization','not_in_public_card','need_field_unconfirmed','no_freshness_history','no_response_history','percentile_not_computed'] as const)}))})), near: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: {specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), basis: faker.helpers.arrayElement(['synthetic_demo'] as const)}, strength: faker.helpers.arrayElement(['standard','strong'] as const), public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignment','task_alignment','work_conditions_match','salary_compatibility','declared_grade'] as const), state: faker.helpers.arrayElement(['supports','partial','gap','declared_only'] as const)})), components: {fit: faker.number.float({min: 0, max: 1, fractionDigits: 2}), coverage: faker.number.float({min: 0, max: 1, fractionDigits: 2}), domain: faker.number.float({min: 0, max: 1, fractionDigits: 2}), semantics: faker.number.float({min: 0, max: 1, fractionDigits: 2}), percentile: faker.helpers.arrayElement([faker.number.float({min: 0, max: 1, fractionDigits: 2}),null,]), competition: faker.number.float({min: 0, max: 1, fractionDigits: 2}), freshness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), responsiveness: faker.number.float({min: 0, max: 1, fractionDigits: 2}), rank_score: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, unknown_flags: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({component: faker.helpers.arrayElement(['semantics','percentile','assessment','freshness','responsiveness','experience_band','work_formats','salary_compatibility','domain'] as const), reason: faker.helpers.arrayElement(['ml_unavailable','cohort_below_30','no_confirmation_for_specialization','not_in_public_card','need_field_unconfirmed','no_freshness_history','no_response_history','percentile_not_computed'] as const)}))})), unconfirmed: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), category: null, strength: null, public_context: {stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const),null,]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const),null,]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, evidence_summary: Array.from({ length: faker.number.int({min: 1, max: 12}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(['confirmed_category','required_skill_evidence','desired_skill_evidence','domain_alignment','task_alignment','work_conditions_match','salary_compatibility','declared_grade'] as const), state: faker.helpers.arrayElement(['supports','partial','gap','declared_only'] as const)})), components: {fit: faker.number.float({min: 0, max: 1, fractionDigits: 2}), coverage: faker.number.float({min: 0, max: 1, fractionDigits: 2})}, unknown_flags: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({component: faker.helpers.arrayElement(['semantics','percentile','assessment','freshness','responsiveness','experience_band','work_formats','salary_compatibility','domain'] as const), reason: faker.helpers.arrayElement(['ml_unavailable','cohort_below_30','no_confirmation_for_specialization','not_in_public_card','need_field_unconfirmed','no_freshness_history','no_response_history','percentile_not_computed'] as const)}))}))}, truncated: faker.datatype.boolean(), ...overrideResponse}) export const getListMyOrganizationsMockHandler = (overrideResponse?: MyOrganizationList | ((info: Parameters[1]>[0]) => Promise | MyOrganizationList), options?: RequestHandlerOptions) => { diff --git a/frontend/src/shared/api/endpoints/privacy/privacy.msw.ts b/frontend/src/shared/api/endpoints/privacy/privacy.msw.ts index 30bfb12..64ecb3e 100644 --- a/frontend/src/shared/api/endpoints/privacy/privacy.msw.ts +++ b/frontend/src/shared/api/endpoints/privacy/privacy.msw.ts @@ -35,13 +35,13 @@ import type { } from '../../schemas'; -export const getGetOrganizationCandidateCardResponseMock = (overrideResponse: Partial> = {}): AnonymousCardContent => ({pseudonym: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), strength: faker.helpers.arrayElement(['standard','strong'] as const)})), null]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const), null]), self_assessment: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed','unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,])})), null]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,]), ...overrideResponse}) +export const getGetOrganizationCandidateCardResponseMock = (overrideResponse: Partial> = {}): AnonymousCardContent => ({pseudonym: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), strength: faker.helpers.arrayElement(['standard','strong'] as const), basis: faker.helpers.arrayElement(['synthetic_demo'] as const)})), null]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const), null]), self_assessment: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed','unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,])})), null]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,]), ...overrideResponse}) export const getGetMyPrivacySettingsResponseMock = (overrideResponse: Partial> = {}): PrivacySettings => ({publication: {state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, search_status: {value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, hidden_organizations_total: faker.number.int({min: 0, max: 1000}), ...overrideResponse}) export const getSetMyPublicationResponseMock = (overrideResponse: Partial> = {}): Publication => ({state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse}) -export const getGetMyCardPreviewResponseAnonymousCardContentMock = (overrideResponse: Partial = {}): AnonymousCardContent => ({...{pseudonym: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), strength: faker.helpers.arrayElement(['standard','strong'] as const)})), null]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const), null]), self_assessment: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed','unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,])})), null]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, ...overrideResponse}); +export const getGetMyCardPreviewResponseAnonymousCardContentMock = (overrideResponse: Partial = {}): AnonymousCardContent => ({...{pseudonym: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), strength: faker.helpers.arrayElement(['standard','strong'] as const), basis: faker.helpers.arrayElement(['synthetic_demo'] as const)})), null]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const), null]), self_assessment: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed','unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,])})), null]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, ...overrideResponse}); export const getGetMyCardPreviewResponseOrganizationEvidenceMock = (overrideResponse: Partial = {}): OrganizationEvidence => ({...{items: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({skill: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa','go','postgresql','kafka','docker'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), trust: faker.number.int({min: 0, max: 3}), basis: faker.helpers.arrayElement(['synthetic_demo'] as const), calibration_status: faker.helpers.arrayElement(['uncalibrated'] as const), observed_year: faker.number.int({min: 2000, max: 9999})}))}, ...overrideResponse}); diff --git a/frontend/src/shared/api/privacy-contract.test.ts b/frontend/src/shared/api/privacy-contract.test.ts index bbef9a7..9739c2e 100644 --- a/frontend/src/shared/api/privacy-contract.test.ts +++ b/frontend/src/shared/api/privacy-contract.test.ts @@ -214,7 +214,9 @@ describe("generated HiddenOrganization", () => { describe("generated AnonymousCardContent", () => { const card = { pseudonym: `cv1_${"a".repeat(43)}`, - categories: [{ specialization: "backend", grade: "middle", strength: "standard" }], + categories: [ + { specialization: "backend", grade: "middle", strength: "standard", basis: "synthetic_demo" }, + ], stack: ["postgresql", "kafka"], self_assessment: [ { diff --git a/frontend/src/shared/api/profile-contract.test.ts b/frontend/src/shared/api/profile-contract.test.ts index 67236cc..693e4e7 100644 --- a/frontend/src/shared/api/profile-contract.test.ts +++ b/frontend/src/shared/api/profile-contract.test.ts @@ -113,6 +113,7 @@ const profile = { { specialization: "backend", grade: "junior", + basis: "synthetic_demo", confirmed_at: "2026-10-04T18:10:00Z", attempt_id: "0192b3c4-d5e6-7f80-9a1b-2c3d4e5f6a7b", }, @@ -326,6 +327,16 @@ describe("generated CandidateProfile", () => { expect(ProfileConfirmedCategory.safeParse(profile.confirmed_categories[0]).success).toBe(true); expect(ProfileConfirmedCategory.safeParse(withoutAttempt).success).toBe(false); }); + + it("requires a confirmed category to state its basis, so a demonstration never reads as a measurement", () => { + const withoutBasis = without(profile.confirmed_categories[0] ?? {}, "basis"); + + expect(ProfileConfirmedCategory.safeParse(withoutBasis).success).toBe(false); + expect( + ProfileConfirmedCategory.safeParse({ ...profile.confirmed_categories[0], basis: "measured" }) + .success, + ).toBe(false); + }); }); it("exposes the profile DTOs without a confirmed grade or a category in requests", () => { diff --git a/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts index 598c659..00e129b 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentAvailability.zod.ts @@ -20,6 +20,7 @@ export const AssessmentAvailability = zod.object({ "specializations": zod.array(zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Currently confirmed grade of the specialization, or null.'), + "confirmed_basis": zod.union([zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'),zod.null()]).describe('What the confirmed grade rests on, or null exactly when `confirmed_grade` is null. `synthetic_demo` marks a demonstration category, which is not a validated measurement and must not be shown as a real confirmation.'), "active_attempt_id": zod.uuid().nullable().describe('Identifier of the active attempt of the specialization, or null.'), "grades": zod.array(zod.object({ "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), diff --git a/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts b/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts index e06009b..0d7bdba 100644 --- a/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts +++ b/frontend/src/shared/api/schemas/assessment/assessmentSpecializationAvailability.zod.ts @@ -17,6 +17,7 @@ export const assessmentSpecializationAvailabilityGradesMax = 10; export const AssessmentSpecializationAvailability = zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "confirmed_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Currently confirmed grade of the specialization, or null.'), + "confirmed_basis": zod.union([zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'),zod.null()]).describe('What the confirmed grade rests on, or null exactly when `confirmed_grade` is null. `synthetic_demo` marks a demonstration category, which is not a validated measurement and must not be shown as a real confirmation.'), "active_attempt_id": zod.uuid().nullable().describe('Identifier of the active attempt of the specialization, or null.'), "grades": zod.array(zod.object({ "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), diff --git a/frontend/src/shared/api/schemas/candidate/candidateProfile.zod.ts b/frontend/src/shared/api/schemas/candidate/candidateProfile.zod.ts index 0a591c5..cf40f92 100644 --- a/frontend/src/shared/api/schemas/candidate/candidateProfile.zod.ts +++ b/frontend/src/shared/api/schemas/candidate/candidateProfile.zod.ts @@ -319,9 +319,10 @@ export const CandidateProfile = zod.object({ "confirmed_categories": zod.array(zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'), "confirmed_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "attempt_id": zod.uuid().describe('Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate.') -}).describe('A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`.')).max(candidateProfileConfirmedCategoriesMax).describe('Categories that assessment results confirmed, at most one per specialization, in catalog order. Read-only and empty until an assessment confirms a grade.'), +}).describe('A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category that is not a validated measurement.')).max(candidateProfileConfirmedCategoriesMax).describe('Categories that assessment results confirmed, at most one per specialization, in catalog order. Read-only and empty until an assessment confirms a grade.'), "updated_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the last change, or null before the first save.') }).describe('The private profile of the current candidate: full name and contacts, stack, roles, work experience, soft skills, and desired terms, each value with its confirmation state and provenance. It is personal data that only the candidate reads. It is never an organization-visible schema: an organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant, and no organization schema refers to this one.\nEvery value is a claim of trust level 0. The `self_assessed_grade` of a role is what the candidate says; the `confirmed_categories` list is what assessment results established, and the two are never mixed. A candidate who has not saved the profile gets version 0, every single field `unknown`, empty lists, and null `updated_at`.\nThe profile is manual by nature and complete without a file: no field requires a resume, the ML service, or an FSP account, and a candidate with none of them has the same fields. Work formats live in the questionnaire; a candidate\'s assessment starts from the questionnaire, not from this profile.') diff --git a/frontend/src/shared/api/schemas/candidate/profileConfirmedCategory.zod.ts b/frontend/src/shared/api/schemas/candidate/profileConfirmedCategory.zod.ts index b64315e..95e16b5 100644 --- a/frontend/src/shared/api/schemas/candidate/profileConfirmedCategory.zod.ts +++ b/frontend/src/shared/api/schemas/candidate/profileConfirmedCategory.zod.ts @@ -9,9 +9,10 @@ import * as zod from 'zod'; export const ProfileConfirmedCategory = zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.'), "confirmed_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "attempt_id": zod.uuid().describe('Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate.') -}).describe('A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`.') +}).describe('A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category that is not a validated measurement.') export type ProfileConfirmedCategory = zod.input; export type ProfileConfirmedCategoryOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/organization/matchCategory.zod.ts b/frontend/src/shared/api/schemas/organization/matchCategory.zod.ts index 078ee24..bcd2bce 100644 --- a/frontend/src/shared/api/schemas/organization/matchCategory.zod.ts +++ b/frontend/src/shared/api/schemas/organization/matchCategory.zod.ts @@ -8,8 +8,9 @@ import * as zod from 'zod'; export const MatchCategory = zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), - "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.') -}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization.') + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.') +}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation.') export type MatchCategory = zod.input; export type MatchCategoryOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/organization/matchConfirmedCandidate.zod.ts b/frontend/src/shared/api/schemas/organization/matchConfirmedCandidate.zod.ts index ded2613..46aae9f 100644 --- a/frontend/src/shared/api/schemas/organization/matchConfirmedCandidate.zod.ts +++ b/frontend/src/shared/api/schemas/organization/matchConfirmedCandidate.zod.ts @@ -54,8 +54,9 @@ export const MatchConfirmedCandidate = zod.object({ "declared_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Candidate-declared grade for this specialization, never a confirmation.'), "category": zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), - "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.') -}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.') +}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation.'), "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of a confirmed assessment for this specialization.'), "public_context": zod.object({ "stack": zod.union([zod.array(zod.enum(['go', 'postgresql', 'kafka', 'docker']).describe('A stack code that the anonymous card may expose. Search filters do not accept arbitrary profile text or candidate-provided evidence.')).max(matchConfirmedCandidatePublicContextStackOneMax),zod.null()]), diff --git a/frontend/src/shared/api/schemas/organization/matchSearchGroups.zod.ts b/frontend/src/shared/api/schemas/organization/matchSearchGroups.zod.ts index 0d806c6..a8176a5 100644 --- a/frontend/src/shared/api/schemas/organization/matchSearchGroups.zod.ts +++ b/frontend/src/shared/api/schemas/organization/matchSearchGroups.zod.ts @@ -114,8 +114,9 @@ export const MatchSearchGroups = zod.object({ "declared_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Candidate-declared grade for this specialization, never a confirmation.'), "category": zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), - "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.') -}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.') +}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation.'), "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of a confirmed assessment for this specialization.'), "public_context": zod.object({ "stack": zod.union([zod.array(zod.enum(['go', 'postgresql', 'kafka', 'docker']).describe('A stack code that the anonymous card may expose. Search filters do not accept arbitrary profile text or candidate-provided evidence.')).max(matchSearchGroupsMainItemPublicContextStackOneMax),zod.null()]), @@ -150,8 +151,9 @@ export const MatchSearchGroups = zod.object({ "declared_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Candidate-declared grade for this specialization, never a confirmation.'), "category": zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), - "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.') -}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.') +}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation.'), "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of a confirmed assessment for this specialization.'), "public_context": zod.object({ "stack": zod.union([zod.array(zod.enum(['go', 'postgresql', 'kafka', 'docker']).describe('A stack code that the anonymous card may expose. Search filters do not accept arbitrary profile text or candidate-provided evidence.')).max(matchSearchGroupsNearItemPublicContextStackOneMax),zod.null()]), diff --git a/frontend/src/shared/api/schemas/organization/matchSearchResponse.zod.ts b/frontend/src/shared/api/schemas/organization/matchSearchResponse.zod.ts index 5b48d43..3e10c7c 100644 --- a/frontend/src/shared/api/schemas/organization/matchSearchResponse.zod.ts +++ b/frontend/src/shared/api/schemas/organization/matchSearchResponse.zod.ts @@ -142,8 +142,9 @@ export const MatchSearchResponse = zod.object({ "declared_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Candidate-declared grade for this specialization, never a confirmation.'), "category": zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), - "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.') -}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.') +}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation.'), "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of a confirmed assessment for this specialization.'), "public_context": zod.object({ "stack": zod.union([zod.array(zod.enum(['go', 'postgresql', 'kafka', 'docker']).describe('A stack code that the anonymous card may expose. Search filters do not accept arbitrary profile text or candidate-provided evidence.')).max(matchSearchResponseGroupsMainItemPublicContextStackOneMax),zod.null()]), @@ -178,8 +179,9 @@ export const MatchSearchResponse = zod.object({ "declared_grade": zod.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Candidate-declared grade for this specialization, never a confirmation.'), "category": zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), - "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.') -}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.') +}).describe('A confirmed category. Its specialization must equal the enclosing match entry\'s specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation.'), "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of a confirmed assessment for this specialization.'), "public_context": zod.object({ "stack": zod.union([zod.array(zod.enum(['go', 'postgresql', 'kafka', 'docker']).describe('A stack code that the anonymous card may expose. Search filters do not accept arbitrary profile text or candidate-provided evidence.')).max(matchSearchResponseGroupsNearItemPublicContextStackOneMax),zod.null()]), diff --git a/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts b/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts index 3d978c8..54ffea1 100644 --- a/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts +++ b/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts @@ -25,8 +25,9 @@ export const AnonymousCardContent = zod.object({ "categories": zod.array(zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), - "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of the authoritative confirmation.') -}).describe('A category confirmed by assessment results, as the card shows it.')).max(anonymousCardContentCategoriesMax).nullable().describe('Categories confirmed by assessment results, or null.'), + "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of the authoritative confirmation.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.') +}).describe('A category confirmed by assessment results, as the card shows it. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which is never a standard confirmation.')).max(anonymousCardContentCategoriesMax).nullable().describe('Categories confirmed by assessment results, or null.'), "stack": zod.array(zod.enum(['go', 'postgresql', 'kafka', 'docker'])).max(anonymousCardContentStackMax).nullable().describe('Recognized confirmed technology codes only, or null.'), "self_assessment": zod.array(zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), diff --git a/frontend/src/shared/api/schemas/privacy/cardCategory.zod.ts b/frontend/src/shared/api/schemas/privacy/cardCategory.zod.ts index ba5f311..0af5829 100644 --- a/frontend/src/shared/api/schemas/privacy/cardCategory.zod.ts +++ b/frontend/src/shared/api/schemas/privacy/cardCategory.zod.ts @@ -9,8 +9,9 @@ import * as zod from 'zod'; export const CardCategory = zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), - "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of the authoritative confirmation.') -}).describe('A category confirmed by assessment results, as the card shows it.') + "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of the authoritative confirmation.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.') +}).describe('A category confirmed by assessment results, as the card shows it. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which is never a standard confirmation.') export type CardCategory = zod.input; export type CardCategoryOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts b/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts index 5d226e8..bf370b2 100644 --- a/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts +++ b/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts @@ -39,8 +39,9 @@ export const CardPreview = zod.object({ "categories": zod.array(zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'), - "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of the authoritative confirmation.') -}).describe('A category confirmed by assessment results, as the card shows it.')).max(cardPreviewCardOneCategoriesMax).nullable().describe('Categories confirmed by assessment results, or null.'), + "strength": zod.enum(['standard', 'strong']).describe('Coarse strength of the authoritative confirmation.'), + "basis": zod.enum(['synthetic_demo']).describe('What the measurement rests on.\n\n- synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.') +}).describe('A category confirmed by assessment results, as the card shows it. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which is never a standard confirmation.')).max(cardPreviewCardOneCategoriesMax).nullable().describe('Categories confirmed by assessment results, or null.'), "stack": zod.array(zod.enum(['go', 'postgresql', 'kafka', 'docker'])).max(cardPreviewCardOneStackMax).nullable().describe('Recognized confirmed technology codes only, or null.'), "self_assessment": zod.array(zod.object({ "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), diff --git a/frontend/src/widgets/match-list/ui/match-list.test.tsx b/frontend/src/widgets/match-list/ui/match-list.test.tsx index fc2080c..139c88f 100644 --- a/frontend/src/widgets/match-list/ui/match-list.test.tsx +++ b/frontend/src/widgets/match-list/ui/match-list.test.tsx @@ -47,7 +47,7 @@ describe("match list", () => { expect(html).toContain("Подтвержденная категория"); expect(html).toContain("Заявленный кандидатом грейд"); expect(html).toContain("Грейд подтвержден: Middle"); - expect(html).toContain("Backend, Middle. Сильное подтверждение"); + expect(html).toContain("Backend, Middle. Демонстрационное подтверждение"); }); it("offers a specialization switch when the result holds several specializations", () => {