diff --git a/api/README.en.md b/api/README.en.md index f5e59da..920b6f4 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -34,7 +34,7 @@ Every error is an RFC 9457 problem with the `application/problem+json` media typ | `method_not_allowed` | 405 | Unsupported method; see `Allow` | | `idempotency_in_progress` | 409 | A request with the same Idempotency-Key is still running | | `state_conflict` | 409 | The operation is not allowed in the current state of the resource | -| `version_conflict` | 412 | If-Match does not match the current version | +| `version_conflict` | 412 | If-Match, or a body `expected_version`, does not match the current version | | `payload_too_large` | 413 | The body exceeds the operation limit | | `unsupported_media_type` | 415 | The request Content-Type is not accepted | | `idempotency_key_reused` | 422 | The Idempotency-Key was used with a different request | @@ -73,7 +73,7 @@ Because the replay check comes before If-Match, a retry of a completed change re ### Versions: ETag and If-Match -A response with a versioned resource returns a strong `ETag`, for example `"v7"`. An operation that changes such a resource says in its description that it requires `If-Match` with that value. A missing value returns 428 `precondition_required`; a value that does not equal the current ETag returns 412 `version_conflict` and changes nothing. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. Weak tags, lists, and `*` fail validation with 400. +A response with a versioned resource returns a strong `ETag`, for example `"v7"`. An operation that changes such a resource says in its description that it requires `If-Match` with that value. A missing value returns 428 `precondition_required`; a value that does not equal the current ETag returns 412 `version_conflict` and changes nothing. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. Weak tags, lists, and `*` fail validation with 400. The questionnaire carries its version as `expected_version` in the body instead; see Catalog and questionnaire below. ### Pagination @@ -135,6 +135,34 @@ How the generated server (ogen v1.24.0) evaluates the schemes, and the mapping p - Any other handler error stops evaluation and reaches `NewError` as a `SecurityError` whose `Security` is `SessionCookie` or `SessionCsrf`. An unsatisfied requirement reaches `NewError` as a `SecurityError` with `ErrSecurityRequirementIsNotSatisfied` and no `Security` field. - Planned mapping: `HandleSessionCookie` skips a missing or invalid session; `HandleSessionCsrf` skips when the context has no principal (401) and returns a typed error for a wrong token. `NewError` maps a `SessionCsrf` error and an unsatisfied requirement with a principal in the context to 403 `csrf_check_failed`, and every other security failure to 401 `unauthenticated`. A 401 from `Logout` also clears the cookie. +### Catalog and questionnaire + +The `catalog` and `candidate` tags cover the specialization catalog and the candidate questionnaire (PRD FR03). The operations are in the contract; their business logic is not implemented yet, so the catalog answers 501 `not_implemented` and the questionnaire answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). + +| Method and path | operationId | Security | Success | Specific errors | +| --- | --- | --- | --- | --- | +| `GET /api/v1/specializations` | `GetSpecializationCatalog` | public | 200 `SpecializationCatalog` | none | +| `GET /api/v1/me/questionnaire` | `GetMyQuestionnaire` | session | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | +| `PUT /api/v1/me/questionnaire` | `SaveMyQuestionnaire` | session and CSRF | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 412 `version_conflict` | + +Every operation also declares the `default` problem response. + +Catalog: + +- Five directions and nine specializations: Development (`backend`, `frontend`, `mobile`), Infrastructure (`network_engineer`, `devops_sre`), Data (`data_analyst`, `ds_ml`), Security (`information_security`), Quality (`qa`). The MVP grade scale is `intern`, `junior`, `middle`, `senior`; Lead and Architect come after the MVP. The codes are enums, so adding a value is a contract change. Titles are Russian plain text. +- A category is a specialization together with a confirmed grade. Task languages (`python`, `go`) and stack tags are attributes of a chosen specialization and never form a category: Backend with Go is the category `backend`. Algorithms is a shared assessment module, not a specialization. +- Each specialization has `test_availability`: `status` (`available` or `in_development`), the `grades` with a published task bank, and the `task_languages` that bank offers. The MVP opens an assessment only for a category with a published bank. The server derives the values from the published banks, so they change without a contract change; the example in the contract is illustrative and says nothing about a deployed bank. +- The catalog is public (`security: []`): it is the same for every caller, contains no personal data, is shown before registration, and can be cached. + +Questionnaire: + +- The candidate comes from the session; an employer account answers 403 `forbidden`. A candidate without a saved questionnaire gets 200 with `version: 0`, no specializations, and null `work_context` and `updated_at` rather than 404, so the first save reads the version the same way as later ones. +- Each chosen specialization has `self_assessed_grade`, `task_languages`, `stack`, and `experience` in months or null when not stated; `work_context` holds only the acceptable work formats and no personal data. The questionnaire never contains a confirmed grade or a category, and unknown fields such as `confirmed_grade` answer 400. The self-assessed grade is the expected grade that the `candidate_assessment` onboarding step offers first; it influences where the assessment starts but adds no points, and no self-assessed grade or stack tag such as "Senior" assigns a category. A real profile stays invisible to employers until an assessment confirms a category. +- The schema allows one or two specializations on save and rejects an unknown specialization, grade, task language, or work format. JSON Schema `uniqueItems` cannot compare array items by one field, so the server rejects a repeated specialization with 400 and the pointer `/specializations//specialization`. It also rejects a task language that the specialization's published bank does not offer, with the pointer of that language. A specialization whose test is `in_development` can be chosen; no assessment starts for it. +- Concurrency uses `expected_version` in the body instead of If-Match, because the generated client cannot read the `ETag` header yet. The first save sends 0. A stale value answers 412 `version_conflict`, the same status and code as a failed If-Match, because the client does the same thing: it reads the questionnaire again. `version_conflict` keeps its 412 status, so `state_conflict` (409) is not used here. +- PUT replaces the whole questionnaire and needs no Idempotency-Key. A body equal to the stored state changes nothing, keeps the version, and answers 200 even with an older `expected_version`, so a retry after a lost response does not fail with 412. +- Order of checks for a save: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), domain rules (400), version (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server. + ### Generator checks `testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core. @@ -159,6 +187,7 @@ Known generator limitations: - ogen writes the header name in its canonical Go form (`Etag`); HTTP header names are case-insensitive. - ogen requires a `SecurityHandler` as soon as the contract has security schemes and evaluates the schemes in the order of their generated type names, so renaming a scheme can change the order; `TestGeneratedServerSecurityOrder` fails if it does. Security failures reach `NewError` without a response header, so clearing the cookie on a 401 from `Logout` needs handwritten code. - Orval does not expose security scheme values as typed arguments, so `X-CSRF-Token` is not a generated parameter; the shared API client is planned to attach it to mutating requests. Orval also generates no type for `Set-Cookie`, which the browser handles. +- Orval Zod schemas ignore `uniqueItems` and do not reject unknown fields of `additionalProperties: false` objects; the server stays authoritative for both. - Orval clears `src/shared/api/endpoints/` and `src/shared/api/schemas/` before generation (`clean: true`), because a schema used by several tags moves from a tag directory to the schema root. See the [development guide](../docs/en/DEVELOPMENT.md). diff --git a/api/README.md b/api/README.md index 5c7e396..73b5b36 100644 --- a/api/README.md +++ b/api/README.md @@ -34,7 +34,7 @@ | `method_not_allowed` | 405 | Метод не поддерживается; см. `Allow` | | `idempotency_in_progress` | 409 | Запрос с тем же Idempotency-Key еще выполняется | | `state_conflict` | 409 | Операция недопустима в текущем состоянии ресурса | -| `version_conflict` | 412 | If-Match не совпадает с текущей версией | +| `version_conflict` | 412 | If-Match или `expected_version` в теле не совпадает с текущей версией | | `payload_too_large` | 413 | Тело превышает лимит операции | | `unsupported_media_type` | 415 | Content-Type запроса не принимается | | `idempotency_key_reused` | 422 | Idempotency-Key уже использован с другим запросом | @@ -73,7 +73,7 @@ ### Версии: ETag и If-Match -Ответ с версионируемым ресурсом возвращает сильный `ETag`, например `"v7"`. Операция, изменяющая такой ресурс, указывает в описании, что требует `If-Match` с этим значением. Отсутствующее значение дает 428 `precondition_required`; значение, не равное текущему ETag, дает 412 `version_conflict` без изменений. В схеме параметр необязательный, чтобы отсутствие заголовка доходило до приложения, которое отвечает 428. Слабые теги, списки и `*` не проходят валидацию и дают 400. +Ответ с версионируемым ресурсом возвращает сильный `ETag`, например `"v7"`. Операция, изменяющая такой ресурс, указывает в описании, что требует `If-Match` с этим значением. Отсутствующее значение дает 428 `precondition_required`; значение, не равное текущему ETag, дает 412 `version_conflict` без изменений. В схеме параметр необязательный, чтобы отсутствие заголовка доходило до приложения, которое отвечает 428. Слабые теги, списки и `*` не проходят валидацию и дают 400. Анкета вместо этого передает версию в теле как `expected_version`; см. раздел "Каталог и анкета" ниже. ### Пагинация @@ -135,6 +135,34 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`. - Запланированное отображение: `HandleSessionCookie` пропускает отсутствующую или недействительную сессию; `HandleSessionCsrf` пропускает проверку, если в контексте нет principal (401), и возвращает типизированную ошибку при неверном токене. `NewError` отображает ошибку `SessionCsrf` и невыполненное требование с principal в контексте в 403 `csrf_check_failed`, а любой другой сбой защиты - в 401 `unauthenticated`. 401 от `Logout` также удаляет cookie. +### Каталог и анкета + +Теги `catalog` и `candidate` описывают каталог специализаций и анкету кандидата (FR03 в PRD). Операции есть в контракте, бизнес-логика еще не реализована: каталог отвечает 501 `not_implemented`, а анкета - 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`). + +| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | +| --- | --- | --- | --- | --- | +| `GET /api/v1/specializations` | `GetSpecializationCatalog` | публичная | 200 `SpecializationCatalog` | нет | +| `GET /api/v1/me/questionnaire` | `GetMyQuestionnaire` | сессия | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` | +| `PUT /api/v1/me/questionnaire` | `SaveMyQuestionnaire` | сессия и CSRF | 200 `CandidateQuestionnaire`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 412 `version_conflict` | + +Каждая операция также объявляет problem-ответ `default`. + +Каталог: + +- Пять направлений и девять специализаций: Разработка (`backend`, `frontend`, `mobile`), Инфраструктура (`network_engineer`, `devops_sre`), Данные (`data_analyst`, `ds_ml`), Безопасность (`information_security`), Качество (`qa`). Шкала грейдов MVP: `intern`, `junior`, `middle`, `senior`; Lead и Architect появятся после MVP. Коды заданы перечислениями, поэтому новое значение - изменение контракта. Названия - русский простой текст. +- Категория - это специализация вместе с подтвержденным грейдом. Языки заданий (`python`, `go`) и теги стека - атрибуты выбранной специализации и никогда не образуют категорию: Backend с Go - это категория `backend`. Алгоритмы - общий модуль оценки, а не специализация. +- У каждой специализации есть `test_availability`: `status` (`available` или `in_development`), `grades` с опубликованным банком заданий и `task_languages`, которые этот банк предлагает. MVP открывает оценку только для категории с опубликованным банком. Сервер выводит значения из опубликованных банков, поэтому они меняются без изменения контракта; пример в контракте иллюстративный и ничего не говорит о развернутом банке. +- Каталог публичный (`security: []`): он одинаков для всех, не содержит персональных данных, показывается до регистрации и может кешироваться. + +Анкета: + +- Кандидат берется из сессии; аккаунт работодателя получает 403 `forbidden`. Кандидат без сохраненной анкеты получает 200 с `version: 0`, без специализаций и с null в `work_context` и `updated_at`, а не 404, поэтому первое сохранение читает версию так же, как последующие. +- У каждой выбранной специализации есть `self_assessed_grade`, `task_languages`, `stack` и `experience` в месяцах или null, если опыт не указан; `work_context` содержит только допустимые форматы работы и не содержит персональных данных. Анкета никогда не содержит подтвержденный грейд или категорию, а неизвестные поля, например `confirmed_grade`, дают 400. Самооценка - это ожидаемый грейд, который шаг онбординга `candidate_assessment` предлагает первым; она влияет на старт оценки, но не добавляет баллов, и ни самооценка, ни тег стека вроде "Senior" не присваивают категорию. Реальный профиль не виден работодателям, пока оценка не подтвердит категорию. +- При сохранении схема допускает одну или две специализации и отклоняет неизвестные специализацию, грейд, язык заданий или формат работы. JSON Schema `uniqueItems` не умеет сравнивать элементы массива по одному полю, поэтому повтор специализации отклоняет сервер: 400 с pointer `/specializations//specialization`. Сервер также отклоняет язык заданий, которого нет в опубликованном банке специализации, с pointer на этот язык. Специализацию с тестом `in_development` выбрать можно; оценка для нее не начинается. +- Конкурентные изменения контролирует `expected_version` в теле, а не If-Match, потому что сгенерированный клиент пока не читает заголовок `ETag`. Первое сохранение отправляет 0. Устаревшее значение дает 412 `version_conflict` - тот же статус и код, что при несовпадении If-Match, потому что действие клиента то же: прочитать анкету снова. `version_conflict` сохраняет статус 412, поэтому `state_conflict` (409) здесь не используется. +- PUT заменяет анкету целиком, и Idempotency-Key ему не нужен. Тело, равное сохраненному состоянию, ничего не меняет, сохраняет версию и дает 200 даже со старым `expected_version`, поэтому повтор после потерянного ответа не падает с 412. +- Порядок проверок при сохранении: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), доменные правила (400), версия (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер. + ### Проверки генераторов `testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core. @@ -159,6 +187,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - ogen записывает имя заголовка в канонической Go-форме (`Etag`); имена HTTP-заголовков не зависят от регистра. - ogen требует `SecurityHandler`, как только в контракте есть схемы защиты, и проверяет схемы в порядке имен их сгенерированных типов, поэтому переименование схемы может изменить порядок; тогда `TestGeneratedServerSecurityOrder` упадет. Сбои защиты попадают в `NewError` без заголовков ответа, поэтому удаление cookie при 401 от `Logout` требует ручного кода. - Orval не делает значения схем защиты типизированными аргументами, поэтому `X-CSRF-Token` не является сгенерированным параметром; его планируется добавлять к изменяющим запросам в общем API-клиенте. Тип для `Set-Cookie` Orval тоже не генерирует, этот заголовок обрабатывает браузер. +- Zod-схемы Orval игнорируют `uniqueItems` и не отклоняют неизвестные поля объектов с `additionalProperties: false`; в обоих случаях решает сервер. - Orval очищает `src/shared/api/endpoints/` и `src/shared/api/schemas/` перед генерацией (`clean: true`), потому что схема, используемая несколькими тегами, переезжает из каталога тега в корень схем. Подробнее: [разработка](../docs/ru/DEVELOPMENT.md). diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index 39ee1c9..36ded00 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -235,3 +235,193 @@ CandidateSession: onboarding_step: candidate_questionnaire created_at: "2026-10-05T09:30:00Z" csrf_token: Xk4pR9tV2mQ7wL1sN8bC5dF0gH3jZ6yA9eU2iO7rT4c +SpecializationCatalog: + summary: Illustrative MVP catalog with the Backend and Network Engineer banks published + description: >- + Illustrative values. The directions, specializations, and grades follow + the MVP scale; `test_availability` comes from the published task banks, + so the grades and languages shown here are not a statement about any + deployed bank. + value: + directions: + - code: development + title: Разработка + specializations: + - code: backend + title: Backend + test_availability: + status: available + grades: [intern, junior, middle, senior] + task_languages: [python, go] + note: null + - code: frontend + title: Frontend + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: mobile + title: Mobile + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: infrastructure + title: Инфраструктура + specializations: + - code: network_engineer + title: Сетевой инженер + test_availability: + status: available + grades: [junior, middle] + task_languages: [] + note: null + - code: devops_sre + title: DevOps/SRE + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: data + title: Данные + specializations: + - code: data_analyst + title: Аналитик данных + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: ds_ml + title: DS/ML + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: security + title: Безопасность + specializations: + - code: information_security + title: Информационная безопасность + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: quality + title: Качество + specializations: + - code: qa + title: QA + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + grades: + - code: intern + title: Стажер + - code: junior + title: Junior + - code: middle + title: Middle + - code: senior + title: Senior +NewCandidateQuestionnaire: + summary: A candidate who has not saved the questionnaire yet + value: + version: 0 + specializations: [] + work_context: null + updated_at: null +BackendGoAndNetworkEngineerQuestionnaire: + summary: Backend with Go and Network Engineer, two independent specializations + description: >- + Go is a task language of the `backend` specialization and PostgreSQL and + gRPC are stack tags; none of them is a category. The candidate has two + specializations, `backend` and `network_engineer`, each assessed + independently. The self-assessed grades are claims; no confirmed grade + appears. + value: + version: 3 + specializations: + - specialization: backend + self_assessed_grade: middle + task_languages: [go] + stack: [PostgreSQL, gRPC, Kafka] + experience: + commercial_months: 30 + academic_months: 12 + - specialization: network_engineer + self_assessed_grade: junior + task_languages: [] + stack: [Cisco IOS, BGP] + experience: null + work_context: + work_formats: [remote, hybrid] + updated_at: "2026-10-05T09:30:00Z" +BackendGoAndNetworkEngineerQuestionnaireUpdate: + summary: Save Backend with Go and Network Engineer over version 2 + value: + expected_version: 2 + specializations: + - specialization: backend + self_assessed_grade: middle + task_languages: [go] + stack: [PostgreSQL, gRPC, Kafka] + experience: + commercial_months: 30 + academic_months: 12 + - specialization: network_engineer + self_assessed_grade: junior + task_languages: [] + stack: [Cisco IOS, BGP] + experience: null + work_context: + work_formats: [remote, hybrid] +QuestionnaireTooManySpecializations: + summary: Three specializations were sent; at most two are allowed + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f + errors: + - in: body + pointer: /specializations + code: invalid + message: The value does not match the contract. +QuestionnaireUnknownGrade: + summary: A self-assessed grade outside the grade scale, such as lead + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 7d8e9f0a-1b2c-4d3e-9f4a-5b6c7d8e9f0a + errors: + - in: body + pointer: /specializations/0/self_assessed_grade + code: invalid + message: The value does not match the contract. +QuestionnaireRepeatedSpecialization: + summary: The same specialization was chosen twice + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 8e9f0a1b-2c3d-4e4f-8a5b-6c7d8e9f0a1b + errors: + - in: body + pointer: /specializations/1/specialization + code: invalid + message: The value does not match the contract. diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index 55d2d58..7e798cd 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -213,3 +213,51 @@ CsrfCheckFailed: examples: csrf_check_failed: $ref: ./examples.yml#/CsrfCheckFailed +CsrfCheckFailedOrForbidden: + description: >- + The request failed cross-site request protection, code + csrf_check_failed: the X-CSRF-Token header is missing or does not belong + to the session, or the Origin is not allowed. Or the account may not + perform the operation, code forbidden. Nothing was changed in either + case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + csrf_check_failed: + $ref: ./examples.yml#/CsrfCheckFailed + forbidden: + $ref: ./examples.yml#/Forbidden +QuestionnaireValidationFailed: + description: >- + The body does not match the contract or violates a questionnaire rule: + more than two specializations, an unknown specialization, grade, or task + language, an unknown field such as confirmed_grade, a repeated + specialization, or a task language that the specialization's published + bank does not offer; code validation_failed with body pointers. When the + decoder does not record the path of a nested field, the pointer is the + whole body. Nothing was changed. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + too_many_specializations: + $ref: ./examples.yml#/QuestionnaireTooManySpecializations + unknown_grade: + $ref: ./examples.yml#/QuestionnaireUnknownGrade + repeated_specialization: + $ref: ./examples.yml#/QuestionnaireRepeatedSpecialization +QuestionnaireVersionConflict: + description: >- + `expected_version` is not the current questionnaire version; code + version_conflict. Nothing was changed; read the questionnaire again + before retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/VersionConflict diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index a364207..2a692d5 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -23,6 +23,195 @@ PageInfo: maxLength: 512 pattern: ^[A-Za-z0-9_-]+$ description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. +DirectionCode: + type: string + description: 'Stable code of a professional direction, the group that a specialization belongs to. + + + - development: Development. + + - infrastructure: Infrastructure. + + - data: Data. + + - security: Security. + + - quality: Quality. + + + Adding a value is a contract change.' + enum: + - development + - infrastructure + - data + - security + - quality +SpecializationCode: + type: string + description: '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. + + + - backend: Backend (development). + + - frontend: Frontend (development). + + - mobile: Mobile (development). + + - network_engineer: Network Engineer (infrastructure). + + - devops_sre: DevOps/SRE (infrastructure). + + - data_analyst: Data Analyst (data). + + - ds_ml: DS/ML (data). + + - information_security: Information security (security). + + - qa: QA (quality). + + + Adding a value is a contract change; renaming or removing one is a breaking change.' + enum: + - backend + - frontend + - mobile + - network_engineer + - devops_sre + - data_analyst + - ds_ml + - information_security + - qa +GradeCode: + type: string + description: '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.' + enum: + - intern + - junior + - middle + - senior +TaskLanguage: + type: string + description: Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate's platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change. + enum: + - python + - go +TestAvailabilityStatus: + type: string + description: Whether an assessment can start for the specialization. `available` means that a published task bank exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no grade of the specialization has a published bank yet; the specialization can still be chosen in the questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the catalog or in demo data never means that a test is ready. + enum: + - available + - in_development +TestAvailability: + type: object + description: Assessment availability of a specialization, derived by the server from the published task banks at the time of the request. The MVP opens an assessment only for a category, a specialization and a grade, that has a published bank. `status` is `available` exactly when `grades` is not empty; for `in_development` both `grades` and `task_languages` are empty. + additionalProperties: false + required: + - status + - grades + - task_languages + - note + properties: + status: + $ref: '#/TestAvailabilityStatus' + grades: + type: array + maxItems: 10 + uniqueItems: true + description: Grades of the specialization with a published task bank, in ascending order. Only these categories can be assessed and confirmed. + items: + $ref: '#/GradeCode' + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: Task languages that the published bank offers for this specialization. Empty when the bank does not offer a choice of language, as for Network Engineer, or when no bank is published. The questionnaire accepts only these languages for the specialization. + items: + $ref: '#/TaskLanguage' + note: + type: + - string + - 'null' + minLength: 1 + maxLength: 300 + description: Short Russian note for the candidate, for example why the test is not available yet, or null. Plain text; the client shows it as text, never as HTML. +CatalogSpecialization: + type: object + description: Specialization in the catalog with its assessment availability. + additionalProperties: false + required: + - code + - title + - test_availability + properties: + code: + $ref: '#/SpecializationCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + test_availability: + $ref: '#/TestAvailability' +CatalogDirection: + type: object + description: Professional direction with its specializations. Each specialization belongs to exactly one direction. + additionalProperties: false + required: + - code + - title + - specializations + properties: + code: + $ref: '#/DirectionCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + specializations: + type: array + minItems: 1 + maxItems: 20 + description: Specializations of the direction in display order. + items: + $ref: '#/CatalogSpecialization' +CatalogGrade: + type: object + description: Grade of the scale with its display name. + additionalProperties: false + required: + - code + - title + properties: + code: + $ref: '#/GradeCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. +SpecializationCatalog: + type: object + description: Catalog of directions, specializations, and the grade scale that the questionnaire and the assessment use. The catalog is reference data and identical for every caller; it contains no personal data. + additionalProperties: false + required: + - directions + - grades + properties: + directions: + type: array + minItems: 1 + maxItems: 20 + description: Directions in display order. + items: + $ref: '#/CatalogDirection' + grades: + type: array + minItems: 1 + maxItems: 10 + description: Grade scale in ascending order. + items: + $ref: '#/CatalogGrade' HealthResponse: type: object additionalProperties: false @@ -68,7 +257,7 @@ OnboardingStep: - candidate_questionnaire: candidate questionnaire. - - candidate_assessment: choice of the expected grade and the assessment. + - candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. The first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step (planned). - employer_company: company profile of the employer. @@ -338,7 +527,7 @@ ProblemCode: - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. - - version_conflict (412): If-Match does not match the current version. + - version_conflict (412): If-Match, or an `expected_version` field in the request body, does not match the current version; nothing was changed. - payload_too_large (413): the request body exceeds the limit. @@ -411,3 +600,140 @@ ProblemFieldLocation: - path - header - cookie +QuestionnaireVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the candidate questionnaire. A candidate without a saved questionnaire has version 0; every save that changes the questionnaire advances it by one. + examples: + - 3 +StackTag: + type: string + minLength: 1 + maxLength: 50 + pattern: ^\S(?:.*\S)?$ + description: 'Free technology tag of the candidate''s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.' +WorkFormat: + type: string + description: 'Acceptable work format: `remote`, `office`, or `hybrid`.' + enum: + - remote + - office + - hybrid +WorkContext: + type: object + description: Working context of the candidate's search. It holds no personal data such as an address or a city; location, relocation, and salary expectations belong to the candidate profile. + additionalProperties: false + required: + - work_formats + properties: + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + description: Acceptable work formats. + items: + $ref: '#/WorkFormat' +CandidateExperience: + type: object + description: 'Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade.' + additionalProperties: false + required: + - commercial_months + - academic_months + properties: + commercial_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of commercial work in the specialization. + academic_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of study, internships, or academic projects in the specialization. +QuestionnaireSpecialization: + type: object + description: 'One specialization chosen by the candidate with the candidate''s self-assessment. `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed grade, and with it a category, comes only from an assessment result and is never part of the questionnaire; unknown fields such as `confirmed_grade` or `category` are rejected. Task languages and the stack are attributes of the chosen specialization, not categories.' + additionalProperties: false + required: + - specialization + - self_assessed_grade + - task_languages + - stack + - experience + properties: + specialization: + $ref: '#/SpecializationCode' + self_assessed_grade: + $ref: '#/GradeCode' + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: Task languages in which the candidate wants to solve assessment tasks of this specialization. Each value must be one of `test_availability.task_languages` of the specialization in the current catalog; any other value answers 400 validation_failed with a pointer to it. Empty when the bank offers no choice of language. + items: + $ref: '#/TaskLanguage' + stack: + type: array + maxItems: 20 + uniqueItems: true + description: Technology tags of the candidate in this specialization. + items: + $ref: '#/StackTag' + experience: + description: Stated experience, or null when the candidate did not state it. + oneOf: + - $ref: '#/CandidateExperience' + - type: 'null' +CandidateQuestionnaire: + type: object + description: 'Questionnaire of the current candidate: the chosen specializations with self-assessed grades and the working context. It never contains a confirmed grade or a category; those come only from assessment results. A candidate who has not saved the questionnaire yet gets version 0, no specializations, and null `work_context` and `updated_at`.' + additionalProperties: false + required: + - version + - specializations + - work_context + - updated_at + properties: + version: + $ref: '#/QuestionnaireVersion' + specializations: + type: array + maxItems: 2 + description: Chosen specializations in the order the candidate gave them, each specialization at most once. Each one is assessed independently. + items: + $ref: '#/QuestionnaireSpecialization' + work_context: + description: Working context, or null before the first save. + oneOf: + - $ref: '#/WorkContext' + - type: 'null' + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' +CandidateQuestionnaireUpdate: + type: object + description: Complete new state of the questionnaire. It replaces the stored specializations and working context as a whole. Unknown fields are rejected, so a request cannot set a confirmed grade or a category. + additionalProperties: false + required: + - expected_version + - specializations + - work_context + properties: + expected_version: + $ref: '#/QuestionnaireVersion' + specializations: + type: array + minItems: 1 + maxItems: 2 + description: One or two chosen specializations. The schema limits the count; the server also requires each specialization to appear at most once and answers a repeated one with 400 validation_failed and the pointer of the repeated item's `specialization`, for example `/specializations/1/specialization`. + items: + $ref: '#/QuestionnaireSpecialization' + work_context: + $ref: '#/WorkContext' diff --git a/api/core/components/schemas/catalog_schemas.yml b/api/core/components/schemas/catalog_schemas.yml new file mode 100644 index 0000000..62a54b3 --- /dev/null +++ b/api/core/components/schemas/catalog_schemas.yml @@ -0,0 +1,212 @@ +schemas: + DirectionCode: + type: string + description: |- + Stable code of a professional direction, the group that a specialization belongs to. + + - development: Development. + - infrastructure: Infrastructure. + - data: Data. + - security: Security. + - quality: Quality. + + Adding a value is a contract change. + enum: + - development + - infrastructure + - data + - security + - quality + SpecializationCode: + type: string + description: |- + 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. + + - backend: Backend (development). + - frontend: Frontend (development). + - mobile: Mobile (development). + - network_engineer: Network Engineer (infrastructure). + - devops_sre: DevOps/SRE (infrastructure). + - data_analyst: Data Analyst (data). + - ds_ml: DS/ML (data). + - information_security: Information security (security). + - qa: QA (quality). + + Adding a value is a contract change; renaming or removing one is a breaking change. + enum: + - backend + - frontend + - mobile + - network_engineer + - devops_sre + - data_analyst + - ds_ml + - information_security + - qa + GradeCode: + type: string + description: |- + 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. + enum: + - intern + - junior + - middle + - senior + TaskLanguage: + type: string + description: >- + Programming language in which assessment tasks of a specialization are + offered and solved. It is the language of the task bank, not the + candidate's platform stack, and it never forms a separate category. + Only banks that offer a choice of language define task languages; the + first Backend bank offers Python and Go. Adding a value is a contract + change. + enum: + - python + - go + TestAvailabilityStatus: + type: string + description: >- + Whether an assessment can start for the specialization. `available` + means that a published task bank exists for at least one grade, listed + in `TestAvailability.grades`. `in_development` means that no grade of + the specialization has a published bank yet; the specialization can + still be chosen in the questionnaire, but no assessment starts and no + category can be confirmed for it. Presence in the catalog or in demo + data never means that a test is ready. + enum: + - available + - in_development + TestAvailability: + type: object + description: >- + Assessment availability of a specialization, derived by the server from + the published task banks at the time of the request. The MVP opens an + assessment only for a category, a specialization and a grade, that has + a published bank. `status` is `available` exactly when `grades` is not + empty; for `in_development` both `grades` and `task_languages` are + empty. + additionalProperties: false + required: + - status + - grades + - task_languages + - note + properties: + status: + $ref: "#/schemas/TestAvailabilityStatus" + grades: + type: array + maxItems: 10 + uniqueItems: true + description: >- + Grades of the specialization with a published task bank, in + ascending order. Only these categories can be assessed and + confirmed. + items: + $ref: "#/schemas/GradeCode" + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: >- + Task languages that the published bank offers for this + specialization. Empty when the bank does not offer a choice of + language, as for Network Engineer, or when no bank is published. + The questionnaire accepts only these languages for the + specialization. + items: + $ref: "#/schemas/TaskLanguage" + note: + type: + - string + - "null" + minLength: 1 + maxLength: 300 + description: >- + Short Russian note for the candidate, for example why the test is + not available yet, or null. Plain text; the client shows it as + text, never as HTML. + CatalogSpecialization: + type: object + description: Specialization in the catalog with its assessment availability. + additionalProperties: false + required: + - code + - title + - test_availability + properties: + code: + $ref: "#/schemas/SpecializationCode" + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + test_availability: + $ref: "#/schemas/TestAvailability" + CatalogDirection: + type: object + description: >- + Professional direction with its specializations. Each specialization + belongs to exactly one direction. + additionalProperties: false + required: + - code + - title + - specializations + properties: + code: + $ref: "#/schemas/DirectionCode" + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + specializations: + type: array + minItems: 1 + maxItems: 20 + description: Specializations of the direction in display order. + items: + $ref: "#/schemas/CatalogSpecialization" + CatalogGrade: + type: object + description: Grade of the scale with its display name. + additionalProperties: false + required: + - code + - title + properties: + code: + $ref: "#/schemas/GradeCode" + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + SpecializationCatalog: + type: object + description: >- + Catalog of directions, specializations, and the grade scale that the + questionnaire and the assessment use. The catalog is reference data and + identical for every caller; it contains no personal data. + additionalProperties: false + required: + - directions + - grades + properties: + directions: + type: array + minItems: 1 + maxItems: 20 + description: Directions in display order. + items: + $ref: "#/schemas/CatalogDirection" + grades: + type: array + minItems: 1 + maxItems: 10 + description: Grade scale in ascending order. + items: + $ref: "#/schemas/CatalogGrade" diff --git a/api/core/components/schemas/identity_schemas.yml b/api/core/components/schemas/identity_schemas.yml index f2e3259..5213d03 100644 --- a/api/core/components/schemas/identity_schemas.yml +++ b/api/core/components/schemas/identity_schemas.yml @@ -56,7 +56,7 @@ schemas: - candidate_consents: candidate consents beyond C1, which was given at registration. - candidate_profile: candidate profile. - candidate_questionnaire: candidate questionnaire. - - candidate_assessment: choice of the expected grade and the assessment. + - candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. The first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step (planned). - employer_company: company profile of the employer. - completed: onboarding is finished; the client opens the scenario home. diff --git a/api/core/components/schemas/problem_schemas.yml b/api/core/components/schemas/problem_schemas.yml index 72cde46..d26369f 100644 --- a/api/core/components/schemas/problem_schemas.yml +++ b/api/core/components/schemas/problem_schemas.yml @@ -81,7 +81,7 @@ schemas: - method_not_allowed (405): the route does not support the method. - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. - - version_conflict (412): If-Match does not match the current version. + - version_conflict (412): If-Match, or an `expected_version` field in the request body, does not match the current version; nothing was changed. - payload_too_large (413): the request body exceeds the limit. - unsupported_media_type (415): the request Content-Type is not accepted. - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. diff --git a/api/core/components/schemas/questionnaire_schemas.yml b/api/core/components/schemas/questionnaire_schemas.yml new file mode 100644 index 0000000..5a45f8c --- /dev/null +++ b/api/core/components/schemas/questionnaire_schemas.yml @@ -0,0 +1,187 @@ +schemas: + QuestionnaireVersion: + type: integer + format: int64 + minimum: 0 + description: >- + Version of the candidate questionnaire. A candidate without a saved + questionnaire has version 0; every save that changes the questionnaire + advances it by one. + examples: + - 3 + StackTag: + type: string + minLength: 1 + maxLength: 50 + pattern: '^\S(?:.*\S)?$' + description: >- + Free technology tag of the candidate's stack, for example PostgreSQL, + Kubernetes, or Django. A tag is a descriptive attribute: it never + forms a category, never selects the task language, and never changes + a grade, so a tag such as "Senior" has no effect on any category. It + has no leading or trailing whitespace and no line breaks. The server + compares tags without regard to letter case. Clients show tags as + text, never as HTML. + WorkFormat: + type: string + description: "Acceptable work format: `remote`, `office`, or `hybrid`." + enum: + - remote + - office + - hybrid + WorkContext: + type: object + description: >- + Working context of the candidate's search. It holds no personal data + such as an address or a city; location, relocation, and salary + expectations belong to the candidate profile. + additionalProperties: false + required: + - work_formats + properties: + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + description: Acceptable work formats. + items: + $ref: "#/schemas/WorkFormat" + CandidateExperience: + type: object + description: >- + Experience that the candidate states for one specialization, in whole + months. It is self-reported context: it never adds assessment points + and never confirms a grade. + additionalProperties: false + required: + - commercial_months + - academic_months + properties: + commercial_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of commercial work in the specialization. + academic_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: >- + Months of study, internships, or academic projects in the + specialization. + QuestionnaireSpecialization: + type: object + description: >- + One specialization chosen by the candidate with the candidate's + self-assessment. `self_assessed_grade` is a claim: it influences where + the assessment starts and which grade the assessment step offers + first, but it adds no points and never becomes a confirmed grade. A + confirmed grade, and with it a category, comes only from an assessment + result and is never part of the questionnaire; unknown fields such as + `confirmed_grade` or `category` are rejected. Task languages and the + stack are attributes of the chosen specialization, not categories. + additionalProperties: false + required: + - specialization + - self_assessed_grade + - task_languages + - stack + - experience + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + self_assessed_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: >- + Task languages in which the candidate wants to solve assessment + tasks of this specialization. Each value must be one of + `test_availability.task_languages` of the specialization in the + current catalog; any other value answers 400 validation_failed + with a pointer to it. Empty when the bank offers no choice of + language. + items: + $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + stack: + type: array + maxItems: 20 + uniqueItems: true + description: Technology tags of the candidate in this specialization. + items: + $ref: "#/schemas/StackTag" + experience: + description: >- + Stated experience, or null when the candidate did not state it. + oneOf: + - $ref: "#/schemas/CandidateExperience" + - type: "null" + CandidateQuestionnaire: + type: object + description: >- + Questionnaire of the current candidate: the chosen specializations with + self-assessed grades and the working context. It never contains a + confirmed grade or a category; those come only from assessment + results. A candidate who has not saved the questionnaire yet gets + version 0, no specializations, and null `work_context` and + `updated_at`. + additionalProperties: false + required: + - version + - specializations + - work_context + - updated_at + properties: + version: + $ref: "#/schemas/QuestionnaireVersion" + specializations: + type: array + maxItems: 2 + description: >- + Chosen specializations in the order the candidate gave them, each + specialization at most once. Each one is assessed independently. + items: + $ref: "#/schemas/QuestionnaireSpecialization" + work_context: + description: Working context, or null before the first save. + oneOf: + - $ref: "#/schemas/WorkContext" + - type: "null" + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + CandidateQuestionnaireUpdate: + type: object + description: >- + Complete new state of the questionnaire. It replaces the stored + specializations and working context as a whole. Unknown fields are + rejected, so a request cannot set a confirmed grade or a category. + additionalProperties: false + required: + - expected_version + - specializations + - work_context + properties: + expected_version: + $ref: "#/schemas/QuestionnaireVersion" + specializations: + type: array + minItems: 1 + maxItems: 2 + description: >- + One or two chosen specializations. The schema limits the count; the + server also requires each specialization to appear at most once and + answers a repeated one with 400 validation_failed and the pointer + of the repeated item's `specialization`, for example + `/specializations/1/specialization`. + items: + $ref: "#/schemas/QuestionnaireSpecialization" + work_context: + $ref: "#/schemas/WorkContext" diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 629cdfe..a5a03fc 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -11,6 +11,10 @@ tags: description: Liveness of the API process. - name: identity description: Registration, email verification, login, logout, and the current account. Sessions are server-side and travel in an HttpOnly cookie; mutating requests that require a session also carry a CSRF token. + - name: catalog + description: 'Public reference data: directions, specializations with their assessment availability, and the grade scale.' + - name: candidate + description: Data of the current candidate, such as the questionnaire with the chosen specializations and self-assessed grades. Confirmed grades and categories come only from assessment results. paths: /api/v1/healthz: get: @@ -369,6 +373,116 @@ paths: $ref: '#/components/responses/Unauthenticated' default: $ref: '#/components/responses/Problem' + /api/v1/specializations: + get: + operationId: GetSpecializationCatalog + summary: Read the catalog of directions, specializations, and grades. + description: |- + Public operation without a session. Returns the directions with their specializations, the assessment availability of each specialization, and the grade scale. The candidate picks specializations and self-assessed grades from this catalog for the questionnaire, and the client joins the codes stored in the questionnaire with the titles here. + + The catalog is public because it is the same for every caller and contains no personal data: the product shows it before registration, and a public read lets intermediaries and the browser cache it. It reveals nothing beyond what the landing pages already show. + + A category is a specialization together with a confirmed grade. Task languages and the stack are attributes of a chosen specialization and never appear as categories. `test_availability` is derived from the published task banks at the time of the request, so it changes when a bank is published, without a contract change: the MVP opens an assessment only for a category with a published bank, and every other specialization is marked `in_development`. Presence in the catalog never means that its test is ready. + security: [] + tags: + - catalog + responses: + '200': + description: The catalog. + content: + application/json: + schema: + $ref: '#/components/schemas/SpecializationCatalog' + examples: + mvp: + $ref: '#/components/examples/SpecializationCatalog' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/questionnaire: + get: + operationId: GetMyQuestionnaire + summary: Read the questionnaire of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. A candidate who has not saved the questionnaire yet gets 200 with version 0 and no specializations rather than 404, so the client reads the version for the first save in the same way as for later ones and a missing questionnaire is not an error state. + + The response never contains a confirmed grade or a category; those come only from assessment results. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - candidate + responses: + '200': + description: The questionnaire of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateQuestionnaire' + examples: + new_candidate: + $ref: '#/components/examples/NewCandidateQuestionnaire' + backend_go_and_network_engineer: + $ref: '#/components/examples/BackendGoAndNetworkEngineerQuestionnaire' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + put: + operationId: SaveMyQuestionnaire + summary: Replace the questionnaire of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new state: one or two specializations, each with a self-assessed grade, task languages, stack tags, and stated experience or null, and the working context. It replaces the stored questionnaire as a whole. + + Self-assessment is a claim. It influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never writes a confirmed grade or a category: a self-assessed `senior`, or the word "Senior" in a stack tag, never assigns the Senior category. A real profile stays invisible to employers until an assessment confirms a category. Choosing a specialization whose test is `in_development` is allowed; no assessment starts for it until its bank is published. Removing a specialization from the questionnaire does not change assessment results. + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first save. If it is not the current version, the server answers 412 version_conflict and changes nothing; the client reads the questionnaire again. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet. The status and code are the same as for a failed If-Match, since the client action is the same. + + The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose specializations and working context equal the stored ones changes nothing, keeps the version, and answers 200 with the current questionnaire even when `expected_version` is older, so a retry after a lost response of a successful save succeeds instead of failing with 412. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), domain rules (400), then the version (412). The schema rejects more than two specializations, an unknown grade, specialization, or task language, and unknown fields. The server also rejects a repeated specialization and a task language that the specialization's published bank does not offer, with 400 validation_failed and pointers to the items, for example `/specializations/1/specialization` or `/specializations/0/task_languages/0`. + + A successful save on the onboarding step candidate_questionnaire advances the account to candidate_assessment (planned). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - candidate + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateQuestionnaireUpdate' + examples: + backend_go_and_network_engineer: + $ref: '#/components/examples/BackendGoAndNetworkEngineerQuestionnaireUpdate' + responses: + '200': + description: The saved questionnaire with its new version. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateQuestionnaire' + examples: + backend_go_and_network_engineer: + $ref: '#/components/examples/BackendGoAndNetworkEngineerQuestionnaire' + '400': + $ref: '#/components/responses/QuestionnaireValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '412': + $ref: '#/components/responses/QuestionnaireVersionConflict' + default: + $ref: '#/components/responses/Problem' components: schemas: Problem: @@ -437,7 +551,7 @@ components: - method_not_allowed (405): the route does not support the method. - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. - - version_conflict (412): If-Match does not match the current version. + - version_conflict (412): If-Match, or an `expected_version` field in the request body, does not match the current version; nothing was changed. - payload_too_large (413): the request body exceeds the limit. - unsupported_media_type (415): the request Content-Type is not accepted. - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. @@ -560,7 +674,7 @@ components: - candidate_consents: candidate consents beyond C1, which was given at registration. - candidate_profile: candidate profile. - candidate_questionnaire: candidate questionnaire. - - candidate_assessment: choice of the expected grade and the assessment. + - candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. The first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step (planned). - employer_company: company profile of the employer. - completed: onboarding is finished; the client opens the scenario home. @@ -749,6 +863,318 @@ components: $ref: '#/components/schemas/Account' csrf_token: $ref: '#/components/schemas/CsrfToken' + DirectionCode: + type: string + description: |- + Stable code of a professional direction, the group that a specialization belongs to. + + - development: Development. + - infrastructure: Infrastructure. + - data: Data. + - security: Security. + - quality: Quality. + + Adding a value is a contract change. + enum: + - development + - infrastructure + - data + - security + - quality + SpecializationCode: + type: string + description: |- + 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. + + - backend: Backend (development). + - frontend: Frontend (development). + - mobile: Mobile (development). + - network_engineer: Network Engineer (infrastructure). + - devops_sre: DevOps/SRE (infrastructure). + - data_analyst: Data Analyst (data). + - ds_ml: DS/ML (data). + - information_security: Information security (security). + - qa: QA (quality). + + Adding a value is a contract change; renaming or removing one is a breaking change. + enum: + - backend + - frontend + - mobile + - network_engineer + - devops_sre + - data_analyst + - ds_ml + - information_security + - qa + GradeCode: + type: string + description: '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.' + enum: + - intern + - junior + - middle + - senior + TaskLanguage: + type: string + description: Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate's platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change. + enum: + - python + - go + TestAvailabilityStatus: + type: string + description: Whether an assessment can start for the specialization. `available` means that a published task bank exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no grade of the specialization has a published bank yet; the specialization can still be chosen in the questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the catalog or in demo data never means that a test is ready. + enum: + - available + - in_development + TestAvailability: + type: object + description: Assessment availability of a specialization, derived by the server from the published task banks at the time of the request. The MVP opens an assessment only for a category, a specialization and a grade, that has a published bank. `status` is `available` exactly when `grades` is not empty; for `in_development` both `grades` and `task_languages` are empty. + additionalProperties: false + required: + - status + - grades + - task_languages + - note + properties: + status: + $ref: '#/components/schemas/TestAvailabilityStatus' + grades: + type: array + maxItems: 10 + uniqueItems: true + description: Grades of the specialization with a published task bank, in ascending order. Only these categories can be assessed and confirmed. + items: + $ref: '#/components/schemas/GradeCode' + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: Task languages that the published bank offers for this specialization. Empty when the bank does not offer a choice of language, as for Network Engineer, or when no bank is published. The questionnaire accepts only these languages for the specialization. + items: + $ref: '#/components/schemas/TaskLanguage' + note: + type: + - string + - 'null' + minLength: 1 + maxLength: 300 + description: Short Russian note for the candidate, for example why the test is not available yet, or null. Plain text; the client shows it as text, never as HTML. + CatalogSpecialization: + type: object + description: Specialization in the catalog with its assessment availability. + additionalProperties: false + required: + - code + - title + - test_availability + properties: + code: + $ref: '#/components/schemas/SpecializationCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + test_availability: + $ref: '#/components/schemas/TestAvailability' + CatalogDirection: + type: object + description: Professional direction with its specializations. Each specialization belongs to exactly one direction. + additionalProperties: false + required: + - code + - title + - specializations + properties: + code: + $ref: '#/components/schemas/DirectionCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + specializations: + type: array + minItems: 1 + maxItems: 20 + description: Specializations of the direction in display order. + items: + $ref: '#/components/schemas/CatalogSpecialization' + CatalogGrade: + type: object + description: Grade of the scale with its display name. + additionalProperties: false + required: + - code + - title + properties: + code: + $ref: '#/components/schemas/GradeCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + SpecializationCatalog: + type: object + description: Catalog of directions, specializations, and the grade scale that the questionnaire and the assessment use. The catalog is reference data and identical for every caller; it contains no personal data. + additionalProperties: false + required: + - directions + - grades + properties: + directions: + type: array + minItems: 1 + maxItems: 20 + description: Directions in display order. + items: + $ref: '#/components/schemas/CatalogDirection' + grades: + type: array + minItems: 1 + maxItems: 10 + description: Grade scale in ascending order. + items: + $ref: '#/components/schemas/CatalogGrade' + QuestionnaireVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the candidate questionnaire. A candidate without a saved questionnaire has version 0; every save that changes the questionnaire advances it by one. + examples: + - 3 + StackTag: + type: string + minLength: 1 + maxLength: 50 + pattern: ^\S(?:.*\S)?$ + description: 'Free technology tag of the candidate''s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.' + WorkFormat: + type: string + description: 'Acceptable work format: `remote`, `office`, or `hybrid`.' + enum: + - remote + - office + - hybrid + WorkContext: + type: object + description: Working context of the candidate's search. It holds no personal data such as an address or a city; location, relocation, and salary expectations belong to the candidate profile. + additionalProperties: false + required: + - work_formats + properties: + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + description: Acceptable work formats. + items: + $ref: '#/components/schemas/WorkFormat' + CandidateExperience: + type: object + description: 'Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade.' + additionalProperties: false + required: + - commercial_months + - academic_months + properties: + commercial_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of commercial work in the specialization. + academic_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of study, internships, or academic projects in the specialization. + QuestionnaireSpecialization: + type: object + description: 'One specialization chosen by the candidate with the candidate''s self-assessment. `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed grade, and with it a category, comes only from an assessment result and is never part of the questionnaire; unknown fields such as `confirmed_grade` or `category` are rejected. Task languages and the stack are attributes of the chosen specialization, not categories.' + additionalProperties: false + required: + - specialization + - self_assessed_grade + - task_languages + - stack + - experience + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + self_assessed_grade: + $ref: '#/components/schemas/GradeCode' + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: Task languages in which the candidate wants to solve assessment tasks of this specialization. Each value must be one of `test_availability.task_languages` of the specialization in the current catalog; any other value answers 400 validation_failed with a pointer to it. Empty when the bank offers no choice of language. + items: + $ref: '#/components/schemas/TaskLanguage' + stack: + type: array + maxItems: 20 + uniqueItems: true + description: Technology tags of the candidate in this specialization. + items: + $ref: '#/components/schemas/StackTag' + experience: + description: Stated experience, or null when the candidate did not state it. + oneOf: + - $ref: '#/components/schemas/CandidateExperience' + - type: 'null' + CandidateQuestionnaire: + type: object + description: 'Questionnaire of the current candidate: the chosen specializations with self-assessed grades and the working context. It never contains a confirmed grade or a category; those come only from assessment results. A candidate who has not saved the questionnaire yet gets version 0, no specializations, and null `work_context` and `updated_at`.' + additionalProperties: false + required: + - version + - specializations + - work_context + - updated_at + properties: + version: + $ref: '#/components/schemas/QuestionnaireVersion' + specializations: + type: array + maxItems: 2 + description: Chosen specializations in the order the candidate gave them, each specialization at most once. Each one is assessed independently. + items: + $ref: '#/components/schemas/QuestionnaireSpecialization' + work_context: + description: Working context, or null before the first save. + oneOf: + - $ref: '#/components/schemas/WorkContext' + - type: 'null' + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + CandidateQuestionnaireUpdate: + type: object + description: Complete new state of the questionnaire. It replaces the stored specializations and working context as a whole. Unknown fields are rejected, so a request cannot set a confirmed grade or a category. + additionalProperties: false + required: + - expected_version + - specializations + - work_context + properties: + expected_version: + $ref: '#/components/schemas/QuestionnaireVersion' + specializations: + type: array + minItems: 1 + maxItems: 2 + description: One or two chosen specializations. The schema limits the count; the server also requires each specialization to appear at most once and answers a repeated one with 400 validation_failed and the pointer of the repeated item's `specialization`, for example `/specializations/1/specialization`. + items: + $ref: '#/components/schemas/QuestionnaireSpecialization' + work_context: + $ref: '#/components/schemas/WorkContext' HealthResponse: type: object additionalProperties: false @@ -1035,6 +1461,39 @@ components: examples: csrf_check_failed: $ref: '#/components/examples/CsrfCheckFailed' + CsrfCheckFailedOrForbidden: + description: 'The request failed cross-site request protection, code csrf_check_failed: the X-CSRF-Token header is missing or does not belong to the session, or the Origin is not allowed. Or the account may not perform the operation, code forbidden. Nothing was changed in either case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + csrf_check_failed: + $ref: '#/components/examples/CsrfCheckFailed' + forbidden: + $ref: '#/components/examples/Forbidden' + QuestionnaireValidationFailed: + description: 'The body does not match the contract or violates a questionnaire rule: more than two specializations, an unknown specialization, grade, or task language, an unknown field such as confirmed_grade, a repeated specialization, or a task language that the specialization''s published bank does not offer; code validation_failed with body pointers. When the decoder does not record the path of a nested field, the pointer is the whole body. Nothing was changed.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + too_many_specializations: + $ref: '#/components/examples/QuestionnaireTooManySpecializations' + unknown_grade: + $ref: '#/components/examples/QuestionnaireUnknownGrade' + repeated_specialization: + $ref: '#/components/examples/QuestionnaireRepeatedSpecialization' + QuestionnaireVersionConflict: + description: '`expected_version` is not the current questionnaire version; code version_conflict. Nothing was changed; read the questionnaire again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/VersionConflict' securitySchemes: sessionCookie: type: apiKey @@ -1242,6 +1701,142 @@ components: scenario: candidate onboarding_step: candidate_questionnaire created_at: '2026-10-05T09:30:00Z' + SpecializationCatalog: + summary: Illustrative MVP catalog with the Backend and Network Engineer banks published + description: Illustrative values. The directions, specializations, and grades follow the MVP scale; `test_availability` comes from the published task banks, so the grades and languages shown here are not a statement about any deployed bank. + value: + directions: + - code: development + title: Разработка + specializations: + - code: backend + title: Backend + test_availability: + status: available + grades: + - intern + - junior + - middle + - senior + task_languages: + - python + - go + note: null + - code: frontend + title: Frontend + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: mobile + title: Mobile + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: infrastructure + title: Инфраструктура + specializations: + - code: network_engineer + title: Сетевой инженер + test_availability: + status: available + grades: + - junior + - middle + task_languages: [] + note: null + - code: devops_sre + title: DevOps/SRE + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: data + title: Данные + specializations: + - code: data_analyst + title: Аналитик данных + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: ds_ml + title: DS/ML + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: security + title: Безопасность + specializations: + - code: information_security + title: Информационная безопасность + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: quality + title: Качество + specializations: + - code: qa + title: QA + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + grades: + - code: intern + title: Стажер + - code: junior + title: Junior + - code: middle + title: Middle + - code: senior + title: Senior + NewCandidateQuestionnaire: + summary: A candidate who has not saved the questionnaire yet + value: + version: 0 + specializations: [] + work_context: null + updated_at: null + BackendGoAndNetworkEngineerQuestionnaire: + summary: Backend with Go and Network Engineer, two independent specializations + description: Go is a task language of the `backend` specialization and PostgreSQL and gRPC are stack tags; none of them is a category. The candidate has two specializations, `backend` and `network_engineer`, each assessed independently. The self-assessed grades are claims; no confirmed grade appears. + value: + version: 3 + specializations: + - specialization: backend + self_assessed_grade: middle + task_languages: + - go + stack: + - PostgreSQL + - gRPC + - Kafka + experience: + commercial_months: 30 + academic_months: 12 + - specialization: network_engineer + self_assessed_grade: junior + task_languages: [] + stack: + - Cisco IOS + - BGP + experience: null + work_context: + work_formats: + - remote + - hybrid + updated_at: '2026-10-05T09:30:00Z' Forbidden: summary: The caller may not access the object value: @@ -1251,15 +1846,75 @@ components: code: forbidden detail: You do not have permission to perform this operation. trace_id: 7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d - StateConflict: - summary: The resource state does not allow the operation + BackendGoAndNetworkEngineerQuestionnaireUpdate: + summary: Save Backend with Go and Network Engineer over version 2 value: - type: urn:lincodex:problem:state_conflict - title: Resource state conflict - status: 409 - code: state_conflict - detail: The resource is in a state that does not allow this operation. - trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b + expected_version: 2 + specializations: + - specialization: backend + self_assessed_grade: middle + task_languages: + - go + stack: + - PostgreSQL + - gRPC + - Kafka + experience: + commercial_months: 30 + academic_months: 12 + - specialization: network_engineer + self_assessed_grade: junior + task_languages: [] + stack: + - Cisco IOS + - BGP + experience: null + work_context: + work_formats: + - remote + - hybrid + QuestionnaireTooManySpecializations: + summary: Three specializations were sent; at most two are allowed + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f + errors: + - in: body + pointer: /specializations + code: invalid + message: The value does not match the contract. + QuestionnaireUnknownGrade: + summary: A self-assessed grade outside the grade scale, such as lead + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 7d8e9f0a-1b2c-4d3e-9f4a-5b6c7d8e9f0a + errors: + - in: body + pointer: /specializations/0/self_assessed_grade + code: invalid + message: The value does not match the contract. + QuestionnaireRepeatedSpecialization: + summary: The same specialization was chosen twice + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 8e9f0a1b-2c3d-4e4f-8a5b-6c7d8e9f0a1b + errors: + - in: body + pointer: /specializations/1/specialization + code: invalid + message: The value does not match the contract. VersionConflict: summary: If-Match does not match the current version value: @@ -1269,6 +1924,15 @@ components: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 3e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b + StateConflict: + summary: The resource state does not allow the operation + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b PayloadTooLarge: summary: The request body exceeds the limit value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index d85358c..07ca05f 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -12,6 +12,15 @@ tags: Registration, email verification, login, logout, and the current account. Sessions are server-side and travel in an HttpOnly cookie; mutating requests that require a session also carry a CSRF token. + - name: catalog + description: >- + Public reference data: directions, specializations with their + assessment availability, and the grade scale. + - name: candidate + description: >- + Data of the current candidate, such as the questionnaire with the + chosen specializations and self-assessed grades. Confirmed grades and + categories come only from assessment results. # Operations require a session unless they declare `security: []`, so a new # operation that omits security is protected by default. security: @@ -33,6 +42,10 @@ paths: $ref: ./routes/identity_sessions_current.yml /api/v1/identity/me: $ref: ./routes/identity_me.yml + /api/v1/specializations: + $ref: ./routes/catalog_specializations.yml + /api/v1/me/questionnaire: + $ref: ./routes/candidate_questionnaire.yml components: schemas: Problem: @@ -85,6 +98,42 @@ components: $ref: ./components/schemas.yml#/Account Session: $ref: ./components/schemas.yml#/Session + DirectionCode: + $ref: ./components/schemas.yml#/DirectionCode + SpecializationCode: + $ref: ./components/schemas.yml#/SpecializationCode + GradeCode: + $ref: ./components/schemas.yml#/GradeCode + TaskLanguage: + $ref: ./components/schemas.yml#/TaskLanguage + TestAvailabilityStatus: + $ref: ./components/schemas.yml#/TestAvailabilityStatus + TestAvailability: + $ref: ./components/schemas.yml#/TestAvailability + CatalogSpecialization: + $ref: ./components/schemas.yml#/CatalogSpecialization + CatalogDirection: + $ref: ./components/schemas.yml#/CatalogDirection + CatalogGrade: + $ref: ./components/schemas.yml#/CatalogGrade + SpecializationCatalog: + $ref: ./components/schemas.yml#/SpecializationCatalog + QuestionnaireVersion: + $ref: ./components/schemas.yml#/QuestionnaireVersion + StackTag: + $ref: ./components/schemas.yml#/StackTag + WorkFormat: + $ref: ./components/schemas.yml#/WorkFormat + WorkContext: + $ref: ./components/schemas.yml#/WorkContext + CandidateExperience: + $ref: ./components/schemas.yml#/CandidateExperience + QuestionnaireSpecialization: + $ref: ./components/schemas.yml#/QuestionnaireSpecialization + CandidateQuestionnaire: + $ref: ./components/schemas.yml#/CandidateQuestionnaire + CandidateQuestionnaireUpdate: + $ref: ./components/schemas.yml#/CandidateQuestionnaireUpdate parameters: IdempotencyKey: $ref: ./components/parameters.yml#/IdempotencyKey @@ -142,6 +191,12 @@ components: $ref: ./components/responses.yml#/InvalidCredentials CsrfCheckFailed: $ref: ./components/responses.yml#/CsrfCheckFailed + CsrfCheckFailedOrForbidden: + $ref: ./components/responses.yml#/CsrfCheckFailedOrForbidden + QuestionnaireValidationFailed: + $ref: ./components/responses.yml#/QuestionnaireValidationFailed + QuestionnaireVersionConflict: + $ref: ./components/responses.yml#/QuestionnaireVersionConflict securitySchemes: sessionCookie: type: apiKey diff --git a/api/core/routes/candidate_questionnaire.yml b/api/core/routes/candidate_questionnaire.yml new file mode 100644 index 0000000..8d11be8 --- /dev/null +++ b/api/core/routes/candidate_questionnaire.yml @@ -0,0 +1,84 @@ +get: + operationId: GetMyQuestionnaire + summary: Read the questionnaire of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. A candidate who has not saved the questionnaire yet gets 200 with version 0 and no specializations rather than 404, so the client reads the version for the first save in the same way as for later ones and a missing questionnaire is not an error state. + + The response never contains a confirmed grade or a category; those come only from assessment results. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - candidate + responses: + "200": + description: The questionnaire of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateQuestionnaire + examples: + new_candidate: + $ref: ../components/examples.yml#/NewCandidateQuestionnaire + backend_go_and_network_engineer: + $ref: ../components/examples.yml#/BackendGoAndNetworkEngineerQuestionnaire + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem +put: + operationId: SaveMyQuestionnaire + summary: Replace the questionnaire of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new state: one or two specializations, each with a self-assessed grade, task languages, stack tags, and stated experience or null, and the working context. It replaces the stored questionnaire as a whole. + + Self-assessment is a claim. It influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never writes a confirmed grade or a category: a self-assessed `senior`, or the word "Senior" in a stack tag, never assigns the Senior category. A real profile stays invisible to employers until an assessment confirms a category. Choosing a specialization whose test is `in_development` is allowed; no assessment starts for it until its bank is published. Removing a specialization from the questionnaire does not change assessment results. + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first save. If it is not the current version, the server answers 412 version_conflict and changes nothing; the client reads the questionnaire again. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet. The status and code are the same as for a failed If-Match, since the client action is the same. + + The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose specializations and working context equal the stored ones changes nothing, keeps the version, and answers 200 with the current questionnaire even when `expected_version` is older, so a retry after a lost response of a successful save succeeds instead of failing with 412. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), domain rules (400), then the version (412). The schema rejects more than two specializations, an unknown grade, specialization, or task language, and unknown fields. The server also rejects a repeated specialization and a task language that the specialization's published bank does not offer, with 400 validation_failed and pointers to the items, for example `/specializations/1/specialization` or `/specializations/0/task_languages/0`. + + A successful save on the onboarding step candidate_questionnaire advances the account to candidate_assessment (planned). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - candidate + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateQuestionnaireUpdate + examples: + backend_go_and_network_engineer: + $ref: ../components/examples.yml#/BackendGoAndNetworkEngineerQuestionnaireUpdate + responses: + "200": + description: The saved questionnaire with its new version. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateQuestionnaire + examples: + backend_go_and_network_engineer: + $ref: ../components/examples.yml#/BackendGoAndNetworkEngineerQuestionnaire + "400": + $ref: ../components/responses.yml#/QuestionnaireValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "412": + $ref: ../components/responses.yml#/QuestionnaireVersionConflict + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/catalog_specializations.yml b/api/core/routes/catalog_specializations.yml new file mode 100644 index 0000000..7ca2c31 --- /dev/null +++ b/api/core/routes/catalog_specializations.yml @@ -0,0 +1,24 @@ +get: + operationId: GetSpecializationCatalog + summary: Read the catalog of directions, specializations, and grades. + description: |- + Public operation without a session. Returns the directions with their specializations, the assessment availability of each specialization, and the grade scale. The candidate picks specializations and self-assessed grades from this catalog for the questionnaire, and the client joins the codes stored in the questionnaire with the titles here. + + The catalog is public because it is the same for every caller and contains no personal data: the product shows it before registration, and a public read lets intermediaries and the browser cache it. It reveals nothing beyond what the landing pages already show. + + A category is a specialization together with a confirmed grade. Task languages and the stack are attributes of a chosen specialization and never appear as categories. `test_availability` is derived from the published task banks at the time of the request, so it changes when a bank is published, without a contract change: the MVP opens an assessment only for a category with a published bank, and every other specialization is marked `in_development`. Presence in the catalog never means that its test is ready. + security: [] + tags: + - catalog + responses: + "200": + description: The catalog. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SpecializationCatalog + examples: + mvp: + $ref: ../components/examples.yml#/SpecializationCatalog + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/testdata/openapi-3.2.0.yml b/api/testdata/openapi-3.2.0.yml index 85caf32..335283a 100644 --- a/api/testdata/openapi-3.2.0.yml +++ b/api/testdata/openapi-3.2.0.yml @@ -244,7 +244,7 @@ components: - method_not_allowed (405): the route does not support the method. - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. - - version_conflict (412): If-Match does not match the current version. + - version_conflict (412): If-Match, or an `expected_version` field in the request body, does not match the current version; nothing was changed. - payload_too_large (413): the request body exceeds the limit. - unsupported_media_type (415): the request Content-Type is not accepted. - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index 09424b7..7527ae9 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -22,6 +22,7 @@ var regexMap = map[string]ogenregex.Regexp{ "^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"), "^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"), "^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"), + "^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"), "^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="), } var ( diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 4195fd1..dc2760b 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -879,6 +879,347 @@ func (s *Server) handleGetHealthzRequest(args [0]string, argsEscaped bool, w htt } } +// handleGetMyQuestionnaireRequest handles GetMyQuestionnaire operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, never from +// a request parameter. A candidate who has not saved the questionnaire yet gets 200 with version 0 and +// no specializations rather than 404, so the client reads the version for the first save in the same +// way as for later ones and a missing questionnaire is not an error state. +// +// The response never contains a confirmed grade or a category; those come only from assessment +// results. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer +// account answers 403 forbidden. +// +// GET /api/v1/me/questionnaire +func (s *Server) handleGetMyQuestionnaireRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyQuestionnaire"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/questionnaire"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyQuestionnaireOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetMyQuestionnaireOperation, + ID: "GetMyQuestionnaire", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyQuestionnaireOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + + var response GetMyQuestionnaireRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyQuestionnaireOperation, + OperationSummary: "Read the questionnaire of the current candidate.", + OperationID: "GetMyQuestionnaire", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = GetMyQuestionnaireRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyQuestionnaire(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetMyQuestionnaire(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetMyQuestionnaireResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetSpecializationCatalogRequest handles GetSpecializationCatalog operation. +// +// Public operation without a session. Returns the directions with their specializations, the +// assessment availability of each specialization, and the grade scale. The candidate picks +// specializations and self-assessed grades from this catalog for the questionnaire, and the client +// joins the codes stored in the questionnaire with the titles here. +// +// The catalog is public because it is the same for every caller and contains no personal data: the +// product shows it before registration, and a public read lets intermediaries and the browser cache +// it. It reveals nothing beyond what the landing pages already show. +// +// A category is a specialization together with a confirmed grade. Task languages and the stack are +// attributes of a chosen specialization and never appear as categories. `test_availability` is derived +// from the published task banks at the time of the request, so it changes when a bank is published, +// without a contract change: the MVP opens an assessment only for a category with a published bank, +// and every other specialization is marked `in_development`. Presence in the catalog never means that +// its test is ready. +// +// GET /api/v1/specializations +func (s *Server) handleGetSpecializationCatalogRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetSpecializationCatalog"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/specializations"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetSpecializationCatalogOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + ) + + var rawBody []byte + + var response *SpecializationCatalog + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetSpecializationCatalogOperation, + OperationSummary: "Read the catalog of directions, specializations, and grades.", + OperationID: "GetSpecializationCatalog", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = *SpecializationCatalog + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetSpecializationCatalog(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetSpecializationCatalog(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetSpecializationCatalogResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleLoginRequest handles Login operation. // // Public operation that starts a server session. The server verifies the password with Argon2id; for @@ -1627,3 +1968,252 @@ func (s *Server) handleResendEmailVerificationRequest(args [0]string, argsEscape return } } + +// handleSaveMyQuestionnaireRequest handles SaveMyQuestionnaire operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The body is the complete new state: one or two specializations, each with a +// self-assessed grade, task languages, stack tags, and stated experience or null, and the working +// context. It replaces the stored questionnaire as a whole. +// +// Self-assessment is a claim. It influences where the assessment starts and which grade the assessment +// step offers first, but it adds no points and never writes a confirmed grade or a category: a +// self-assessed `senior`, or the word "Senior" in a stack tag, never assigns the Senior category. A +// real profile stays invisible to employers until an assessment confirms a category. Choosing a +// specialization whose test is `in_development` is allowed; no assessment starts for it until its bank +// is published. Removing a specialization from the questionnaire does not change assessment results. +// +// Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, +// 0 for the first save. If it is not the current version, the server answers 412 version_conflict and +// changes nothing; the client reads the questionnaire again. The version travels in the body rather +// than in If-Match because the generated client cannot read the ETag response header yet. The status +// and code are the same as for a failed If-Match, since the client action is the same. +// +// The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose +// specializations and working context equal the stored ones changes nothing, keeps the version, and +// answers 200 with the current questionnaire even when `expected_version` is older, so a retry after a +// lost response of a successful save succeeds instead of failing with 412. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden for an employer), domain rules (400), then the version (412). The +// schema rejects more than two specializations, an unknown grade, specialization, or task language, +// and unknown fields. The server also rejects a repeated specialization and a task language that the +// specialization's published bank does not offer, with 400 validation_failed and pointers to the +// items, for example `/specializations/1/specialization` or `/specializations/0/task_languages/0`. +// +// A successful save on the onboarding step candidate_questionnaire advances the account to +// candidate_assessment (planned). +// +// PUT /api/v1/me/questionnaire +func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("SaveMyQuestionnaire"), + semconv.HTTPRequestMethodKey.String("PUT"), + semconv.HTTPRouteKey.String("/api/v1/me/questionnaire"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), SaveMyQuestionnaireOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: SaveMyQuestionnaireOperation, + ID: "SaveMyQuestionnaire", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, SaveMyQuestionnaireOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, SaveMyQuestionnaireOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + request, rawBody, close, err := s.decodeSaveMyQuestionnaireRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response SaveMyQuestionnaireRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: SaveMyQuestionnaireOperation, + OperationSummary: "Replace the questionnaire of the current candidate.", + OperationID: "SaveMyQuestionnaire", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *CandidateQuestionnaireUpdate + Params = struct{} + Response = SaveMyQuestionnaireRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.SaveMyQuestionnaire(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.SaveMyQuestionnaire(ctx, request) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeSaveMyQuestionnaireResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index 234c2bf..cea35aa 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -17,6 +17,10 @@ type GetCurrentSessionRes interface { getCurrentSessionRes() } +type GetMyQuestionnaireRes interface { + getMyQuestionnaireRes() +} + type LoginRes interface { loginRes() } @@ -32,3 +36,7 @@ type RegisterAccountRes interface { type ResendEmailVerificationRes interface { resendEmailVerificationRes() } + +type SaveMyQuestionnaireRes interface { + saveMyQuestionnaireRes() +} 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 2d7c332..5f86e46 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -226,6 +226,781 @@ func (s *AccountScenario) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *CandidateExperience) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CandidateExperience) encodeFields(e *jx.Encoder) { + { + e.FieldStart("commercial_months") + e.Int32(s.CommercialMonths) + } + { + e.FieldStart("academic_months") + e.Int32(s.AcademicMonths) + } +} + +var jsonFieldsNameOfCandidateExperience = [2]string{ + 0: "commercial_months", + 1: "academic_months", +} + +// Decode decodes CandidateExperience from json. +func (s *CandidateExperience) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateExperience to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "commercial_months": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.CommercialMonths = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"commercial_months\"") + } + case "academic_months": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.AcademicMonths = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"academic_months\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CandidateExperience") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCandidateExperience) { + name = jsonFieldsNameOfCandidateExperience[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CandidateExperience) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateExperience) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CandidateQuestionnaire) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CandidateQuestionnaire) encodeFields(e *jx.Encoder) { + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("specializations") + e.ArrStart() + for _, elem := range s.Specializations { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("work_context") + s.WorkContext.Encode(e) + } + { + e.FieldStart("updated_at") + s.UpdatedAt.Encode(e) + } +} + +var jsonFieldsNameOfCandidateQuestionnaire = [4]string{ + 0: "version", + 1: "specializations", + 2: "work_context", + 3: "updated_at", +} + +// Decode decodes CandidateQuestionnaire from json. +func (s *CandidateQuestionnaire) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateQuestionnaire to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "specializations": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Specializations = make([]QuestionnaireSpecialization, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem QuestionnaireSpecialization + if err := elem.Decode(d); err != nil { + return err + } + s.Specializations = append(s.Specializations, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specializations\"") + } + case "work_context": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.WorkContext.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"work_context\"") + } + case "updated_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.UpdatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"updated_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CandidateQuestionnaire") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCandidateQuestionnaire) { + name = jsonFieldsNameOfCandidateQuestionnaire[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CandidateQuestionnaire) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateQuestionnaire) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CandidateQuestionnaireUpdate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CandidateQuestionnaireUpdate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + e.FieldStart("specializations") + e.ArrStart() + for _, elem := range s.Specializations { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("work_context") + s.WorkContext.Encode(e) + } +} + +var jsonFieldsNameOfCandidateQuestionnaireUpdate = [3]string{ + 0: "expected_version", + 1: "specializations", + 2: "work_context", +} + +// Decode decodes CandidateQuestionnaireUpdate from json. +func (s *CandidateQuestionnaireUpdate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateQuestionnaireUpdate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "specializations": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Specializations = make([]QuestionnaireSpecialization, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem QuestionnaireSpecialization + if err := elem.Decode(d); err != nil { + return err + } + s.Specializations = append(s.Specializations, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specializations\"") + } + case "work_context": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.WorkContext.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"work_context\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CandidateQuestionnaireUpdate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCandidateQuestionnaireUpdate) { + name = jsonFieldsNameOfCandidateQuestionnaireUpdate[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CandidateQuestionnaireUpdate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateQuestionnaireUpdate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CatalogDirection) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CatalogDirection) encodeFields(e *jx.Encoder) { + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + e.FieldStart("title") + e.Str(s.Title) + } + { + e.FieldStart("specializations") + e.ArrStart() + for _, elem := range s.Specializations { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfCatalogDirection = [3]string{ + 0: "code", + 1: "title", + 2: "specializations", +} + +// Decode decodes CatalogDirection from json. +func (s *CatalogDirection) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CatalogDirection to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "code": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + case "specializations": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.Specializations = make([]CatalogSpecialization, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CatalogSpecialization + if err := elem.Decode(d); err != nil { + return err + } + s.Specializations = append(s.Specializations, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specializations\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CatalogDirection") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCatalogDirection) { + name = jsonFieldsNameOfCatalogDirection[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CatalogDirection) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CatalogDirection) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CatalogGrade) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CatalogGrade) encodeFields(e *jx.Encoder) { + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + e.FieldStart("title") + e.Str(s.Title) + } +} + +var jsonFieldsNameOfCatalogGrade = [2]string{ + 0: "code", + 1: "title", +} + +// Decode decodes CatalogGrade from json. +func (s *CatalogGrade) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CatalogGrade to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "code": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CatalogGrade") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCatalogGrade) { + name = jsonFieldsNameOfCatalogGrade[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CatalogGrade) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CatalogGrade) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CatalogSpecialization) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CatalogSpecialization) encodeFields(e *jx.Encoder) { + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + e.FieldStart("title") + e.Str(s.Title) + } + { + e.FieldStart("test_availability") + s.TestAvailability.Encode(e) + } +} + +var jsonFieldsNameOfCatalogSpecialization = [3]string{ + 0: "code", + 1: "title", + 2: "test_availability", +} + +// Decode decodes CatalogSpecialization from json. +func (s *CatalogSpecialization) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CatalogSpecialization to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "code": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "title": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + case "test_availability": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.TestAvailability.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"test_availability\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CatalogSpecialization") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCatalogSpecialization) { + name = jsonFieldsNameOfCatalogSpecialization[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CatalogSpecialization) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CatalogSpecialization) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ConfirmEmailBadRequest as json. func (s *ConfirmEmailBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -561,6 +1336,52 @@ func (s *CsrfToken) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes DirectionCode as json. +func (s DirectionCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes DirectionCode from json. +func (s *DirectionCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DirectionCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch DirectionCode(v) { + case DirectionCodeDevelopment: + *s = DirectionCodeDevelopment + case DirectionCodeInfrastructure: + *s = DirectionCodeInfrastructure + case DirectionCodeData: + *s = DirectionCodeData + case DirectionCodeSecurity: + *s = DirectionCodeSecurity + case DirectionCodeQuality: + *s = DirectionCodeQuality + default: + *s = DirectionCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s DirectionCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DirectionCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes EmailAddress as json. func (s EmailAddress) Encode(e *jx.Encoder) { unwrapped := string(s) @@ -945,6 +1766,126 @@ func (s *EmailVerificationResultEmailVerified) UnmarshalJSON(data []byte) error return s.Decode(d) } +// Encode encodes GetMyQuestionnaireForbidden as json. +func (s *GetMyQuestionnaireForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyQuestionnaireForbidden from json. +func (s *GetMyQuestionnaireForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyQuestionnaireForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyQuestionnaireForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyQuestionnaireForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyQuestionnaireForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyQuestionnaireUnauthorized as json. +func (s *GetMyQuestionnaireUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyQuestionnaireUnauthorized from json. +func (s *GetMyQuestionnaireUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyQuestionnaireUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyQuestionnaireUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyQuestionnaireUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyQuestionnaireUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GradeCode as json. +func (s GradeCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes GradeCode from json. +func (s *GradeCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GradeCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch GradeCode(v) { + case GradeCodeIntern: + *s = GradeCodeIntern + case GradeCodeJunior: + *s = GradeCodeJunior + case GradeCodeMiddle: + *s = GradeCodeMiddle + case GradeCodeSenior: + *s = GradeCodeSenior + default: + *s = GradeCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s GradeCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GradeCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *HealthResponse) Encode(e *jx.Encoder) { e.ObjStart() @@ -1512,6 +2453,184 @@ func (s *NewPassword) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes CandidateExperience as json. +func (o NilCandidateExperience) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes CandidateExperience from json. +func (o *NilCandidateExperience) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilCandidateExperience to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v CandidateExperience + 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 NilCandidateExperience) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilCandidateExperience) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes string as json. +func (o NilString) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes string from json. +func (o *NilString) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilString to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v string + o.Value = v + o.Null = true + return nil + } + o.Null = false + v, err := d.Str() + if err != nil { + return err + } + o.Value = string(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilString) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilString) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes Timestamp as json. +func (o NilTimestamp) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes Timestamp from json. +func (o *NilTimestamp) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilTimestamp to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v Timestamp + 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 NilTimestamp) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilTimestamp) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes WorkContext as json. +func (o NilWorkContext) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes WorkContext from json. +func (o *NilWorkContext) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilWorkContext to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v WorkContext + 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 NilWorkContext) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilWorkContext) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes OnboardingStep as json. func (s OnboardingStep) Encode(e *jx.Encoder) { e.Str(string(s)) @@ -2227,6 +3346,224 @@ func (s *ProblemFieldLocation) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *QuestionnaireSpecialization) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *QuestionnaireSpecialization) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("self_assessed_grade") + s.SelfAssessedGrade.Encode(e) + } + { + e.FieldStart("task_languages") + e.ArrStart() + for _, elem := range s.TaskLanguages { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("stack") + e.ArrStart() + for _, elem := range s.Stack { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("experience") + s.Experience.Encode(e) + } +} + +var jsonFieldsNameOfQuestionnaireSpecialization = [5]string{ + 0: "specialization", + 1: "self_assessed_grade", + 2: "task_languages", + 3: "stack", + 4: "experience", +} + +// Decode decodes QuestionnaireSpecialization from json. +func (s *QuestionnaireSpecialization) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode QuestionnaireSpecialization to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specialization": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "self_assessed_grade": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.SelfAssessedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"self_assessed_grade\"") + } + case "task_languages": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.TaskLanguages = make([]TaskLanguage, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TaskLanguage + if err := elem.Decode(d); err != nil { + return err + } + s.TaskLanguages = append(s.TaskLanguages, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_languages\"") + } + case "stack": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + s.Stack = make([]StackTag, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem StackTag + if err := elem.Decode(d); err != nil { + return err + } + s.Stack = append(s.Stack, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"stack\"") + } + case "experience": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Experience.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"experience\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode QuestionnaireSpecialization") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00011111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfQuestionnaireSpecialization) { + name = jsonFieldsNameOfQuestionnaireSpecialization[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *QuestionnaireSpecialization) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *QuestionnaireSpecialization) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes QuestionnaireVersion as json. +func (s QuestionnaireVersion) Encode(e *jx.Encoder) { + unwrapped := int64(s) + + e.Int64(unwrapped) +} + +// Decode decodes QuestionnaireVersion from json. +func (s *QuestionnaireVersion) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode QuestionnaireVersion to nil") + } + var unwrapped int64 + if err := func() error { + v, err := d.Int64() + unwrapped = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = QuestionnaireVersion(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s QuestionnaireVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *QuestionnaireVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes RegisterAccountBadRequest as json. func (s *RegisterAccountBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -2594,6 +3931,158 @@ func (s *ResendEmailVerificationForbidden) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes SaveMyQuestionnaireBadRequest as json. +func (s *SaveMyQuestionnaireBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SaveMyQuestionnaireBadRequest from json. +func (s *SaveMyQuestionnaireBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SaveMyQuestionnaireBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SaveMyQuestionnaireBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SaveMyQuestionnaireBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SaveMyQuestionnaireBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SaveMyQuestionnaireForbidden as json. +func (s *SaveMyQuestionnaireForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SaveMyQuestionnaireForbidden from json. +func (s *SaveMyQuestionnaireForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SaveMyQuestionnaireForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SaveMyQuestionnaireForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SaveMyQuestionnaireForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SaveMyQuestionnaireForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SaveMyQuestionnairePreconditionFailed as json. +func (s *SaveMyQuestionnairePreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SaveMyQuestionnairePreconditionFailed from json. +func (s *SaveMyQuestionnairePreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SaveMyQuestionnairePreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SaveMyQuestionnairePreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SaveMyQuestionnairePreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SaveMyQuestionnairePreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SaveMyQuestionnaireUnauthorized as json. +func (s *SaveMyQuestionnaireUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SaveMyQuestionnaireUnauthorized from json. +func (s *SaveMyQuestionnaireUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SaveMyQuestionnaireUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SaveMyQuestionnaireUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SaveMyQuestionnaireUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SaveMyQuestionnaireUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *Session) Encode(e *jx.Encoder) { e.ObjStart() @@ -2703,6 +4192,476 @@ func (s *Session) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *SpecializationCatalog) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SpecializationCatalog) encodeFields(e *jx.Encoder) { + { + e.FieldStart("directions") + e.ArrStart() + for _, elem := range s.Directions { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("grades") + e.ArrStart() + for _, elem := range s.Grades { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfSpecializationCatalog = [2]string{ + 0: "directions", + 1: "grades", +} + +// Decode decodes SpecializationCatalog from json. +func (s *SpecializationCatalog) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SpecializationCatalog to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "directions": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Directions = make([]CatalogDirection, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CatalogDirection + if err := elem.Decode(d); err != nil { + return err + } + s.Directions = append(s.Directions, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"directions\"") + } + case "grades": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Grades = make([]CatalogGrade, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CatalogGrade + if err := elem.Decode(d); err != nil { + return err + } + s.Grades = append(s.Grades, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"grades\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SpecializationCatalog") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfSpecializationCatalog) { + name = jsonFieldsNameOfSpecializationCatalog[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SpecializationCatalog) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SpecializationCatalog) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SpecializationCode as json. +func (s SpecializationCode) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SpecializationCode from json. +func (s *SpecializationCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SpecializationCode to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SpecializationCode(v) { + case SpecializationCodeBackend: + *s = SpecializationCodeBackend + case SpecializationCodeFrontend: + *s = SpecializationCodeFrontend + case SpecializationCodeMobile: + *s = SpecializationCodeMobile + case SpecializationCodeNetworkEngineer: + *s = SpecializationCodeNetworkEngineer + case SpecializationCodeDevopsSre: + *s = SpecializationCodeDevopsSre + case SpecializationCodeDataAnalyst: + *s = SpecializationCodeDataAnalyst + case SpecializationCodeDsMl: + *s = SpecializationCodeDsMl + case SpecializationCodeInformationSecurity: + *s = SpecializationCodeInformationSecurity + case SpecializationCodeQa: + *s = SpecializationCodeQa + default: + *s = SpecializationCode(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SpecializationCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SpecializationCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes StackTag as json. +func (s StackTag) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes StackTag from json. +func (s *StackTag) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode StackTag to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = StackTag(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s StackTag) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *StackTag) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TaskLanguage as json. +func (s TaskLanguage) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes TaskLanguage from json. +func (s *TaskLanguage) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TaskLanguage to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch TaskLanguage(v) { + case TaskLanguagePython: + *s = TaskLanguagePython + case TaskLanguageGo: + *s = TaskLanguageGo + default: + *s = TaskLanguage(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TaskLanguage) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TaskLanguage) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *TestAvailability) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *TestAvailability) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("grades") + e.ArrStart() + for _, elem := range s.Grades { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("task_languages") + e.ArrStart() + for _, elem := range s.TaskLanguages { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("note") + s.Note.Encode(e) + } +} + +var jsonFieldsNameOfTestAvailability = [4]string{ + 0: "status", + 1: "grades", + 2: "task_languages", + 3: "note", +} + +// Decode decodes TestAvailability from json. +func (s *TestAvailability) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestAvailability to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "grades": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Grades = make([]GradeCode, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem GradeCode + if err := elem.Decode(d); err != nil { + return err + } + s.Grades = append(s.Grades, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"grades\"") + } + case "task_languages": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.TaskLanguages = make([]TaskLanguage, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem TaskLanguage + if err := elem.Decode(d); err != nil { + return err + } + s.TaskLanguages = append(s.TaskLanguages, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"task_languages\"") + } + case "note": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Note.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"note\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode TestAvailability") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfTestAvailability) { + name = jsonFieldsNameOfTestAvailability[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *TestAvailability) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestAvailability) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes TestAvailabilityStatus as json. +func (s TestAvailabilityStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes TestAvailabilityStatus from json. +func (s *TestAvailabilityStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode TestAvailabilityStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch TestAvailabilityStatus(v) { + case TestAvailabilityStatusAvailable: + *s = TestAvailabilityStatusAvailable + case TestAvailabilityStatusInDevelopment: + *s = TestAvailabilityStatusInDevelopment + default: + *s = TestAvailabilityStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s TestAvailabilityStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *TestAvailabilityStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes Timestamp as json. func (s Timestamp) Encode(e *jx.Encoder) { unwrapped := time.Time(s) @@ -2782,3 +4741,151 @@ func (s *VerificationToken) UnmarshalJSON(data []byte) error { d := jx.DecodeBytes(data) return s.Decode(d) } + +// Encode implements json.Marshaler. +func (s *WorkContext) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *WorkContext) encodeFields(e *jx.Encoder) { + { + e.FieldStart("work_formats") + e.ArrStart() + for _, elem := range s.WorkFormats { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfWorkContext = [1]string{ + 0: "work_formats", +} + +// Decode decodes WorkContext from json. +func (s *WorkContext) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode WorkContext to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "work_formats": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.WorkFormats = make([]WorkFormat, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem WorkFormat + if err := elem.Decode(d); err != nil { + return err + } + s.WorkFormats = append(s.WorkFormats, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"work_formats\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode WorkContext") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfWorkContext) { + name = jsonFieldsNameOfWorkContext[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *WorkContext) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *WorkContext) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes WorkFormat as json. +func (s WorkFormat) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes WorkFormat from json. +func (s *WorkFormat) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode WorkFormat to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch WorkFormat(v) { + case WorkFormatRemote: + *s = WorkFormatRemote + case WorkFormatOffice: + *s = WorkFormatOffice + case WorkFormatHybrid: + *s = WorkFormatHybrid + default: + *s = WorkFormat(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s WorkFormat) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *WorkFormat) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index 38cba76..f34be9a 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -6,13 +6,16 @@ package api type OperationName = string const ( - ConfirmEmailOperation OperationName = "ConfirmEmail" - GetConsentTextOperation OperationName = "GetConsentText" - GetCurrentAccountOperation OperationName = "GetCurrentAccount" - GetCurrentSessionOperation OperationName = "GetCurrentSession" - GetHealthzOperation OperationName = "GetHealthz" - LoginOperation OperationName = "Login" - LogoutOperation OperationName = "Logout" - RegisterAccountOperation OperationName = "RegisterAccount" - ResendEmailVerificationOperation OperationName = "ResendEmailVerification" + ConfirmEmailOperation OperationName = "ConfirmEmail" + GetConsentTextOperation OperationName = "GetConsentText" + GetCurrentAccountOperation OperationName = "GetCurrentAccount" + GetCurrentSessionOperation OperationName = "GetCurrentSession" + GetHealthzOperation OperationName = "GetHealthz" + GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire" + GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog" + LoginOperation OperationName = "Login" + LogoutOperation OperationName = "Logout" + RegisterAccountOperation OperationName = "RegisterAccount" + ResendEmailVerificationOperation OperationName = "ResendEmailVerification" + SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire" ) diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index a96a608..404eda8 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -329,3 +329,82 @@ func (s *Server) decodeResendEmailVerificationRequest(r *http.Request) ( return req, rawBody, close, validate.InvalidContentType(ct) } } + +func (s *Server) decodeSaveMyQuestionnaireRequest(r *http.Request) ( + req *CandidateQuestionnaireUpdate, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request CandidateQuestionnaireUpdate + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index 1029d7f..048e78c 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -227,6 +227,78 @@ func encodeGetHealthzResponse(response *HealthResponse, w http.ResponseWriter, s return nil } +func encodeGetMyQuestionnaireResponse(response GetMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CandidateQuestionnaireHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyQuestionnaireUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyQuestionnaireForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeGetSpecializationCatalogResponse(response *SpecializationCatalog, w http.ResponseWriter, span trace.Span) error { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil +} + func encodeLoginResponse(response LoginRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *SessionHeaders: @@ -587,6 +659,89 @@ func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes, } } +func encodeSaveMyQuestionnaireResponse(response SaveMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CandidateQuestionnaireHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SaveMyQuestionnaireBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SaveMyQuestionnaireUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SaveMyQuestionnaireForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SaveMyQuestionnairePreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error { w.Header().Set("Content-Type", "application/problem+json") code := response.StatusCode diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index 2be152e..4577762 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,21 +11,24 @@ import ( ) var ( - rn12AllowedHeaders = map[string]string{ + rn14AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn1AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn10AllowedHeaders = map[string]string{ + rn12AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn9AllowedHeaders = map[string]string{ + rn11AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn6AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } + rn9AllowedHeaders = map[string]string{ + "PUT": "Content-Type,X-Csrf-Token", + } ) func (s *Server) cutPrefix(path string) (string, bool) { @@ -180,7 +183,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn12AllowedHeaders, + allowedHeaders: rn14AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -257,7 +260,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn10AllowedHeaders, + allowedHeaders: rn12AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -281,7 +284,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn9AllowedHeaders, + allowedHeaders: rn11AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -321,6 +324,58 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } + case 'm': // Prefix: "me/questionnaire" + + if l := len("me/questionnaire"); len(elem) >= l && elem[0:l] == "me/questionnaire" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r) + case "PUT": + s.handleSaveMyQuestionnaireRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,PUT", + allowedHeaders: rn9AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 's': // Prefix: "specializations" + + if l := len("specializations"); len(elem) >= l && elem[0:l] == "specializations" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetSpecializationCatalogRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + } } @@ -668,6 +723,65 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } + case 'm': // Prefix: "me/questionnaire" + + if l := len("me/questionnaire"); len(elem) >= l && elem[0:l] == "me/questionnaire" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyQuestionnaireOperation + r.summary = "Read the questionnaire of the current candidate." + r.operationID = "GetMyQuestionnaire" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/questionnaire" + r.args = args + r.count = 0 + return r, true + case "PUT": + r.name = SaveMyQuestionnaireOperation + r.summary = "Replace the questionnaire of the current candidate." + r.operationID = "SaveMyQuestionnaire" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/questionnaire" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 's': // Prefix: "specializations" + + if l := len("specializations"); len(elem) >= l && elem[0:l] == "specializations" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetSpecializationCatalogOperation + r.summary = "Read the catalog of directions, specializations, and grades." + r.operationID = "GetSpecializationCatalog" + r.operationGroup = "" + r.pathPattern = "/api/v1/specializations" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + } } 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 9923e4a..8f214dd 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -196,6 +196,271 @@ func (s *CacheControlNoStore) UnmarshalText(data []byte) error { } } +// Experience that the candidate states for one specialization, in whole months. It is self-reported +// context: it never adds assessment points and never confirms a grade. +// Ref: #/components/schemas/CandidateExperience +type CandidateExperience struct { + // Months of commercial work in the specialization. + CommercialMonths int32 `json:"commercial_months"` + // Months of study, internships, or academic projects in the specialization. + AcademicMonths int32 `json:"academic_months"` +} + +// GetCommercialMonths returns the value of CommercialMonths. +func (s *CandidateExperience) GetCommercialMonths() int32 { + return s.CommercialMonths +} + +// GetAcademicMonths returns the value of AcademicMonths. +func (s *CandidateExperience) GetAcademicMonths() int32 { + return s.AcademicMonths +} + +// SetCommercialMonths sets the value of CommercialMonths. +func (s *CandidateExperience) SetCommercialMonths(val int32) { + s.CommercialMonths = val +} + +// SetAcademicMonths sets the value of AcademicMonths. +func (s *CandidateExperience) SetAcademicMonths(val int32) { + s.AcademicMonths = val +} + +// Questionnaire of the current candidate: the chosen specializations with self-assessed grades and the +// working context. It never contains a confirmed grade or a category; those come only from assessment +// results. A candidate who has not saved the questionnaire yet gets version 0, no specializations, and +// null `work_context` and `updated_at`. +// Ref: #/components/schemas/CandidateQuestionnaire +type CandidateQuestionnaire struct { + Version QuestionnaireVersion `json:"version"` + // Chosen specializations in the order the candidate gave them, each specialization at most once. Each + // one is assessed independently. + Specializations []QuestionnaireSpecialization `json:"specializations"` + // Working context, or null before the first save. + WorkContext NilWorkContext `json:"work_context"` + // Time of the last change, or null before the first save. + UpdatedAt NilTimestamp `json:"updated_at"` +} + +// GetVersion returns the value of Version. +func (s *CandidateQuestionnaire) GetVersion() QuestionnaireVersion { + return s.Version +} + +// GetSpecializations returns the value of Specializations. +func (s *CandidateQuestionnaire) GetSpecializations() []QuestionnaireSpecialization { + return s.Specializations +} + +// GetWorkContext returns the value of WorkContext. +func (s *CandidateQuestionnaire) GetWorkContext() NilWorkContext { + return s.WorkContext +} + +// GetUpdatedAt returns the value of UpdatedAt. +func (s *CandidateQuestionnaire) GetUpdatedAt() NilTimestamp { + return s.UpdatedAt +} + +// SetVersion sets the value of Version. +func (s *CandidateQuestionnaire) SetVersion(val QuestionnaireVersion) { + s.Version = val +} + +// SetSpecializations sets the value of Specializations. +func (s *CandidateQuestionnaire) SetSpecializations(val []QuestionnaireSpecialization) { + s.Specializations = val +} + +// SetWorkContext sets the value of WorkContext. +func (s *CandidateQuestionnaire) SetWorkContext(val NilWorkContext) { + s.WorkContext = val +} + +// SetUpdatedAt sets the value of UpdatedAt. +func (s *CandidateQuestionnaire) SetUpdatedAt(val NilTimestamp) { + s.UpdatedAt = val +} + +// CandidateQuestionnaireHeaders wraps CandidateQuestionnaire with response headers. +type CandidateQuestionnaireHeaders struct { + CacheControl CacheControlNoStore + Response CandidateQuestionnaire +} + +// GetCacheControl returns the value of CacheControl. +func (s *CandidateQuestionnaireHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *CandidateQuestionnaireHeaders) GetResponse() CandidateQuestionnaire { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *CandidateQuestionnaireHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *CandidateQuestionnaireHeaders) SetResponse(val CandidateQuestionnaire) { + s.Response = val +} + +func (*CandidateQuestionnaireHeaders) getMyQuestionnaireRes() {} +func (*CandidateQuestionnaireHeaders) saveMyQuestionnaireRes() {} + +// Complete new state of the questionnaire. It replaces the stored specializations and working context +// as a whole. Unknown fields are rejected, so a request cannot set a confirmed grade or a category. +// Ref: #/components/schemas/CandidateQuestionnaireUpdate +type CandidateQuestionnaireUpdate struct { + ExpectedVersion QuestionnaireVersion `json:"expected_version"` + // One or two chosen specializations. The schema limits the count; the server also requires each + // specialization to appear at most once and answers a repeated one with 400 validation_failed and the + // pointer of the repeated item's `specialization`, for example `/specializations/1/specialization`. + Specializations []QuestionnaireSpecialization `json:"specializations"` + WorkContext WorkContext `json:"work_context"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *CandidateQuestionnaireUpdate) GetExpectedVersion() QuestionnaireVersion { + return s.ExpectedVersion +} + +// GetSpecializations returns the value of Specializations. +func (s *CandidateQuestionnaireUpdate) GetSpecializations() []QuestionnaireSpecialization { + return s.Specializations +} + +// GetWorkContext returns the value of WorkContext. +func (s *CandidateQuestionnaireUpdate) GetWorkContext() WorkContext { + return s.WorkContext +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *CandidateQuestionnaireUpdate) SetExpectedVersion(val QuestionnaireVersion) { + s.ExpectedVersion = val +} + +// SetSpecializations sets the value of Specializations. +func (s *CandidateQuestionnaireUpdate) SetSpecializations(val []QuestionnaireSpecialization) { + s.Specializations = val +} + +// SetWorkContext sets the value of WorkContext. +func (s *CandidateQuestionnaireUpdate) SetWorkContext(val WorkContext) { + s.WorkContext = val +} + +// Professional direction with its specializations. Each specialization belongs to exactly one +// direction. +// Ref: #/components/schemas/CatalogDirection +type CatalogDirection struct { + Code DirectionCode `json:"code"` + // Display name in Russian. Plain text. + Title string `json:"title"` + // Specializations of the direction in display order. + Specializations []CatalogSpecialization `json:"specializations"` +} + +// GetCode returns the value of Code. +func (s *CatalogDirection) GetCode() DirectionCode { + return s.Code +} + +// GetTitle returns the value of Title. +func (s *CatalogDirection) GetTitle() string { + return s.Title +} + +// GetSpecializations returns the value of Specializations. +func (s *CatalogDirection) GetSpecializations() []CatalogSpecialization { + return s.Specializations +} + +// SetCode sets the value of Code. +func (s *CatalogDirection) SetCode(val DirectionCode) { + s.Code = val +} + +// SetTitle sets the value of Title. +func (s *CatalogDirection) SetTitle(val string) { + s.Title = val +} + +// SetSpecializations sets the value of Specializations. +func (s *CatalogDirection) SetSpecializations(val []CatalogSpecialization) { + s.Specializations = val +} + +// Grade of the scale with its display name. +// Ref: #/components/schemas/CatalogGrade +type CatalogGrade struct { + Code GradeCode `json:"code"` + // Display name in Russian. Plain text. + Title string `json:"title"` +} + +// GetCode returns the value of Code. +func (s *CatalogGrade) GetCode() GradeCode { + return s.Code +} + +// GetTitle returns the value of Title. +func (s *CatalogGrade) GetTitle() string { + return s.Title +} + +// SetCode sets the value of Code. +func (s *CatalogGrade) SetCode(val GradeCode) { + s.Code = val +} + +// SetTitle sets the value of Title. +func (s *CatalogGrade) SetTitle(val string) { + s.Title = val +} + +// Specialization in the catalog with its assessment availability. +// Ref: #/components/schemas/CatalogSpecialization +type CatalogSpecialization struct { + Code SpecializationCode `json:"code"` + // Display name in Russian. Plain text. + Title string `json:"title"` + TestAvailability TestAvailability `json:"test_availability"` +} + +// GetCode returns the value of Code. +func (s *CatalogSpecialization) GetCode() SpecializationCode { + return s.Code +} + +// GetTitle returns the value of Title. +func (s *CatalogSpecialization) GetTitle() string { + return s.Title +} + +// GetTestAvailability returns the value of TestAvailability. +func (s *CatalogSpecialization) GetTestAvailability() TestAvailability { + return s.TestAvailability +} + +// SetCode sets the value of Code. +func (s *CatalogSpecialization) SetCode(val SpecializationCode) { + s.Code = val +} + +// SetTitle sets the value of Title. +func (s *CatalogSpecialization) SetTitle(val string) { + s.Title = val +} + +// SetTestAvailability sets the value of TestAvailability. +func (s *CatalogSpecialization) SetTestAvailability(val TestAvailability) { + s.TestAvailability = val +} + type ConfirmEmailBadRequest Problem func (*ConfirmEmailBadRequest) confirmEmailRes() {} @@ -299,6 +564,78 @@ type ConsentTextVersion string type CsrfToken string +// Stable code of a professional direction, the group that a specialization belongs to. +// +// - development: Development. +// - infrastructure: Infrastructure. +// - data: Data. +// - security: Security. +// - quality: Quality. +// +// Adding a value is a contract change. +// Ref: #/components/schemas/DirectionCode +type DirectionCode string + +const ( + DirectionCodeDevelopment DirectionCode = "development" + DirectionCodeInfrastructure DirectionCode = "infrastructure" + DirectionCodeData DirectionCode = "data" + DirectionCodeSecurity DirectionCode = "security" + DirectionCodeQuality DirectionCode = "quality" +) + +// AllValues returns all DirectionCode values. +func (DirectionCode) AllValues() []DirectionCode { + return []DirectionCode{ + DirectionCodeDevelopment, + DirectionCodeInfrastructure, + DirectionCodeData, + DirectionCodeSecurity, + DirectionCodeQuality, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s DirectionCode) MarshalText() ([]byte, error) { + switch s { + case DirectionCodeDevelopment: + return []byte(s), nil + case DirectionCodeInfrastructure: + return []byte(s), nil + case DirectionCodeData: + return []byte(s), nil + case DirectionCodeSecurity: + return []byte(s), nil + case DirectionCodeQuality: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *DirectionCode) UnmarshalText(data []byte) error { + switch DirectionCode(data) { + case DirectionCodeDevelopment: + *s = DirectionCodeDevelopment + return nil + case DirectionCodeInfrastructure: + *s = DirectionCodeInfrastructure + return nil + case DirectionCodeData: + *s = DirectionCodeData + return nil + case DirectionCodeSecurity: + *s = DirectionCodeSecurity + return nil + case DirectionCodeQuality: + *s = DirectionCodeQuality + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + type EmailAddress string // Token from the email verification link. @@ -417,6 +754,74 @@ func (s *GetCurrentSessionOKHeaders) SetResponse(val Session) { func (*GetCurrentSessionOKHeaders) getCurrentSessionRes() {} +type GetMyQuestionnaireForbidden Problem + +func (*GetMyQuestionnaireForbidden) getMyQuestionnaireRes() {} + +type GetMyQuestionnaireUnauthorized Problem + +func (*GetMyQuestionnaireUnauthorized) getMyQuestionnaireRes() {} + +// 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. +// Ref: #/components/schemas/GradeCode +type GradeCode string + +const ( + GradeCodeIntern GradeCode = "intern" + GradeCodeJunior GradeCode = "junior" + GradeCodeMiddle GradeCode = "middle" + GradeCodeSenior GradeCode = "senior" +) + +// AllValues returns all GradeCode values. +func (GradeCode) AllValues() []GradeCode { + return []GradeCode{ + GradeCodeIntern, + GradeCodeJunior, + GradeCodeMiddle, + GradeCodeSenior, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s GradeCode) MarshalText() ([]byte, error) { + switch s { + case GradeCodeIntern: + return []byte(s), nil + case GradeCodeJunior: + return []byte(s), nil + case GradeCodeMiddle: + return []byte(s), nil + case GradeCodeSenior: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *GradeCode) UnmarshalText(data []byte) error { + switch GradeCode(data) { + case GradeCodeIntern: + *s = GradeCodeIntern + return nil + case GradeCodeJunior: + *s = GradeCodeJunior + return nil + case GradeCodeMiddle: + *s = GradeCodeMiddle + return nil + case GradeCodeSenior: + *s = GradeCodeSenior + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Ref: #/components/schemas/HealthResponse type HealthResponse struct { Status HealthResponseStatus `json:"status"` @@ -581,13 +986,196 @@ func (*LogoutNoContent) logoutRes() {} type NewPassword string +// NewNilCandidateExperience returns new NilCandidateExperience with value set to v. +func NewNilCandidateExperience(v CandidateExperience) NilCandidateExperience { + return NilCandidateExperience{ + Value: v, + } +} + +// NilCandidateExperience is nullable CandidateExperience. +type NilCandidateExperience struct { + Value CandidateExperience + Null bool +} + +// SetTo sets value to v. +func (o *NilCandidateExperience) SetTo(v CandidateExperience) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilCandidateExperience) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilCandidateExperience) SetToNull() { + o.Null = true + var v CandidateExperience + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilCandidateExperience) Get() (v CandidateExperience, 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 NilCandidateExperience) Or(d CandidateExperience) CandidateExperience { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilString returns new NilString with value set to v. +func NewNilString(v string) NilString { + return NilString{ + Value: v, + } +} + +// NilString is nullable string. +type NilString struct { + Value string + Null bool +} + +// SetTo sets value to v. +func (o *NilString) SetTo(v string) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilString) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilString) SetToNull() { + o.Null = true + var v string + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilString) Get() (v string, 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 NilString) Or(d string) string { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilTimestamp returns new NilTimestamp with value set to v. +func NewNilTimestamp(v Timestamp) NilTimestamp { + return NilTimestamp{ + Value: v, + } +} + +// NilTimestamp is nullable Timestamp. +type NilTimestamp struct { + Value Timestamp + Null bool +} + +// SetTo sets value to v. +func (o *NilTimestamp) SetTo(v Timestamp) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilTimestamp) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilTimestamp) SetToNull() { + o.Null = true + var v Timestamp + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilTimestamp) Get() (v Timestamp, 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 NilTimestamp) Or(d Timestamp) Timestamp { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilWorkContext returns new NilWorkContext with value set to v. +func NewNilWorkContext(v WorkContext) NilWorkContext { + return NilWorkContext{ + Value: v, + } +} + +// NilWorkContext is nullable WorkContext. +type NilWorkContext struct { + Value WorkContext + Null bool +} + +// SetTo sets value to v. +func (o *NilWorkContext) SetTo(v WorkContext) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilWorkContext) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilWorkContext) SetToNull() { + o.Null = true + var v WorkContext + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilWorkContext) Get() (v WorkContext, 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 NilWorkContext) Or(d WorkContext) WorkContext { + if v, ok := o.Get(); ok { + return v + } + return d +} + // Saved onboarding step that the account returns to after login. The server stores it and advances it // as each step completes; clients route by it and never set it directly. // // - candidate_consents: candidate consents beyond C1, which was given at registration. // - candidate_profile: candidate profile. // - candidate_questionnaire: candidate questionnaire. -// - candidate_assessment: choice of the expected grade and the assessment. +// - candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in +// the questionnaire, and this step offers it first; only an assessment result confirms a grade. The +// first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step +// (planned). // - employer_company: company profile of the employer. // - completed: onboarding is finished; the client opens the scenario home. // @@ -934,7 +1522,8 @@ func (*Problem) logoutRes() {} // - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. // - state_conflict (409): the operation conflicts with the current state of the resource, for example // an invitation that was already accepted. -// - version_conflict (412): If-Match does not match the current version. +// - version_conflict (412): If-Match, or an `expected_version` field in the request body, does not +// match the current version; nothing was changed. // - payload_too_large (413): the request body exceeds the limit. // - unsupported_media_type (415): the request Content-Type is not accepted. // - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. @@ -1284,6 +1873,79 @@ func (s *ProblemStatusCode) SetResponse(val Problem) { s.Response = val } +// One specialization chosen by the candidate with the candidate's self-assessment. +// `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the +// assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed +// grade, and with it a category, comes only from an assessment result and is never part of the +// questionnaire; unknown fields such as `confirmed_grade` or `category` are rejected. Task languages +// and the stack are attributes of the chosen specialization, not categories. +// Ref: #/components/schemas/QuestionnaireSpecialization +type QuestionnaireSpecialization struct { + Specialization SpecializationCode `json:"specialization"` + SelfAssessedGrade GradeCode `json:"self_assessed_grade"` + // Task languages in which the candidate wants to solve assessment tasks of this specialization. Each + // value must be one of `test_availability.task_languages` of the specialization in the current + // catalog; any other value answers 400 validation_failed with a pointer to it. Empty when the bank + // offers no choice of language. + TaskLanguages []TaskLanguage `json:"task_languages"` + // Technology tags of the candidate in this specialization. + Stack []StackTag `json:"stack"` + // Stated experience, or null when the candidate did not state it. + Experience NilCandidateExperience `json:"experience"` +} + +// GetSpecialization returns the value of Specialization. +func (s *QuestionnaireSpecialization) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetSelfAssessedGrade returns the value of SelfAssessedGrade. +func (s *QuestionnaireSpecialization) GetSelfAssessedGrade() GradeCode { + return s.SelfAssessedGrade +} + +// GetTaskLanguages returns the value of TaskLanguages. +func (s *QuestionnaireSpecialization) GetTaskLanguages() []TaskLanguage { + return s.TaskLanguages +} + +// GetStack returns the value of Stack. +func (s *QuestionnaireSpecialization) GetStack() []StackTag { + return s.Stack +} + +// GetExperience returns the value of Experience. +func (s *QuestionnaireSpecialization) GetExperience() NilCandidateExperience { + return s.Experience +} + +// SetSpecialization sets the value of Specialization. +func (s *QuestionnaireSpecialization) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetSelfAssessedGrade sets the value of SelfAssessedGrade. +func (s *QuestionnaireSpecialization) SetSelfAssessedGrade(val GradeCode) { + s.SelfAssessedGrade = val +} + +// SetTaskLanguages sets the value of TaskLanguages. +func (s *QuestionnaireSpecialization) SetTaskLanguages(val []TaskLanguage) { + s.TaskLanguages = val +} + +// SetStack sets the value of Stack. +func (s *QuestionnaireSpecialization) SetStack(val []StackTag) { + s.Stack = val +} + +// SetExperience sets the value of Experience. +func (s *QuestionnaireSpecialization) SetExperience(val NilCandidateExperience) { + s.Experience = val +} + +type QuestionnaireVersion int64 + type RegisterAccountBadRequest Problem func (*RegisterAccountBadRequest) registerAccountRes() {} @@ -1357,6 +2019,22 @@ type ResendEmailVerificationForbidden Problem func (*ResendEmailVerificationForbidden) resendEmailVerificationRes() {} +type SaveMyQuestionnaireBadRequest Problem + +func (*SaveMyQuestionnaireBadRequest) saveMyQuestionnaireRes() {} + +type SaveMyQuestionnaireForbidden Problem + +func (*SaveMyQuestionnaireForbidden) saveMyQuestionnaireRes() {} + +type SaveMyQuestionnairePreconditionFailed Problem + +func (*SaveMyQuestionnairePreconditionFailed) saveMyQuestionnaireRes() {} + +type SaveMyQuestionnaireUnauthorized Problem + +func (*SaveMyQuestionnaireUnauthorized) saveMyQuestionnaireRes() {} + // Current session as the client may see it: the account and the CSRF token. The session identifier // itself travels only in the HttpOnly session cookie and never appears in a body. // Ref: #/components/schemas/Session @@ -1474,6 +2152,298 @@ func (s *SessionHeaders) SetResponse(val Session) { func (*SessionHeaders) loginRes() {} +// Catalog of directions, specializations, and the grade scale that the questionnaire and the +// assessment use. The catalog is reference data and identical for every caller; it contains no +// personal data. +// Ref: #/components/schemas/SpecializationCatalog +type SpecializationCatalog struct { + // Directions in display order. + Directions []CatalogDirection `json:"directions"` + // Grade scale in ascending order. + Grades []CatalogGrade `json:"grades"` +} + +// GetDirections returns the value of Directions. +func (s *SpecializationCatalog) GetDirections() []CatalogDirection { + return s.Directions +} + +// GetGrades returns the value of Grades. +func (s *SpecializationCatalog) GetGrades() []CatalogGrade { + return s.Grades +} + +// SetDirections sets the value of Directions. +func (s *SpecializationCatalog) SetDirections(val []CatalogDirection) { + s.Directions = val +} + +// SetGrades sets the value of Grades. +func (s *SpecializationCatalog) SetGrades(val []CatalogGrade) { + s.Grades = val +} + +// 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. +// +// - backend: Backend (development). +// - frontend: Frontend (development). +// - mobile: Mobile (development). +// - network_engineer: Network Engineer (infrastructure). +// - devops_sre: DevOps/SRE (infrastructure). +// - data_analyst: Data Analyst (data). +// - ds_ml: DS/ML (data). +// - information_security: Information security (security). +// - qa: QA (quality). +// +// Adding a value is a contract change; renaming or removing one is a breaking change. +// Ref: #/components/schemas/SpecializationCode +type SpecializationCode string + +const ( + SpecializationCodeBackend SpecializationCode = "backend" + SpecializationCodeFrontend SpecializationCode = "frontend" + SpecializationCodeMobile SpecializationCode = "mobile" + SpecializationCodeNetworkEngineer SpecializationCode = "network_engineer" + SpecializationCodeDevopsSre SpecializationCode = "devops_sre" + SpecializationCodeDataAnalyst SpecializationCode = "data_analyst" + SpecializationCodeDsMl SpecializationCode = "ds_ml" + SpecializationCodeInformationSecurity SpecializationCode = "information_security" + SpecializationCodeQa SpecializationCode = "qa" +) + +// AllValues returns all SpecializationCode values. +func (SpecializationCode) AllValues() []SpecializationCode { + return []SpecializationCode{ + SpecializationCodeBackend, + SpecializationCodeFrontend, + SpecializationCodeMobile, + SpecializationCodeNetworkEngineer, + SpecializationCodeDevopsSre, + SpecializationCodeDataAnalyst, + SpecializationCodeDsMl, + SpecializationCodeInformationSecurity, + SpecializationCodeQa, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SpecializationCode) MarshalText() ([]byte, error) { + switch s { + case SpecializationCodeBackend: + return []byte(s), nil + case SpecializationCodeFrontend: + return []byte(s), nil + case SpecializationCodeMobile: + return []byte(s), nil + case SpecializationCodeNetworkEngineer: + return []byte(s), nil + case SpecializationCodeDevopsSre: + return []byte(s), nil + case SpecializationCodeDataAnalyst: + return []byte(s), nil + case SpecializationCodeDsMl: + return []byte(s), nil + case SpecializationCodeInformationSecurity: + return []byte(s), nil + case SpecializationCodeQa: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SpecializationCode) UnmarshalText(data []byte) error { + switch SpecializationCode(data) { + case SpecializationCodeBackend: + *s = SpecializationCodeBackend + return nil + case SpecializationCodeFrontend: + *s = SpecializationCodeFrontend + return nil + case SpecializationCodeMobile: + *s = SpecializationCodeMobile + return nil + case SpecializationCodeNetworkEngineer: + *s = SpecializationCodeNetworkEngineer + return nil + case SpecializationCodeDevopsSre: + *s = SpecializationCodeDevopsSre + return nil + case SpecializationCodeDataAnalyst: + *s = SpecializationCodeDataAnalyst + return nil + case SpecializationCodeDsMl: + *s = SpecializationCodeDsMl + return nil + case SpecializationCodeInformationSecurity: + *s = SpecializationCodeInformationSecurity + return nil + case SpecializationCodeQa: + *s = SpecializationCodeQa + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type StackTag string + +// Programming language in which assessment tasks of a specialization are offered and solved. It is the +// language of the task bank, not the candidate's platform stack, and it never forms a separate +// category. Only banks that offer a choice of language define task languages; the first Backend bank +// offers Python and Go. Adding a value is a contract change. +// Ref: #/components/schemas/TaskLanguage +type TaskLanguage string + +const ( + TaskLanguagePython TaskLanguage = "python" + TaskLanguageGo TaskLanguage = "go" +) + +// AllValues returns all TaskLanguage values. +func (TaskLanguage) AllValues() []TaskLanguage { + return []TaskLanguage{ + TaskLanguagePython, + TaskLanguageGo, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s TaskLanguage) MarshalText() ([]byte, error) { + switch s { + case TaskLanguagePython: + return []byte(s), nil + case TaskLanguageGo: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *TaskLanguage) UnmarshalText(data []byte) error { + switch TaskLanguage(data) { + case TaskLanguagePython: + *s = TaskLanguagePython + return nil + case TaskLanguageGo: + *s = TaskLanguageGo + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Assessment availability of a specialization, derived by the server from the published task banks at +// the time of the request. The MVP opens an assessment only for a category, a specialization and a +// grade, that has a published bank. `status` is `available` exactly when `grades` is not empty; for +// `in_development` both `grades` and `task_languages` are empty. +// Ref: #/components/schemas/TestAvailability +type TestAvailability struct { + Status TestAvailabilityStatus `json:"status"` + // Grades of the specialization with a published task bank, in ascending order. Only these categories + // can be assessed and confirmed. + Grades []GradeCode `json:"grades"` + // Task languages that the published bank offers for this specialization. Empty when the bank does not + // offer a choice of language, as for Network Engineer, or when no bank is published. The questionnaire + // accepts only these languages for the specialization. + TaskLanguages []TaskLanguage `json:"task_languages"` + // Short Russian note for the candidate, for example why the test is not available yet, or null. Plain + // text; the client shows it as text, never as HTML. + Note NilString `json:"note"` +} + +// GetStatus returns the value of Status. +func (s *TestAvailability) GetStatus() TestAvailabilityStatus { + return s.Status +} + +// GetGrades returns the value of Grades. +func (s *TestAvailability) GetGrades() []GradeCode { + return s.Grades +} + +// GetTaskLanguages returns the value of TaskLanguages. +func (s *TestAvailability) GetTaskLanguages() []TaskLanguage { + return s.TaskLanguages +} + +// GetNote returns the value of Note. +func (s *TestAvailability) GetNote() NilString { + return s.Note +} + +// SetStatus sets the value of Status. +func (s *TestAvailability) SetStatus(val TestAvailabilityStatus) { + s.Status = val +} + +// SetGrades sets the value of Grades. +func (s *TestAvailability) SetGrades(val []GradeCode) { + s.Grades = val +} + +// SetTaskLanguages sets the value of TaskLanguages. +func (s *TestAvailability) SetTaskLanguages(val []TaskLanguage) { + s.TaskLanguages = val +} + +// SetNote sets the value of Note. +func (s *TestAvailability) SetNote(val NilString) { + s.Note = val +} + +// Whether an assessment can start for the specialization. `available` means that a published task bank +// exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no +// grade of the specialization has a published bank yet; the specialization can still be chosen in the +// questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the +// catalog or in demo data never means that a test is ready. +// Ref: #/components/schemas/TestAvailabilityStatus +type TestAvailabilityStatus string + +const ( + TestAvailabilityStatusAvailable TestAvailabilityStatus = "available" + TestAvailabilityStatusInDevelopment TestAvailabilityStatus = "in_development" +) + +// AllValues returns all TestAvailabilityStatus values. +func (TestAvailabilityStatus) AllValues() []TestAvailabilityStatus { + return []TestAvailabilityStatus{ + TestAvailabilityStatusAvailable, + TestAvailabilityStatusInDevelopment, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s TestAvailabilityStatus) MarshalText() ([]byte, error) { + switch s { + case TestAvailabilityStatusAvailable: + return []byte(s), nil + case TestAvailabilityStatusInDevelopment: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *TestAvailabilityStatus) UnmarshalText(data []byte) error { + switch TestAvailabilityStatus(data) { + case TestAvailabilityStatusAvailable: + *s = TestAvailabilityStatusAvailable + return nil + case TestAvailabilityStatusInDevelopment: + *s = TestAvailabilityStatusInDevelopment + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + type Timestamp time.Time // TooManyRequestsHeaders wraps Problem with response headers. @@ -1508,3 +2478,71 @@ func (*TooManyRequestsHeaders) registerAccountRes() {} func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} type VerificationToken string + +// Working context of the candidate's search. It holds no personal data such as an address or a city; +// location, relocation, and salary expectations belong to the candidate profile. +// Ref: #/components/schemas/WorkContext +type WorkContext struct { + // Acceptable work formats. + WorkFormats []WorkFormat `json:"work_formats"` +} + +// GetWorkFormats returns the value of WorkFormats. +func (s *WorkContext) GetWorkFormats() []WorkFormat { + return s.WorkFormats +} + +// SetWorkFormats sets the value of WorkFormats. +func (s *WorkContext) SetWorkFormats(val []WorkFormat) { + s.WorkFormats = val +} + +// Acceptable work format: `remote`, `office`, or `hybrid`. +// Ref: #/components/schemas/WorkFormat +type WorkFormat string + +const ( + WorkFormatRemote WorkFormat = "remote" + WorkFormatOffice WorkFormat = "office" + WorkFormatHybrid WorkFormat = "hybrid" +) + +// AllValues returns all WorkFormat values. +func (WorkFormat) AllValues() []WorkFormat { + return []WorkFormat{ + WorkFormatRemote, + WorkFormatOffice, + WorkFormatHybrid, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s WorkFormat) MarshalText() ([]byte, error) { + switch s { + case WorkFormatRemote: + return []byte(s), nil + case WorkFormatOffice: + return []byte(s), nil + case WorkFormatHybrid: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *WorkFormat) UnmarshalText(data []byte) error { + switch WorkFormat(data) { + case WorkFormatRemote: + *s = WorkFormatRemote + return nil + case WorkFormatOffice: + *s = WorkFormatOffice + return nil + case WorkFormatHybrid: + *s = WorkFormatHybrid + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index 0021bc5..ea8dfd0 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -56,9 +56,11 @@ func findAuthorization(h http.Header, prefix string) (string, bool) { // operationRolesSessionCookie is a private map storing roles per operation. var operationRolesSessionCookie = map[string][]string{ - GetCurrentAccountOperation: []string{}, - GetCurrentSessionOperation: []string{}, - LogoutOperation: []string{}, + GetCurrentAccountOperation: []string{}, + GetCurrentSessionOperation: []string{}, + GetMyQuestionnaireOperation: []string{}, + LogoutOperation: []string{}, + SaveMyQuestionnaireOperation: []string{}, } // GetRolesForSessionCookie returns the required roles for the given operation. @@ -84,7 +86,8 @@ func GetRolesForSessionCookie(operation string) []string { // operationRolesSessionCsrf is a private map storing roles per operation. var operationRolesSessionCsrf = map[string][]string{ - LogoutOperation: []string{}, + LogoutOperation: []string{}, + SaveMyQuestionnaireOperation: []string{}, } // GetRolesForSessionCsrf returns the required roles for the given operation. diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index 73c49b8..9c832cc 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -71,6 +71,39 @@ type Handler interface { // // GET /api/v1/healthz GetHealthz(ctx context.Context) (*HealthResponse, error) + // GetMyQuestionnaire implements GetMyQuestionnaire operation. + // + // Requires the session cookie of a candidate account. The candidate comes from the session, never from + // a request parameter. A candidate who has not saved the questionnaire yet gets 200 with version 0 and + // no specializations rather than 404, so the client reads the version for the first save in the same + // way as for later ones and a missing questionnaire is not an error state. + // + // The response never contains a confirmed grade or a category; those come only from assessment + // results. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer + // account answers 403 forbidden. + // + // GET /api/v1/me/questionnaire + GetMyQuestionnaire(ctx context.Context) (GetMyQuestionnaireRes, error) + // GetSpecializationCatalog implements GetSpecializationCatalog operation. + // + // Public operation without a session. Returns the directions with their specializations, the + // assessment availability of each specialization, and the grade scale. The candidate picks + // specializations and self-assessed grades from this catalog for the questionnaire, and the client + // joins the codes stored in the questionnaire with the titles here. + // + // The catalog is public because it is the same for every caller and contains no personal data: the + // product shows it before registration, and a public read lets intermediaries and the browser cache + // it. It reveals nothing beyond what the landing pages already show. + // + // A category is a specialization together with a confirmed grade. Task languages and the stack are + // attributes of a chosen specialization and never appear as categories. `test_availability` is derived + // from the published task banks at the time of the request, so it changes when a bank is published, + // without a contract change: the MVP opens an assessment only for a category with a published bank, + // and every other specialization is marked `in_development`. Presence in the catalog never means that + // its test is ready. + // + // GET /api/v1/specializations + GetSpecializationCatalog(ctx context.Context) (*SpecializationCatalog, error) // Login implements Login operation. // // Public operation that starts a server session. The server verifies the password with Argon2id; for @@ -164,6 +197,43 @@ type Handler interface { // // POST /api/v1/identity/email-verification-requests ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (ResendEmailVerificationRes, error) + // SaveMyQuestionnaire implements SaveMyQuestionnaire operation. + // + // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, + // and an allowed Origin. The body is the complete new state: one or two specializations, each with a + // self-assessed grade, task languages, stack tags, and stated experience or null, and the working + // context. It replaces the stored questionnaire as a whole. + // + // Self-assessment is a claim. It influences where the assessment starts and which grade the assessment + // step offers first, but it adds no points and never writes a confirmed grade or a category: a + // self-assessed `senior`, or the word "Senior" in a stack tag, never assigns the Senior category. A + // real profile stays invisible to employers until an assessment confirms a category. Choosing a + // specialization whose test is `in_development` is allowed; no assessment starts for it until its bank + // is published. Removing a specialization from the questionnaire does not change assessment results. + // + // Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, + // 0 for the first save. If it is not the current version, the server answers 412 version_conflict and + // changes nothing; the client reads the questionnaire again. The version travels in the body rather + // than in If-Match because the generated client cannot read the ETag response header yet. The status + // and code are the same as for a failed If-Match, since the client action is the same. + // + // The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose + // specializations and working context equal the stored ones changes nothing, keeps the version, and + // answers 200 with the current questionnaire even when `expected_version` is older, so a retry after a + // lost response of a successful save succeeds instead of failing with 412. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden for an employer), domain rules (400), then the version (412). The + // schema rejects more than two specializations, an unknown grade, specialization, or task language, + // and unknown fields. The server also rejects a repeated specialization and a task language that the + // specialization's published bank does not offer, with 400 validation_failed and pointers to the + // items, for example `/specializations/1/specialization` or `/specializations/0/task_languages/0`. + // + // A successful save on the onboarding step candidate_questionnaire advances the account to + // candidate_assessment (planned). + // + // PUT /api/v1/me/questionnaire + SaveMyQuestionnaire(ctx context.Context, req *CandidateQuestionnaireUpdate) (SaveMyQuestionnaireRes, error) // NewError creates *ProblemStatusCode from error returned by handler. // // Used for common default response. diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 9e83fbf..87e8122 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -91,6 +91,45 @@ func (UnimplementedHandler) GetHealthz(ctx context.Context) (r *HealthResponse, return r, ht.ErrNotImplemented } +// GetMyQuestionnaire implements GetMyQuestionnaire operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, never from +// a request parameter. A candidate who has not saved the questionnaire yet gets 200 with version 0 and +// no specializations rather than 404, so the client reads the version for the first save in the same +// way as for later ones and a missing questionnaire is not an error state. +// +// The response never contains a confirmed grade or a category; those come only from assessment +// results. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer +// account answers 403 forbidden. +// +// GET /api/v1/me/questionnaire +func (UnimplementedHandler) GetMyQuestionnaire(ctx context.Context) (r GetMyQuestionnaireRes, _ error) { + return r, ht.ErrNotImplemented +} + +// GetSpecializationCatalog implements GetSpecializationCatalog operation. +// +// Public operation without a session. Returns the directions with their specializations, the +// assessment availability of each specialization, and the grade scale. The candidate picks +// specializations and self-assessed grades from this catalog for the questionnaire, and the client +// joins the codes stored in the questionnaire with the titles here. +// +// The catalog is public because it is the same for every caller and contains no personal data: the +// product shows it before registration, and a public read lets intermediaries and the browser cache +// it. It reveals nothing beyond what the landing pages already show. +// +// A category is a specialization together with a confirmed grade. Task languages and the stack are +// attributes of a chosen specialization and never appear as categories. `test_availability` is derived +// from the published task banks at the time of the request, so it changes when a bank is published, +// without a contract change: the MVP opens an assessment only for a category with a published bank, +// and every other specialization is marked `in_development`. Presence in the catalog never means that +// its test is ready. +// +// GET /api/v1/specializations +func (UnimplementedHandler) GetSpecializationCatalog(ctx context.Context) (r *SpecializationCatalog, _ error) { + return r, ht.ErrNotImplemented +} + // Login implements Login operation. // // Public operation that starts a server session. The server verifies the password with Argon2id; for @@ -196,6 +235,46 @@ func (UnimplementedHandler) ResendEmailVerification(ctx context.Context, req *Em return r, ht.ErrNotImplemented } +// SaveMyQuestionnaire implements SaveMyQuestionnaire operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The body is the complete new state: one or two specializations, each with a +// self-assessed grade, task languages, stack tags, and stated experience or null, and the working +// context. It replaces the stored questionnaire as a whole. +// +// Self-assessment is a claim. It influences where the assessment starts and which grade the assessment +// step offers first, but it adds no points and never writes a confirmed grade or a category: a +// self-assessed `senior`, or the word "Senior" in a stack tag, never assigns the Senior category. A +// real profile stays invisible to employers until an assessment confirms a category. Choosing a +// specialization whose test is `in_development` is allowed; no assessment starts for it until its bank +// is published. Removing a specialization from the questionnaire does not change assessment results. +// +// Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, +// 0 for the first save. If it is not the current version, the server answers 412 version_conflict and +// changes nothing; the client reads the questionnaire again. The version travels in the body rather +// than in If-Match because the generated client cannot read the ETag response header yet. The status +// and code are the same as for a failed If-Match, since the client action is the same. +// +// The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose +// specializations and working context equal the stored ones changes nothing, keeps the version, and +// answers 200 with the current questionnaire even when `expected_version` is older, so a retry after a +// lost response of a successful save succeeds instead of failing with 412. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden for an employer), domain rules (400), then the version (412). The +// schema rejects more than two specializations, an unknown grade, specialization, or task language, +// and unknown fields. The server also rejects a repeated specialization and a task language that the +// specialization's published bank does not offer, with 400 validation_failed and pointers to the +// items, for example `/specializations/1/specialization` or `/specializations/0/task_languages/0`. +// +// A successful save on the onboarding step candidate_questionnaire advances the account to +// candidate_assessment (planned). +// +// PUT /api/v1/me/questionnaire +func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *CandidateQuestionnaireUpdate) (r SaveMyQuestionnaireRes, _ error) { + return r, ht.ErrNotImplemented +} + // NewError creates *ProblemStatusCode from error returned by handler. // // Used for common default response. 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 58ce294..ba744da 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -108,6 +108,426 @@ func (s CacheControlNoStore) Validate() error { } } +func (s *CandidateExperience) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 600, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.CommercialMonths)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "commercial_months", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 600, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.AcademicMonths)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "academic_months", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CandidateQuestionnaire) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if s.Specializations == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2, + MaxLengthSet: true, + }).ValidateLength(len(s.Specializations)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Specializations { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specializations", + Error: err, + }) + } + if err := func() error { + if value, ok := s.WorkContext.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: "work_context", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CandidateQuestionnaireHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CandidateQuestionnaireUpdate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if s.Specializations == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 2, + MaxLengthSet: true, + }).ValidateLength(len(s.Specializations)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Specializations { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specializations", + Error: err, + }) + } + if err := func() error { + if err := s.WorkContext.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "work_context", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CatalogDirection) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 100, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if err := func() error { + if s.Specializations == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Specializations)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Specializations { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specializations", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CatalogGrade) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 100, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CatalogSpecialization) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 100, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if err := func() error { + if err := s.TestAvailability.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "test_availability", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *ConfirmEmailBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -230,6 +650,23 @@ func (s CsrfToken) Validate() error { return nil } +func (s DirectionCode) Validate() error { + switch s { + case "development": + return nil + case "infrastructure": + return nil + case "data": + return nil + case "security": + return nil + case "quality": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s EmailAddress) Validate() error { alias := (string)(s) if err := (validate.String{ @@ -384,6 +821,37 @@ func (s *GetCurrentSessionOKHeaders) Validate() error { return nil } +func (s *GetMyQuestionnaireForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyQuestionnaireUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s GradeCode) Validate() error { + switch s { + case "intern": + return nil + case "junior": + return nil + case "middle": + return nil + case "senior": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *HealthResponse) Validate() error { if s == nil { return validate.ErrNilPointer @@ -1084,6 +1552,154 @@ func (s *ProblemStatusCode) Validate() error { return nil } +func (s *QuestionnaireSpecialization) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.SelfAssessedGrade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "self_assessed_grade", + Error: err, + }) + } + if err := func() error { + if s.TaskLanguages == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2, + MaxLengthSet: true, + }).ValidateLength(len(s.TaskLanguages)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.TaskLanguages); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.TaskLanguages { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "task_languages", + Error: err, + }) + } + if err := func() error { + if s.Stack == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Stack)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Stack); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Stack { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "stack", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Experience.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: "experience", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s QuestionnaireVersion) Validate() error { + alias := (int64)(s) + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(alias)); err != nil { + return errors.Wrap(err, "int") + } + return nil +} + func (s *RegisterAccountBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -1188,6 +1804,38 @@ func (s *ResendEmailVerificationForbidden) Validate() error { return nil } +func (s *SaveMyQuestionnaireBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SaveMyQuestionnaireForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SaveMyQuestionnairePreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SaveMyQuestionnaireUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *Session) Validate() error { if s == nil { return validate.ErrNilPointer @@ -1279,6 +1927,288 @@ func (s *SessionHeaders) Validate() error { return nil } +func (s *SpecializationCatalog) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Directions == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Directions)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Directions { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "directions", + Error: err, + }) + } + if err := func() error { + if s.Grades == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.Grades)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Grades { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "grades", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SpecializationCode) Validate() error { + switch s { + case "backend": + return nil + case "frontend": + return nil + case "mobile": + return nil + case "network_engineer": + return nil + case "devops_sre": + return nil + case "data_analyst": + return nil + case "ds_ml": + return nil + case "information_security": + return nil + case "qa": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s StackTag) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 50, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s TaskLanguage) Validate() error { + switch s { + case "python": + return nil + case "go": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *TestAvailability) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if s.Grades == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.Grades)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Grades); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Grades { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "grades", + Error: err, + }) + } + if err := func() error { + if s.TaskLanguages == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 2, + MaxLengthSet: true, + }).ValidateLength(len(s.TaskLanguages)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.TaskLanguages); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.TaskLanguages { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "task_languages", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Note.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 300, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "note", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s TestAvailabilityStatus) Validate() error { + switch s { + case "available": + return nil + case "in_development": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *TooManyRequestsHeaders) Validate() error { if s == nil { return validate.ErrNilPointer @@ -1349,3 +2279,67 @@ func (s VerificationToken) Validate() error { } return nil } + +func (s *WorkContext) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.WorkFormats == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 3, + MaxLengthSet: true, + }).ValidateLength(len(s.WorkFormats)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.WorkFormats); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.WorkFormats { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "work_formats", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s WorkFormat) Validate() error { + switch s { + case "remote": + return nil + case "office": + return nil + case "hybrid": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index e695af7..29a8f9f 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -411,6 +411,159 @@ func TestGeneratedServerSecurityOrder(t *testing.T) { } } +const questionnairePath = "/api/v1/me/questionnaire" + +// Questionnaire specialization items shared by the questionnaire tests. +const ( + backendWithGo = `{"specialization":"backend","self_assessed_grade":"middle","task_languages":["go"],"stack":["PostgreSQL"],"experience":{"commercial_months":30,"academic_months":12}}` + networkEngineer = `{"specialization":"network_engineer","self_assessed_grade":"junior","task_languages":[],"stack":[],"experience":null}` + frontendInterest = `{"specialization":"frontend","self_assessed_grade":"junior","task_languages":[],"stack":["React"],"experience":null}` +) + +// questionnaireBody returns a SaveMyQuestionnaire body with the given +// specialization items. +func questionnaireBody(specializations ...string) string { + return `{"expected_version":0,"specializations":[` + strings.Join(specializations, ",") + `],"work_context":{"work_formats":["remote"]}}` +} + +// The schema alone must reject the questionnaire values that FR03 forbids: +// more than two specializations, a grade outside the scale, a task language +// that is not a bank language, and a confirmed grade set by the candidate. +// Security accepts the session here, so the request reaches body validation; +// a valid body then answers 501 until the questionnaire is implemented. +func TestQuestionnaireSchemaValidationPrecedesImplementation(t *testing.T) { + for _, test := range []struct { + name string + body string + statusCode int + pointer string + code string + }{ + { + // Go is a task language of the backend specialization, not a + // category of its own. + name: "Backend with Go and Network Engineer", + body: questionnaireBody(backendWithGo, networkEngineer), + statusCode: http.StatusNotImplemented, + }, + { + name: "three specializations", + body: questionnaireBody(backendWithGo, networkEngineer, frontendInterest), + statusCode: http.StatusBadRequest, + pointer: "/specializations", + code: "invalid", + }, + { + name: "no specialization", + body: questionnaireBody(), + statusCode: http.StatusBadRequest, + pointer: "/specializations", + code: "invalid", + }, + { + name: "grade outside the MVP scale", + body: questionnaireBody(strings.Replace(backendWithGo, `"middle"`, `"lead"`, 1)), + statusCode: http.StatusBadRequest, + pointer: "/specializations/0/self_assessed_grade", + code: "invalid", + }, + { + // A language is never a specialization code. + name: "language as a specialization", + body: questionnaireBody(strings.Replace(backendWithGo, `"backend"`, `"go"`, 1)), + statusCode: http.StatusBadRequest, + pointer: "/specializations/0/specialization", + code: "invalid", + }, + { + name: "task language outside the bank languages", + body: questionnaireBody(strings.Replace(backendWithGo, `["go"]`, `["rust"]`, 1)), + statusCode: http.StatusBadRequest, + pointer: "/specializations/0/task_languages/0", + code: "invalid", + }, + { + // The decoder does not record the path of an unknown field in a + // nested object, so the pointer is the whole body. + name: "confirmed grade set by the candidate", + body: questionnaireBody(strings.Replace(backendWithGo, `"stack"`, `"confirmed_grade":"senior","stack"`, 1)), + statusCode: http.StatusBadRequest, + pointer: "", + code: "invalid", + }, + { + name: "missing expected version", + body: strings.Replace(questionnaireBody(backendWithGo), `"expected_version":0,`, "", 1), + statusCode: http.StatusBadRequest, + pointer: "/expected_version", + code: "required", + }, + } { + t.Run(test.name, func(t *testing.T) { + logger := slog.New(slog.DiscardHandler) + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + response := serveIdentityRequest(t, router, identityRequest{ + method: http.MethodPut, path: questionnairePath, body: test.body, + headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}, + }) + + if test.statusCode == http.StatusNotImplemented { + requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) + return + } + body := requireProblem(t, response, test.statusCode, api.ProblemCodeValidationFailed) + want := api.ProblemFieldError{In: api.ProblemFieldLocationBody, Pointer: test.pointer, Code: test.code} + for _, field := range body.Errors { + if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code { + return + } + } + t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want) + }) + } +} + +// The catalog is public; the questionnaire stays closed without a session. +func TestCatalogAndQuestionnaireAccessBeforeImplementation(t *testing.T) { + for _, test := range []struct { + name string + request identityRequest + statusCode int + code api.ProblemCode + }{ + { + name: "public catalog", + request: identityRequest{method: http.MethodGet, path: "/api/v1/specializations"}, + statusCode: http.StatusNotImplemented, + code: api.ProblemCodeNotImplemented, + }, + { + name: "questionnaire read without a session", + request: identityRequest{method: http.MethodGet, path: questionnairePath}, + statusCode: http.StatusUnauthorized, + code: api.ProblemCodeUnauthenticated, + }, + { + name: "questionnaire save with a denied session", + request: identityRequest{ + method: http.MethodPut, path: questionnairePath, body: questionnaireBody(backendWithGo), + headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}, + }, + statusCode: http.StatusUnauthorized, + code: api.ProblemCodeUnauthenticated, + }, + } { + t.Run(test.name, func(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + requireProblem(t, serveIdentityRequest(t, router, test.request), test.statusCode, test.code) + }) + } +} + func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) { var logs bytes.Buffer logger := slog.New(slog.NewJSONHandler(&logs, nil)) diff --git a/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts b/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts new file mode 100644 index 0000000..0c9dc72 --- /dev/null +++ b/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts @@ -0,0 +1,71 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + faker +} from '@faker-js/faker'; + +import { + HttpResponse, + http +} from 'msw'; +import type { + RequestHandlerOptions +} from 'msw'; + +import { + GradeCode, + SpecializationCode, + TaskLanguage, + WorkFormat +} from '../../schemas'; +import type { + CandidateExperience, + CandidateQuestionnaire, + WorkContext +} from '../../schemas'; + + +export const getGetMyQuestionnaireResponseCandidateExperienceMock = (overrideResponse: Partial = {}): CandidateExperience => ({...{commercial_months: faker.number.int({min: 0, max: 600}), academic_months: faker.number.int({min: 0, max: 600})}, ...overrideResponse}); + +export const getGetMyQuestionnaireResponseWorkContextMock = (overrideResponse: Partial = {}): WorkContext => ({...{work_formats: faker.helpers.arrayElements(Object.values(WorkFormat))}, ...overrideResponse}); + +export const getGetMyQuestionnaireResponseMock = (overrideResponse: Partial> = {}): CandidateQuestionnaire => ({version: faker.number.int({min: 0}), specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), self_assessed_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), stack: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"))), experience: faker.helpers.arrayElement([{...getGetMyQuestionnaireResponseCandidateExperienceMock()},null,])})), work_context: faker.helpers.arrayElement([{...getGetMyQuestionnaireResponseWorkContextMock()},null,]), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) + +export const getSaveMyQuestionnaireResponseCandidateExperienceMock = (overrideResponse: Partial = {}): CandidateExperience => ({...{commercial_months: faker.number.int({min: 0, max: 600}), academic_months: faker.number.int({min: 0, max: 600})}, ...overrideResponse}); + +export const getSaveMyQuestionnaireResponseWorkContextMock = (overrideResponse: Partial = {}): WorkContext => ({...{work_formats: faker.helpers.arrayElements(Object.values(WorkFormat))}, ...overrideResponse}); + +export const getSaveMyQuestionnaireResponseMock = (overrideResponse: Partial> = {}): CandidateQuestionnaire => ({version: faker.number.int({min: 0}), specializations: Array.from({ length: faker.number.int({min: 1, max: 2}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), self_assessed_grade: faker.helpers.arrayElement(Object.values(GradeCode)), task_languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), stack: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\S(?:.*\\S)?$"))), experience: faker.helpers.arrayElement([{...getSaveMyQuestionnaireResponseCandidateExperienceMock()},null,])})), work_context: faker.helpers.arrayElement([{...getSaveMyQuestionnaireResponseWorkContextMock()},null,]), 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) => { + return http.get('*/api/v1/me/questionnaire', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMyQuestionnaireResponseMock(), + { status: 200 + }) + }, options) +} + +export const getSaveMyQuestionnaireMockHandler = (overrideResponse?: CandidateQuestionnaire | ((info: Parameters[1]>[0]) => Promise | CandidateQuestionnaire), options?: RequestHandlerOptions) => { + return http.put('*/api/v1/me/questionnaire', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getSaveMyQuestionnaireResponseMock(), + { status: 200 + }) + }, options) +} +export const getCandidateMock = () => [ + getGetMyQuestionnaireMockHandler(), + getSaveMyQuestionnaireMockHandler() +] diff --git a/frontend/src/shared/api/endpoints/candidate/candidate.ts b/frontend/src/shared/api/endpoints/candidate/candidate.ts new file mode 100644 index 0000000..16793db --- /dev/null +++ b/frontend/src/shared/api/endpoints/candidate/candidate.ts @@ -0,0 +1,255 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + CandidateQuestionnaire, + CandidateQuestionnaireUpdate, + Problem +} from '../../schemas'; + +import { apiRequest } from '../../client'; +import type { ErrorType } from '../../client'; + + +type SecondParameter unknown> = Parameters[1]; + + + +const withQueryKey = (query: T, queryKey: K): T & { queryKey: K } => { + const result = { queryKey } as T & { queryKey: K }; + for (const key of Object.keys(query)) { + // The explicit queryKey always wins, matching the previous + // `{ ...query, queryKey }` spread where it was set last. + if (key === 'queryKey') continue; + Object.defineProperty(result, key, { + enumerable: true, + configurable: true, + get: () => (query as Record)[key], + }); + } + return result; +}; + +export const getGetMyQuestionnaireUrl = () => { + + + + + return `/api/v1/me/questionnaire` +} + +/** + * Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. A candidate who has not saved the questionnaire yet gets 200 with version 0 and no specializations rather than 404, so the client reads the version for the first save in the same way as for later ones and a missing questionnaire is not an error state. + * + * The response never contains a confirmed grade or a category; those come only from assessment results. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + * @summary Read the questionnaire of the current candidate. + */ +export const getMyQuestionnaire = async ( options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyQuestionnaireUrl(), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyQuestionnaireQueryKey = () => { + return [ + `/api/v1/me/questionnaire` + ] as const; + } + + +export const getGetMyQuestionnaireQueryOptions = >, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyQuestionnaireQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyQuestionnaire({ signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyQuestionnaireQueryResult = NonNullable>> +export type GetMyQuestionnaireQueryError = ErrorType + + +export function useGetMyQuestionnaire>, TError = ErrorType>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyQuestionnaire>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyQuestionnaire>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the questionnaire of the current candidate. + */ + +export function useGetMyQuestionnaire>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyQuestionnaireQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getSaveMyQuestionnaireUrl = () => { + + + + + return `/api/v1/me/questionnaire` +} + +/** + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new state: one or two specializations, each with a self-assessed grade, task languages, stack tags, and stated experience or null, and the working context. It replaces the stored questionnaire as a whole. + * + * Self-assessment is a claim. It influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never writes a confirmed grade or a category: a self-assessed `senior`, or the word "Senior" in a stack tag, never assigns the Senior category. A real profile stays invisible to employers until an assessment confirms a category. Choosing a specialization whose test is `in_development` is allowed; no assessment starts for it until its bank is published. Removing a specialization from the questionnaire does not change assessment results. + * + * Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first save. If it is not the current version, the server answers 412 version_conflict and changes nothing; the client reads the questionnaire again. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet. The status and code are the same as for a failed If-Match, since the client action is the same. + * + * The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose specializations and working context equal the stored ones changes nothing, keeps the version, and answers 200 with the current questionnaire even when `expected_version` is older, so a retry after a lost response of a successful save succeeds instead of failing with 412. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), domain rules (400), then the version (412). The schema rejects more than two specializations, an unknown grade, specialization, or task language, and unknown fields. The server also rejects a repeated specialization and a task language that the specialization's published bank does not offer, with 400 validation_failed and pointers to the items, for example `/specializations/1/specialization` or `/specializations/0/task_languages/0`. + * + * A successful save on the onboarding step candidate_questionnaire advances the account to candidate_assessment (planned). + * @summary Replace the questionnaire of the current candidate. + */ +export const saveMyQuestionnaire = async (candidateQuestionnaireUpdate: CandidateQuestionnaireUpdate, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getSaveMyQuestionnaireUrl(), + { + ...options, + method: 'PUT', + headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) }, + body: JSON.stringify(candidateQuestionnaireUpdate) + } +);} + + + + + +export const getSaveMyQuestionnaireMutationKey = () => ['saveMyQuestionnaire'] as const; + +export const getSaveMyQuestionnaireMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SaveMyQuestionnaireMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,SaveMyQuestionnaireMutationVariables, TContext> => { + +const mutationKey = getSaveMyQuestionnaireMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, SaveMyQuestionnaireMutationVariables> = (props) => { + const {data} = props ?? {}; + + return saveMyQuestionnaire(data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type SaveMyQuestionnaireMutationResult = NonNullable>> + export type SaveMyQuestionnaireMutationBody = CandidateQuestionnaireUpdate + export type SaveMyQuestionnaireMutationError = ErrorType + export type SaveMyQuestionnaireMutationVariables = {data: CandidateQuestionnaireUpdate} + + /** + * @summary Replace the questionnaire of the current candidate. + */ +export const useSaveMyQuestionnaire = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SaveMyQuestionnaireMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + SaveMyQuestionnaireMutationVariables, + TContext + > => { + return useMutation(getSaveMyQuestionnaireMutationOptions(options), queryClient); + } diff --git a/frontend/src/shared/api/endpoints/catalog/catalog.msw.ts b/frontend/src/shared/api/endpoints/catalog/catalog.msw.ts new file mode 100644 index 0000000..710446b --- /dev/null +++ b/frontend/src/shared/api/endpoints/catalog/catalog.msw.ts @@ -0,0 +1,47 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + faker +} from '@faker-js/faker'; + +import { + HttpResponse, + http +} from 'msw'; +import type { + RequestHandlerOptions +} from 'msw'; + +import { + DirectionCode, + GradeCode, + SpecializationCode, + TaskLanguage, + TestAvailabilityStatus +} from '../../schemas'; +import type { + SpecializationCatalog +} from '../../schemas'; + + +export const getGetSpecializationCatalogResponseMock = (overrideResponse: Partial> = {}): SpecializationCatalog => ({directions: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(Object.values(DirectionCode)), title: faker.string.alpha({length: {min: 1, max: 100}}), specializations: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(Object.values(SpecializationCode)), title: faker.string.alpha({length: {min: 1, max: 100}}), test_availability: {status: faker.helpers.arrayElement(Object.values(TestAvailabilityStatus)), grades: faker.helpers.arrayElements(Object.values(GradeCode)), task_languages: faker.helpers.arrayElements(Object.values(TaskLanguage)), note: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}), null])}}))})), grades: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({code: faker.helpers.arrayElement(Object.values(GradeCode)), title: faker.string.alpha({length: {min: 1, max: 100}})})), ...overrideResponse}) + + +export const getGetSpecializationCatalogMockHandler = (overrideResponse?: SpecializationCatalog | ((info: Parameters[1]>[0]) => Promise | SpecializationCatalog), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/specializations', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetSpecializationCatalogResponseMock(), + { status: 200 + }) + }, options) +} +export const getCatalogMock = () => [ + getGetSpecializationCatalogMockHandler() +] diff --git a/frontend/src/shared/api/endpoints/catalog/catalog.ts b/frontend/src/shared/api/endpoints/catalog/catalog.ts new file mode 100644 index 0000000..ac23939 --- /dev/null +++ b/frontend/src/shared/api/endpoints/catalog/catalog.ts @@ -0,0 +1,154 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + Problem, + SpecializationCatalog +} from '../../schemas'; + +import { apiRequest } from '../../client'; +import type { ErrorType } from '../../client'; + + +type SecondParameter unknown> = Parameters[1]; + + + +const withQueryKey = (query: T, queryKey: K): T & { queryKey: K } => { + const result = { queryKey } as T & { queryKey: K }; + for (const key of Object.keys(query)) { + // The explicit queryKey always wins, matching the previous + // `{ ...query, queryKey }` spread where it was set last. + if (key === 'queryKey') continue; + Object.defineProperty(result, key, { + enumerable: true, + configurable: true, + get: () => (query as Record)[key], + }); + } + return result; +}; + +export const getGetSpecializationCatalogUrl = () => { + + + + + return `/api/v1/specializations` +} + +/** + * Public operation without a session. Returns the directions with their specializations, the assessment availability of each specialization, and the grade scale. The candidate picks specializations and self-assessed grades from this catalog for the questionnaire, and the client joins the codes stored in the questionnaire with the titles here. + * + * The catalog is public because it is the same for every caller and contains no personal data: the product shows it before registration, and a public read lets intermediaries and the browser cache it. It reveals nothing beyond what the landing pages already show. + * + * A category is a specialization together with a confirmed grade. Task languages and the stack are attributes of a chosen specialization and never appear as categories. `test_availability` is derived from the published task banks at the time of the request, so it changes when a bank is published, without a contract change: the MVP opens an assessment only for a category with a published bank, and every other specialization is marked `in_development`. Presence in the catalog never means that its test is ready. + * @summary Read the catalog of directions, specializations, and grades. + */ +export const getSpecializationCatalog = async ( options?: Parameters[1]): Promise => { + + return apiRequest(getGetSpecializationCatalogUrl(), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetSpecializationCatalogQueryKey = () => { + return [ + `/api/v1/specializations` + ] as const; + } + + +export const getGetSpecializationCatalogQueryOptions = >, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetSpecializationCatalogQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => getSpecializationCatalog({ signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetSpecializationCatalogQueryResult = NonNullable>> +export type GetSpecializationCatalogQueryError = ErrorType + + +export function useGetSpecializationCatalog>, TError = ErrorType>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetSpecializationCatalog>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetSpecializationCatalog>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the catalog of directions, specializations, and grades. + */ + +export function useGetSpecializationCatalog>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetSpecializationCatalogQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + diff --git a/frontend/src/shared/api/endpoints/index.msw.ts b/frontend/src/shared/api/endpoints/index.msw.ts index a7e742b..1ea9c04 100644 --- a/frontend/src/shared/api/endpoints/index.msw.ts +++ b/frontend/src/shared/api/endpoints/index.msw.ts @@ -1,2 +1,4 @@ +export { getCandidateMock } from './candidate/candidate.msw' +export { getCatalogMock } from './catalog/catalog.msw' export { getHealthMock } from './health/health.msw' export { getIdentityMock } from './identity/identity.msw' diff --git a/frontend/src/shared/api/endpoints/index.ts b/frontend/src/shared/api/endpoints/index.ts index 3641307..f8ece84 100644 --- a/frontend/src/shared/api/endpoints/index.ts +++ b/frontend/src/shared/api/endpoints/index.ts @@ -1,2 +1,4 @@ +export * from './candidate/candidate'; +export * from './catalog/catalog'; export * from './health/health'; export * from './identity/identity'; diff --git a/frontend/src/shared/api/schemas/candidate/candidateExperience.zod.ts b/frontend/src/shared/api/schemas/candidate/candidateExperience.zod.ts new file mode 100644 index 0000000..16d9305 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/candidateExperience.zod.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const candidateExperienceCommercialMonthsMin = 0; +export const candidateExperienceCommercialMonthsMax = 600; + +export const candidateExperienceAcademicMonthsMin = 0; +export const candidateExperienceAcademicMonthsMax = 600; + + +export const CandidateExperience = zod.object({ + "commercial_months": zod.int().min(candidateExperienceCommercialMonthsMin).max(candidateExperienceCommercialMonthsMax).describe('Months of commercial work in the specialization.'), + "academic_months": zod.int().min(candidateExperienceAcademicMonthsMin).max(candidateExperienceAcademicMonthsMax).describe('Months of study, internships, or academic projects in the specialization.') +}).describe('Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade.') + +export type CandidateExperience = zod.input; +export type CandidateExperienceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/candidateQuestionnaire.zod.ts b/frontend/src/shared/api/schemas/candidate/candidateQuestionnaire.zod.ts new file mode 100644 index 0000000..92ea6e7 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/candidateQuestionnaire.zod.ts @@ -0,0 +1,49 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const candidateQuestionnaireVersionMin = 0; + +export const candidateQuestionnaireSpecializationsItemTaskLanguagesMax = 2; + +export const candidateQuestionnaireSpecializationsItemStackItemMax = 50; + + +export const candidateQuestionnaireSpecializationsItemStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const candidateQuestionnaireSpecializationsItemStackMax = 20; + +export const candidateQuestionnaireSpecializationsItemExperienceOneCommercialMonthsMin = 0; +export const candidateQuestionnaireSpecializationsItemExperienceOneCommercialMonthsMax = 600; + +export const candidateQuestionnaireSpecializationsItemExperienceOneAcademicMonthsMin = 0; +export const candidateQuestionnaireSpecializationsItemExperienceOneAcademicMonthsMax = 600; + +export const candidateQuestionnaireSpecializationsMax = 2; + +export const candidateQuestionnaireWorkContextOneWorkFormatsMax = 3; + + +export const CandidateQuestionnaire = zod.object({ + "version": zod.int().min(candidateQuestionnaireVersionMin).describe('Version of the candidate questionnaire. A candidate without a saved questionnaire has version 0; every save that changes the questionnaire advances it by one.'), + "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.'), + "self_assessed_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.'), + "task_languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(candidateQuestionnaireSpecializationsItemTaskLanguagesMax).describe('Task languages in which the candidate wants to solve assessment tasks of this specialization. Each value must be one of `test_availability.task_languages` of the specialization in the current catalog; any other value answers 400 validation_failed with a pointer to it. Empty when the bank offers no choice of language.'), + "stack": zod.array(zod.string().min(1).max(candidateQuestionnaireSpecializationsItemStackItemMax).regex(candidateQuestionnaireSpecializationsItemStackItemRegExp).describe('Free technology tag of the candidate\'s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.')).max(candidateQuestionnaireSpecializationsItemStackMax).describe('Technology tags of the candidate in this specialization.'), + "experience": zod.union([zod.object({ + "commercial_months": zod.int().min(candidateQuestionnaireSpecializationsItemExperienceOneCommercialMonthsMin).max(candidateQuestionnaireSpecializationsItemExperienceOneCommercialMonthsMax).describe('Months of commercial work in the specialization.'), + "academic_months": zod.int().min(candidateQuestionnaireSpecializationsItemExperienceOneAcademicMonthsMin).max(candidateQuestionnaireSpecializationsItemExperienceOneAcademicMonthsMax).describe('Months of study, internships, or academic projects in the specialization.') +}).describe('Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade.'),zod.null()]).describe('Stated experience, or null when the candidate did not state it.') +}).describe('One specialization chosen by the candidate with the candidate\'s self-assessment. `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed grade, and with it a category, comes only from an assessment result and is never part of the questionnaire; unknown fields such as `confirmed_grade` or `category` are rejected. Task languages and the stack are attributes of the chosen specialization, not categories.')).max(candidateQuestionnaireSpecializationsMax).describe('Chosen specializations in the order the candidate gave them, each specialization at most once. Each one is assessed independently.'), + "work_context": zod.union([zod.object({ + "work_formats": zod.array(zod.enum(['remote', 'office', 'hybrid']).describe('Acceptable work format: `remote`, `office`, or `hybrid`.')).min(1).max(candidateQuestionnaireWorkContextOneWorkFormatsMax).describe('Acceptable work formats.') +}).describe('Working context of the candidate\'s search. It holds no personal data such as an address or a city; location, relocation, and salary expectations belong to the candidate profile.'),zod.null()]).describe('Working context, or null before the first save.'), + "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('Questionnaire of the current candidate: the chosen specializations with self-assessed grades and the working context. It never contains a confirmed grade or a category; those come only from assessment results. A candidate who has not saved the questionnaire yet gets version 0, no specializations, and null `work_context` and `updated_at`.') + +export type CandidateQuestionnaire = zod.input; +export type CandidateQuestionnaireOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/candidateQuestionnaireUpdate.zod.ts b/frontend/src/shared/api/schemas/candidate/candidateQuestionnaireUpdate.zod.ts new file mode 100644 index 0000000..033833d --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/candidateQuestionnaireUpdate.zod.ts @@ -0,0 +1,48 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const candidateQuestionnaireUpdateExpectedVersionMin = 0; + +export const candidateQuestionnaireUpdateSpecializationsItemTaskLanguagesMax = 2; + +export const candidateQuestionnaireUpdateSpecializationsItemStackItemMax = 50; + + +export const candidateQuestionnaireUpdateSpecializationsItemStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const candidateQuestionnaireUpdateSpecializationsItemStackMax = 20; + +export const candidateQuestionnaireUpdateSpecializationsItemExperienceOneCommercialMonthsMin = 0; +export const candidateQuestionnaireUpdateSpecializationsItemExperienceOneCommercialMonthsMax = 600; + +export const candidateQuestionnaireUpdateSpecializationsItemExperienceOneAcademicMonthsMin = 0; +export const candidateQuestionnaireUpdateSpecializationsItemExperienceOneAcademicMonthsMax = 600; + +export const candidateQuestionnaireUpdateSpecializationsMax = 2; + +export const candidateQuestionnaireUpdateWorkContextWorkFormatsMax = 3; + + +export const CandidateQuestionnaireUpdate = zod.object({ + "expected_version": zod.int().min(candidateQuestionnaireUpdateExpectedVersionMin).describe('Version of the candidate questionnaire. A candidate without a saved questionnaire has version 0; every save that changes the questionnaire advances it by one.'), + "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.'), + "self_assessed_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.'), + "task_languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(candidateQuestionnaireUpdateSpecializationsItemTaskLanguagesMax).describe('Task languages in which the candidate wants to solve assessment tasks of this specialization. Each value must be one of `test_availability.task_languages` of the specialization in the current catalog; any other value answers 400 validation_failed with a pointer to it. Empty when the bank offers no choice of language.'), + "stack": zod.array(zod.string().min(1).max(candidateQuestionnaireUpdateSpecializationsItemStackItemMax).regex(candidateQuestionnaireUpdateSpecializationsItemStackItemRegExp).describe('Free technology tag of the candidate\'s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.')).max(candidateQuestionnaireUpdateSpecializationsItemStackMax).describe('Technology tags of the candidate in this specialization.'), + "experience": zod.union([zod.object({ + "commercial_months": zod.int().min(candidateQuestionnaireUpdateSpecializationsItemExperienceOneCommercialMonthsMin).max(candidateQuestionnaireUpdateSpecializationsItemExperienceOneCommercialMonthsMax).describe('Months of commercial work in the specialization.'), + "academic_months": zod.int().min(candidateQuestionnaireUpdateSpecializationsItemExperienceOneAcademicMonthsMin).max(candidateQuestionnaireUpdateSpecializationsItemExperienceOneAcademicMonthsMax).describe('Months of study, internships, or academic projects in the specialization.') +}).describe('Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade.'),zod.null()]).describe('Stated experience, or null when the candidate did not state it.') +}).describe('One specialization chosen by the candidate with the candidate\'s self-assessment. `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed grade, and with it a category, comes only from an assessment result and is never part of the questionnaire; unknown fields such as `confirmed_grade` or `category` are rejected. Task languages and the stack are attributes of the chosen specialization, not categories.')).min(1).max(candidateQuestionnaireUpdateSpecializationsMax).describe('One or two chosen specializations. The schema limits the count; the server also requires each specialization to appear at most once and answers a repeated one with 400 validation_failed and the pointer of the repeated item\'s `specialization`, for example `/specializations/1/specialization`.'), + "work_context": zod.object({ + "work_formats": zod.array(zod.enum(['remote', 'office', 'hybrid']).describe('Acceptable work format: `remote`, `office`, or `hybrid`.')).min(1).max(candidateQuestionnaireUpdateWorkContextWorkFormatsMax).describe('Acceptable work formats.') +}).describe('Working context of the candidate\'s search. It holds no personal data such as an address or a city; location, relocation, and salary expectations belong to the candidate profile.') +}).describe('Complete new state of the questionnaire. It replaces the stored specializations and working context as a whole. Unknown fields are rejected, so a request cannot set a confirmed grade or a category.') + +export type CandidateQuestionnaireUpdate = zod.input; +export type CandidateQuestionnaireUpdateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/index.ts b/frontend/src/shared/api/schemas/candidate/index.ts new file mode 100644 index 0000000..8b8b710 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/index.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ + +export * from './candidateExperience.zod'; +export * from './candidateQuestionnaire.zod'; +export * from './candidateQuestionnaireUpdate.zod'; +export * from './questionnaireSpecialization.zod'; +export * from './questionnaireVersion.zod'; +export * from './saveMyQuestionnaireBody.zod'; +export * from './stackTag.zod'; +export * from './workContext.zod'; +export * from './workFormat.zod'; diff --git a/frontend/src/shared/api/schemas/candidate/questionnaireSpecialization.zod.ts b/frontend/src/shared/api/schemas/candidate/questionnaireSpecialization.zod.ts new file mode 100644 index 0000000..f10a650 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/questionnaireSpecialization.zod.ts @@ -0,0 +1,36 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const questionnaireSpecializationTaskLanguagesMax = 2; + +export const questionnaireSpecializationStackItemMax = 50; + + +export const questionnaireSpecializationStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const questionnaireSpecializationStackMax = 20; + +export const questionnaireSpecializationExperienceOneCommercialMonthsMin = 0; +export const questionnaireSpecializationExperienceOneCommercialMonthsMax = 600; + +export const questionnaireSpecializationExperienceOneAcademicMonthsMin = 0; +export const questionnaireSpecializationExperienceOneAcademicMonthsMax = 600; + + +export const QuestionnaireSpecialization = 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.'), + "self_assessed_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.'), + "task_languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(questionnaireSpecializationTaskLanguagesMax).describe('Task languages in which the candidate wants to solve assessment tasks of this specialization. Each value must be one of `test_availability.task_languages` of the specialization in the current catalog; any other value answers 400 validation_failed with a pointer to it. Empty when the bank offers no choice of language.'), + "stack": zod.array(zod.string().min(1).max(questionnaireSpecializationStackItemMax).regex(questionnaireSpecializationStackItemRegExp).describe('Free technology tag of the candidate\'s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.')).max(questionnaireSpecializationStackMax).describe('Technology tags of the candidate in this specialization.'), + "experience": zod.union([zod.object({ + "commercial_months": zod.int().min(questionnaireSpecializationExperienceOneCommercialMonthsMin).max(questionnaireSpecializationExperienceOneCommercialMonthsMax).describe('Months of commercial work in the specialization.'), + "academic_months": zod.int().min(questionnaireSpecializationExperienceOneAcademicMonthsMin).max(questionnaireSpecializationExperienceOneAcademicMonthsMax).describe('Months of study, internships, or academic projects in the specialization.') +}).describe('Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade.'),zod.null()]).describe('Stated experience, or null when the candidate did not state it.') +}).describe('One specialization chosen by the candidate with the candidate\'s self-assessment. `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed grade, and with it a category, comes only from an assessment result and is never part of the questionnaire; unknown fields such as `confirmed_grade` or `category` are rejected. Task languages and the stack are attributes of the chosen specialization, not categories.') + +export type QuestionnaireSpecialization = zod.input; +export type QuestionnaireSpecializationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/questionnaireVersion.zod.ts b/frontend/src/shared/api/schemas/candidate/questionnaireVersion.zod.ts new file mode 100644 index 0000000..33748d4 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/questionnaireVersion.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const QuestionnaireVersionMin = 0; + + +export const QuestionnaireVersion = zod.int().min(QuestionnaireVersionMin).describe('Version of the candidate questionnaire. A candidate without a saved questionnaire has version 0; every save that changes the questionnaire advances it by one.') + +export type QuestionnaireVersion = zod.input; +export type QuestionnaireVersionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/saveMyQuestionnaireBody.zod.ts b/frontend/src/shared/api/schemas/candidate/saveMyQuestionnaireBody.zod.ts new file mode 100644 index 0000000..7dc151b --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/saveMyQuestionnaireBody.zod.ts @@ -0,0 +1,48 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const saveMyQuestionnaireBodyExpectedVersionMin = 0; + +export const saveMyQuestionnaireBodySpecializationsItemTaskLanguagesMax = 2; + +export const saveMyQuestionnaireBodySpecializationsItemStackItemMax = 50; + + +export const saveMyQuestionnaireBodySpecializationsItemStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const saveMyQuestionnaireBodySpecializationsItemStackMax = 20; + +export const saveMyQuestionnaireBodySpecializationsItemExperienceOneCommercialMonthsMin = 0; +export const saveMyQuestionnaireBodySpecializationsItemExperienceOneCommercialMonthsMax = 600; + +export const saveMyQuestionnaireBodySpecializationsItemExperienceOneAcademicMonthsMin = 0; +export const saveMyQuestionnaireBodySpecializationsItemExperienceOneAcademicMonthsMax = 600; + +export const saveMyQuestionnaireBodySpecializationsMax = 2; + +export const saveMyQuestionnaireBodyWorkContextWorkFormatsMax = 3; + + +export const SaveMyQuestionnaireBody = zod.object({ + "expected_version": zod.int().min(saveMyQuestionnaireBodyExpectedVersionMin).describe('Version of the candidate questionnaire. A candidate without a saved questionnaire has version 0; every save that changes the questionnaire advances it by one.'), + "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.'), + "self_assessed_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.'), + "task_languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(saveMyQuestionnaireBodySpecializationsItemTaskLanguagesMax).describe('Task languages in which the candidate wants to solve assessment tasks of this specialization. Each value must be one of `test_availability.task_languages` of the specialization in the current catalog; any other value answers 400 validation_failed with a pointer to it. Empty when the bank offers no choice of language.'), + "stack": zod.array(zod.string().min(1).max(saveMyQuestionnaireBodySpecializationsItemStackItemMax).regex(saveMyQuestionnaireBodySpecializationsItemStackItemRegExp).describe('Free technology tag of the candidate\'s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.')).max(saveMyQuestionnaireBodySpecializationsItemStackMax).describe('Technology tags of the candidate in this specialization.'), + "experience": zod.union([zod.object({ + "commercial_months": zod.int().min(saveMyQuestionnaireBodySpecializationsItemExperienceOneCommercialMonthsMin).max(saveMyQuestionnaireBodySpecializationsItemExperienceOneCommercialMonthsMax).describe('Months of commercial work in the specialization.'), + "academic_months": zod.int().min(saveMyQuestionnaireBodySpecializationsItemExperienceOneAcademicMonthsMin).max(saveMyQuestionnaireBodySpecializationsItemExperienceOneAcademicMonthsMax).describe('Months of study, internships, or academic projects in the specialization.') +}).describe('Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade.'),zod.null()]).describe('Stated experience, or null when the candidate did not state it.') +}).describe('One specialization chosen by the candidate with the candidate\'s self-assessment. `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed grade, and with it a category, comes only from an assessment result and is never part of the questionnaire; unknown fields such as `confirmed_grade` or `category` are rejected. Task languages and the stack are attributes of the chosen specialization, not categories.')).min(1).max(saveMyQuestionnaireBodySpecializationsMax).describe('One or two chosen specializations. The schema limits the count; the server also requires each specialization to appear at most once and answers a repeated one with 400 validation_failed and the pointer of the repeated item\'s `specialization`, for example `/specializations/1/specialization`.'), + "work_context": zod.object({ + "work_formats": zod.array(zod.enum(['remote', 'office', 'hybrid']).describe('Acceptable work format: `remote`, `office`, or `hybrid`.')).min(1).max(saveMyQuestionnaireBodyWorkContextWorkFormatsMax).describe('Acceptable work formats.') +}).describe('Working context of the candidate\'s search. It holds no personal data such as an address or a city; location, relocation, and salary expectations belong to the candidate profile.') +}).describe('Complete new state of the questionnaire. It replaces the stored specializations and working context as a whole. Unknown fields are rejected, so a request cannot set a confirmed grade or a category.') + +export type SaveMyQuestionnaireBody = zod.input; +export type SaveMyQuestionnaireBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/stackTag.zod.ts b/frontend/src/shared/api/schemas/candidate/stackTag.zod.ts new file mode 100644 index 0000000..7dff2c3 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/stackTag.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const StackTagMax = 50; + + +export const StackTagRegExp = new RegExp('^\\S(?:.*\\S)?$'); + +export const StackTag = zod.string().min(1).max(StackTagMax).regex(StackTagRegExp).describe('Free technology tag of the candidate\'s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.') + +export type StackTag = zod.input; +export type StackTagOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/workContext.zod.ts b/frontend/src/shared/api/schemas/candidate/workContext.zod.ts new file mode 100644 index 0000000..5d70b2d --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/workContext.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const workContextWorkFormatsMax = 3; + + +export const WorkContext = zod.object({ + "work_formats": zod.array(zod.enum(['remote', 'office', 'hybrid']).describe('Acceptable work format: `remote`, `office`, or `hybrid`.')).min(1).max(workContextWorkFormatsMax).describe('Acceptable work formats.') +}).describe('Working context of the candidate\'s search. It holds no personal data such as an address or a city; location, relocation, and salary expectations belong to the candidate profile.') + +export type WorkContext = zod.input; +export type WorkContextOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/workFormat.zod.ts b/frontend/src/shared/api/schemas/candidate/workFormat.zod.ts new file mode 100644 index 0000000..1931e88 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/workFormat.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const WorkFormat = zod.enum(['remote', 'office', 'hybrid']).describe('Acceptable work format: `remote`, `office`, or `hybrid`.') + +export type WorkFormat = zod.input; +export type WorkFormatOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/catalog/catalogDirection.zod.ts b/frontend/src/shared/api/schemas/catalog/catalogDirection.zod.ts new file mode 100644 index 0000000..4e2536d --- /dev/null +++ b/frontend/src/shared/api/schemas/catalog/catalogDirection.zod.ts @@ -0,0 +1,38 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const catalogDirectionTitleMax = 100; + +export const catalogDirectionSpecializationsItemTitleMax = 100; + +export const catalogDirectionSpecializationsItemTestAvailabilityGradesMax = 10; + +export const catalogDirectionSpecializationsItemTestAvailabilityTaskLanguagesMax = 2; + +export const catalogDirectionSpecializationsItemTestAvailabilityNoteMax = 300; + +export const catalogDirectionSpecializationsMax = 20; + + +export const CatalogDirection = zod.object({ + "code": zod.enum(['development', 'infrastructure', 'data', 'security', 'quality']).describe('Stable code of a professional direction, the group that a specialization belongs to.\n\n- development: Development.\n- infrastructure: Infrastructure.\n- data: Data.\n- security: Security.\n- quality: Quality.\n\nAdding a value is a contract change.'), + "title": zod.string().min(1).max(catalogDirectionTitleMax).describe('Display name in Russian. Plain text.'), + "specializations": zod.array(zod.object({ + "code": 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.'), + "title": zod.string().min(1).max(catalogDirectionSpecializationsItemTitleMax).describe('Display name in Russian. Plain text.'), + "test_availability": zod.object({ + "status": zod.enum(['available', 'in_development']).describe('Whether an assessment can start for the specialization. `available` means that a published task bank exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no grade of the specialization has a published bank yet; the specialization can still be chosen in the questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the catalog or in demo data never means that a test is ready.'), + "grades": zod.array(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.')).max(catalogDirectionSpecializationsItemTestAvailabilityGradesMax).describe('Grades of the specialization with a published task bank, in ascending order. Only these categories can be assessed and confirmed.'), + "task_languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(catalogDirectionSpecializationsItemTestAvailabilityTaskLanguagesMax).describe('Task languages that the published bank offers for this specialization. Empty when the bank does not offer a choice of language, as for Network Engineer, or when no bank is published. The questionnaire accepts only these languages for the specialization.'), + "note": zod.string().min(1).max(catalogDirectionSpecializationsItemTestAvailabilityNoteMax).nullable().describe('Short Russian note for the candidate, for example why the test is not available yet, or null. Plain text; the client shows it as text, never as HTML.') +}).describe('Assessment availability of a specialization, derived by the server from the published task banks at the time of the request. The MVP opens an assessment only for a category, a specialization and a grade, that has a published bank. `status` is `available` exactly when `grades` is not empty; for `in_development` both `grades` and `task_languages` are empty.') +}).describe('Specialization in the catalog with its assessment availability.')).min(1).max(catalogDirectionSpecializationsMax).describe('Specializations of the direction in display order.') +}).describe('Professional direction with its specializations. Each specialization belongs to exactly one direction.') + +export type CatalogDirection = zod.input; +export type CatalogDirectionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/catalog/catalogGrade.zod.ts b/frontend/src/shared/api/schemas/catalog/catalogGrade.zod.ts new file mode 100644 index 0000000..fb09efe --- /dev/null +++ b/frontend/src/shared/api/schemas/catalog/catalogGrade.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const catalogGradeTitleMax = 100; + + +export const CatalogGrade = zod.object({ + "code": 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.'), + "title": zod.string().min(1).max(catalogGradeTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Grade of the scale with its display name.') + +export type CatalogGrade = zod.input; +export type CatalogGradeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/catalog/catalogSpecialization.zod.ts b/frontend/src/shared/api/schemas/catalog/catalogSpecialization.zod.ts new file mode 100644 index 0000000..14e384e --- /dev/null +++ b/frontend/src/shared/api/schemas/catalog/catalogSpecialization.zod.ts @@ -0,0 +1,30 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const catalogSpecializationTitleMax = 100; + +export const catalogSpecializationTestAvailabilityGradesMax = 10; + +export const catalogSpecializationTestAvailabilityTaskLanguagesMax = 2; + +export const catalogSpecializationTestAvailabilityNoteMax = 300; + + +export const CatalogSpecialization = zod.object({ + "code": 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.'), + "title": zod.string().min(1).max(catalogSpecializationTitleMax).describe('Display name in Russian. Plain text.'), + "test_availability": zod.object({ + "status": zod.enum(['available', 'in_development']).describe('Whether an assessment can start for the specialization. `available` means that a published task bank exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no grade of the specialization has a published bank yet; the specialization can still be chosen in the questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the catalog or in demo data never means that a test is ready.'), + "grades": zod.array(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.')).max(catalogSpecializationTestAvailabilityGradesMax).describe('Grades of the specialization with a published task bank, in ascending order. Only these categories can be assessed and confirmed.'), + "task_languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(catalogSpecializationTestAvailabilityTaskLanguagesMax).describe('Task languages that the published bank offers for this specialization. Empty when the bank does not offer a choice of language, as for Network Engineer, or when no bank is published. The questionnaire accepts only these languages for the specialization.'), + "note": zod.string().min(1).max(catalogSpecializationTestAvailabilityNoteMax).nullable().describe('Short Russian note for the candidate, for example why the test is not available yet, or null. Plain text; the client shows it as text, never as HTML.') +}).describe('Assessment availability of a specialization, derived by the server from the published task banks at the time of the request. The MVP opens an assessment only for a category, a specialization and a grade, that has a published bank. `status` is `available` exactly when `grades` is not empty; for `in_development` both `grades` and `task_languages` are empty.') +}).describe('Specialization in the catalog with its assessment availability.') + +export type CatalogSpecialization = zod.input; +export type CatalogSpecializationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/catalog/directionCode.zod.ts b/frontend/src/shared/api/schemas/catalog/directionCode.zod.ts new file mode 100644 index 0000000..05b86d4 --- /dev/null +++ b/frontend/src/shared/api/schemas/catalog/directionCode.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const DirectionCode = zod.enum(['development', 'infrastructure', 'data', 'security', 'quality']).describe('Stable code of a professional direction, the group that a specialization belongs to.\n\n- development: Development.\n- infrastructure: Infrastructure.\n- data: Data.\n- security: Security.\n- quality: Quality.\n\nAdding a value is a contract change.') + +export type DirectionCode = zod.input; +export type DirectionCodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/catalog/index.ts b/frontend/src/shared/api/schemas/catalog/index.ts new file mode 100644 index 0000000..e74a1e1 --- /dev/null +++ b/frontend/src/shared/api/schemas/catalog/index.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ + +export * from './catalogDirection.zod'; +export * from './catalogGrade.zod'; +export * from './catalogSpecialization.zod'; +export * from './directionCode.zod'; +export * from './specializationCatalog.zod'; +export * from './testAvailability.zod'; +export * from './testAvailabilityStatus.zod'; diff --git a/frontend/src/shared/api/schemas/catalog/specializationCatalog.zod.ts b/frontend/src/shared/api/schemas/catalog/specializationCatalog.zod.ts new file mode 100644 index 0000000..74663d7 --- /dev/null +++ b/frontend/src/shared/api/schemas/catalog/specializationCatalog.zod.ts @@ -0,0 +1,50 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const specializationCatalogDirectionsItemTitleMax = 100; + +export const specializationCatalogDirectionsItemSpecializationsItemTitleMax = 100; + +export const specializationCatalogDirectionsItemSpecializationsItemTestAvailabilityGradesMax = 10; + +export const specializationCatalogDirectionsItemSpecializationsItemTestAvailabilityTaskLanguagesMax = 2; + +export const specializationCatalogDirectionsItemSpecializationsItemTestAvailabilityNoteMax = 300; + +export const specializationCatalogDirectionsItemSpecializationsMax = 20; + +export const specializationCatalogDirectionsMax = 20; + +export const specializationCatalogGradesItemTitleMax = 100; + +export const specializationCatalogGradesMax = 10; + + +export const SpecializationCatalog = zod.object({ + "directions": zod.array(zod.object({ + "code": zod.enum(['development', 'infrastructure', 'data', 'security', 'quality']).describe('Stable code of a professional direction, the group that a specialization belongs to.\n\n- development: Development.\n- infrastructure: Infrastructure.\n- data: Data.\n- security: Security.\n- quality: Quality.\n\nAdding a value is a contract change.'), + "title": zod.string().min(1).max(specializationCatalogDirectionsItemTitleMax).describe('Display name in Russian. Plain text.'), + "specializations": zod.array(zod.object({ + "code": 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.'), + "title": zod.string().min(1).max(specializationCatalogDirectionsItemSpecializationsItemTitleMax).describe('Display name in Russian. Plain text.'), + "test_availability": zod.object({ + "status": zod.enum(['available', 'in_development']).describe('Whether an assessment can start for the specialization. `available` means that a published task bank exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no grade of the specialization has a published bank yet; the specialization can still be chosen in the questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the catalog or in demo data never means that a test is ready.'), + "grades": zod.array(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.')).max(specializationCatalogDirectionsItemSpecializationsItemTestAvailabilityGradesMax).describe('Grades of the specialization with a published task bank, in ascending order. Only these categories can be assessed and confirmed.'), + "task_languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(specializationCatalogDirectionsItemSpecializationsItemTestAvailabilityTaskLanguagesMax).describe('Task languages that the published bank offers for this specialization. Empty when the bank does not offer a choice of language, as for Network Engineer, or when no bank is published. The questionnaire accepts only these languages for the specialization.'), + "note": zod.string().min(1).max(specializationCatalogDirectionsItemSpecializationsItemTestAvailabilityNoteMax).nullable().describe('Short Russian note for the candidate, for example why the test is not available yet, or null. Plain text; the client shows it as text, never as HTML.') +}).describe('Assessment availability of a specialization, derived by the server from the published task banks at the time of the request. The MVP opens an assessment only for a category, a specialization and a grade, that has a published bank. `status` is `available` exactly when `grades` is not empty; for `in_development` both `grades` and `task_languages` are empty.') +}).describe('Specialization in the catalog with its assessment availability.')).min(1).max(specializationCatalogDirectionsItemSpecializationsMax).describe('Specializations of the direction in display order.') +}).describe('Professional direction with its specializations. Each specialization belongs to exactly one direction.')).min(1).max(specializationCatalogDirectionsMax).describe('Directions in display order.'), + "grades": zod.array(zod.object({ + "code": 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.'), + "title": zod.string().min(1).max(specializationCatalogGradesItemTitleMax).describe('Display name in Russian. Plain text.') +}).describe('Grade of the scale with its display name.')).min(1).max(specializationCatalogGradesMax).describe('Grade scale in ascending order.') +}).describe('Catalog of directions, specializations, and the grade scale that the questionnaire and the assessment use. The catalog is reference data and identical for every caller; it contains no personal data.') + +export type SpecializationCatalog = zod.input; +export type SpecializationCatalogOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/catalog/testAvailability.zod.ts b/frontend/src/shared/api/schemas/catalog/testAvailability.zod.ts new file mode 100644 index 0000000..a33b4e0 --- /dev/null +++ b/frontend/src/shared/api/schemas/catalog/testAvailability.zod.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const testAvailabilityGradesMax = 10; + +export const testAvailabilityTaskLanguagesMax = 2; + +export const testAvailabilityNoteMax = 300; + + +export const TestAvailability = zod.object({ + "status": zod.enum(['available', 'in_development']).describe('Whether an assessment can start for the specialization. `available` means that a published task bank exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no grade of the specialization has a published bank yet; the specialization can still be chosen in the questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the catalog or in demo data never means that a test is ready.'), + "grades": zod.array(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.')).max(testAvailabilityGradesMax).describe('Grades of the specialization with a published task bank, in ascending order. Only these categories can be assessed and confirmed.'), + "task_languages": zod.array(zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.')).max(testAvailabilityTaskLanguagesMax).describe('Task languages that the published bank offers for this specialization. Empty when the bank does not offer a choice of language, as for Network Engineer, or when no bank is published. The questionnaire accepts only these languages for the specialization.'), + "note": zod.string().min(1).max(testAvailabilityNoteMax).nullable().describe('Short Russian note for the candidate, for example why the test is not available yet, or null. Plain text; the client shows it as text, never as HTML.') +}).describe('Assessment availability of a specialization, derived by the server from the published task banks at the time of the request. The MVP opens an assessment only for a category, a specialization and a grade, that has a published bank. `status` is `available` exactly when `grades` is not empty; for `in_development` both `grades` and `task_languages` are empty.') + +export type TestAvailability = zod.input; +export type TestAvailabilityOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/catalog/testAvailabilityStatus.zod.ts b/frontend/src/shared/api/schemas/catalog/testAvailabilityStatus.zod.ts new file mode 100644 index 0000000..6ee3eeb --- /dev/null +++ b/frontend/src/shared/api/schemas/catalog/testAvailabilityStatus.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const TestAvailabilityStatus = zod.enum(['available', 'in_development']).describe('Whether an assessment can start for the specialization. `available` means that a published task bank exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no grade of the specialization has a published bank yet; the specialization can still be chosen in the questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the catalog or in demo data never means that a test is ready.') + +export type TestAvailabilityStatus = zod.input; +export type TestAvailabilityStatusOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/gradeCode.zod.ts b/frontend/src/shared/api/schemas/gradeCode.zod.ts new file mode 100644 index 0000000..c614267 --- /dev/null +++ b/frontend/src/shared/api/schemas/gradeCode.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const GradeCode = 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.') + +export type GradeCode = zod.input; +export type GradeCodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/account.zod.ts b/frontend/src/shared/api/schemas/identity/account.zod.ts index 53fa7b1..f2cd8ad 100644 --- a/frontend/src/shared/api/schemas/identity/account.zod.ts +++ b/frontend/src/shared/api/schemas/identity/account.zod.ts @@ -15,7 +15,7 @@ export const Account = zod.object({ "email": zod.email().min(accountEmailMin).max(accountEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'), "email_verified": zod.boolean().describe('Whether the address is verified. A session exists only for a verified account, so this is true in every current response.'), "scenario": zod.enum(['candidate', 'employer']).describe('Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.'), - "onboarding_step": zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: choice of the expected grade and the assessment.\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.'), + "onboarding_step": zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. The first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step (planned).\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.'), "created_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') }).describe('Current account view. It never contains password hashes, token hashes, session identifiers, or other storage secrets.') diff --git a/frontend/src/shared/api/schemas/identity/emailVerificationResult.zod.ts b/frontend/src/shared/api/schemas/identity/emailVerificationResult.zod.ts index 6486d3a..1825bc9 100644 --- a/frontend/src/shared/api/schemas/identity/emailVerificationResult.zod.ts +++ b/frontend/src/shared/api/schemas/identity/emailVerificationResult.zod.ts @@ -9,7 +9,7 @@ import * as zod from 'zod'; export const EmailVerificationResult = zod.object({ "email_verified": zod.literal(true).describe('Always true in a successful response.'), "scenario": zod.enum(['candidate', 'employer']).describe('Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.'), - "onboarding_step": zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: choice of the expected grade and the assessment.\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.') + "onboarding_step": zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. The first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step (planned).\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.') }).describe('Result of a successful email verification. It does not start a session; the user signs in next and continues from `onboarding_step`.') export type EmailVerificationResult = zod.input; diff --git a/frontend/src/shared/api/schemas/identity/index.ts b/frontend/src/shared/api/schemas/identity/index.ts index 650246d..d4a7ad0 100644 --- a/frontend/src/shared/api/schemas/identity/index.ts +++ b/frontend/src/shared/api/schemas/identity/index.ts @@ -28,5 +28,4 @@ export * from './registerAccountHeaders.zod'; export * from './registrationRequest.zod'; export * from './resendEmailVerificationBody.zod'; export * from './session.zod'; -export * from './timestamp.zod'; export * from './verificationToken.zod'; diff --git a/frontend/src/shared/api/schemas/identity/onboardingStep.zod.ts b/frontend/src/shared/api/schemas/identity/onboardingStep.zod.ts index fb6a06c..4801faf 100644 --- a/frontend/src/shared/api/schemas/identity/onboardingStep.zod.ts +++ b/frontend/src/shared/api/schemas/identity/onboardingStep.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const OnboardingStep = zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: choice of the expected grade and the assessment.\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.') +export const OnboardingStep = zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. The first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step (planned).\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.') export type OnboardingStep = zod.input; export type OnboardingStepOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/session.zod.ts b/frontend/src/shared/api/schemas/identity/session.zod.ts index 9381143..527454c 100644 --- a/frontend/src/shared/api/schemas/identity/session.zod.ts +++ b/frontend/src/shared/api/schemas/identity/session.zod.ts @@ -21,7 +21,7 @@ export const Session = zod.object({ "email": zod.email().min(sessionAccountEmailMin).max(sessionAccountEmailMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'), "email_verified": zod.boolean().describe('Whether the address is verified. A session exists only for a verified account, so this is true in every current response.'), "scenario": zod.enum(['candidate', 'employer']).describe('Scenario chosen at registration: `candidate` looks for an offer and passes the assessment, `employer` represents a company that searches for candidates. The scenario selects the onboarding steps.'), - "onboarding_step": zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: choice of the expected grade and the assessment.\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.'), + "onboarding_step": zod.enum(['candidate_consents', 'candidate_profile', 'candidate_questionnaire', 'candidate_assessment', 'employer_company', 'completed']).describe('Saved onboarding step that the account returns to after login. The server stores it and advances it as each step completes; clients route by it and never set it directly.\n\n- candidate_consents: candidate consents beyond C1, which was given at registration.\n- candidate_profile: candidate profile.\n- candidate_questionnaire: candidate questionnaire.\n- candidate_assessment: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. The first successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step (planned).\n- employer_company: company profile of the employer.\n- completed: onboarding is finished; the client opens the scenario home.\n\nCandidate steps follow the order above and end with completed; the employer has employer_company and then completed. New steps may be added as onboarding grows; adding a value is a contract change.'), "created_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') }).describe('Current account view. It never contains password hashes, token hashes, session identifiers, or other storage secrets.'), "csrf_token": zod.string().min(sessionCsrfTokenMin).max(sessionCsrfTokenMax).regex(sessionCsrfTokenRegExp).describe('CSRF token bound to the current session. The client keeps it in memory only and sends it in the X-CSRF-Token header of every mutating request that requires a session. It changes when a new session starts.') diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index 491f0c8..66d397c 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -5,10 +5,16 @@ * OpenAPI spec version: 0.1.0 */ +export * from './gradeCode.zod'; export * from './pageInfo.zod'; export * from './problem.zod'; export * from './problemCode.zod'; export * from './problemFieldError.zod'; export * from './problemFieldLocation.zod'; +export * from './specializationCode.zod'; +export * from './taskLanguage.zod'; +export * from './timestamp.zod'; +export * from './candidate'; +export * from './catalog'; export * from './health'; export * from './identity'; diff --git a/frontend/src/shared/api/schemas/problem.zod.ts b/frontend/src/shared/api/schemas/problem.zod.ts index b35086d..e3e9995 100644 --- a/frontend/src/shared/api/schemas/problem.zod.ts +++ b/frontend/src/shared/api/schemas/problem.zod.ts @@ -38,7 +38,7 @@ export const Problem = zod.object({ "type": zod.string().max(problemTypeMax).describe('URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference.'), "title": zod.string().min(1).max(problemTitleMax).describe('Short, fixed English summary of the problem type. It does not change between occurrences.'), "status": zod.int().min(problemStatusMin).max(problemStatusMax).describe('HTTP status code generated by the origin server.'), - "code": zod.enum(['validation_failed', 'verification_token_invalid', 'verification_token_expired', 'unauthenticated', 'invalid_credentials', 'forbidden', 'email_not_verified', 'csrf_check_failed', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in.\n- verification_token_expired (400): the email verification token is past its lifetime; request a new link.\n- unauthenticated (401): no valid session or credentials.\n- invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished.\n- forbidden (403): the caller is authenticated but not allowed.\n- email_not_verified (403): the credentials are correct but the email is not verified yet.\n- csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.'), + "code": zod.enum(['validation_failed', 'verification_token_invalid', 'verification_token_expired', 'unauthenticated', 'invalid_credentials', 'forbidden', 'email_not_verified', 'csrf_check_failed', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in.\n- verification_token_expired (400): the email verification token is past its lifetime; request a new link.\n- unauthenticated (401): no valid session or credentials.\n- invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished.\n- forbidden (403): the caller is authenticated but not allowed.\n- email_not_verified (403): the credentials are correct but the email is not verified yet.\n- csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match, or an `expected_version` field in the request body, does not match the current version; nothing was changed.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.'), "detail": zod.string().max(problemDetailMax).exactOptional().describe('Safe English explanation of this occurrence. It never contains internal error text or request values.'), "instance": zod.string().max(problemInstanceMax).exactOptional().describe('URI reference that identifies this occurrence, when one exists.'), "trace_id": zod.string().min(1).max(problemTraceIdMax).regex(problemTraceIdRegExp).exactOptional().describe('Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret.'), diff --git a/frontend/src/shared/api/schemas/problemCode.zod.ts b/frontend/src/shared/api/schemas/problemCode.zod.ts index a3f6107..50514b6 100644 --- a/frontend/src/shared/api/schemas/problemCode.zod.ts +++ b/frontend/src/shared/api/schemas/problemCode.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const ProblemCode = zod.enum(['validation_failed', 'verification_token_invalid', 'verification_token_expired', 'unauthenticated', 'invalid_credentials', 'forbidden', 'email_not_verified', 'csrf_check_failed', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in.\n- verification_token_expired (400): the email verification token is past its lifetime; request a new link.\n- unauthenticated (401): no valid session or credentials.\n- invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished.\n- forbidden (403): the caller is authenticated but not allowed.\n- email_not_verified (403): the credentials are correct but the email is not verified yet.\n- csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.') +export const ProblemCode = zod.enum(['validation_failed', 'verification_token_invalid', 'verification_token_expired', 'unauthenticated', 'invalid_credentials', 'forbidden', 'email_not_verified', 'csrf_check_failed', 'not_found', 'method_not_allowed', 'idempotency_in_progress', 'state_conflict', 'version_conflict', 'payload_too_large', 'unsupported_media_type', 'idempotency_key_reused', 'precondition_required', 'rate_limited', 'internal', 'not_implemented']).describe('Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- verification_token_invalid (400): the email verification token is unknown, already used, or replaced by a newer one; request a new link or sign in.\n- verification_token_expired (400): the email verification token is past its lifetime; request a new link.\n- unauthenticated (401): no valid session or credentials.\n- invalid_credentials (401): the email and password do not match an account; an unknown email and a wrong password are not distinguished.\n- forbidden (403): the caller is authenticated but not allowed.\n- email_not_verified (403): the credentials are correct but the email is not verified yet.\n- csrf_check_failed (403): the request failed cross-site request protection: a missing or wrong X-CSRF-Token or a disallowed Origin.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match, or an `expected_version` field in the request body, does not match the current version; nothing was changed.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet.') export type ProblemCode = zod.input; export type ProblemCodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/specializationCode.zod.ts b/frontend/src/shared/api/schemas/specializationCode.zod.ts new file mode 100644 index 0000000..25483fa --- /dev/null +++ b/frontend/src/shared/api/schemas/specializationCode.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const SpecializationCode = 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.') + +export type SpecializationCode = zod.input; +export type SpecializationCodeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/taskLanguage.zod.ts b/frontend/src/shared/api/schemas/taskLanguage.zod.ts new file mode 100644 index 0000000..7d1ae78 --- /dev/null +++ b/frontend/src/shared/api/schemas/taskLanguage.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const TaskLanguage = zod.enum(['python', 'go']).describe('Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate\'s platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change.') + +export type TaskLanguage = zod.input; +export type TaskLanguageOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/identity/timestamp.zod.ts b/frontend/src/shared/api/schemas/timestamp.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/identity/timestamp.zod.ts rename to frontend/src/shared/api/schemas/timestamp.zod.ts