feat(profile): add the manual candidate profile contract and storage

This commit is contained in:
shira committed 2026-10-06 21:10:04 +03:00
1 parent d21fd49a42
commit e52ffe7bcb
97 files changed
+20442 -63

No files matched your search

+58
View File
@@ -176,6 +176,64 @@ Questionnaire:
- 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.
### Candidate profile
The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD, TASK-066). The operations are in the contract and the business logic is not implemented yet, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` once a session is accepted and the schema is valid.
| Method and path | operationId | Protection | Success | Specific errors |
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/profile` | `GetMyProfile` | session | 200 `CandidateProfile`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
| `PUT /api/v1/me/profile` | `SaveMyProfile` | session and CSRF | 200 `CandidateProfile`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 412 `version_conflict` |
Each operation also declares the default problem response. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, and `version_conflict`.
What the profile holds:
- The full name and contacts (`full_name`, `contacts.email`, `contacts.phone`, `contacts.telegram`), the stack (`stack`, `StackTag` tags), roles (`roles`: a catalog specialization and a self-assessed grade), work experience (`experience`: entries with a month-precision period `YYYY-MM`, a specialization, and a description of the tasks rather than a job title), soft skills (`soft_skills`, free text), and terms (`terms`: place, readiness to relocate, and the lowest salary with its currency, period, and tax basis). This is personal data of the candidate; the description of each such schema says so, and the values never reach logs, metrics, URLs, or events.
- Contacts are exactly the four kinds that the consent C4 can disclose (`ContactFieldKind`), with the same formats (E.164, the leading `@` of a Telegram name, a single line of up to 200 characters for the name), so a disclosure never converts or drops a stored value. The contact email of the profile is not the login of the account: the server sends no mail to it and does not verify it.
- Acceptable work formats are not repeated in the profile: they stay only in the `WorkContext` of the questionnaire.
- The profile is private: only its owner reads it, and no organization, invitation, or need schema refers to it (`$ref`). An organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant. The lowest salary is never disclosed to an organization; an invitation shows only a compatibility indicator that the server computes.
Self-assessment and confirmed category:
- The grade of a role (`roles[].self_assessed_grade`) is a claim of the candidate, the same one that the questionnaire calls `self_assessed_grade`; it adds nothing and never becomes a confirmed grade. The confirmed category is a separate list, `confirmed_categories` (specialization, grade, time, and the assessment attempt that confirmed it). It is read-only, the server derives it from assessment results, no request carries it, and the profile storage has no column for it. A request with `confirmed_grade`, `category`, or `confirmed_categories` is rejected as an unknown field.
Source and confirmation:
- Every value carries `status` and `source`. For a single field `status` is `confirmed`, `extracted`, or `unknown`; for `unknown` the value and the source are null, and the server fills in no default. For a list item `status` is `confirmed` or `extracted`. `source` holds `origin` (`manual`; `extracted_from_resume` and `imported` are planned and no MVP operation produces them), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`.
- Every claim of the profile has `trust_level` 0, whatever its source: a schema limit (`minimum` and `maximum` are 0), a CHECK in the database, and a type in the domain. Confirming a suggestion changes its status, not its level; higher levels belong to evidence (an assessment result, a confirmation by a third party), which is stored separately and never written into a claim.
- A request carries a decision for each value (`value` and `status`): `confirmed` sets a manual value or confirms a stored suggestion with the same value (the source and the quote are kept), and `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the same value. Any other use of `extracted` answers 400 with the pointer of that status, for example `/stack/1/status`, so a form submitted unchanged confirms nothing by accident, as for needs. The client never sends the source, the trust level, or the confirmation time.
Version and retries:
- The version starts at 0 for a candidate without a saved profile; such a candidate gets 200 with every field `unknown` and empty lists, not 404. `PUT` replaces the whole profile and a list replaces the list; a field sent as null becomes unknown and is removed.
- Concurrent edits are controlled by `expected_version` in the body, as in the questionnaire: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing, and the client reads the profile again, so an edit from another tab is never lost silently. A body that changes nothing keeps the version and answers 200 even with an older version, so no Idempotency-Key is needed. Every saved change advances the version by one.
- Order of checks: session (401), CSRF and Origin (403 `csrf_check_failed`), request validation (400), account scenario (403 `forbidden` for an employer), a version above the current one (412), domain rules that depend on the body alone (400), then the rules that depend on the stored claims, with the version: a decision `extracted` for something that is not a stored suggestion answers 412 on a stale version (another tab may have confirmed the value) and 400 on the current one; an unchanged body is 200; any other change over a stale version is 412. A version above the current one never existed and answers 412 even for an unchanged body. The domain rules that the schema cannot express are: a repeated tag, skill, or role specialization (without regard to letter case for tags and skills), a period that ends before it starts or lies in the future, and a decision `extracted` for something that is not a stored suggestion. The 400 response never repeats a submitted value.
No file, ML, or FSP:
- The profile is filled in entirely by hand. No field requires a resume, ML extraction, or an FSP account, and the migration and queries create no mandatory link to a file, ML, or FSP. Resume upload and linking an FSP ID are planned additive features; they will add their own fields and sources without changing these.
Relation to the questionnaire (TASK-150):
- The questionnaire (`/me/questionnaire`) names at most two specializations for assessment; the profile is what the candidate presents about themselves. Same-named concepts are not duplicated under different meanings: the self-assessed grade and the stack are the same claim in two places (in the questionnaire for the start of the assessment and per specialization, in the profile for display), saved separately, and the server never copies one into the other; the total months of experience in the questionnaire and the experience entries of the profile are different claims; work formats live only in the questionnaire, while place, relocation, and salary live only in the profile. The schema descriptions of both sides refer to each other.
Storage (migration 00013, TASK-066): `candidate_profiles` (the profile row: `user_id`, `version`, times) and `candidate_profile_claims` (one row per stored claim: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). A missing row means `unknown`. Each kind of value has a CHECK for the format and bounds of the contract; `trust_level` is always 0; the tables have no file column, no FSP column, and no confirmed grade. Details are in [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-profile).
Open questions for the product owner and legal:
- Contact kinds: only the four C4 kinds are allowed. Whether links to GitHub, social networks, or a website are needed (the PRD hides them until an invitation is accepted); that would be a contract change in `ContactFieldKind` too.
- The 152-FZ basis: which consent covers storing the profile (C1 at registration or a separate one), whether the name and the contacts need separate consents, the retention periods, and the deletion procedure. Today deleting an account cascades to its profile, and there are no retention rules.
- The order of the version and the domain rules: the version is checked before the rules that depend on stored claims (a stale tab gets 412, not 400); the product owner should confirm.
- Full replacement: `PUT` drops stored import suggestions that the client did not render and send back with the status `extracted`; whether that is acceptable or the server should keep suggestions that were never shown.
- The minimum for the onboarding step `candidate_profile`: the contract requires no field; which fields complete the step is the product owner's decision.
- One source between the questionnaire and the profile: keep the self-assessment and the stack independent, or store one claim and show it in both places.
- Soft skills: there is no taxonomy, only free text, up to 10 items of 50 characters; whether a dictionary is needed.
- Experience: employer names and descriptions are personal data; how the anonymous card generalizes them (PRD: industry and size) is for the card contract (TASK-185), not this one.
- Contact verification (confirming the phone or the email of the profile) is not provided: contacts are claims of level 0.
`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation`, and `TestProfileAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/profile-contract.test.ts` pins the generated Zod rules, the request types without a confirmed grade, and the absence of profile fields from the organization, invitation, and need schemas.
### Assessment
The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`).
+58
View File
@@ -176,6 +176,64 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- PUT заменяет анкету целиком, и Idempotency-Key ему не нужен. Тело, равное сохраненному состоянию, ничего не меняет, сохраняет версию и дает 200 даже со старым `expected_version`, поэтому повтор после потерянного ответа не падает с 412.
- Порядок проверок при сохранении: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), доменные правила (400), версия (412). `TestQuestionnaireSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер.
### Профиль кандидата
Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD, TASK-066). Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидной схемы - 501 `not_implemented`.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
| `GET /api/v1/me/profile` | `GetMyProfile` | сессия | 200 `CandidateProfile`, `Cache-Control: no-store` | 401 `unauthenticated`, 403 `forbidden` |
| `PUT /api/v1/me/profile` | `SaveMyProfile` | сессия и CSRF | 200 `CandidateProfile`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 412 `version_conflict` |
Каждая операция также объявляет problem-ответ `default`. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed` и `version_conflict`.
Состав профиля:
- Полное имя и контакты (`full_name`, `contacts.email`, `contacts.phone`, `contacts.telegram`), стек (`stack`, теги `StackTag`), роли (`roles`: специализация каталога и самооценка грейда), опыт работы (`experience`: записи с периодом по месяцам `YYYY-MM`, специализацией и описанием задач, а не названием должности), софт-скиллы (`soft_skills`, свободный текст) и условия (`terms`: место, готовность к переезду и минимальная зарплата с валютой, периодом и налоговой базой). Это ПДн кандидата; каждое такое поле в описании схемы помечено как персональные данные, а значения не попадают в логи, метрики, URL и события.
- Контакты - ровно те четыре вида, которые может раскрыть согласие C4 (`ContactFieldKind`), с теми же форматами (E.164, `@` у Telegram, одна строка до 200 символов для имени), поэтому раскрытие никогда не преобразует и не отбрасывает сохраненное значение. Контактный email профиля - не логин аккаунта: сервер не отправляет на него почту и не проверяет его.
- Допустимые форматы работы в профиле не повторяются: они остаются только в `WorkContext` анкеты.
- Профиль закрыт: его читает только владелец, а ни одна схема организации, приглашения или потребности его не ссылает (`$ref`). Организация видит кандидата только через анонимную карточку и, после принятого приглашения, через контактное разрешение. Минимальная зарплата не раскрывается организации никогда; приглашение показывает только индикатор совместимости, который считает сервер.
Самооценка и подтвержденная категория:
- Грейд роли (`roles[].self_assessed_grade`) - заявление кандидата, то же, что анкета называет `self_assessed_grade`; он ничего не добавляет и никогда не становится подтвержденным грейдом. Подтвержденная категория - отдельный список `confirmed_categories` (специализация, грейд, время и попытка оценки, которая его подтвердила). Он только для чтения, сервер выводит его из результатов оценки, ни один запрос его не несет, а в хранилище профиля для него нет столбца. Запрос с полем `confirmed_grade`, `category` или `confirmed_categories` отклоняется как неизвестное поле.
Источник и подтверждение:
- Каждое значение несет `status` и `source`. У одиночного поля `status` равен `confirmed`, `extracted` или `unknown`; при `unknown` значение и источник равны null, а сервер ничего не подставляет по умолчанию. У элемента списка `status` равен `confirmed` или `extracted`. `source` - `origin` (`manual`; запланированы `extracted_from_resume` и `imported`, ни одна операция MVP их не создает), `trust_level`, `quote`, `extraction_version` и `confirmed_at`.
- Каждое заявление профиля имеет `trust_level` 0, какой бы ни был источник: ограничение схемы (`minimum` и `maximum` равны 0), CHECK в базе и тип в домене. Подтверждение предложения меняет статус, а не уровень; более высокие уровни относятся к доказательствам (результату оценки, подтверждению третьей стороной), которые хранятся отдельно и не записываются в заявление.
- Запрос несет решение по каждому значению (`value` и `status`): `confirmed` задает ручное значение или подтверждает сохраненное предложение с тем же значением (тогда источник и цитата сохраняются), `extracted` оставляет сохраненное предложение неподтвержденным и допустим только с точно тем же значением. Любое другое использование `extracted` дает 400 с pointer на этот статус, например `/stack/1/status`, поэтому форма без изменений ничего не подтверждает случайно, как и в потребностях. Источник, уровень доверия и время подтверждения клиент не отправляет.
Версия и повторы:
- Версия начинается с 0 для кандидата без сохраненного профиля; такой кандидат получает 200 со всеми полями `unknown` и пустыми списками, а не 404. `PUT` заменяет профиль целиком, а список заменяет список; поле, посланное как null, становится неизвестным и удаляется.
- Конкурентные изменения контролирует `expected_version` в теле, как в анкете: сгенерированный клиент пока не читает `ETag`. Устаревшее значение дает 412 `version_conflict` без изменений, и клиент читает профиль заново; правка из другой вкладки не теряется молча. Тело без изменений сохраняет версию и дает 200 даже со старой версией, поэтому Idempotency-Key не нужен. Каждое сохраненное изменение увеличивает версию на единицу.
- Порядок проверок: сессия (401), CSRF и Origin (403 `csrf_check_failed`), валидация запроса (400), сценарий аккаунта (403 `forbidden` для работодателя), версия выше текущей (412), доменные правила, зависящие только от тела (400), затем правила, зависящие от сохраненных заявлений, и версия: решение `extracted` не для сохраненного предложения при устаревшей версии дает 412 (другая вкладка могла подтвердить значение), при текущей - 400; тело без изменений - 200; любое другое изменение по устаревшей версии - 412. Версия выше текущей никогда не существовала и дает 412 даже для тела без изменений. Доменные правила, которые схема не выражает: повтор тега, навыка или специализации роли (без учета регистра для тегов и навыков), период, который кончается раньше начала или лежит в будущем, и решение `extracted` не для сохраненного предложения. Ответ 400 не повторяет присланное значение.
Без файла, ML и ФСП:
- Профиль полностью заполняется вручную. Ни одно поле не требует резюме, извлечения ML или аккаунта ФСП, а миграция и запросы не создают обязательной связи с файлом, ML или ФСП. Загрузка резюме и привязка ФСП ID - запланированные аддитивные возможности; они добавят свои поля и источники, не меняя этих.
Связь с анкетой (TASK-150):
- Анкета (`/me/questionnaire`) задает не более двух специализаций для оценки; профиль - то, что кандидат показывает о себе. Одноименные понятия не дублируются под разным смыслом: самооценка грейда и стек - одно и то же заявление в двух местах (в анкете для старта оценки и по специализации, в профиле для показа), сохраняются раздельно, и сервер не копирует одно в другое; общий опыт в месяцах в анкете и записи опыта в профиле - разные заявления; форматы работы живут только в анкете, а место, переезд и зарплата - только в профиле. Описания схем обеих сторон ссылаются друг на друга.
Хранение (миграция 00013, TASK-066): `candidate_profiles` (строка профиля: `user_id`, `version`, времена) и `candidate_profile_claims` (по строке на сохраненное заявление: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). Отсутствие строки значит `unknown`. Для каждого вида значения есть CHECK формата и границ контракта; `trust_level` всегда 0; в таблицах нет ни столбца файла, ни столбца ФСП, ни подтвержденного грейда. Подробности - в [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#профиль-кандидата).
Открытые вопросы к владельцу продукта и юристу:
- Виды контактов: допустимы только четыре вида C4. Нужны ли ссылки на GitHub, соцсети или сайт (PRD прячет их до принятия приглашения), и тогда это изменение контракта и в `ContactFieldKind`.
- Основание по 152-ФЗ: какое согласие покрывает хранение профиля (C1 при регистрации или отдельное), нужны ли отдельные согласия для имени и контактов, сроки хранения и порядок удаления. Сейчас удаление аккаунта каскадно удаляет профиль, а правил хранения нет.
- Порядок версии и доменных правил: выбрано проверять версию раньше правил, зависящих от сохраненных заявлений (устаревшая вкладка получает 412, а не 400); нужно подтверждение владельца продукта.
- Полная замена: `PUT` удаляет сохраненные предложения импорта, которых клиент не показал и не вернул со статусом `extracted`; допустимо ли это или сервер должен сохранять непоказанные предложения.
- Минимум для шага онбординга `candidate_profile`: контракт не требует ни одного поля; какие поля нужны, чтобы шаг считался пройденным, решает владелец продукта.
- Единый источник между анкетой и профилем: оставить самооценку и стек независимыми или хранить одно заявление и показывать в обоих местах.
- Софт-скиллы: таксономии нет, свободный текст до 10 штук по 50 символов; нужен ли справочник.
- Опыт: названия работодателей и описания - ПДн; как анонимная карточка их обобщает (PRD: отрасль и размер), решает контракт карточки (TASK-185), а не этот.
- Проверка контактов (подтверждение телефона или email профиля) не предусмотрена: контакты - заявления уровня 0.
`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation` и `TestProfileAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/profile-contract.test.ts` - сгенерированные правила Zod, типы запросов без подтвержденного грейда и отсутствие полей профиля в схемах организации, приглашения и потребности.
### Оценка
Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`).
+277
View File
@@ -3779,3 +3779,280 @@ OrganizationStaleVersion:
code: version_conflict
detail: The resource changed after it was read. Read it again before retrying.
trace_id: 5c6d7e8f-9a0b-4c1d-8e3f-4a5b6c7d8e90
NewCandidateProfile:
summary: A candidate who has not saved the profile yet
value:
version: 0
full_name:
status: unknown
value: null
source: null
contacts:
email:
status: unknown
value: null
source: null
phone:
status: unknown
value: null
source: null
telegram:
status: unknown
value: null
source: null
stack: []
roles: []
experience: []
soft_skills: []
terms:
location:
status: unknown
value: null
source: null
relocation:
status: unknown
value: null
source: null
salary_minimum:
status: unknown
value: null
source: null
confirmed_categories: []
updated_at: null
BackendCandidateProfile:
summary: A manual Backend profile with one unconfirmed suggestion
description: >-
The candidate typed most values, so they are `manual`. The phone number
and the Kafka tag are suggestions that an imported document produced
(planned): they are `extracted`, unconfirmed, and, like every claim,
trust level 0. The candidate claims Middle in `roles`, while the only
confirmed category is Backend Junior from an assessment result; the two
are separate fields and the profile never merges them. The example
values are fictional.
value:
version: 3
full_name:
status: confirmed
value: Anna Sokolova
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
contacts:
email:
status: confirmed
value: anna.sokolova@example.com
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
phone:
status: extracted
value: "+79000000000"
source:
origin: extracted_from_resume
trust_level: 0
quote: "Tel.: +7 900 000-00-00"
extraction_version: resume-rules.2026-10.1
confirmed_at: null
telegram:
status: unknown
value: null
source: null
stack:
- tag: PostgreSQL
status: confirmed
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
- tag: Kafka
status: extracted
source:
origin: extracted_from_resume
trust_level: 0
quote: "Event streaming with Kafka"
extraction_version: resume-rules.2026-10.1
confirmed_at: null
roles:
- specialization: backend
self_assessed_grade: middle
status: confirmed
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
experience:
- employer_name: Example Payments
specialization: backend
started_on: "2022-03"
ended_on: null
summary: Moved the payout service to an event model and owned its on-call rotation.
status: confirmed
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
soft_skills:
- skill: Mentoring
status: confirmed
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
terms:
location:
status: confirmed
value: Kazan
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
relocation:
status: confirmed
value: false
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
salary_minimum:
status: confirmed
value:
amount: 180000
currency: RUB
period: month
tax_basis: net
source:
origin: manual
trust_level: 0
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
confirmed_categories:
- specialization: backend
grade: junior
confirmed_at: "2026-10-04T18:10:00Z"
attempt_id: 0192b3c4-d5e6-7f80-9a1b-2c3d4e5f6a7b
updated_at: "2026-10-05T09:30:00Z"
BackendCandidateProfileUpdate:
summary: Save the Backend profile over version 2
description: >-
The candidate keeps the phone number and the Kafka tag as unconfirmed
suggestions by sending `extracted` with exactly their stored values, and
confirms or sets everything else. The values are fictional.
value:
expected_version: 2
full_name:
value: Anna Sokolova
status: confirmed
contacts:
email:
value: anna.sokolova@example.com
status: confirmed
phone:
value: "+79000000000"
status: extracted
telegram: null
stack:
- tag: PostgreSQL
status: confirmed
- tag: Kafka
status: extracted
roles:
- specialization: backend
self_assessed_grade: middle
status: confirmed
experience:
- employer_name: Example Payments
specialization: backend
started_on: "2022-03"
ended_on: null
summary: Moved the payout service to an event model and owned its on-call rotation.
status: confirmed
soft_skills:
- skill: Mentoring
status: confirmed
terms:
location:
value: Kazan
status: confirmed
relocation:
value: false
status: confirmed
salary_minimum:
value:
amount: 180000
currency: RUB
period: month
tax_basis: net
status: confirmed
ProfilePhoneNotE164:
summary: The phone number is not in the E.164 format
description: A rule of the schema. The pointer names the value inside the decision, and the body never repeats the submitted number.
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: 6d7e8f9a-0b1c-4d2e-8f4a-5b6c7d8e9f01
errors:
- in: body
pointer: /contacts/phone/value
code: invalid
message: The value does not match the contract.
ProfileExtractedValueChanged:
summary: A decision extracted for a tag that is not a stored suggestion
description: A domain rule of the server, checked after the schema. A suggestion can stay unconfirmed only with exactly its stored value; send confirmed to set a manual value.
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: 7e8f9a0b-1c2d-4e3f-9a5b-6c7d8e9f0a12
errors:
- in: body
pointer: /stack/1/status
code: invalid
message: The value does not match the contract.
ProfileRepeatedRole:
summary: The same specialization appears in two roles
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: 8f9a0b1c-2d3e-4f4a-8b6c-7d8e9f0a1b23
errors:
- in: body
pointer: /roles/1/specialization
code: invalid
message: The value does not match the contract.
ProfileStaleVersion:
summary: The save carried a stale expected_version
description: The profile changed, for example in another tab, after the client read it. Nothing was changed; the client reads the profile again and reapplies its edits.
value:
type: urn:lincodex:problem:version_conflict
title: Resource version conflict
status: 412
code: version_conflict
detail: The resource changed after it was read. Read it again before retrying.
trace_id: 9a0b1c2d-3e4f-4a5b-9c7d-8e9f0a1b2c34
+34
View File
@@ -590,3 +590,37 @@ OrganizationVersionConflict:
examples:
version_conflict:
$ref: ./examples.yml#/OrganizationStaleVersion
ProfileValidationFailed:
description: >-
The body does not match the contract or violates a profile rule: an
unknown field such as confirmed_grade, category, trust_level, or source,
a phone number outside E.164, a Telegram username without the leading @,
an email that is not an address, a month outside the YYYY-MM format, a
salary that is not a positive multiple of 1000, more items than a list
allows, a repeated tag, skill, or role specialization, a period that
ends before it starts or lies in the future, a decision extracted for a
value that is not a stored suggestion, or a missing or invalid
expected_version; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed. The problem never repeats a submitted value, because the body is personal data.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
phone_not_e164:
$ref: ./examples.yml#/ProfilePhoneNotE164
extracted_value_changed:
$ref: ./examples.yml#/ProfileExtractedValueChanged
repeated_role:
$ref: ./examples.yml#/ProfileRepeatedRole
ProfileVersionConflict:
description: >-
`expected_version` is not the current profile version; code
version_conflict. Nothing was changed; read the profile again before
retrying.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
version_conflict:
$ref: ./examples.yml#/ProfileStaleVersion
+728 -3
View File
@@ -1206,6 +1206,731 @@ AssessmentAvailability:
description: Questionnaire specializations in questionnaire order.
items:
$ref: '#/AssessmentSpecializationAvailability'
ProfileVersion:
type: integer
format: int64
minimum: 0
description: Version of the candidate profile. A candidate who has not saved the profile has version 0; every save that changes the profile advances it by one. The client sends the version it read as `expected_version`.
examples:
- 4
ProfileItemStatus:
type: string
description: 'Confirmation state of a profile list item, and the decision that a request sends for a field or an item.
- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.
- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.
A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.'
enum:
- confirmed
- extracted
ProfileClaimStatus:
type: string
description: 'Confirmation state of a single profile field.
- confirmed: the candidate typed the value or confirmed a suggestion.
- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.
- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'
enum:
- confirmed
- extracted
- unknown
ProfileClaimOrigin:
type: string
description: 'Where the value of a profile field or item came from. The server sets it; a request never sends it.
- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.
- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.
- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.
Confirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'
enum:
- manual
- extracted_from_resume
- imported
ProfileClaimTrustLevel:
type: integer
format: int32
minimum: 0
maximum: 0
description: 'Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'
examples:
- 0
ProfileClaimQuote:
type: string
minLength: 1
maxLength: 300
description: Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.
ProfileClaimSource:
type: object
description: 'Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'
additionalProperties: false
required:
- origin
- trust_level
- quote
- extraction_version
- confirmed_at
properties:
origin:
$ref: '#/ProfileClaimOrigin'
trust_level:
$ref: '#/ProfileClaimTrustLevel'
quote:
description: Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.
oneOf:
- $ref: '#/ProfileClaimQuote'
- type: 'null'
extraction_version:
description: Extractor version for an extracted or imported value, or null for a manual value.
oneOf:
- $ref: '#/NeedVersionLabel'
- type: 'null'
confirmed_at:
description: Time the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.
oneOf:
- $ref: '#/Timestamp'
- type: 'null'
ProfileLocationName:
type: string
minLength: 1
maxLength: 100
pattern: ^\S(?:.*\S)?$
description: City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.
ProfileSalaryMinimum:
type: object
description: 'The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.'
additionalProperties: false
required:
- amount
- currency
- period
- tax_basis
properties:
amount:
$ref: '#/RubAmount'
currency:
$ref: '#/CurrencyCode'
period:
$ref: '#/SalaryPeriod'
tax_basis:
$ref: '#/SalaryTaxBasis'
ProfileSoftSkill:
type: string
minLength: 1
maxLength: 50
pattern: ^\S(?:.*\S)?$
description: Soft skill as the candidate wrote it, for example "Mentoring" or "Negotiation". The platform has no soft skill taxonomy, so the text is free; it never changes a category or a grade. It has no leading or trailing whitespace and no line breaks. The server compares skills without regard to letter case. Plain text; clients show it as text, never as HTML.
ProfileEmployerName:
type: string
minLength: 1
maxLength: 200
pattern: ^\S(?:.*\S)?$
description: Name of the employer in one experience entry, as the candidate wrote it. It is personal data of the candidate's career. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.
ProfileExperienceSummary:
type: string
minLength: 1
maxLength: 1000
description: Tasks and results of the candidate in one experience entry. It describes the work rather than a job title. It may contain line breaks and personal data of the candidate; it must not contain personal data of other people. Plain text; clients show it as text, never as HTML.
ProfileYearMonth:
type: string
minLength: 7
maxLength: 7
pattern: ^[0-9]{4}-(0[1-9]|1[0-2])$
description: Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.
examples:
- 2024-03
ProfileFullNameClaim:
type: object
description: Full name of the candidate with its confirmation state and provenance. The value is personal data. It is disclosed to one organization only through the contact grant of the consent C4 and never appears in an organization-visible schema. `value` and `source` are null exactly when `status` is `unknown`.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: '#/ProfileClaimStatus'
value:
oneOf:
- $ref: '#/ContactFullName'
- type: 'null'
source:
oneOf:
- $ref: '#/ProfileClaimSource'
- type: 'null'
ProfileEmailClaim:
type: object
description: 'Contact email of the candidate with its confirmation state and provenance. It is personal data. It is a contact channel that the candidate gives, not the login of the account: the two may differ, the server never sends mail to it and never verifies it. `value` and `source` are null exactly when `status` is `unknown`.'
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: '#/ProfileClaimStatus'
value:
oneOf:
- $ref: '#/EmailAddress'
- type: 'null'
source:
oneOf:
- $ref: '#/ProfileClaimSource'
- type: 'null'
ProfilePhoneClaim:
type: object
description: Contact phone number of the candidate with its confirmation state and provenance. It is personal data, stored in the E.164 format of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: '#/ProfileClaimStatus'
value:
oneOf:
- $ref: '#/ContactPhoneNumber'
- type: 'null'
source:
oneOf:
- $ref: '#/ProfileClaimSource'
- type: 'null'
ProfileTelegramClaim:
type: object
description: Telegram username of the candidate with its confirmation state and provenance. It is personal data, stored with the leading @ of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: '#/ProfileClaimStatus'
value:
oneOf:
- $ref: '#/ContactTelegramUsername'
- type: 'null'
source:
oneOf:
- $ref: '#/ProfileClaimSource'
- type: 'null'
ProfileLocationClaim:
type: object
description: Place of the candidate with its confirmation state and provenance. It is personal data. `value` and `source` are null exactly when `status` is `unknown`.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: '#/ProfileClaimStatus'
value:
oneOf:
- $ref: '#/ProfileLocationName'
- type: 'null'
source:
oneOf:
- $ref: '#/ProfileClaimSource'
- type: 'null'
ProfileRelocationClaim:
type: object
description: Whether the candidate is ready to relocate, with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; the server never assumes an answer.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: '#/ProfileClaimStatus'
value:
type:
- boolean
- 'null'
source:
oneOf:
- $ref: '#/ProfileClaimSource'
- type: 'null'
ProfileSalaryMinimumClaim:
type: object
description: Lowest acceptable salary with its confirmation state and provenance. It is personal data that no organization reads. `value` and `source` are null exactly when `status` is `unknown`; the server never substitutes zero or a market estimate.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: '#/ProfileClaimStatus'
value:
oneOf:
- $ref: '#/ProfileSalaryMinimum'
- type: 'null'
source:
oneOf:
- $ref: '#/ProfileClaimSource'
- type: 'null'
ProfileContacts:
type: object
description: Contact channels of the candidate. Each channel is a claim of its own, and the candidate fills in any subset. The kinds are the ones that the contact disclosure (consent C4) can pass on, with the same value formats, so a disclosure never has to convert or drop a stored value; adding a kind, such as a link to a code repository, is a contract change in both places. Contacts leave the profile only through a contact grant, never in a card or a search result. All values are personal data.
additionalProperties: false
required:
- email
- phone
- telegram
properties:
email:
$ref: '#/ProfileEmailClaim'
phone:
$ref: '#/ProfilePhoneClaim'
telegram:
$ref: '#/ProfileTelegramClaim'
ProfileTerms:
type: object
description: 'Conditions that the candidate wants: the place, readiness to relocate, and the lowest salary. Acceptable work formats are not repeated here; they are the `work_formats` of the questionnaire `WorkContext`, the only place that holds them. These are the candidate''s wishes, never the terms of an invitation, which an organization offers and which the invitation contract describes.'
additionalProperties: false
required:
- location
- relocation
- salary_minimum
properties:
location:
$ref: '#/ProfileLocationClaim'
relocation:
$ref: '#/ProfileRelocationClaim'
salary_minimum:
$ref: '#/ProfileSalaryMinimumClaim'
ProfileStackItem:
type: object
description: 'One technology tag of the candidate''s stack with its confirmation state and provenance. The profile stack is one list for the whole profile; the questionnaire holds the tags of each chosen specialization with the same `StackTag` meaning, and the two lists are independent: the server never copies one into the other. A tag is a descriptive attribute and never forms a category.'
additionalProperties: false
required:
- tag
- status
- source
properties:
tag:
$ref: '#/StackTag'
status:
$ref: '#/ProfileItemStatus'
source:
$ref: '#/ProfileClaimSource'
ProfileSoftSkillItem:
type: object
description: One soft skill of the candidate with its confirmation state and provenance. It is a claim; no assessment checks it.
additionalProperties: false
required:
- skill
- status
- source
properties:
skill:
$ref: '#/ProfileSoftSkill'
status:
$ref: '#/ProfileItemStatus'
source:
$ref: '#/ProfileClaimSource'
ProfileRoleItem:
type: object
description: 'One role of the candidate: a specialization of the catalog with the grade that the candidate claims for it. `self_assessed_grade` is a claim, the same one that the questionnaire calls `self_assessed_grade` for its at most two chosen specializations: it influences nothing but the display and never becomes a confirmed grade or a category. The questionnaire value starts the assessment and the profile value is what the profile shows; the two are saved separately and the server never copies one into the other. A confirmed grade comes only from an assessment result and appears in `confirmed_categories` of the profile, never in a role; unknown fields such as `confirmed_grade` or `category` are rejected.'
additionalProperties: false
required:
- specialization
- self_assessed_grade
- status
- source
properties:
specialization:
$ref: '#/SpecializationCode'
self_assessed_grade:
description: Grade that the candidate claims in the specialization, or null when the candidate names none.
oneOf:
- $ref: '#/GradeCode'
- type: 'null'
status:
$ref: '#/ProfileItemStatus'
source:
$ref: '#/ProfileClaimSource'
ProfileExperienceItem:
type: object
description: 'One entry of the candidate''s work history with its confirmation state and provenance. An entry describes the work by its specialization and tasks rather than by a job title, and it is a claim of trust level 0. It is different from the `CandidateExperience` of the questionnaire, which holds only the total months of commercial and academic experience of a chosen specialization as a hint for the assessment: the two are saved separately, and the server neither adds the entries up for the questionnaire nor fills the entries from it. An entry is personal data.'
additionalProperties: false
required:
- employer_name
- specialization
- started_on
- ended_on
- summary
- status
- source
properties:
employer_name:
description: Employer of the entry, or null when the candidate gives none.
oneOf:
- $ref: '#/ProfileEmployerName'
- type: 'null'
specialization:
$ref: '#/SpecializationCode'
started_on:
$ref: '#/ProfileYearMonth'
ended_on:
description: Last month of the work, or null when the candidate still works there. It is not earlier than `started_on`.
oneOf:
- $ref: '#/ProfileYearMonth'
- type: 'null'
summary:
description: Tasks and results of the entry, or null when the candidate gives none.
oneOf:
- $ref: '#/ProfileExperienceSummary'
- type: 'null'
status:
$ref: '#/ProfileItemStatus'
source:
$ref: '#/ProfileClaimSource'
ProfileConfirmedCategory:
type: object
description: 'A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`.'
additionalProperties: false
required:
- specialization
- grade
- confirmed_at
- attempt_id
properties:
specialization:
$ref: '#/SpecializationCode'
grade:
$ref: '#/GradeCode'
confirmed_at:
$ref: '#/Timestamp'
attempt_id:
type: string
format: uuid
description: Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate.
CandidateProfile:
type: object
description: 'The private profile of the current candidate: full name and contacts, stack, roles, work experience, soft skills, and desired terms, each value with its confirmation state and provenance. It is personal data that only the candidate reads. It is never an organization-visible schema: an organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant, and no organization schema refers to this one.
Every value is a claim of trust level 0. The `self_assessed_grade` of a role is what the candidate says; the `confirmed_categories` list is what assessment results established, and the two are never mixed. A candidate who has not saved the profile gets version 0, every single field `unknown`, empty lists, and null `updated_at`.
The profile is manual by nature and complete without a file: no field requires a resume, the ML service, or an FSP account, and a candidate with none of them has the same fields. Work formats live in the questionnaire; a candidate''s assessment starts from the questionnaire, not from this profile.'
additionalProperties: false
required:
- version
- full_name
- contacts
- stack
- roles
- experience
- soft_skills
- terms
- confirmed_categories
- updated_at
properties:
version:
$ref: '#/ProfileVersion'
full_name:
$ref: '#/ProfileFullNameClaim'
contacts:
$ref: '#/ProfileContacts'
stack:
type: array
maxItems: 30
description: Technology tags in the order the candidate gave them, each tag at most once without regard to letter case.
items:
$ref: '#/ProfileStackItem'
roles:
type: array
maxItems: 9
description: Roles in the order the candidate gave them, each specialization at most once.
items:
$ref: '#/ProfileRoleItem'
experience:
type: array
maxItems: 20
description: Work history entries in the order the candidate gave them.
items:
$ref: '#/ProfileExperienceItem'
soft_skills:
type: array
maxItems: 10
description: Soft skills in the order the candidate gave them, each skill at most once without regard to letter case.
items:
$ref: '#/ProfileSoftSkillItem'
terms:
$ref: '#/ProfileTerms'
confirmed_categories:
type: array
maxItems: 9
description: Categories that assessment results confirmed, at most one per specialization, in catalog order. Read-only and empty until an assessment confirms a grade.
items:
$ref: '#/ProfileConfirmedCategory'
updated_at:
description: Time of the last change, or null before the first save.
oneOf:
- $ref: '#/Timestamp'
- type: 'null'
ProfileFullNameInput:
type: object
description: Decision about the full name in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: '#/ContactFullName'
status:
$ref: '#/ProfileItemStatus'
ProfileEmailInput:
type: object
description: Decision about the contact email in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: '#/EmailAddress'
status:
$ref: '#/ProfileItemStatus'
ProfilePhoneInput:
type: object
description: Decision about the contact phone number in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: '#/ContactPhoneNumber'
status:
$ref: '#/ProfileItemStatus'
ProfileTelegramInput:
type: object
description: Decision about the Telegram username in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: '#/ContactTelegramUsername'
status:
$ref: '#/ProfileItemStatus'
ProfileLocationInput:
type: object
description: Decision about the place in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: '#/ProfileLocationName'
status:
$ref: '#/ProfileItemStatus'
ProfileRelocationInput:
type: object
description: Decision about readiness to relocate in a request; see CandidateProfileUpdate for the rules of `status`.
additionalProperties: false
required:
- value
- status
properties:
value:
type: boolean
status:
$ref: '#/ProfileItemStatus'
ProfileSalaryMinimumInput:
type: object
description: Decision about the lowest salary in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: '#/ProfileSalaryMinimum'
status:
$ref: '#/ProfileItemStatus'
ProfileContactsInput:
type: object
description: 'Decisions about the contact channels in a request. A channel sent as null is unknown: it is removed if it was set.'
additionalProperties: false
required:
- email
- phone
- telegram
properties:
email:
oneOf:
- $ref: '#/ProfileEmailInput'
- type: 'null'
phone:
oneOf:
- $ref: '#/ProfilePhoneInput'
- type: 'null'
telegram:
oneOf:
- $ref: '#/ProfileTelegramInput'
- type: 'null'
ProfileTermsInput:
type: object
description: 'Decisions about the desired terms in a request. A field sent as null is unknown: it is removed if it was set.'
additionalProperties: false
required:
- location
- relocation
- salary_minimum
properties:
location:
oneOf:
- $ref: '#/ProfileLocationInput'
- type: 'null'
relocation:
oneOf:
- $ref: '#/ProfileRelocationInput'
- type: 'null'
salary_minimum:
oneOf:
- $ref: '#/ProfileSalaryMinimumInput'
- type: 'null'
ProfileStackItemInput:
type: object
description: Decision about one stack tag in a request; see CandidateProfileUpdate for the rules of `status`.
additionalProperties: false
required:
- tag
- status
properties:
tag:
$ref: '#/StackTag'
status:
$ref: '#/ProfileItemStatus'
ProfileSoftSkillItemInput:
type: object
description: Decision about one soft skill in a request; see CandidateProfileUpdate for the rules of `status`.
additionalProperties: false
required:
- skill
- status
properties:
skill:
$ref: '#/ProfileSoftSkill'
status:
$ref: '#/ProfileItemStatus'
ProfileRoleItemInput:
type: object
description: 'Decision about one role in a request; see CandidateProfileUpdate for the rules of `status`. The object has no confirmed grade and no category: unknown fields are rejected.'
additionalProperties: false
required:
- specialization
- self_assessed_grade
- status
properties:
specialization:
$ref: '#/SpecializationCode'
self_assessed_grade:
description: Grade that the candidate claims, or null when the candidate names none.
oneOf:
- $ref: '#/GradeCode'
- type: 'null'
status:
$ref: '#/ProfileItemStatus'
ProfileExperienceItemInput:
type: object
description: Decision about one work history entry in a request; see CandidateProfileUpdate for the rules of `status`. The server also requires `ended_on` not to precede `started_on` and no month to lie in the future, and answers 400 with the pointer of the month.
additionalProperties: false
required:
- employer_name
- specialization
- started_on
- ended_on
- summary
- status
properties:
employer_name:
oneOf:
- $ref: '#/ProfileEmployerName'
- type: 'null'
specialization:
$ref: '#/SpecializationCode'
started_on:
$ref: '#/ProfileYearMonth'
ended_on:
oneOf:
- $ref: '#/ProfileYearMonth'
- type: 'null'
summary:
oneOf:
- $ref: '#/ProfileExperienceSummary'
- type: 'null'
status:
$ref: '#/ProfileItemStatus'
CandidateProfileUpdate:
type: object
description: 'Complete new state of the candidate profile. It replaces every stored value as a whole: a single field sent as null is unknown and is removed, and a list replaces the stored list. The body is personal data.
Each value carries a decision `status`. `confirmed` sets a manual value or confirms a stored suggestion; confirming a suggestion with exactly its stored value keeps its origin and quote, and any other value makes the claim manual. `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the stored value; any other use answers 400 with the pointer of that status, for example `/stack/1/status`. The provenance, the trust level, and the confirmed categories are not part of the request, and unknown fields are rejected, so a request can neither mark a claim as verified nor write a confirmed grade or a category.'
additionalProperties: false
required:
- expected_version
- full_name
- contacts
- stack
- roles
- experience
- soft_skills
- terms
properties:
expected_version:
$ref: '#/ProfileVersion'
full_name:
oneOf:
- $ref: '#/ProfileFullNameInput'
- type: 'null'
contacts:
$ref: '#/ProfileContactsInput'
stack:
type: array
maxItems: 30
description: Technology tags. The schema limits the count; the server also answers 400 with the pointer of a tag that repeats an earlier one without regard to letter case, for example `/stack/2/tag`.
items:
$ref: '#/ProfileStackItemInput'
roles:
type: array
maxItems: 9
description: Roles. The server answers 400 with the pointer of a role whose specialization repeats an earlier one, for example `/roles/1/specialization`.
items:
$ref: '#/ProfileRoleItemInput'
experience:
type: array
maxItems: 20
description: Work history entries.
items:
$ref: '#/ProfileExperienceItemInput'
soft_skills:
type: array
maxItems: 10
description: Soft skills. The server answers 400 with the pointer of a skill that repeats an earlier one without regard to letter case.
items:
$ref: '#/ProfileSoftSkillItemInput'
terms:
$ref: '#/ProfileTermsInput'
DirectionCode:
type: string
description: 'Stable code of a professional direction, the group that a specialization belongs to.
@@ -4322,7 +5047,7 @@ WorkFormat:
- 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.
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 (`ProfileTerms`). The acceptable work formats live only here: the profile does not repeat them.'
additionalProperties: false
required:
- work_formats
@@ -4337,7 +5062,7 @@ WorkContext:
$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.'
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. The work history entries of the candidate profile (`ProfileExperienceItem`) are a different, detailed claim: the two are saved separately and the server neither adds the entries up nor fills them from these totals.'
additionalProperties: false
required:
- commercial_months
@@ -4357,7 +5082,7 @@ CandidateExperience:
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.'
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. The candidate profile states the same kind of claim in the `roles` of `CandidateProfile` (`ProfileRoleItem.self_assessed_grade`): the questionnaire value starts the assessment and the profile value is what the profile shows, the two are saved separately, and neither is ever a confirmed grade.'
additionalProperties: false
required:
- specialization
@@ -0,0 +1,933 @@
schemas:
ProfileVersion:
type: integer
format: int64
minimum: 0
description: >-
Version of the candidate profile. A candidate who has not saved the
profile has version 0; every save that changes the profile advances it
by one. The client sends the version it read as `expected_version`.
examples:
- 4
ProfileItemStatus:
type: string
description: |-
Confirmation state of a profile list item, and the decision that a request sends for a field or an item.
- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.
- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.
A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.
enum:
- confirmed
- extracted
ProfileClaimStatus:
type: string
description: |-
Confirmation state of a single profile field.
- confirmed: the candidate typed the value or confirmed a suggestion.
- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.
- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.
enum:
- confirmed
- extracted
- unknown
ProfileClaimOrigin:
type: string
description: |-
Where the value of a profile field or item came from. The server sets it; a request never sends it.
- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.
- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.
- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.
Confirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.
enum:
- manual
- extracted_from_resume
- imported
ProfileClaimTrustLevel:
type: integer
format: int32
minimum: 0
maximum: 0
description: >-
Trust level of a profile claim. Every claim of the profile has trust
level 0, whatever its origin: a manual value, an imported value, and
a value that the candidate confirmed are all unverified statements.
Confirming a suggestion changes its status, never its trust level.
Higher levels belong to evidence, such as an assessment result or a
confirmation by a third party, which are separate resources and never
write a level into a profile claim.
examples:
- 0
ProfileClaimQuote:
type: string
minLength: 1
maxLength: 300
description: >-
Exact excerpt of the imported document that the value was extracted
from, so the candidate can check it. It may contain personal data of
the candidate. It may contain line breaks. Plain text; clients show it
as text, never as HTML.
ProfileClaimSource:
type: object
description: >-
Provenance and confirmation of one profile value: its origin, the
trust level, the excerpt it was extracted from, the extractor version,
and the time the candidate confirmed it. Read-only; the server derives
it and a request cannot set it. The imported document or source itself
is not referenced: the profile never requires a file, the ML service,
or an FSP account, and a later link to them is an additive field.
additionalProperties: false
required:
- origin
- trust_level
- quote
- extraction_version
- confirmed_at
properties:
origin:
$ref: "#/schemas/ProfileClaimOrigin"
trust_level:
$ref: "#/schemas/ProfileClaimTrustLevel"
quote:
description: >-
Excerpt of the imported document that supports the value, or null
for a manual value and for an extracted value that the extractor
did not tie to one excerpt.
oneOf:
- $ref: "#/schemas/ProfileClaimQuote"
- type: "null"
extraction_version:
description: >-
Extractor version for an extracted or imported value, or null for
a manual value.
oneOf:
- $ref: "./need_schemas.yml#/schemas/NeedVersionLabel"
- type: "null"
confirmed_at:
description: >-
Time the candidate typed or confirmed the value, or null while the
value is an unconfirmed suggestion.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
ProfileLocationName:
type: string
minLength: 1
maxLength: 100
pattern: '^\S(?:.*\S)?$'
description: >-
City or region where the candidate lives or wants to work, as free
text. It is personal data of the candidate and never a street
address. It has no leading or trailing whitespace and no line breaks.
Plain text; clients show it as text, never as HTML.
ProfileSalaryMinimum:
type: object
description: >-
The lowest salary that the candidate accepts, in whole rubles with its
base: the currency, the pay period, and the tax basis. It is private
to the candidate: no organization reads it, and the invitation only
shows a compatibility indicator that the server derives from it. It
is personal data. The amount is a positive multiple of 1000.
additionalProperties: false
required:
- amount
- currency
- period
- tax_basis
properties:
amount:
$ref: "./need_schemas.yml#/schemas/RubAmount"
currency:
$ref: "./need_schemas.yml#/schemas/CurrencyCode"
period:
$ref: "./need_schemas.yml#/schemas/SalaryPeriod"
tax_basis:
$ref: "./need_schemas.yml#/schemas/SalaryTaxBasis"
ProfileSoftSkill:
type: string
minLength: 1
maxLength: 50
pattern: '^\S(?:.*\S)?$'
description: >-
Soft skill as the candidate wrote it, for example "Mentoring" or
"Negotiation". The platform has no soft skill taxonomy, so the text is
free; it never changes a category or a grade. It has no leading or
trailing whitespace and no line breaks. The server compares skills
without regard to letter case. Plain text; clients show it as text,
never as HTML.
ProfileEmployerName:
type: string
minLength: 1
maxLength: 200
pattern: '^\S(?:.*\S)?$'
description: >-
Name of the employer in one experience entry, as the candidate wrote
it. It is personal data of the candidate's career. It has no leading
or trailing whitespace and no line breaks. Plain text; clients show
it as text, never as HTML.
ProfileExperienceSummary:
type: string
minLength: 1
maxLength: 1000
description: >-
Tasks and results of the candidate in one experience entry. It
describes the work rather than a job title. It may contain line
breaks and personal data of the candidate; it must not contain
personal data of other people. Plain text; clients show it as text,
never as HTML.
ProfileYearMonth:
type: string
minLength: 7
maxLength: 7
pattern: "^[0-9]{4}-(0[1-9]|1[0-2])$"
description: >-
Calendar month in the `YYYY-MM` format, for example 2024-03. An
experience period has month precision only, so the contract holds no
exact date of employment. The server rejects a month that lies in the
future.
examples:
- "2024-03"
ProfileFullNameClaim:
type: object
description: >-
Full name of the candidate with its confirmation state and provenance.
The value is personal data. It is disclosed to one organization only
through the contact grant of the consent C4 and never appears in an
organization-visible schema. `value` and `source` are null exactly
when `status` is `unknown`.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: "#/schemas/ProfileClaimStatus"
value:
oneOf:
- $ref: "./contact_grant_schemas.yml#/schemas/ContactFullName"
- type: "null"
source:
oneOf:
- $ref: "#/schemas/ProfileClaimSource"
- type: "null"
ProfileEmailClaim:
type: object
description: >-
Contact email of the candidate with its confirmation state and
provenance. It is personal data. It is a contact channel that the
candidate gives, not the login of the account: the two may differ, the
server never sends mail to it and never verifies it. `value` and
`source` are null exactly when `status` is `unknown`.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: "#/schemas/ProfileClaimStatus"
value:
oneOf:
- $ref: "./identity_schemas.yml#/schemas/EmailAddress"
- type: "null"
source:
oneOf:
- $ref: "#/schemas/ProfileClaimSource"
- type: "null"
ProfilePhoneClaim:
type: object
description: >-
Contact phone number of the candidate with its confirmation state and
provenance. It is personal data, stored in the E.164 format of the
contact disclosure. `value` and `source` are null exactly when
`status` is `unknown`.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: "#/schemas/ProfileClaimStatus"
value:
oneOf:
- $ref: "./contact_grant_schemas.yml#/schemas/ContactPhoneNumber"
- type: "null"
source:
oneOf:
- $ref: "#/schemas/ProfileClaimSource"
- type: "null"
ProfileTelegramClaim:
type: object
description: >-
Telegram username of the candidate with its confirmation state and
provenance. It is personal data, stored with the leading @ of the
contact disclosure. `value` and `source` are null exactly when
`status` is `unknown`.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: "#/schemas/ProfileClaimStatus"
value:
oneOf:
- $ref: "./contact_grant_schemas.yml#/schemas/ContactTelegramUsername"
- type: "null"
source:
oneOf:
- $ref: "#/schemas/ProfileClaimSource"
- type: "null"
ProfileLocationClaim:
type: object
description: >-
Place of the candidate with its confirmation state and provenance. It
is personal data. `value` and `source` are null exactly when `status`
is `unknown`.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: "#/schemas/ProfileClaimStatus"
value:
oneOf:
- $ref: "#/schemas/ProfileLocationName"
- type: "null"
source:
oneOf:
- $ref: "#/schemas/ProfileClaimSource"
- type: "null"
ProfileRelocationClaim:
type: object
description: >-
Whether the candidate is ready to relocate, with its confirmation
state and provenance. `value` and `source` are null exactly when
`status` is `unknown`; the server never assumes an answer.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: "#/schemas/ProfileClaimStatus"
value:
type:
- boolean
- "null"
source:
oneOf:
- $ref: "#/schemas/ProfileClaimSource"
- type: "null"
ProfileSalaryMinimumClaim:
type: object
description: >-
Lowest acceptable salary with its confirmation state and provenance.
It is personal data that no organization reads. `value` and `source`
are null exactly when `status` is `unknown`; the server never
substitutes zero or a market estimate.
additionalProperties: false
required:
- status
- value
- source
properties:
status:
$ref: "#/schemas/ProfileClaimStatus"
value:
oneOf:
- $ref: "#/schemas/ProfileSalaryMinimum"
- type: "null"
source:
oneOf:
- $ref: "#/schemas/ProfileClaimSource"
- type: "null"
ProfileContacts:
type: object
description: >-
Contact channels of the candidate. Each channel is a claim of its own,
and the candidate fills in any subset. The kinds are the ones that
the contact disclosure (consent C4) can pass on, with the same value
formats, so a disclosure never has to convert or drop a stored value;
adding a kind, such as a link to a code repository, is a contract
change in both places. Contacts leave the profile only through a
contact grant, never in a card or a search result. All values are
personal data.
additionalProperties: false
required:
- email
- phone
- telegram
properties:
email:
$ref: "#/schemas/ProfileEmailClaim"
phone:
$ref: "#/schemas/ProfilePhoneClaim"
telegram:
$ref: "#/schemas/ProfileTelegramClaim"
ProfileTerms:
type: object
description: >-
Conditions that the candidate wants: the place, readiness to relocate,
and the lowest salary. Acceptable work formats are not repeated here;
they are the `work_formats` of the questionnaire `WorkContext`, the
only place that holds them. These are the candidate's wishes, never
the terms of an invitation, which an organization offers and which
the invitation contract describes.
additionalProperties: false
required:
- location
- relocation
- salary_minimum
properties:
location:
$ref: "#/schemas/ProfileLocationClaim"
relocation:
$ref: "#/schemas/ProfileRelocationClaim"
salary_minimum:
$ref: "#/schemas/ProfileSalaryMinimumClaim"
ProfileStackItem:
type: object
description: >-
One technology tag of the candidate's stack with its confirmation state
and provenance. The profile stack is one list for the whole profile;
the questionnaire holds the tags of each chosen specialization with the
same `StackTag` meaning, and the two lists are independent: the server
never copies one into the other. A tag is a descriptive attribute and
never forms a category.
additionalProperties: false
required:
- tag
- status
- source
properties:
tag:
$ref: "./questionnaire_schemas.yml#/schemas/StackTag"
status:
$ref: "#/schemas/ProfileItemStatus"
source:
$ref: "#/schemas/ProfileClaimSource"
ProfileSoftSkillItem:
type: object
description: >-
One soft skill of the candidate with its confirmation state and
provenance. It is a claim; no assessment checks it.
additionalProperties: false
required:
- skill
- status
- source
properties:
skill:
$ref: "#/schemas/ProfileSoftSkill"
status:
$ref: "#/schemas/ProfileItemStatus"
source:
$ref: "#/schemas/ProfileClaimSource"
ProfileRoleItem:
type: object
description: >-
One role of the candidate: a specialization of the catalog with the
grade that the candidate claims for it. `self_assessed_grade` is a
claim, the same one that the questionnaire calls `self_assessed_grade`
for its at most two chosen specializations: it influences nothing but
the display and never becomes a confirmed grade or a category. The
questionnaire value starts the assessment and the profile value is what
the profile shows; the two are saved separately and the server never
copies one into the other. A confirmed grade comes only from an
assessment result and appears in `confirmed_categories` of the profile,
never in a role; unknown fields such as `confirmed_grade` or `category`
are rejected.
additionalProperties: false
required:
- specialization
- self_assessed_grade
- status
- source
properties:
specialization:
$ref: "./catalog_schemas.yml#/schemas/SpecializationCode"
self_assessed_grade:
description: >-
Grade that the candidate claims in the specialization, or null when
the candidate names none.
oneOf:
- $ref: "./catalog_schemas.yml#/schemas/GradeCode"
- type: "null"
status:
$ref: "#/schemas/ProfileItemStatus"
source:
$ref: "#/schemas/ProfileClaimSource"
ProfileExperienceItem:
type: object
description: >-
One entry of the candidate's work history with its confirmation state
and provenance. An entry describes the work by its specialization and
tasks rather than by a job title, and it is a claim of trust level 0.
It is different from the `CandidateExperience` of the questionnaire,
which holds only the total months of commercial and academic
experience of a chosen specialization as a hint for the assessment:
the two are saved separately, and the server neither adds the entries
up for the questionnaire nor fills the entries from it. An entry is
personal data.
additionalProperties: false
required:
- employer_name
- specialization
- started_on
- ended_on
- summary
- status
- source
properties:
employer_name:
description: Employer of the entry, or null when the candidate gives none.
oneOf:
- $ref: "#/schemas/ProfileEmployerName"
- type: "null"
specialization:
$ref: "./catalog_schemas.yml#/schemas/SpecializationCode"
started_on:
$ref: "#/schemas/ProfileYearMonth"
ended_on:
description: >-
Last month of the work, or null when the candidate still works
there. It is not earlier than `started_on`.
oneOf:
- $ref: "#/schemas/ProfileYearMonth"
- type: "null"
summary:
description: Tasks and results of the entry, or null when the candidate gives none.
oneOf:
- $ref: "#/schemas/ProfileExperienceSummary"
- type: "null"
status:
$ref: "#/schemas/ProfileItemStatus"
source:
$ref: "#/schemas/ProfileClaimSource"
ProfileConfirmedCategory:
type: object
description: >-
A category that an assessment result confirmed: the specialization
with the confirmed grade. It is read-only and derived by the server
from the assessment results of the candidate; no request carries it
and the profile storage holds no such column, so neither a form nor an
import can write a confirmed grade. It is separate from the claims of
the profile and from the self-assessed grades in `roles`.
additionalProperties: false
required:
- specialization
- grade
- confirmed_at
- attempt_id
properties:
specialization:
$ref: "./catalog_schemas.yml#/schemas/SpecializationCode"
grade:
$ref: "./catalog_schemas.yml#/schemas/GradeCode"
confirmed_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
attempt_id:
type: string
format: uuid
description: >-
Assessment attempt whose result confirmed the grade. The attempt
belongs to the candidate.
CandidateProfile:
type: object
description: >-
The private profile of the current candidate: full name and contacts,
stack, roles, work experience, soft skills, and desired terms, each
value with its confirmation state and provenance. It is personal data
that only the candidate reads. It is never an organization-visible
schema: an organization sees a candidate only through the anonymous
card and, after an accepted invitation, through the contact grant, and
no organization schema refers to this one.
Every value is a claim of trust level 0. The `self_assessed_grade` of a
role is what the candidate says; the `confirmed_categories` list is
what assessment results established, and the two are never mixed. A
candidate who has not saved the profile gets version 0, every single
field `unknown`, empty lists, and null `updated_at`.
The profile is manual by nature and complete without a file: no field
requires a resume, the ML service, or an FSP account, and a candidate
with none of them has the same fields. Work formats live in the
questionnaire; a candidate's assessment starts from the questionnaire,
not from this profile.
additionalProperties: false
required:
- version
- full_name
- contacts
- stack
- roles
- experience
- soft_skills
- terms
- confirmed_categories
- updated_at
properties:
version:
$ref: "#/schemas/ProfileVersion"
full_name:
$ref: "#/schemas/ProfileFullNameClaim"
contacts:
$ref: "#/schemas/ProfileContacts"
stack:
type: array
maxItems: 30
description: >-
Technology tags in the order the candidate gave them, each tag at
most once without regard to letter case.
items:
$ref: "#/schemas/ProfileStackItem"
roles:
type: array
maxItems: 9
description: >-
Roles in the order the candidate gave them, each specialization at
most once.
items:
$ref: "#/schemas/ProfileRoleItem"
experience:
type: array
maxItems: 20
description: Work history entries in the order the candidate gave them.
items:
$ref: "#/schemas/ProfileExperienceItem"
soft_skills:
type: array
maxItems: 10
description: >-
Soft skills in the order the candidate gave them, each skill at
most once without regard to letter case.
items:
$ref: "#/schemas/ProfileSoftSkillItem"
terms:
$ref: "#/schemas/ProfileTerms"
confirmed_categories:
type: array
maxItems: 9
description: >-
Categories that assessment results confirmed, at most one per
specialization, in catalog order. Read-only and empty until an
assessment confirms a grade.
items:
$ref: "#/schemas/ProfileConfirmedCategory"
updated_at:
description: Time of the last change, or null before the first save.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
ProfileFullNameInput:
type: object
description: >-
Decision about the full name in a request; see CandidateProfileUpdate
for the rules of `status`. The value is personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: "./contact_grant_schemas.yml#/schemas/ContactFullName"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileEmailInput:
type: object
description: >-
Decision about the contact email in a request; see
CandidateProfileUpdate for the rules of `status`. The value is
personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: "./identity_schemas.yml#/schemas/EmailAddress"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfilePhoneInput:
type: object
description: >-
Decision about the contact phone number in a request; see
CandidateProfileUpdate for the rules of `status`. The value is
personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: "./contact_grant_schemas.yml#/schemas/ContactPhoneNumber"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileTelegramInput:
type: object
description: >-
Decision about the Telegram username in a request; see
CandidateProfileUpdate for the rules of `status`. The value is
personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: "./contact_grant_schemas.yml#/schemas/ContactTelegramUsername"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileLocationInput:
type: object
description: >-
Decision about the place in a request; see CandidateProfileUpdate for
the rules of `status`. The value is personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: "#/schemas/ProfileLocationName"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileRelocationInput:
type: object
description: >-
Decision about readiness to relocate in a request; see
CandidateProfileUpdate for the rules of `status`.
additionalProperties: false
required:
- value
- status
properties:
value:
type: boolean
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileSalaryMinimumInput:
type: object
description: >-
Decision about the lowest salary in a request; see
CandidateProfileUpdate for the rules of `status`. The value is
personal data.
additionalProperties: false
required:
- value
- status
properties:
value:
$ref: "#/schemas/ProfileSalaryMinimum"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileContactsInput:
type: object
description: >-
Decisions about the contact channels in a request. A channel sent as
null is unknown: it is removed if it was set.
additionalProperties: false
required:
- email
- phone
- telegram
properties:
email:
oneOf:
- $ref: "#/schemas/ProfileEmailInput"
- type: "null"
phone:
oneOf:
- $ref: "#/schemas/ProfilePhoneInput"
- type: "null"
telegram:
oneOf:
- $ref: "#/schemas/ProfileTelegramInput"
- type: "null"
ProfileTermsInput:
type: object
description: >-
Decisions about the desired terms in a request. A field sent as null
is unknown: it is removed if it was set.
additionalProperties: false
required:
- location
- relocation
- salary_minimum
properties:
location:
oneOf:
- $ref: "#/schemas/ProfileLocationInput"
- type: "null"
relocation:
oneOf:
- $ref: "#/schemas/ProfileRelocationInput"
- type: "null"
salary_minimum:
oneOf:
- $ref: "#/schemas/ProfileSalaryMinimumInput"
- type: "null"
ProfileStackItemInput:
type: object
description: >-
Decision about one stack tag in a request; see CandidateProfileUpdate
for the rules of `status`.
additionalProperties: false
required:
- tag
- status
properties:
tag:
$ref: "./questionnaire_schemas.yml#/schemas/StackTag"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileSoftSkillItemInput:
type: object
description: >-
Decision about one soft skill in a request; see
CandidateProfileUpdate for the rules of `status`.
additionalProperties: false
required:
- skill
- status
properties:
skill:
$ref: "#/schemas/ProfileSoftSkill"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileRoleItemInput:
type: object
description: >-
Decision about one role in a request; see CandidateProfileUpdate for
the rules of `status`. The object has no confirmed grade and no
category: unknown fields are rejected.
additionalProperties: false
required:
- specialization
- self_assessed_grade
- status
properties:
specialization:
$ref: "./catalog_schemas.yml#/schemas/SpecializationCode"
self_assessed_grade:
description: Grade that the candidate claims, or null when the candidate names none.
oneOf:
- $ref: "./catalog_schemas.yml#/schemas/GradeCode"
- type: "null"
status:
$ref: "#/schemas/ProfileItemStatus"
ProfileExperienceItemInput:
type: object
description: >-
Decision about one work history entry in a request; see
CandidateProfileUpdate for the rules of `status`. The server also
requires `ended_on` not to precede `started_on` and no month to lie in
the future, and answers 400 with the pointer of the month.
additionalProperties: false
required:
- employer_name
- specialization
- started_on
- ended_on
- summary
- status
properties:
employer_name:
oneOf:
- $ref: "#/schemas/ProfileEmployerName"
- type: "null"
specialization:
$ref: "./catalog_schemas.yml#/schemas/SpecializationCode"
started_on:
$ref: "#/schemas/ProfileYearMonth"
ended_on:
oneOf:
- $ref: "#/schemas/ProfileYearMonth"
- type: "null"
summary:
oneOf:
- $ref: "#/schemas/ProfileExperienceSummary"
- type: "null"
status:
$ref: "#/schemas/ProfileItemStatus"
CandidateProfileUpdate:
type: object
description: >-
Complete new state of the candidate profile. It replaces every stored
value as a whole: a single field sent as null is unknown and is removed,
and a list replaces the stored list. The body is personal data.
Each value carries a decision `status`. `confirmed` sets a manual value
or confirms a stored suggestion; confirming a suggestion with exactly
its stored value keeps its origin and quote, and any other value makes
the claim manual. `extracted` keeps a stored suggestion unconfirmed and
is accepted only with exactly the stored value; any other use answers
400 with the pointer of that status, for example `/stack/1/status`. The
provenance, the trust level, and the confirmed categories are not part
of the request, and unknown fields are rejected, so a request can
neither mark a claim as verified nor write a confirmed grade or a
category.
additionalProperties: false
required:
- expected_version
- full_name
- contacts
- stack
- roles
- experience
- soft_skills
- terms
properties:
expected_version:
$ref: "#/schemas/ProfileVersion"
full_name:
oneOf:
- $ref: "#/schemas/ProfileFullNameInput"
- type: "null"
contacts:
$ref: "#/schemas/ProfileContactsInput"
stack:
type: array
maxItems: 30
description: >-
Technology tags. The schema limits the count; the server also
answers 400 with the pointer of a tag that repeats an earlier one
without regard to letter case, for example `/stack/2/tag`.
items:
$ref: "#/schemas/ProfileStackItemInput"
roles:
type: array
maxItems: 9
description: >-
Roles. The server answers 400 with the pointer of a role whose
specialization repeats an earlier one, for example
`/roles/1/specialization`.
items:
$ref: "#/schemas/ProfileRoleItemInput"
experience:
type: array
maxItems: 20
description: Work history entries.
items:
$ref: "#/schemas/ProfileExperienceItemInput"
soft_skills:
type: array
maxItems: 10
description: >-
Soft skills. The server answers 400 with the pointer of a skill
that repeats an earlier one without regard to letter case.
items:
$ref: "#/schemas/ProfileSoftSkillItemInput"
terms:
$ref: "#/schemas/ProfileTermsInput"
@@ -34,7 +34,9 @@ schemas:
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.
expectations belong to the candidate profile (`ProfileTerms`). The
acceptable work formats live only here: the profile does not repeat
them.
additionalProperties: false
required:
- work_formats
@@ -52,7 +54,10 @@ schemas:
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.
and never confirms a grade. The work history entries of the candidate
profile (`ProfileExperienceItem`) are a different, detailed claim: the
two are saved separately and the server neither adds the entries up
nor fills them from these totals.
additionalProperties: false
required:
- commercial_months
@@ -82,7 +87,12 @@ schemas:
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.
stack are attributes of the chosen specialization, not categories. The
candidate profile states the same kind of claim in the `roles` of
`CandidateProfile` (`ProfileRoleItem.self_assessed_grade`): the
questionnaire value starts the assessment and the profile value is what
the profile shows, the two are saved separately, and neither is ever a
confirmed grade.
additionalProperties: false
required:
- specialization
File diff suppressed because it is too large. Load diff
+95 -3
View File
@@ -18,9 +18,11 @@ tags:
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.
Data of the current candidate: the questionnaire with the chosen
specializations and self-assessed grades, and the private profile
with full name, contacts, stack, roles, experience, soft skills, and
desired terms. Confirmed grades and categories come only from
assessment results.
- name: assessment
description: >-
Assessment attempts of the current candidate: availability, start and
@@ -85,6 +87,8 @@ paths:
$ref: ./routes/catalog_specializations.yml
/api/v1/me/questionnaire:
$ref: ./routes/candidate_questionnaire.yml
/api/v1/me/profile:
$ref: ./routes/candidate_profile.yml
/api/v1/me/assessment-availability:
$ref: ./routes/candidate_assessment_availability.yml
/api/v1/me/assessment-attempts:
@@ -225,6 +229,90 @@ components:
$ref: ./components/schemas.yml#/CandidateQuestionnaire
CandidateQuestionnaireUpdate:
$ref: ./components/schemas.yml#/CandidateQuestionnaireUpdate
ProfileVersion:
$ref: ./components/schemas.yml#/ProfileVersion
ProfileItemStatus:
$ref: ./components/schemas.yml#/ProfileItemStatus
ProfileClaimStatus:
$ref: ./components/schemas.yml#/ProfileClaimStatus
ProfileClaimOrigin:
$ref: ./components/schemas.yml#/ProfileClaimOrigin
ProfileClaimTrustLevel:
$ref: ./components/schemas.yml#/ProfileClaimTrustLevel
ProfileClaimQuote:
$ref: ./components/schemas.yml#/ProfileClaimQuote
ProfileClaimSource:
$ref: ./components/schemas.yml#/ProfileClaimSource
ProfileLocationName:
$ref: ./components/schemas.yml#/ProfileLocationName
ProfileSalaryMinimum:
$ref: ./components/schemas.yml#/ProfileSalaryMinimum
ProfileSoftSkill:
$ref: ./components/schemas.yml#/ProfileSoftSkill
ProfileEmployerName:
$ref: ./components/schemas.yml#/ProfileEmployerName
ProfileExperienceSummary:
$ref: ./components/schemas.yml#/ProfileExperienceSummary
ProfileYearMonth:
$ref: ./components/schemas.yml#/ProfileYearMonth
ProfileFullNameClaim:
$ref: ./components/schemas.yml#/ProfileFullNameClaim
ProfileEmailClaim:
$ref: ./components/schemas.yml#/ProfileEmailClaim
ProfilePhoneClaim:
$ref: ./components/schemas.yml#/ProfilePhoneClaim
ProfileTelegramClaim:
$ref: ./components/schemas.yml#/ProfileTelegramClaim
ProfileLocationClaim:
$ref: ./components/schemas.yml#/ProfileLocationClaim
ProfileRelocationClaim:
$ref: ./components/schemas.yml#/ProfileRelocationClaim
ProfileSalaryMinimumClaim:
$ref: ./components/schemas.yml#/ProfileSalaryMinimumClaim
ProfileContacts:
$ref: ./components/schemas.yml#/ProfileContacts
ProfileTerms:
$ref: ./components/schemas.yml#/ProfileTerms
ProfileStackItem:
$ref: ./components/schemas.yml#/ProfileStackItem
ProfileSoftSkillItem:
$ref: ./components/schemas.yml#/ProfileSoftSkillItem
ProfileRoleItem:
$ref: ./components/schemas.yml#/ProfileRoleItem
ProfileExperienceItem:
$ref: ./components/schemas.yml#/ProfileExperienceItem
ProfileConfirmedCategory:
$ref: ./components/schemas.yml#/ProfileConfirmedCategory
CandidateProfile:
$ref: ./components/schemas.yml#/CandidateProfile
ProfileFullNameInput:
$ref: ./components/schemas.yml#/ProfileFullNameInput
ProfileEmailInput:
$ref: ./components/schemas.yml#/ProfileEmailInput
ProfilePhoneInput:
$ref: ./components/schemas.yml#/ProfilePhoneInput
ProfileTelegramInput:
$ref: ./components/schemas.yml#/ProfileTelegramInput
ProfileLocationInput:
$ref: ./components/schemas.yml#/ProfileLocationInput
ProfileRelocationInput:
$ref: ./components/schemas.yml#/ProfileRelocationInput
ProfileSalaryMinimumInput:
$ref: ./components/schemas.yml#/ProfileSalaryMinimumInput
ProfileContactsInput:
$ref: ./components/schemas.yml#/ProfileContactsInput
ProfileTermsInput:
$ref: ./components/schemas.yml#/ProfileTermsInput
ProfileStackItemInput:
$ref: ./components/schemas.yml#/ProfileStackItemInput
ProfileSoftSkillItemInput:
$ref: ./components/schemas.yml#/ProfileSoftSkillItemInput
ProfileRoleItemInput:
$ref: ./components/schemas.yml#/ProfileRoleItemInput
ProfileExperienceItemInput:
$ref: ./components/schemas.yml#/ProfileExperienceItemInput
CandidateProfileUpdate:
$ref: ./components/schemas.yml#/CandidateProfileUpdate
AssessmentMode:
$ref: ./components/schemas.yml#/AssessmentMode
AssessmentAttemptVersion:
@@ -728,6 +816,10 @@ components:
$ref: ./components/responses.yml#/QuestionnaireValidationFailed
QuestionnaireVersionConflict:
$ref: ./components/responses.yml#/QuestionnaireVersionConflict
ProfileValidationFailed:
$ref: ./components/responses.yml#/ProfileValidationFailed
ProfileVersionConflict:
$ref: ./components/responses.yml#/ProfileVersionConflict
AssessmentAttemptCreateValidationFailed:
$ref: ./components/responses.yml#/AssessmentAttemptCreateValidationFailed
AssessmentAnswerValidationFailed:
+92
View File
@@ -0,0 +1,92 @@
get:
operationId: GetMyProfile
summary: Read the private profile 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 profile yet gets 200 with version 0, every single field `unknown`, and empty lists rather than 404, so the client reads the version for the first save in the same way as for later ones and a missing profile is not an error state.
The profile is personal data that only its owner reads: full name, contacts, work history, and the lowest salary. It is a private resource and never an organization-visible one; organizations see a candidate through the anonymous card and, after an accepted invitation, through the contact grant, and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and the server never writes its values to logs, metrics, URLs, or events.
Every value carries its confirmation state and provenance, and every claim has trust level 0. The self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results establish and which no request writes. The profile needs no file, no ML extraction, and no FSP account.
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
security:
- sessionCookie: []
tags:
- candidate
responses:
"200":
description: The private profile of the current candidate.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/CandidateProfile
examples:
new_candidate:
$ref: ../components/examples.yml#/NewCandidateProfile
backend_manual_with_suggestion:
$ref: ../components/examples.yml#/BackendCandidateProfile
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
default:
$ref: ../components/responses.yml#/Problem
put:
operationId: SaveMyProfile
summary: Replace the private profile 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 of every field and list; see CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole.
Every field is optional in substance: a profile can be saved with any subset filled and the rest null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or link. Which fields are needed to leave the onboarding step candidate_profile is an open product question that this contract does not decide; a save on that step advancing the account to candidate_questionnaire is planned.
Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level, confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed grade never becomes a confirmed grade or a category.
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, and the client reads the profile again and reapplies its edits, so a concurrent edit from another tab or device is never lost silently. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for the questionnaire; the status and code are the same as for a failed If-Match.
The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose values equal the stored ones, with the same decisions, changes nothing, keeps the version, and answers 200 with the current profile even when `expected_version` is older, so a retry after a lost response of a successful save succeeds instead of failing with 412. A version above the current one never existed and always answers 412 version_conflict, even for an unchanged body.
The save replaces the stored claims as a whole. A suggestion that an import stored and that the client did not render and send back with the decision `extracted` is dropped by the save; a client therefore sends every suggestion that it received, and a client that read an older version gets 412 instead of silently dropping a suggestion it never saw.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), domain rules that depend on the body alone (400), then the rules that depend on the stored claims against the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when `expected_version` is stale, because another save may have confirmed that value, and 400 when it is current; an unchanged body (200); any other change over a stale version (412). The schema rejects an unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is not a positive multiple of 1000, and more items than a list allows. The server also rejects a repeated tag, skill, or role specialization, a period that ends before it starts or lies in the future, and a decision `extracted` for a value that is not a stored suggestion, with 400 validation_failed and pointers to the items, for example `/roles/1/specialization` or `/stack/1/status`. Error bodies never repeat a submitted value.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- candidate
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/CandidateProfileUpdate
examples:
backend_manual:
$ref: ../components/examples.yml#/BackendCandidateProfileUpdate
responses:
"200":
description: >-
The saved profile with its new version, or the current profile when
the body changes nothing.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/CandidateProfile
examples:
backend_manual_with_suggestion:
$ref: ../components/examples.yml#/BackendCandidateProfile
"400":
$ref: ../components/responses.yml#/ProfileValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"412":
$ref: ../components/responses.yml#/ProfileVersionConflict
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,311 @@
-- +goose Up
-- The manual candidate profile (PRD FR02, TASK-066): full name and contacts,
-- stack, roles, work experience, soft skills, and desired terms, each value
-- with its confirmation state and provenance. Enum-like columns are text with
-- CHECK constraints, as in the identity tables.
--
-- The rows are personal data of the candidate (names, contacts, work
-- history, the lowest salary), so the application never copies a value into
-- logs, metrics, events, or URLs. Only the owning account reads them; no
-- organization-visible query selects from these tables.
--
-- The profile stands on its own. Nothing here references a resume file, the
-- object storage, the ML service, or an FSP account: a profile that was typed
-- by hand is complete, and a later import adds its own columns or tables
-- (additively) instead of changing the meaning of these.
--
-- A confirmed grade or category is deliberately not stored here. It comes
-- from assessment results, and the self-assessed grade of a role is only a
-- claim inside the value of a role claim, so no statement against these
-- tables can write a confirmed category.
CREATE TABLE candidate_profiles (
-- The account that owns the profile. One profile per candidate; the
-- profile is created by the first save and the app never reads another
-- account's row.
user_id uuid NOT NULL,
-- Optimistic concurrency version, advanced by every save that changes the
-- profile. A first save creates version 1; the contract's version 0 is
-- the absence of a row.
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT candidate_profiles_pkey PRIMARY KEY (user_id),
-- The profile is personal data of the account and goes with it when the
-- account is erased. The retention rules are an open legal question.
CONSTRAINT candidate_profiles_user_id_fkey FOREIGN KEY (
user_id
) REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT candidate_profiles_version_positive CHECK (version > 0),
CONSTRAINT candidate_profiles_updated_after_creation CHECK (
updated_at >= created_at
)
);
-- One row per stored claim: a single field (kind full_name, contact_*,
-- terms_*, at ordinal 0) or one item of a list (stack, role, experience,
-- soft_skill, at its position). A field without a value has no row, so the
-- contract's `unknown` state is the absence of the row, and every row holds a
-- value with a status of confirmed or extracted. The whole set of a profile is
-- replaced in one transaction with the version bump.
--
-- The value is jsonb because the kinds have different shapes (a string, a
-- boolean, or an object). Each kind has its own CHECK for the shape and the
-- bounds of the contract, and the domain validates the value in full before
-- it is stored.
CREATE TABLE candidate_profile_claims (
user_id uuid NOT NULL,
kind text NOT NULL,
-- Position in a list, from 0; always 0 for a single field.
ordinal smallint NOT NULL,
value jsonb NOT NULL,
-- confirmed: the candidate typed or confirmed the value. extracted: a
-- suggestion from an imported source that nobody confirmed.
status text NOT NULL,
-- manual, or an import origin (planned: extracted_from_resume, imported).
origin text NOT NULL,
-- Every claim of the profile has trust level 0 whatever its origin;
-- higher levels belong to evidence, which is stored elsewhere. The column
-- states the rule in the schema, so an import can never store a claim
-- with a higher level.
trust_level smallint NOT NULL,
-- Excerpt of the imported document that the value came from. It can hold
-- personal data. NULL for a manual value.
quote text,
-- Opaque label of the extractor version. NULL for a manual value.
extraction_version text,
-- When the candidate typed or confirmed the value; NULL while it is an
-- unconfirmed suggestion.
confirmed_at timestamptz,
CONSTRAINT candidate_profile_claims_pkey PRIMARY KEY (
user_id, kind, ordinal
),
-- The claims belong to the profile row and go with it.
CONSTRAINT candidate_profile_claims_user_id_fkey FOREIGN KEY (
user_id
) REFERENCES candidate_profiles (user_id) ON DELETE CASCADE,
CONSTRAINT candidate_profile_claims_kind_ordinal CHECK (
(
kind IN (
'full_name',
'contact_email',
'contact_phone',
'contact_telegram',
'terms_location',
'terms_relocation',
'terms_salary_minimum'
)
AND ordinal = 0
)
OR (kind = 'stack' AND ordinal BETWEEN 0 AND 29)
OR (kind = 'role' AND ordinal BETWEEN 0 AND 8)
OR (kind = 'experience' AND ordinal BETWEEN 0 AND 19)
OR (kind = 'soft_skill' AND ordinal BETWEEN 0 AND 9)
),
CONSTRAINT candidate_profile_claims_status_known CHECK (
status IN ('confirmed', 'extracted')
),
CONSTRAINT candidate_profile_claims_origin_known CHECK (
origin IN ('manual', 'extracted_from_resume', 'imported')
),
CONSTRAINT candidate_profile_claims_trust_level_zero CHECK (
trust_level = 0
),
-- A confirmed value says when; a suggestion does not.
CONSTRAINT candidate_profile_claims_confirmation CHECK (
(status = 'confirmed' AND confirmed_at IS NOT NULL)
OR (status = 'extracted' AND confirmed_at IS NULL)
),
-- A manual value is confirmed by definition and has no import data. An
-- imported value names its extractor, and an unconfirmed one is always
-- an import.
CONSTRAINT candidate_profile_claims_origin_provenance CHECK (
(
origin = 'manual'
AND status = 'confirmed'
AND quote IS NULL
AND extraction_version IS NULL
)
OR (origin <> 'manual' AND extraction_version IS NOT NULL)
),
CONSTRAINT candidate_profile_claims_quote_format CHECK (
quote IS NULL OR (
char_length(quote) BETWEEN 1 AND 300
AND translate(quote, E'\n', '') !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_extraction_version_format CHECK (
extraction_version IS NULL
OR extraction_version ~ '^[A-Za-z0-9._-]{1,64}$'
),
-- Value shapes. The bounds repeat the schemas of the public contract.
CONSTRAINT candidate_profile_claims_full_name_value CHECK (
kind <> 'full_name' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 1 AND 200
AND value #>> '{}' !~ '^\s|\s$'
AND value #>> '{}' !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_contact_email_value CHECK (
kind <> 'contact_email' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 3 AND 254
AND value #>> '{}' ~ '^[^@\s]+@[^@\s]+$'
)
),
-- E.164, the format of the contact disclosure.
CONSTRAINT candidate_profile_claims_contact_phone_value CHECK (
kind <> 'contact_phone' OR (
jsonb_typeof(value) = 'string'
AND value #>> '{}' ~ '^\+[1-9][0-9]{6,14}$'
)
),
CONSTRAINT candidate_profile_claims_contact_telegram_value CHECK (
kind <> 'contact_telegram' OR (
jsonb_typeof(value) = 'string'
AND value #>> '{}' ~ '^@[A-Za-z0-9_]{5,32}$'
)
),
CONSTRAINT candidate_profile_claims_stack_value CHECK (
kind <> 'stack' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 1 AND 50
AND value #>> '{}' !~ '^\s|\s$'
AND value #>> '{}' !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_soft_skill_value CHECK (
kind <> 'soft_skill' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 1 AND 50
AND value #>> '{}' !~ '^\s|\s$'
AND value #>> '{}' !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_terms_location_value CHECK (
kind <> 'terms_location' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 1 AND 100
AND value #>> '{}' !~ '^\s|\s$'
AND value #>> '{}' !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_terms_relocation_value CHECK (
kind <> 'terms_relocation' OR jsonb_typeof(value) = 'boolean'
),
-- A positive multiple of 1000 up to 100 000 000, in the only currency,
-- period, and tax bases of the MVP.
CONSTRAINT candidate_profile_claims_terms_salary_minimum_value CHECK (
kind <> 'terms_salary_minimum' OR (
jsonb_typeof(value) = 'object'
AND value ?& ARRAY['amount', 'currency', 'period', 'tax_basis']
AND value - 'amount' - 'currency' - 'period' - 'tax_basis'
= '{}'::jsonb
AND jsonb_typeof(value -> 'amount') = 'number'
AND value ->> 'amount' ~ '^([1-9][0-9]{0,4}000|100000000)$'
AND value -> 'currency' = '"RUB"'::jsonb
AND value -> 'period' = '"month"'::jsonb
AND value ->> 'tax_basis' IN ('net', 'gross')
)
),
-- The self-assessed grade is a claim of the role. A confirmed grade is not
-- a key of the value.
CONSTRAINT candidate_profile_claims_role_value CHECK (
kind <> 'role' OR (
jsonb_typeof(value) = 'object'
AND value ?& ARRAY['specialization', 'self_assessed_grade']
AND value - 'specialization' - 'self_assessed_grade' = '{}'::jsonb
AND value ->> 'specialization' IN (
'backend',
'frontend',
'mobile',
'network_engineer',
'devops_sre',
'data_analyst',
'ds_ml',
'information_security',
'qa'
)
AND (
jsonb_typeof(value -> 'self_assessed_grade') = 'null'
OR value ->> 'self_assessed_grade' IN (
'intern', 'junior', 'middle', 'senior'
)
)
)
),
CONSTRAINT candidate_profile_claims_experience_value CHECK (
kind <> 'experience' OR (
jsonb_typeof(value) = 'object'
AND value ?& ARRAY[
'employer_name',
'specialization',
'started_on',
'ended_on',
'summary'
]
AND value - 'employer_name' - 'specialization' - 'started_on'
- 'ended_on' - 'summary' = '{}'::jsonb
AND value ->> 'specialization' IN (
'backend',
'frontend',
'mobile',
'network_engineer',
'devops_sre',
'data_analyst',
'ds_ml',
'information_security',
'qa'
)
AND jsonb_typeof(value -> 'started_on') = 'string'
AND value ->> 'started_on' ~ '^[0-9]{4}-(0[1-9]|1[0-2])$'
AND (
jsonb_typeof(value -> 'ended_on') = 'null'
OR (
jsonb_typeof(value -> 'ended_on') = 'string'
AND value ->> 'ended_on' ~ '^[0-9]{4}-(0[1-9]|1[0-2])$'
AND value ->> 'ended_on' >= value ->> 'started_on'
)
)
AND (
jsonb_typeof(value -> 'employer_name') = 'null'
OR (
jsonb_typeof(value -> 'employer_name') = 'string'
AND char_length(value ->> 'employer_name') BETWEEN 1 AND 200
AND value ->> 'employer_name' !~ '^\s|\s$'
AND value ->> 'employer_name' !~ '[[:cntrl:]]'
)
)
AND (
jsonb_typeof(value -> 'summary') = 'null'
OR (
jsonb_typeof(value -> 'summary') = 'string'
AND char_length(value ->> 'summary') BETWEEN 1 AND 1000
AND value ->> 'summary' !~ '^\s|\s$'
AND translate(value ->> 'summary', E'\n', '')
!~ '[[:cntrl:]]'
)
)
)
)
);
-- A tag or a skill appears once and a specialization appears in one role. The
-- indexes compare the stored text exactly; the case-insensitive comparison
-- of the contract belongs to the domain, because PostgreSQL lower() depends
-- on the collation.
CREATE UNIQUE INDEX candidate_profile_claims_stack_key
ON candidate_profile_claims (user_id, (value #>> '{}'))
WHERE kind = 'stack';
CREATE UNIQUE INDEX candidate_profile_claims_soft_skill_key
ON candidate_profile_claims (user_id, (value #>> '{}'))
WHERE kind = 'soft_skill';
CREATE UNIQUE INDEX candidate_profile_claims_role_specialization_key
ON candidate_profile_claims (user_id, (value ->> 'specialization'))
WHERE kind = 'role';
-- +goose Down
DROP TABLE candidate_profile_claims;
DROP TABLE candidate_profiles;
+102
View File
@@ -0,0 +1,102 @@
-- Queries of the manual candidate profile (TASK-066). The profile is personal
-- data of the account that owns it: every statement is scoped by user_id, and
-- no statement selects another account's row. None of them names a file, the
-- ML service, or an FSP account, because the profile needs none.
-- Stores the first save of a profile at version 1. No row returns when the
-- account already has a profile, so a first save that lost a race with
-- another first save from another tab can be told apart and answered as a
-- version conflict.
-- name: InsertCandidateProfile :one
INSERT INTO candidate_profiles (
user_id,
version,
created_at,
updated_at
) VALUES (
sqlc.arg(user_id),
1,
sqlc.arg(at),
sqlc.arg(at)
)
ON CONFLICT (user_id) DO NOTHING
RETURNING user_id, version, created_at, updated_at;
-- Advances the version over the one the caller read, in the same statement.
-- The row lock it takes serializes concurrent saves of one profile. The update
-- time never moves back: an application clock behind the stored time (clock
-- skew between instances) keeps the stored time, which the CHECK
-- candidate_profiles_updated_after_creation also requires. No row
-- returns for a stale version or for an account without a profile, which the
-- caller answers as a version conflict.
-- name: AdvanceCandidateProfileVersion :one
UPDATE candidate_profiles
SET
version = candidate_profiles.version + 1,
updated_at = GREATEST(candidate_profiles.updated_at, sqlc.arg(at))
WHERE
candidate_profiles.user_id = sqlc.arg(user_id)
AND candidate_profiles.version = sqlc.arg(expected_version)
RETURNING user_id, version, created_at, updated_at;
-- Reads the profile row of an account together with every claim in one
-- statement, so the version and the claims come from one snapshot: a save that
-- commits between two separate reads could pair version N with the claims of
-- N+1. A profile without a claim returns one row with NULL claim columns, and
-- no row at all means the account has not saved a profile (contract version
-- 0). Claims come in a stable order: single fields by kind, list items by
-- position. Never replace this with two statements.
-- name: ReadCandidateProfile :many
SELECT
candidate_profiles.user_id,
candidate_profiles.version,
candidate_profiles.created_at,
candidate_profiles.updated_at,
candidate_profile_claims.kind,
candidate_profile_claims.ordinal,
candidate_profile_claims.value,
candidate_profile_claims.status,
candidate_profile_claims.origin,
candidate_profile_claims.trust_level,
candidate_profile_claims.quote,
candidate_profile_claims.extraction_version,
candidate_profile_claims.confirmed_at
FROM candidate_profiles
LEFT JOIN candidate_profile_claims
ON candidate_profile_claims.user_id = candidate_profiles.user_id
WHERE candidate_profiles.user_id = sqlc.arg(user_id)
ORDER BY candidate_profile_claims.kind, candidate_profile_claims.ordinal;
-- Removes the claims that a save replaces. The adapter calls it after the
-- version advanced and before it inserts the new set, in one transaction.
-- name: DeleteCandidateProfileClaims :exec
DELETE FROM candidate_profile_claims
WHERE user_id = sqlc.arg(user_id);
-- Stores one claim of the new set. Provenance fields are the domain's; the
-- statement never takes a trust level from the caller, because every claim
-- has level 0.
-- name: InsertCandidateProfileClaim :exec
INSERT INTO candidate_profile_claims (
user_id,
kind,
ordinal,
value,
status,
origin,
trust_level,
quote,
extraction_version,
confirmed_at
) VALUES (
sqlc.arg(user_id),
sqlc.arg(kind),
sqlc.arg(ordinal),
sqlc.arg(value),
sqlc.arg(status),
sqlc.arg(origin),
0,
sqlc.narg(quote),
sqlc.narg(extraction_version),
sqlc.narg(confirmed_at)
);
@@ -0,0 +1,612 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"slices"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
)
const (
candidateProfileTestTimeout = 3 * time.Minute
// concurrentProfileSaves advance one profile at once from the same
// version, each on its own connection.
concurrentProfileSaves = 8
// candidateProfileMigrationVersion creates candidateProfileTables.
candidateProfileMigrationVersion = 13
)
var (
candidateProfilesTable = pgx.Identifier{"candidate_profiles"}
candidateProfileClaimsTable = pgx.Identifier{"candidate_profile_claims"}
// candidateProfileTables reference users, so a TRUNCATE of users names
// them through usersDependentTables.
candidateProfileTables = []pgx.Identifier{candidateProfileClaimsTable, candidateProfilesTable}
)
// candidateProfileFixture works on the bootstrap database. The tables are
// truncated between subtests.
type candidateProfileFixture struct {
ctx context.Context
pool *pgxpool.Pool
queries *sqlc.Queries
identity identityFixture
now time.Time
}
func TestCandidateProfileStorage(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), candidateProfileTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
now := time.Now().UTC().Truncate(time.Microsecond)
fixture := candidateProfileFixture{
ctx: ctx,
pool: pool,
queries: sqlc.New(pool),
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
now: now,
}
reset := func(t *testing.T) {
t.Helper()
truncateTables(ctx, t, pool, usersDependentTables...)
}
t.Run("saves a profile without a file, the ML service, or an FSP account", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
// Only the name: no resume, no import, no link of any kind.
saved := fixture.save(t, candidate.ID, domain.CandidateProfileInput{
FullName: confirmedDecision("Anna Sokolova"),
}, 0)
if saved.Version() != 1 {
t.Fatalf("saved version = %d, want 1 for the first save", saved.Version())
}
read := fixture.load(t, candidate.ID)
name, ok := read.Content().FullName()
if !ok || name.Value() != "Anna Sokolova" || name.Source().Origin() != domain.ProfileOriginManual || name.Source().TrustLevel() != 0 {
t.Fatalf("stored name = %v, want a manual claim of trust level 0", ok)
}
if _, ok := read.Content().Phone(); ok {
t.Fatal("a field that was not sent came back set")
}
// A profile row with no claim at all is allowed too.
other := fixture.candidate(t, "empty@example.com")
fixture.save(t, other.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Placeholder")}, 0)
fixture.save(t, other.ID, domain.CandidateProfileInput{}, 1)
if empty := fixture.load(t, other.ID); empty.Version() != 2 || !empty.Content().Equal(domain.CandidateProfileContent{}) {
t.Fatalf("empty profile = version %d, want version 2 with no claim", empty.Version())
}
})
t.Run("a complete profile survives the round trip with its provenance", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
input := domain.CandidateProfileInput{
FullName: confirmedDecision("Анна Соколова"),
Email: confirmedDecision("anna.sokolova@example.com"),
Phone: confirmedDecision("+79000000000"),
Telegram: confirmedDecision("@anna_sokolova"),
Stack: []domain.ProfileClaimInput[string]{{Value: "PostgreSQL", Status: domain.ProfileClaimConfirmed}, {Value: "Kafka", Status: domain.ProfileClaimConfirmed}},
Roles: []domain.ProfileClaimInput[domain.ProfileRole]{
{Value: domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeMiddle}, Status: domain.ProfileClaimConfirmed},
{Value: domain.ProfileRole{Specialization: domain.SpecializationQA}, Status: domain.ProfileClaimConfirmed},
},
Experience: []domain.ProfileClaimInput[domain.ProfileExperience]{{
Value: domain.ProfileExperience{EmployerName: "Example Payments", Specialization: domain.SpecializationBackend, StartedOn: "2022-03", Summary: "Первая строка\nВторая строка"},
Status: domain.ProfileClaimConfirmed,
}, {
Value: domain.ProfileExperience{Specialization: domain.SpecializationQA, StartedOn: "2020-01", EndedOn: "2022-02"},
Status: domain.ProfileClaimConfirmed,
}},
SoftSkills: []domain.ProfileClaimInput[string]{{Value: "Mentoring", Status: domain.ProfileClaimConfirmed}},
Location: confirmedDecision("Казань"),
Relocation: confirmedDecision(true),
SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 180000, TaxBasis: domain.ProfileTaxNet}),
}
saved := fixture.save(t, candidate.ID, input, 0)
read := fixture.load(t, candidate.ID)
if !read.Content().Equal(saved.Content()) || read.Version() != 1 || !read.CreatedAt().Equal(fixture.now) || !read.UpdatedAt().Equal(fixture.now) {
t.Fatalf("read profile = version %d, equal %v, want the saved content at version 1", read.Version(), read.Content().Equal(saved.Content()))
}
// A suggestion stored by an import keeps its provenance, and the
// candidate's confirmation keeps it and adds the time.
fixture.insertSuggestion(t, candidate.ID, "contact_phone", 0, `"+79000001111"`)
withSuggestion := fixture.load(t, candidate.ID)
suggestion, ok := withSuggestion.Content().Phone()
if !ok || suggestion.Status() != domain.ProfileClaimExtracted || suggestion.Source().Quote() != "Tel.: +7 900 000-11-11" ||
suggestion.Source().ExtractionVersion() != "resume-rules.2026-10.1" || suggestion.Source().TrustLevel() != 0 {
t.Fatal("the stored suggestion lost its provenance")
}
})
t.Run("the tables hold no link to a file, the ML service, or an FSP account", func(t *testing.T) {
reset(t)
rows, err := pool.Query(ctx, `
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name IN ('candidate_profiles', 'candidate_profile_claims')`)
if err != nil {
t.Fatalf("select columns: %v", err)
}
defer rows.Close()
var columns []string
for rows.Next() {
var table, column string
if err := rows.Scan(&table, &column); err != nil {
t.Fatalf("scan column: %v", err)
}
columns = append(columns, table+"."+column)
}
if err := rows.Err(); err != nil {
t.Fatalf("read columns: %v", err)
}
slices.Sort(columns)
want := []string{
"candidate_profile_claims.confirmed_at", "candidate_profile_claims.extraction_version", "candidate_profile_claims.kind",
"candidate_profile_claims.ordinal", "candidate_profile_claims.origin", "candidate_profile_claims.quote",
"candidate_profile_claims.status", "candidate_profile_claims.trust_level", "candidate_profile_claims.user_id",
"candidate_profile_claims.value",
"candidate_profiles.created_at", "candidate_profiles.updated_at", "candidate_profiles.user_id", "candidate_profiles.version",
}
if !slices.Equal(columns, want) {
t.Fatalf("columns = %v, want exactly %v: no file, ML, FSP, grade, or category column", columns, want)
}
// The only foreign keys point at the account and at the profile row.
var references []string
fkRows, err := pool.Query(ctx, `
SELECT conrelid::regclass::text || ' -> ' || confrelid::regclass::text
FROM pg_constraint
WHERE contype = 'f' AND conrelid IN ('candidate_profiles'::regclass, 'candidate_profile_claims'::regclass)`)
if err != nil {
t.Fatalf("select foreign keys: %v", err)
}
defer fkRows.Close()
for fkRows.Next() {
var reference string
if err := fkRows.Scan(&reference); err != nil {
t.Fatalf("scan foreign key: %v", err)
}
references = append(references, reference)
}
slices.Sort(references)
if !slices.Equal(references, []string{"candidate_profile_claims -> candidate_profiles", "candidate_profiles -> users"}) {
t.Fatalf("foreign keys = %v, want only the account and the profile row", references)
}
})
t.Run("constraints refuse a claim that breaks a rule of the contract", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
type claim struct {
kind, value, status, origin string
ordinal int
trust int
quote, extraction *string
confirmed bool
}
good := claim{kind: "stack", value: `"Go"`, status: "confirmed", origin: "manual", ordinal: 5, confirmed: true}
tests := []struct {
name string
mutate func(*claim)
constraint string
}{
{"trust level above zero", func(c *claim) { c.trust = 1 }, "candidate_profile_claims_trust_level_zero"},
{"unknown kind", func(c *claim) { c.kind = "confirmed_grade" }, "candidate_profile_claims_kind_ordinal"},
{"single field at a position", func(c *claim) { c.kind, c.value, c.ordinal = "full_name", `"Anna"`, 1 }, "candidate_profile_claims_kind_ordinal"},
{"list past its limit", func(c *claim) { c.ordinal = 30 }, "candidate_profile_claims_kind_ordinal"},
// Also breaks the confirmation rule, which sorts first.
{"unknown status", func(c *claim) { c.status = "verified" }, "candidate_profile_claims_confirmation"},
{"unknown origin", func(c *claim) { c.origin = "fsp" }, "candidate_profile_claims_origin_known"},
{"confirmed without a time", func(c *claim) { c.confirmed = false }, "candidate_profile_claims_confirmation"},
{"manual with a quote", func(c *claim) { q := "quote"; c.quote = &q }, "candidate_profile_claims_origin_provenance"},
{"import without an extractor version", func(c *claim) { c.origin = "imported" }, "candidate_profile_claims_origin_provenance"},
{"suggestion that is manual", func(c *claim) { c.status, c.confirmed = "extracted", false }, "candidate_profile_claims_origin_provenance"},
{"extractor version with a space", func(c *claim) { v := "a b"; c.origin, c.extraction = "imported", &v }, "candidate_profile_claims_extraction_version_format"},
{"stack tag with surrounding whitespace", func(c *claim) { c.value = `" Go"` }, "candidate_profile_claims_stack_value"},
{"stack tag that is not a string", func(c *claim) { c.value = `12` }, "candidate_profile_claims_stack_value"},
{"phone outside E.164", func(c *claim) { c.kind, c.value, c.ordinal = "contact_phone", `"8 900 000"`, 0 }, "candidate_profile_claims_contact_phone_value"},
{"telegram without the at sign", func(c *claim) { c.kind, c.value, c.ordinal = "contact_telegram", `"anna"`, 0 }, "candidate_profile_claims_contact_telegram_value"},
{"relocation that is not a boolean", func(c *claim) { c.kind, c.value, c.ordinal = "terms_relocation", `"yes"`, 0 }, "candidate_profile_claims_terms_relocation_value"},
{"salary that is not a multiple of 1000", func(c *claim) {
c.kind, c.value, c.ordinal = "terms_salary_minimum", `{"amount":180500,"currency":"RUB","period":"month","tax_basis":"net"}`, 0
}, "candidate_profile_claims_terms_salary_minimum_value"},
{"salary in another currency", func(c *claim) {
c.kind, c.value, c.ordinal = "terms_salary_minimum", `{"amount":180000,"currency":"USD","period":"month","tax_basis":"net"}`, 0
}, "candidate_profile_claims_terms_salary_minimum_value"},
{"role with a confirmed grade key", func(c *claim) {
c.kind, c.value, c.ordinal = "role", `{"specialization":"backend","self_assessed_grade":null,"confirmed_grade":"senior"}`, 0
}, "candidate_profile_claims_role_value"},
{"role with an unknown grade", func(c *claim) {
c.kind, c.value, c.ordinal = "role", `{"specialization":"backend","self_assessed_grade":"lead"}`, 0
}, "candidate_profile_claims_role_value"},
{"experience that ends before it starts", func(c *claim) {
c.kind, c.ordinal = "experience", 0
c.value = `{"employer_name":null,"specialization":"qa","started_on":"2024-05","ended_on":"2024-04","summary":null}`
}, "candidate_profile_claims_experience_value"},
{"experience month out of range", func(c *claim) {
c.kind, c.ordinal = "experience", 0
c.value = `{"employer_name":null,"specialization":"qa","started_on":"2024-13","ended_on":null,"summary":null}`
}, "candidate_profile_claims_experience_value"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
c := good
test.mutate(&c)
err := fixture.insertRaw(candidate.ID, c.kind, c.ordinal, c.value, c.status, c.origin, c.trust, c.quote, c.extraction, c.confirmed)
assertConstraintViolation(t, err, "23514", test.constraint)
})
}
// The same row without the mutation is accepted, so each refusal
// above comes from its own rule.
if err := fixture.insertRaw(candidate.ID, good.kind, good.ordinal, good.value, good.status, good.origin, 0, nil, nil, true); err != nil {
t.Fatalf("insert of the valid claim error = %v", err)
}
})
t.Run("a tag, a skill, and a role specialization are stored once", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
insert := func(kind string, ordinal int, value string) error {
return fixture.insertRaw(candidate.ID, kind, ordinal, value, "confirmed", "manual", 0, nil, nil, true)
}
if err := insert("stack", 0, `"Go"`); err != nil {
t.Fatalf("insert tag error = %v", err)
}
assertConstraintViolation(t, insert("stack", 1, `"Go"`), "23505", "candidate_profile_claims_stack_key")
if err := insert("soft_skill", 0, `"Mentoring"`); err != nil {
t.Fatalf("insert skill error = %v", err)
}
assertConstraintViolation(t, insert("soft_skill", 1, `"Mentoring"`), "23505", "candidate_profile_claims_soft_skill_key")
if err := insert("role", 0, `{"specialization":"backend","self_assessed_grade":null}`); err != nil {
t.Fatalf("insert role error = %v", err)
}
assertConstraintViolation(t, insert("role", 1, `{"specialization":"backend","self_assessed_grade":"junior"}`), "23505", "candidate_profile_claims_role_specialization_key")
assertConstraintViolation(t, insert("role", 0, `{"specialization":"qa","self_assessed_grade":null}`), "23505", "candidate_profile_claims_pkey")
})
t.Run("a profile needs an account and claims need a profile", func(t *testing.T) {
reset(t)
err := fixture.insertRawProfile(uuid.Must(uuid.NewV7()), 1)
assertConstraintViolation(t, err, "23503", "candidate_profiles_user_id_fkey")
candidate := fixture.candidate(t, "candidate@example.com")
assertConstraintViolation(t, fixture.insertRawProfile(candidate.ID, 0), "23514", "candidate_profiles_version_positive")
err = fixture.insertRaw(candidate.ID, "full_name", 0, `"Anna"`, "confirmed", "manual", 0, nil, nil, true)
assertConstraintViolation(t, err, "23503", "candidate_profile_claims_user_id_fkey")
})
t.Run("erasing the account removes the profile and its claims", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{
FullName: confirmedDecision("Anna"), Phone: confirmedDecision("+79000000000"),
}, 0)
if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, candidate.ID); err != nil {
t.Fatalf("delete the account: %v", err)
}
for _, table := range candidateProfileTables {
var count int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM `+table.Sanitize()).Scan(&count); err != nil || count != 0 {
t.Fatalf("%s rows after the erasure = %d, %v, want 0", table[0], count, err)
}
}
})
t.Run("the version guards against a lost concurrent edit", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
// A second first save loses: the row exists.
if _, err := fixture.queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, At: pgTime(now)}); !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("second InsertCandidateProfile() error = %v, want no row", err)
}
// A stale expected version matches no row.
stale := sqlc.AdvanceCandidateProfileVersionParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 7, At: pgTime(now)}
if _, err := fixture.queries.AdvanceCandidateProfileVersion(ctx, stale); !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("AdvanceCandidateProfileVersion(stale) error = %v, want no row", err)
}
if got := fixture.load(t, candidate.ID).Version(); got != 1 {
t.Fatalf("version after a stale advance = %d, want 1", got)
}
// Eight savers read version 1 and race: exactly one wins.
pool := env.newPoolWithMaxConns(ctx, t, concurrentProfileSaves)
queries := sqlc.New(pool)
var (
group sync.WaitGroup
mutex sync.Mutex
winners int
)
for range concurrentProfileSaves {
group.Go(func() {
_, err := queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{
UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 1, At: pgTime(now.Add(time.Minute)),
})
mutex.Lock()
defer mutex.Unlock()
switch {
case err == nil:
winners++
case !errors.Is(err, pgx.ErrNoRows):
t.Errorf("AdvanceCandidateProfileVersion() error = %v", err)
}
})
}
group.Wait()
if winners != 1 {
t.Fatalf("%d concurrent saves advanced version 1, want exactly one", winners)
}
if got := fixture.load(t, candidate.ID).Version(); got != 2 {
t.Fatalf("version after the race = %d, want 2", got)
}
})
t.Run("two concurrent first saves: one wins and the other sees a conflict", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
pool := env.newPoolWithMaxConns(ctx, t, concurrentProfileSaves)
queries := sqlc.New(pool)
var (
group sync.WaitGroup
mutex sync.Mutex
winners int
losers int
)
for range concurrentProfileSaves {
group.Go(func() {
_, err := queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, At: pgTime(now)})
mutex.Lock()
defer mutex.Unlock()
switch {
case err == nil:
winners++
case errors.Is(err, pgx.ErrNoRows):
losers++ // the caller answers version_conflict
default:
t.Errorf("InsertCandidateProfile() error = %v", err)
}
})
}
group.Wait()
if winners != 1 || losers != concurrentProfileSaves-1 {
t.Fatalf("first saves: %d won and %d lost, want one winner and the rest conflicts", winners, losers)
}
})
t.Run("an earlier application clock never violates the update time rule", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
advanced, err := fixture.queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{
UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 1, At: pgTime(now.Add(-time.Hour)),
})
if err != nil {
t.Fatalf("AdvanceCandidateProfileVersion(earlier time) error = %v, want no CHECK violation", err)
}
if advanced.Version != 2 || !advanced.UpdatedAt.Time.Equal(now) {
t.Fatalf("advanced = version %d at %v, want version 2 keeping %v", advanced.Version, advanced.UpdatedAt.Time, now)
}
})
t.Run("each account keeps its own profile", func(t *testing.T) {
reset(t)
first := fixture.candidate(t, "first@example.com")
second := fixture.candidate(t, "second@example.com")
fixture.save(t, first.ID, domain.CandidateProfileInput{FullName: confirmedDecision("First Person")}, 0)
fixture.save(t, second.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Second Person")}, 0)
name, _ := fixture.load(t, second.ID).Content().FullName()
if name.Value() != "Second Person" {
t.Fatal("an account read the profile of another account")
}
})
}
func TestCandidateProfileMigrationRollsBack(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), candidateProfileTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
assertTablesExist(ctx, t, pool, true, "candidate_profiles", "candidate_profile_claims")
for {
result, err := migrator.DownOne(ctx)
if err != nil {
t.Fatalf("DownOne() error = %v", err)
}
if result.Version == candidateProfileMigrationVersion {
break
}
}
assertTablesExist(ctx, t, pool, false, "candidate_profiles", "candidate_profile_claims")
assertTablesExist(ctx, t, pool, true, "users")
}
func confirmedDecision[V comparable](value V) *domain.ProfileClaimInput[V] {
return &domain.ProfileClaimInput[V]{Value: value, Status: domain.ProfileClaimConfirmed}
}
func pgTime(at time.Time) pgtype.Timestamptz { return pgtype.Timestamptz{Time: at, Valid: true} }
func (fixture candidateProfileFixture) candidate(t *testing.T, email string) domain.User {
t.Helper()
return fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.now.Add(-time.Hour))
}
// save applies input to the stored profile with the domain rules and stores
// the result the way a repository does: a first save inserts version 1, and a
// later one advances the version over expectedVersion and replaces the
// claims, in one transaction.
func (fixture candidateProfileFixture) save(t *testing.T, userID uuid.UUID, input domain.CandidateProfileInput, expectedVersion int64) domain.CandidateProfile {
t.Helper()
profile := fixture.loadOrEmpty(t, userID)
if profile.Version() != expectedVersion {
t.Fatalf("stored version = %d, want %d", profile.Version(), expectedVersion)
}
updated, _, err := profile.Replace(input, expectedVersion, fixture.now)
if err != nil {
t.Fatalf("Replace() error = %v", err)
}
rows, err := updated.Content().StoredClaims()
if err != nil {
t.Fatalf("StoredClaims() error = %v", err)
}
tx, err := fixture.pool.Begin(fixture.ctx)
if err != nil {
t.Fatalf("begin: %v", err)
}
defer func() { _ = tx.Rollback(fixture.ctx) }()
queries := fixture.queries.WithTx(tx)
id := pgtype.UUID{Bytes: userID, Valid: true}
if expectedVersion == 0 {
_, err = queries.InsertCandidateProfile(fixture.ctx, sqlc.InsertCandidateProfileParams{UserID: id, At: pgTime(fixture.now)})
} else {
_, err = queries.AdvanceCandidateProfileVersion(fixture.ctx, sqlc.AdvanceCandidateProfileVersionParams{UserID: id, ExpectedVersion: expectedVersion, At: pgTime(fixture.now)})
}
if err != nil {
t.Fatalf("store the profile row: %v", err)
}
if err := queries.DeleteCandidateProfileClaims(fixture.ctx, id); err != nil {
t.Fatalf("delete claims: %v", err)
}
for _, row := range rows {
err := queries.InsertCandidateProfileClaim(fixture.ctx, sqlc.InsertCandidateProfileClaimParams{
UserID: id, Kind: row.Kind, Ordinal: int16(row.Ordinal), Value: row.Value, Status: row.Status, Origin: row.Origin,
Quote: optionalText(row.Quote), ExtractionVersion: optionalText(row.ExtractionVersion), ConfirmedAt: optionalTime(row.ConfirmedAt),
})
if err != nil {
t.Fatalf("insert claim %s: %v", row.Kind, err)
}
}
if err := tx.Commit(fixture.ctx); err != nil {
t.Fatalf("commit: %v", err)
}
return fixture.load(t, userID)
}
func optionalText(value string) pgtype.Text { return pgtype.Text{String: value, Valid: value != ""} }
func optionalTime(value time.Time) pgtype.Timestamptz {
return pgtype.Timestamptz{Time: value, Valid: !value.IsZero()}
}
// loadOrEmpty reads the profile with the one statement a repository uses, so
// the version and the claims come from one snapshot. An account without a
// profile gets the empty profile of version 0.
func (fixture candidateProfileFixture) loadOrEmpty(t *testing.T, userID uuid.UUID) domain.CandidateProfile {
t.Helper()
rows, err := fixture.queries.ReadCandidateProfile(fixture.ctx, pgtype.UUID{Bytes: userID, Valid: true})
if err != nil {
t.Fatalf("ReadCandidateProfile() error = %v", err)
}
if len(rows) == 0 {
empty, err := domain.EmptyCandidateProfile(userID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
return empty
}
stored := domain.StoredCandidateProfile{UserID: userID, Version: rows[0].Version, CreatedAt: rows[0].CreatedAt.Time, UpdatedAt: rows[0].UpdatedAt.Time}
for _, row := range rows {
if !row.Kind.Valid {
continue // a profile without claims: the LEFT JOIN row has none
}
stored.Claims = append(stored.Claims, domain.StoredProfileClaim{
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: row.Value, Status: row.Status.String, Origin: row.Origin.String,
TrustLevel: int(row.TrustLevel.Int16), Quote: row.Quote.String, ExtractionVersion: row.ExtractionVersion.String,
ConfirmedAt: row.ConfirmedAt.Time,
})
}
profile, err := domain.RestoreCandidateProfile(stored)
if err != nil {
t.Fatalf("RestoreCandidateProfile() error = %v", err)
}
return profile
}
func (fixture candidateProfileFixture) load(t *testing.T, userID uuid.UUID) domain.CandidateProfile {
t.Helper()
profile := fixture.loadOrEmpty(t, userID)
if profile.Version() == 0 {
t.Fatal("the account has no stored profile")
}
return profile
}
// insertSuggestion stores an unconfirmed claim of an import, which no
// operation produces yet, over the stored one of the same kind and position.
func (fixture candidateProfileFixture) insertSuggestion(t *testing.T, userID uuid.UUID, kind string, ordinal int, value string) {
t.Helper()
quote, version := "Tel.: +7 900 000-11-11", "resume-rules.2026-10.1"
if _, err := fixture.pool.Exec(fixture.ctx, `DELETE FROM candidate_profile_claims WHERE user_id = $1 AND kind = $2 AND ordinal = $3`, userID, kind, ordinal); err != nil {
t.Fatalf("remove the stored claim: %v", err)
}
if err := fixture.insertRaw(userID, kind, ordinal, value, "extracted", "extracted_from_resume", 0, &quote, &version, false); err != nil {
t.Fatalf("insert the suggestion: %v", err)
}
}
func (fixture candidateProfileFixture) insertRaw(
userID uuid.UUID, kind string, ordinal int, value, status, origin string, trust int, quote, extraction *string, confirmed bool,
) error {
var confirmedAt any
if confirmed {
confirmedAt = fixture.now
}
_, err := fixture.pool.Exec(fixture.ctx, `
INSERT INTO candidate_profile_claims
(user_id, kind, ordinal, value, status, origin, trust_level, quote, extraction_version, confirmed_at)
VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8, $9, $10)`,
userID, kind, ordinal, value, status, origin, trust, quote, extraction, confirmedAt)
return err
}
func (fixture candidateProfileFixture) insertRawProfile(userID uuid.UUID, version int64) error {
_, err := fixture.pool.Exec(fixture.ctx,
`INSERT INTO candidate_profiles (user_id, version, created_at, updated_at) VALUES ($1, $2, $3, $3)`,
userID, version, fixture.now)
return err
}
// assertConstraintViolation checks the SQLSTATE and the constraint name, never
// the message: a failing row can quote the personal data it held. PostgreSQL
// reports the first failing CHECK in name order, so a row that breaks two
// rules names the one that sorts first; a caller lists the acceptable ones.
func assertConstraintViolation(t *testing.T, err error, code string, constraints ...string) {
t.Helper()
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
t.Fatalf("error = %v, want a PostgreSQL error %s on %v", err, code, constraints)
}
if pgError.Code != code || !slices.Contains(constraints, pgError.ConstraintName) {
t.Fatalf("error = %s on %q, want %s on one of %v", pgError.Code, pgError.ConstraintName, code, constraints)
}
}
@@ -41,7 +41,7 @@ var (
// usersDependentTables is every table that references users, directly or
// through another table of the list. A TRUNCATE of users must name all of
// them, so a migration that adds such a table adds it here.
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables)
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables)
)
// organizationFixture works on the bootstrap database. The tables are
@@ -21,6 +21,7 @@ var regexMap = map[string]ogenregex.Regexp{
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
@@ -4239,6 +4239,208 @@ func (s *Server) handleGetMyInvitationRequest(args [1]string, argsEscaped bool,
}
}
// handleGetMyProfileRequest handles GetMyProfile 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 profile yet gets 200 with version 0, every
// single field `unknown`, and empty lists rather than 404, so the client reads the version for the
// first save in the same way as for later ones and a missing profile is not an error state.
//
// The profile is personal data that only its owner reads: full name, contacts, work history, and the
// lowest salary. It is a private resource and never an organization-visible one; organizations see a
// candidate through the anonymous card and, after an accepted invitation, through the contact grant,
// and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and
// the server never writes its values to logs, metrics, URLs, or events.
//
// Every value carries its confirmation state and provenance, and every claim has trust level 0. The
// self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
// GET /api/v1/me/profile
func (s *Server) handleGetMyProfileRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetMyProfile"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/profile"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyProfileOperation,
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: GetMyProfileOperation,
ID: "GetMyProfile",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetMyProfileOperation, 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 GetMyProfileRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetMyProfileOperation,
OperationSummary: "Read the private profile of the current candidate.",
OperationID: "GetMyProfile",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = struct{}
Params = struct{}
Response = GetMyProfileRes
)
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.GetMyProfile(ctx)
return response, err
},
)
} else {
response, err = s.h.GetMyProfile(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 := encodeGetMyProfileResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetMyQuestionnaireRequest handles GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -8055,6 +8257,269 @@ func (s *Server) handleResendEmailVerificationRequest(args [0]string, argsEscape
}
}
// handleSaveMyProfileRequest handles SaveMyProfile 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 of every field and list; see
// CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole.
//
// Every field is optional in substance: a profile can be saved with any subset filled and the rest
// null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or
// link. Which fields are needed to leave the onboarding step candidate_profile is an open product
// question that this contract does not decide; a save on that step advancing the account to
// candidate_questionnaire is planned.
//
// Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion
// keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level,
// confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed
// grade never becomes a confirmed grade or a category.
//
// 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, and the client reads the profile again and reapplies its edits, so a concurrent
// edit from another tab or device is never lost silently. The version travels in the body rather than
// in If-Match because the generated client cannot read the ETag response header yet, as for the
// questionnaire; the status and code are the same as for a failed If-Match.
//
// The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose
// values equal the stored ones, with the same decisions, changes nothing, keeps the version, and
// answers 200 with the current profile even when `expected_version` is older, so a retry after a lost
// response of a successful save succeeds instead of failing with 412. A version above the current one
// never existed and always answers 412 version_conflict, even for an unchanged body.
//
// The save replaces the stored claims as a whole. A suggestion that an import stored and that the
// client did not render and send back with the decision `extracted` is dropped by the save; a client
// therefore sends every suggestion that it received, and a client that read an older version gets 412
// instead of silently dropping a suggestion it never saw.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for an employer), a version above the current one (412), domain
// rules that depend on the body alone (400), then the rules that depend on the stored claims against
// the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when
// `expected_version` is stale, because another save may have confirmed that value, and 400 when it is
// current; an unchanged body (200); any other change over a stale version (412). The schema rejects an
// unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username
// without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is
// not a positive multiple of 1000, and more items than a list allows. The server also rejects a
// repeated tag, skill, or role specialization, a period that ends before it starts or lies in the
// future, and a decision `extracted` for a value that is not a stored suggestion, with 400
// validation_failed and pointers to the items, for example `/roles/1/specialization` or
// `/stack/1/status`. Error bodies never repeat a submitted value.
//
// PUT /api/v1/me/profile
func (s *Server) handleSaveMyProfileRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("SaveMyProfile"),
semconv.HTTPRequestMethodKey.String("PUT"),
semconv.HTTPRouteKey.String("/api/v1/me/profile"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), SaveMyProfileOperation,
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: SaveMyProfileOperation,
ID: "SaveMyProfile",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, SaveMyProfileOperation, 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, SaveMyProfileOperation, 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.decodeSaveMyProfileRequest(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 SaveMyProfileRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: SaveMyProfileOperation,
OperationSummary: "Replace the private profile of the current candidate.",
OperationID: "SaveMyProfile",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = *CandidateProfileUpdate
Params = struct{}
Response = SaveMyProfileRes
)
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.SaveMyProfile(ctx, request)
return response, err
},
)
} else {
response, err = s.h.SaveMyProfile(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 := encodeSaveMyProfileResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleSaveMyQuestionnaireRequest handles SaveMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -69,6 +69,10 @@ type GetMyInvitationRes interface {
getMyInvitationRes()
}
type GetMyProfileRes interface {
getMyProfileRes()
}
type GetMyQuestionnaireRes interface {
getMyQuestionnaireRes()
}
@@ -137,6 +141,10 @@ type ResendEmailVerificationRes interface {
resendEmailVerificationRes()
}
type SaveMyProfileRes interface {
saveMyProfileRes()
}
type SaveMyQuestionnaireRes interface {
saveMyQuestionnaireRes()
}
File diff suppressed because it is too large. Load diff
@@ -24,6 +24,7 @@ const (
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyProfileOperation OperationName = "GetMyProfile"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
@@ -42,6 +43,7 @@ const (
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RegisterAccountOperation OperationName = "RegisterAccount"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
SaveMyProfileOperation OperationName = "SaveMyProfile"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
@@ -1120,6 +1120,85 @@ func (s *Server) decodeResendEmailVerificationRequest(r *http.Request) (
}
}
func (s *Server) decodeSaveMyProfileRequest(r *http.Request) (
req *CandidateProfileUpdate,
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 CandidateProfileUpdate
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)
}
}
func (s *Server) decodeSaveMyQuestionnaireRequest(r *http.Request) (
req *CandidateQuestionnaireUpdate,
rawBody []byte,
@@ -1766,6 +1766,65 @@ func encodeGetMyInvitationResponse(response GetMyInvitationRes, w http.ResponseW
}
}
func encodeGetMyProfileResponse(response GetMyProfileRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateProfileHeaders:
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 *GetMyProfileUnauthorized:
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 *GetMyProfileForbidden:
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 encodeGetMyQuestionnaireResponse(response GetMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateQuestionnaireHeaders:
@@ -3178,6 +3237,89 @@ func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes,
}
}
func encodeSaveMyProfileResponse(response SaveMyProfileRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateProfileHeaders:
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 *SaveMyProfileBadRequest:
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 *SaveMyProfileUnauthorized:
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 *SaveMyProfileForbidden:
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 *SaveMyProfilePreconditionFailed:
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 encodeSaveMyQuestionnaireResponse(response SaveMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateQuestionnaireHeaders:
@@ -11,16 +11,16 @@ import (
)
var (
rn48AllowedHeaders = map[string]string{
rn49AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn7AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn46AllowedHeaders = map[string]string{
rn47AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn43AllowedHeaders = map[string]string{
rn44AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn25AllowedHeaders = map[string]string{
@@ -29,7 +29,7 @@ var (
rn9AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn51AllowedHeaders = map[string]string{
rn52AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn20AllowedHeaders = map[string]string{
@@ -44,12 +44,15 @@ var (
rn17AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn52AllowedHeaders = map[string]string{
rn53AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn31AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn32AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn10AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
@@ -62,22 +65,22 @@ var (
rn14AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn35AllowedHeaders = map[string]string{
rn36AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn45AllowedHeaders = map[string]string{
rn46AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn50AllowedHeaders = map[string]string{
rn51AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn53AllowedHeaders = map[string]string{
rn54AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn16AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn38AllowedHeaders = map[string]string{
rn39AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
)
@@ -234,7 +237,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn48AllowedHeaders,
allowedHeaders: rn49AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -311,7 +314,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn46AllowedHeaders,
allowedHeaders: rn47AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -335,7 +338,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn43AllowedHeaders,
allowedHeaders: rn44AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -488,7 +491,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn51AllowedHeaders,
allowedHeaders: rn52AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -779,7 +782,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn52AllowedHeaders,
allowedHeaders: rn53AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -819,6 +822,33 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
case 'p': // Prefix: "profile"
if l := len("profile"); len(elem) >= l && elem[0:l] == "profile" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetMyProfileRequest([0]string{}, elemIsEscaped, w, r)
case "PUT":
s.handleSaveMyProfileRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn31AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 'q': // Prefix: "questionnaire"
if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" {
@@ -837,7 +867,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn31AllowedHeaders,
allowedHeaders: rn32AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1049,7 +1079,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn35AllowedHeaders,
allowedHeaders: rn36AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -1129,7 +1159,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn45AllowedHeaders,
allowedHeaders: rn46AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1157,7 +1187,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn50AllowedHeaders,
allowedHeaders: rn51AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1187,7 +1217,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn53AllowedHeaders,
allowedHeaders: rn54AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1265,7 +1295,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn38AllowedHeaders,
allowedHeaders: rn39AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -2080,6 +2110,40 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
}
case 'p': // Prefix: "profile"
if l := len("profile"); len(elem) >= l && elem[0:l] == "profile" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetMyProfileOperation
r.summary = "Read the private profile of the current candidate."
r.operationID = "GetMyProfile"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/profile"
r.args = args
r.count = 0
return r, true
case "PUT":
r.name = SaveMyProfileOperation
r.summary = "Replace the private profile of the current candidate."
r.operationID = "SaveMyProfile"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/profile"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 'q': // Prefix: "questionnaire"
if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" {
File diff suppressed because it is too large. Load diff
@@ -71,6 +71,7 @@ var operationRolesSessionCookie = map[string][]string{
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyInvitationOperation: []string{},
GetMyProfileOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
@@ -85,6 +86,7 @@ var operationRolesSessionCookie = map[string][]string{
ListOrganizationNeedsOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
@@ -129,6 +131,7 @@ var operationRolesSessionCsrf = map[string][]string{
FinalizeMyAssessmentAttemptOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
@@ -603,6 +603,29 @@ type Handler interface {
//
// GET /api/v1/me/invitations/{invitation_id}
GetMyInvitation(ctx context.Context, params GetMyInvitationParams) (GetMyInvitationRes, error)
// GetMyProfile implements GetMyProfile 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 profile yet gets 200 with version 0, every
// single field `unknown`, and empty lists rather than 404, so the client reads the version for the
// first save in the same way as for later ones and a missing profile is not an error state.
//
// The profile is personal data that only its owner reads: full name, contacts, work history, and the
// lowest salary. It is a private resource and never an organization-visible one; organizations see a
// candidate through the anonymous card and, after an accepted invitation, through the contact grant,
// and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and
// the server never writes its values to logs, metrics, URLs, or events.
//
// Every value carries its confirmation state and provenance, and every claim has trust level 0. The
// self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
// GET /api/v1/me/profile
GetMyProfile(ctx context.Context) (GetMyProfileRes, error)
// GetMyQuestionnaire implements GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -1038,6 +1061,57 @@ type Handler interface {
//
// POST /api/v1/identity/email-verification-requests
ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (ResendEmailVerificationRes, error)
// SaveMyProfile implements SaveMyProfile 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 of every field and list; see
// CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole.
//
// Every field is optional in substance: a profile can be saved with any subset filled and the rest
// null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or
// link. Which fields are needed to leave the onboarding step candidate_profile is an open product
// question that this contract does not decide; a save on that step advancing the account to
// candidate_questionnaire is planned.
//
// Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion
// keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level,
// confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed
// grade never becomes a confirmed grade or a category.
//
// 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, and the client reads the profile again and reapplies its edits, so a concurrent
// edit from another tab or device is never lost silently. The version travels in the body rather than
// in If-Match because the generated client cannot read the ETag response header yet, as for the
// questionnaire; the status and code are the same as for a failed If-Match.
//
// The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose
// values equal the stored ones, with the same decisions, changes nothing, keeps the version, and
// answers 200 with the current profile even when `expected_version` is older, so a retry after a lost
// response of a successful save succeeds instead of failing with 412. A version above the current one
// never existed and always answers 412 version_conflict, even for an unchanged body.
//
// The save replaces the stored claims as a whole. A suggestion that an import stored and that the
// client did not render and send back with the decision `extracted` is dropped by the save; a client
// therefore sends every suggestion that it received, and a client that read an older version gets 412
// instead of silently dropping a suggestion it never saw.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for an employer), a version above the current one (412), domain
// rules that depend on the body alone (400), then the rules that depend on the stored claims against
// the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when
// `expected_version` is stale, because another save may have confirmed that value, and 400 when it is
// current; an unchanged body (200); any other change over a stale version (412). The schema rejects an
// unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username
// without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is
// not a positive multiple of 1000, and more items than a list allows. The server also rejects a
// repeated tag, skill, or role specialization, a period that ends before it starts or lies in the
// future, and a decision `extracted` for a value that is not a stored suggestion, with 400
// validation_failed and pointers to the items, for example `/roles/1/specialization` or
// `/stack/1/status`. Error bodies never repeat a submitted value.
//
// PUT /api/v1/me/profile
SaveMyProfile(ctx context.Context, req *CandidateProfileUpdate) (SaveMyProfileRes, error)
// SaveMyQuestionnaire implements SaveMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -662,6 +662,32 @@ func (UnimplementedHandler) GetMyInvitation(ctx context.Context, params GetMyInv
return r, ht.ErrNotImplemented
}
// GetMyProfile implements GetMyProfile 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 profile yet gets 200 with version 0, every
// single field `unknown`, and empty lists rather than 404, so the client reads the version for the
// first save in the same way as for later ones and a missing profile is not an error state.
//
// The profile is personal data that only its owner reads: full name, contacts, work history, and the
// lowest salary. It is a private resource and never an organization-visible one; organizations see a
// candidate through the anonymous card and, after an accepted invitation, through the contact grant,
// and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and
// the server never writes its values to logs, metrics, URLs, or events.
//
// Every value carries its confirmation state and provenance, and every claim has trust level 0. The
// self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
// GET /api/v1/me/profile
func (UnimplementedHandler) GetMyProfile(ctx context.Context) (r GetMyProfileRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetMyQuestionnaire implements GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -1151,6 +1177,60 @@ func (UnimplementedHandler) ResendEmailVerification(ctx context.Context, req *Em
return r, ht.ErrNotImplemented
}
// SaveMyProfile implements SaveMyProfile 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 of every field and list; see
// CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole.
//
// Every field is optional in substance: a profile can be saved with any subset filled and the rest
// null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or
// link. Which fields are needed to leave the onboarding step candidate_profile is an open product
// question that this contract does not decide; a save on that step advancing the account to
// candidate_questionnaire is planned.
//
// Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion
// keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level,
// confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed
// grade never becomes a confirmed grade or a category.
//
// 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, and the client reads the profile again and reapplies its edits, so a concurrent
// edit from another tab or device is never lost silently. The version travels in the body rather than
// in If-Match because the generated client cannot read the ETag response header yet, as for the
// questionnaire; the status and code are the same as for a failed If-Match.
//
// The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose
// values equal the stored ones, with the same decisions, changes nothing, keeps the version, and
// answers 200 with the current profile even when `expected_version` is older, so a retry after a lost
// response of a successful save succeeds instead of failing with 412. A version above the current one
// never existed and always answers 412 version_conflict, even for an unchanged body.
//
// The save replaces the stored claims as a whole. A suggestion that an import stored and that the
// client did not render and send back with the decision `extracted` is dropped by the save; a client
// therefore sends every suggestion that it received, and a client that read an older version gets 412
// instead of silently dropping a suggestion it never saw.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for an employer), a version above the current one (412), domain
// rules that depend on the body alone (400), then the rules that depend on the stored claims against
// the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when
// `expected_version` is stale, because another save may have confirmed that value, and 400 when it is
// current; an unchanged body (200); any other change over a stale version (412). The schema rejects an
// unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username
// without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is
// not a positive multiple of 1000, and more items than a list allows. The server also rejects a
// repeated tag, skill, or role specialization, a period that ends before it starts or lies in the
// future, and a decision `extracted` for a value that is not a stored suggestion, with 400
// validation_failed and pointers to the items, for example `/roles/1/specialization` or
// `/stack/1/status`. Error bodies never repeat a submitted value.
//
// PUT /api/v1/me/profile
func (UnimplementedHandler) SaveMyProfile(ctx context.Context, req *CandidateProfileUpdate) (r SaveMyProfileRes, _ error) {
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,
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,455 @@
package httpadapter
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"slices"
"strings"
"testing"
"github.com/ogen-go/ogen"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
)
const profilePath = "/api/v1/me/profile"
// isProfileSchema names the schemas that exist only for the private candidate
// profile. The schemas it shares with other contracts, such as the contact
// value formats, do not match.
func isProfileSchema(name string) bool {
return name == "CandidateProfile" || name == "CandidateProfileUpdate" || strings.HasPrefix(name, "Profile")
}
func propertyNames(schema *ogen.Schema) []string {
names := make([]string, 0, len(schema.Properties))
for _, property := range schema.Properties {
names = append(names, property.Name)
}
slices.Sort(names)
return names
}
func hasSecurity(operation *ogen.Operation, scheme string) bool {
return slices.ContainsFunc(operation.Security, func(requirement ogen.SecurityRequirement) bool {
_, ok := requirement[scheme]
return ok
})
}
// A save of the profile follows the project conventions of a versioned
// replacement: session and CSRF, the version in the body, 412 for a stale one
// and no Idempotency-Key, because replacing the whole state is idempotent.
func TestCandidateProfileOperationsFollowTheConventions(t *testing.T) {
spec := parsePublicContract(t)
get := operationByID(t, spec, "GetMyProfile")
if !hasSecurity(get, "sessionCookie") || hasSecurity(get, "sessionCsrf") {
t.Errorf("GetMyProfile security = %v, want the session cookie only", get.Security)
}
save := operationByID(t, spec, "SaveMyProfile")
if !hasSecurity(save, "sessionCookie") || !hasSecurity(save, "sessionCsrf") {
t.Errorf("SaveMyProfile security = %v, want the session cookie and the CSRF token", save.Security)
}
for _, status := range []string{"400", "401", "403", "412"} {
if _, ok := save.Responses[status]; !ok {
t.Errorf("SaveMyProfile does not declare %s", status)
}
}
if _, ok := save.Responses["409"]; ok {
t.Error("SaveMyProfile declares 409: a stale version is 412 version_conflict")
}
for _, status := range []string{"401", "403"} {
if _, ok := get.Responses[status]; !ok {
t.Errorf("GetMyProfile does not declare %s", status)
}
}
for _, operation := range []*ogen.Operation{get, save} {
for _, parameter := range operation.Parameters {
if strings.EqualFold(parameter.Name, "Idempotency-Key") || strings.EqualFold(parameter.Name, "If-Match") {
t.Errorf("%s takes %s, want the version in the body", operation.OperationID, parameter.Name)
}
}
ok := operation.Responses["200"]
if ok == nil || ok.Headers["Cache-Control"] == nil {
t.Errorf("%s does not mark its 200 response no-store", operation.OperationID)
}
}
update := resolveSchema(t, spec, save.RequestBody.Content["application/json"].Schema)
if !slices.Contains(update.Required, "expected_version") {
t.Error("the profile update does not require expected_version")
}
version := resolveSchema(t, spec, schemaProperty(t, update, "expected_version"))
if string(version.Minimum) != "0" {
t.Error("expected_version does not start at 0, the version of a profile never saved")
}
problem412 := save.Responses["412"]
if problem412 == nil || problem412.Ref == "" {
t.Error("the 412 response is not a reusable response")
}
}
// The self-assessed grade of a role and the confirmed category are different
// facts: only an assessment result confirms a category, so no request carries
// one and every profile claim stays unverified.
func TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory(t *testing.T) {
spec := parsePublicContract(t)
profile := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfile"})
if !slices.Contains(profile.Required, "confirmed_categories") {
t.Error("the profile does not state confirmed categories apart from the claims")
}
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfileUpdate"})
wantUpdate := []string{"contacts", "expected_version", "experience", "full_name", "roles", "soft_skills", "stack", "terms"}
if got := propertyNames(update); !slices.Equal(got, wantUpdate) {
t.Errorf("CandidateProfileUpdate properties = %v, want %v", got, wantUpdate)
}
role := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileRoleItemInput"})
if got := propertyNames(role); !slices.Equal(got, []string{"self_assessed_grade", "specialization", "status"}) {
t.Errorf("ProfileRoleItemInput properties = %v, want the self-assessed grade only", got)
}
storedRole := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileRoleItem"})
for _, forbidden := range []string{"confirmed_grade", "category", "grade"} {
if slices.Contains(propertyNames(storedRole), forbidden) {
t.Errorf("ProfileRoleItem has %q: a role holds the claim, never a confirmed grade", forbidden)
}
}
category := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileConfirmedCategory"})
for _, field := range []string{"specialization", "grade", "confirmed_at", "attempt_id"} {
if !slices.Contains(category.Required, field) {
t.Errorf("ProfileConfirmedCategory does not require %s: a confirmed category names its assessment", field)
}
}
// The same grade scale and specialization codes as the catalog and the
// questionnaire, not copies of them.
for _, test := range []struct {
schema, property, ref string
}{
{"ProfileConfirmedCategory", "grade", "#/components/schemas/GradeCode"},
{"ProfileConfirmedCategory", "specialization", "#/components/schemas/SpecializationCode"},
{"ProfileRoleItemInput", "specialization", "#/components/schemas/SpecializationCode"},
{"ProfileStackItemInput", "tag", "#/components/schemas/StackTag"},
} {
parent := spec.Components.Schemas[test.schema]
if got := schemaProperty(t, parent, test.property); got.Ref != test.ref {
t.Errorf("%s.%s = %q, want a reference to %s", test.schema, test.property, got.Ref, test.ref)
}
}
// A request cannot set provenance, a trust level, or a confirmed
// category: the request schemas close their objects and name none.
for name, schema := range spec.Components.Schemas {
if !isProfileSchema(name) {
continue
}
if schema.Type == "object" && (schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool) {
t.Errorf("%s accepts unknown fields", name)
}
if !strings.HasSuffix(name, "Input") && name != "CandidateProfileUpdate" {
continue
}
for _, forbidden := range []string{"source", "trust_level", "origin", "confirmed_at", "confirmed_categories", "confirmed_grade", "category", "quote", "extraction_version"} {
if slices.Contains(propertyNames(schema), forbidden) {
t.Errorf("%s accepts %q from the client", name, forbidden)
}
}
}
}
// Every value of the profile carries its confirmation state and its source,
// and the source gives imported claims trust level 0.
func TestCandidateProfileClaimsCarrySourceAndTrustLevelZero(t *testing.T) {
spec := parsePublicContract(t)
source := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileClaimSource"})
for _, field := range []string{"origin", "trust_level", "quote", "extraction_version", "confirmed_at"} {
if !slices.Contains(source.Required, field) {
t.Errorf("ProfileClaimSource does not require %s", field)
}
}
trust := resolveSchema(t, spec, schemaProperty(t, source, "trust_level"))
if string(trust.Minimum) != "0" || string(trust.Maximum) != "0" {
t.Errorf("trust_level range = %s..%s, want exactly 0", trust.Minimum, trust.Maximum)
}
origins := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileClaimOrigin"}))
for _, origin := range []string{"manual", "extracted_from_resume", "imported"} {
if !slices.Contains(origins, origin) {
t.Errorf("ProfileClaimOrigin has no %s", origin)
}
}
for _, name := range []string{
"ProfileFullNameClaim", "ProfileEmailClaim", "ProfilePhoneClaim", "ProfileTelegramClaim",
"ProfileLocationClaim", "ProfileRelocationClaim", "ProfileSalaryMinimumClaim",
} {
claim := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})
for _, field := range []string{"status", "value", "source"} {
if !slices.Contains(claim.Required, field) {
t.Errorf("%s does not require %s", name, field)
}
}
}
for _, name := range []string{"ProfileStackItem", "ProfileSoftSkillItem", "ProfileRoleItem", "ProfileExperienceItem"} {
item := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})
for _, field := range []string{"status", "source"} {
if !slices.Contains(item.Required, field) {
t.Errorf("%s does not require %s", name, field)
}
}
itemSource := schemaProperty(t, spec.Components.Schemas[name], "source")
if itemSource.Ref != "#/components/schemas/ProfileClaimSource" {
t.Errorf("%s.source = %q, want the shared ProfileClaimSource", name, itemSource.Ref)
}
}
// Contacts reuse the formats of the contact disclosure, so a disclosure
// never has to convert a stored value.
for _, test := range []struct{ schema, ref string }{
{"ProfileFullNameClaim", "#/components/schemas/ContactFullName"},
{"ProfilePhoneClaim", "#/components/schemas/ContactPhoneNumber"},
{"ProfileTelegramClaim", "#/components/schemas/ContactTelegramUsername"},
} {
value := schemaProperty(t, spec.Components.Schemas[test.schema], "value")
if len(value.OneOf) == 0 || value.OneOf[0].Ref != test.ref {
t.Errorf("%s.value = %+v, want %s", test.schema, value, test.ref)
}
}
}
// componentsIndex returns the components of the contract as generic JSON, so
// a reference can be followed by its pointer whatever its kind.
func componentsIndex(t *testing.T, spec *ogen.Spec) map[string]any {
t.Helper()
encoded, err := json.Marshal(spec.Components)
if err != nil {
t.Fatalf("encode the components: %v", err)
}
var kinds map[string]map[string]any
if err := json.Unmarshal(encoded, &kinds); err != nil {
t.Fatalf("decode the components: %v", err)
}
index := map[string]any{}
for kind, components := range kinds {
for name, component := range components {
index["#/components/"+kind+"/"+name] = component
}
}
return index
}
func collectReferences(value any, found *[]string) {
switch typed := value.(type) {
case map[string]any:
for key, child := range typed {
if reference, ok := child.(string); ok && key == "$ref" {
*found = append(*found, reference)
continue
}
collectReferences(child, found)
}
case []any:
for _, child := range typed {
collectReferences(child, found)
}
}
}
// reachableSchemas returns the schema names that start reaches by references.
func reachableSchemas(index map[string]any, start any) map[string]bool {
reached := map[string]bool{}
var pending []string
collectReferences(start, &pending)
for len(pending) > 0 {
reference := pending[len(pending)-1]
pending = pending[:len(pending)-1]
if reached[reference] {
continue
}
reached[reference] = true
if component, ok := index[reference]; ok {
collectReferences(component, &pending)
}
}
names := map[string]bool{}
for reference := range reached {
if name, ok := strings.CutPrefix(reference, "#/components/schemas/"); ok {
names[name] = true
}
}
return names
}
// The private profile holds personal data that an organization must never
// read, so no schema that an organization can see may refer to it, and the
// profile schemas refer to nothing of an organization. The check follows
// references through request bodies, responses, parameters, and headers.
func TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs(t *testing.T) {
spec := parsePublicContract(t)
index := componentsIndex(t, spec)
// The profile family is not empty and its operations reach it.
profileOperations := reachableSchemas(index, mustJSONValue(t, spec.Paths[profilePath]))
if !profileOperations["CandidateProfile"] || !profileOperations["CandidateProfileUpdate"] {
t.Fatalf("the profile path reaches %v, want CandidateProfile and CandidateProfileUpdate", profileOperations)
}
// No schema outside the profile family refers to a profile schema.
for name, schema := range spec.Components.Schemas {
if isProfileSchema(name) {
continue
}
for reached := range reachableSchemas(index, mustJSONValue(t, schema)) {
if isProfileSchema(reached) {
t.Errorf("%s reaches the private profile schema %s", name, reached)
}
}
}
// No operation of an organization, and none that an organization can
// read, reaches a profile schema.
for path, item := range spec.Paths {
if !strings.HasPrefix(path, "/api/v1/organizations") {
continue
}
for reached := range reachableSchemas(index, mustJSONValue(t, item)) {
if isProfileSchema(reached) {
t.Errorf("%s reaches the private profile schema %s", path, reached)
}
}
}
// The family refers to no organization, invitation, or need schema except
// the shared money and label leaves it reuses.
shared := []string{"RubAmount", "CurrencyCode", "SalaryPeriod", "SalaryTaxBasis", "NeedVersionLabel"}
for name, schema := range spec.Components.Schemas {
if !isProfileSchema(name) {
continue
}
for reached := range reachableSchemas(index, mustJSONValue(t, schema)) {
isOrganizationSide := strings.HasPrefix(reached, "Organization") || strings.HasPrefix(reached, "Invitation") ||
strings.HasPrefix(reached, "Need") || strings.HasPrefix(reached, "CandidateOrganization") || reached == "ContactDisclosure"
if isOrganizationSide && !slices.Contains(shared, reached) {
t.Errorf("%s reaches the organization-side schema %s", name, reached)
}
}
}
}
func mustJSONValue(t *testing.T, value any) any {
t.Helper()
encoded, err := json.Marshal(value)
if err != nil {
t.Fatalf("encode a contract value: %v", err)
}
var decoded any
if err := json.Unmarshal(encoded, &decoded); err != nil {
t.Fatalf("decode a contract value: %v", err)
}
return decoded
}
// The generated DTOs keep claims and the private profile apart from the
// organization DTOs at the Go type level too.
func TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests(t *testing.T) {
for _, dto := range []any{api.CandidateProfileUpdate{}, api.ProfileRoleItemInput{}, api.ProfileStackItemInput{}, api.ProfileExperienceItemInput{}} {
assertNoJSONFields(t, dto, []string{
"confirmed_grade", "category", "confirmed_categories", "trust_level", "source", "origin", "version", "updated_at",
})
}
assertNoJSONFields(t, api.ProfileRoleItem{}, []string{"confirmed_grade", "category", "grade", "trust_level"})
}
// The profile operations are in the contract before their business logic: a
// schema failure answers 400 before anything else, a valid request with an
// accepted session answers 501, and a denied session answers 401.
func TestProfileSchemaValidationPrecedesImplementation(t *testing.T) {
const (
stackItem = `{"tag":"PostgreSQL","status":"confirmed"}`
roleItem = `{"specialization":"backend","self_assessed_grade":"middle","status":"confirmed"}`
)
body := func(replace ...string) string {
document := `{"expected_version":0,` +
`"full_name":{"value":"Anna Sokolova","status":"confirmed"},` +
`"contacts":{"email":null,"phone":{"value":"+79000000000","status":"confirmed"},"telegram":null},` +
`"stack":[` + stackItem + `],"roles":[` + roleItem + `],"experience":[],"soft_skills":[],` +
`"terms":{"location":null,"relocation":null,"salary_minimum":{"value":{"amount":180000,"currency":"RUB","period":"month","tax_basis":"net"},"status":"confirmed"}}}`
for index := 0; index+1 < len(replace); index += 2 {
if !strings.Contains(document, replace[index]) {
t.Fatalf("body has no %q to replace", replace[index])
}
document = strings.Replace(document, replace[index], replace[index+1], 1)
}
return document
}
for _, test := range []struct {
name string
body string
statusCode int
pointer string
code string
}{
{name: "a valid profile", body: body(), statusCode: http.StatusNotImplemented},
{name: "a profile saved with nothing set", body: `{"expected_version":3,"full_name":null,"contacts":{"email":null,"phone":null,"telegram":null},"stack":[],"roles":[],"experience":[],"soft_skills":[],"terms":{"location":null,"relocation":null,"salary_minimum":null}}`, statusCode: http.StatusNotImplemented},
{name: "missing expected version", body: body(`"expected_version":0,`, ""), statusCode: http.StatusBadRequest, pointer: "/expected_version", code: "required"},
{name: "phone outside E.164", body: body(`+79000000000`, `8 900 000 00 00`), statusCode: http.StatusBadRequest, pointer: "/contacts/phone/value", code: "invalid"},
{name: "decision outside confirmed and extracted", body: body(`"status":"confirmed"}],"roles"`, `"status":"unknown"}],"roles"`), statusCode: http.StatusBadRequest, pointer: "/stack/0/status", code: "invalid"},
{name: "salary not a multiple of 1000", body: body(`180000`, `180500`), statusCode: http.StatusBadRequest, pointer: "/terms/salary_minimum/value/amount", code: "invalid"},
{name: "salary in another currency", body: body(`"RUB"`, `"USD"`), statusCode: http.StatusBadRequest, pointer: "/terms/salary_minimum/value/currency", code: "invalid"},
{name: "grade outside the scale", body: body(`"middle"`, `"lead"`), statusCode: http.StatusBadRequest, pointer: "/roles/0/self_assessed_grade", code: "invalid"},
{name: "confirmed grade sent in a role", body: body(roleItem, strings.Replace(roleItem, `"status"`, `"confirmed_grade":"senior","status"`, 1)), statusCode: http.StatusBadRequest, pointer: "/roles", code: "invalid"},
{name: "confirmed categories sent by the client", body: body(`"experience":[]`, `"experience":[],"confirmed_categories":[]`), statusCode: http.StatusBadRequest, pointer: "", code: "invalid"},
{name: "provenance sent by the client", body: body(stackItem, strings.Replace(stackItem, `"status"`, `"source":{"origin":"imported"},"status"`, 1)), statusCode: http.StatusBadRequest, pointer: "/stack", code: "invalid"},
} {
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: profilePath, 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
}
problemBody := requireProblem(t, response, test.statusCode, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: api.ProblemFieldLocationBody, Pointer: test.pointer, Code: test.code}
for _, field := range problemBody.Errors {
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
return
}
}
t.Fatalf("errors = %+v, want an entry %+v", problemBody.Errors, want)
})
}
}
func TestProfileAccessBeforeImplementation(t *testing.T) {
for _, test := range []struct {
name string
request identityRequest
}{
{"read without a session", identityRequest{method: http.MethodGet, path: profilePath}},
{"save with a denied session", identityRequest{
method: http.MethodPut, path: profilePath,
body: `{"expected_version":0,"full_name":null,"contacts":{"email":null,"phone":null,"telegram":null},"stack":[],"roles":[],"experience":[],"soft_skills":[],"terms":{"location":null,"relocation":null,"salary_minimum":null}}`,
headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken},
}},
} {
t.Run(test.name, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
requireProblem(t, serveIdentityRequest(t, router, test.request), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
})
}
}
@@ -0,0 +1,237 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: candidate.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceCandidateProfileVersion = `-- name: AdvanceCandidateProfileVersion :one
UPDATE candidate_profiles
SET
version = candidate_profiles.version + 1,
updated_at = GREATEST(candidate_profiles.updated_at, $1)
WHERE
candidate_profiles.user_id = $2
AND candidate_profiles.version = $3
RETURNING user_id, version, created_at, updated_at
`
type AdvanceCandidateProfileVersionParams struct {
At pgtype.Timestamptz
UserID pgtype.UUID
ExpectedVersion int64
}
// Advances the version over the one the caller read, in the same statement.
// The row lock it takes serializes concurrent saves of one profile. The update
// time never moves back: an application clock behind the stored time (clock
// skew between instances) keeps the stored time, which the CHECK
// candidate_profiles_updated_after_creation also requires. No row
// returns for a stale version or for an account without a profile, which the
// caller answers as a version conflict.
func (q *Queries) AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error) {
row := q.db.QueryRow(ctx, advanceCandidateProfileVersion, arg.At, arg.UserID, arg.ExpectedVersion)
var i CandidateProfile
err := row.Scan(
&i.UserID,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deleteCandidateProfileClaims = `-- name: DeleteCandidateProfileClaims :exec
DELETE FROM candidate_profile_claims
WHERE user_id = $1
`
// Removes the claims that a save replaces. The adapter calls it after the
// version advanced and before it inserts the new set, in one transaction.
func (q *Queries) DeleteCandidateProfileClaims(ctx context.Context, userID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteCandidateProfileClaims, userID)
return err
}
const insertCandidateProfile = `-- name: InsertCandidateProfile :one
INSERT INTO candidate_profiles (
user_id,
version,
created_at,
updated_at
) VALUES (
$1,
1,
$2,
$2
)
ON CONFLICT (user_id) DO NOTHING
RETURNING user_id, version, created_at, updated_at
`
type InsertCandidateProfileParams struct {
UserID pgtype.UUID
At pgtype.Timestamptz
}
// Queries of the manual candidate profile (TASK-066). The profile is personal
// data of the account that owns it: every statement is scoped by user_id, and
// no statement selects another account's row. None of them names a file, the
// ML service, or an FSP account, because the profile needs none.
// Stores the first save of a profile at version 1. No row returns when the
// account already has a profile, so a first save that lost a race with
// another first save from another tab can be told apart and answered as a
// version conflict.
func (q *Queries) InsertCandidateProfile(ctx context.Context, arg InsertCandidateProfileParams) (CandidateProfile, error) {
row := q.db.QueryRow(ctx, insertCandidateProfile, arg.UserID, arg.At)
var i CandidateProfile
err := row.Scan(
&i.UserID,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertCandidateProfileClaim = `-- name: InsertCandidateProfileClaim :exec
INSERT INTO candidate_profile_claims (
user_id,
kind,
ordinal,
value,
status,
origin,
trust_level,
quote,
extraction_version,
confirmed_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
0,
$7,
$8,
$9
)
`
type InsertCandidateProfileClaimParams struct {
UserID pgtype.UUID
Kind string
Ordinal int16
Value []byte
Status string
Origin string
Quote pgtype.Text
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
}
// Stores one claim of the new set. Provenance fields are the domain's; the
// statement never takes a trust level from the caller, because every claim
// has level 0.
func (q *Queries) InsertCandidateProfileClaim(ctx context.Context, arg InsertCandidateProfileClaimParams) error {
_, err := q.db.Exec(ctx, insertCandidateProfileClaim,
arg.UserID,
arg.Kind,
arg.Ordinal,
arg.Value,
arg.Status,
arg.Origin,
arg.Quote,
arg.ExtractionVersion,
arg.ConfirmedAt,
)
return err
}
const readCandidateProfile = `-- name: ReadCandidateProfile :many
SELECT
candidate_profiles.user_id,
candidate_profiles.version,
candidate_profiles.created_at,
candidate_profiles.updated_at,
candidate_profile_claims.kind,
candidate_profile_claims.ordinal,
candidate_profile_claims.value,
candidate_profile_claims.status,
candidate_profile_claims.origin,
candidate_profile_claims.trust_level,
candidate_profile_claims.quote,
candidate_profile_claims.extraction_version,
candidate_profile_claims.confirmed_at
FROM candidate_profiles
LEFT JOIN candidate_profile_claims
ON candidate_profile_claims.user_id = candidate_profiles.user_id
WHERE candidate_profiles.user_id = $1
ORDER BY candidate_profile_claims.kind, candidate_profile_claims.ordinal
`
type ReadCandidateProfileRow struct {
UserID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Kind pgtype.Text
Ordinal pgtype.Int2
Value []byte
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
Quote pgtype.Text
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
}
// Reads the profile row of an account together with every claim in one
// statement, so the version and the claims come from one snapshot: a save that
// commits between two separate reads could pair version N with the claims of
// N+1. A profile without a claim returns one row with NULL claim columns, and
// no row at all means the account has not saved a profile (contract version
// 0). Claims come in a stable order: single fields by kind, list items by
// position. Never replace this with two statements.
func (q *Queries) ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error) {
rows, err := q.db.Query(ctx, readCandidateProfile, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadCandidateProfileRow
for rows.Next() {
var i ReadCandidateProfileRow
if err := rows.Scan(
&i.UserID,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.Kind,
&i.Ordinal,
&i.Value,
&i.Status,
&i.Origin,
&i.TrustLevel,
&i.Quote,
&i.ExtractionVersion,
&i.ConfirmedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -42,6 +42,26 @@ type AssessmentFamily struct {
RetiredBy pgtype.Text
}
type CandidateProfile struct {
UserID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type CandidateProfileClaim struct {
UserID pgtype.UUID
Kind string
Ordinal int16
Value []byte
Status string
Origin string
TrustLevel int16
Quote pgtype.Text
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
}
type ConsentRecord struct {
ID pgtype.UUID
SubjectID pgtype.UUID
@@ -14,6 +14,14 @@ type Querier interface {
// Adds recipients to the day and the month row. The caller holds their
// locks from LockMailQuotaRows and has checked both limits.
AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error)
// Advances the version over the one the caller read, in the same statement.
// The row lock it takes serializes concurrent saves of one profile. The update
// time never moves back: an application clock behind the stored time (clock
// skew between instances) keeps the stored time, which the CHECK
// candidate_profiles_updated_after_creation also requires. No row
// returns for a stale version or for an account without a profile, which the
// caller answers as a version conflict.
AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error)
// Cancels a job that has not finished. A job whose handler transaction is
// in progress holds its row lock, so the statement waits for it: after the
// handler committed the job is done and nothing is canceled; otherwise the
@@ -77,6 +85,9 @@ type Querier interface {
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
// Removes the claims that a save replaces. The adapter calls it after the
// version advanced and before it inserts the new set, in one transaction.
DeleteCandidateProfileClaims(ctx context.Context, userID pgtype.UUID) error
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
@@ -201,6 +212,19 @@ type Querier interface {
// returns no row instead of an error, so a conflict does not abort the
// surrounding transaction.
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
// Queries of the manual candidate profile (TASK-066). The profile is personal
// data of the account that owns it: every statement is scoped by user_id, and
// no statement selects another account's row. None of them names a file, the
// ML service, or an FSP account, because the profile needs none.
// Stores the first save of a profile at version 1. No row returns when the
// account already has a profile, so a first save that lost a race with
// another first save from another tab can be told apart and answered as a
// version conflict.
InsertCandidateProfile(ctx context.Context, arg InsertCandidateProfileParams) (CandidateProfile, error)
// Stores one claim of the new set. Provenance fields are the domain's; the
// statement never takes a trust level from the caller, because every claim
// has level 0.
InsertCandidateProfileClaim(ctx context.Context, arg InsertCandidateProfileClaimParams) error
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
// subject, purpose, and text version already exists when no row returns;
// the insert then changes nothing and does not abort the transaction.
@@ -342,6 +366,14 @@ type Querier interface {
// the publication time set by the guard trigger. No row means the version
// was not a draft any more.
PublishAssessmentFamily(ctx context.Context, arg PublishAssessmentFamilyParams) (AssessmentFamily, error)
// Reads the profile row of an account together with every claim in one
// statement, so the version and the claims come from one snapshot: a save that
// commits between two separate reads could pair version N with the claims of
// N+1. A profile without a claim returns one row with NULL claim columns, and
// no row at all means the account has not saved a profile (contract version
// 0). Claims come in a stable order: single fields by kind, list items by
// position. Never replace this with two statements.
ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error)
// Advances a delivery past one attempt and appends the attempt in one
// statement, so both happen or neither does, inside or outside a
// transaction. The update applies only while the stored version still
File diff suppressed because it is too large. Load diff
+564
View File
@@ -0,0 +1,564 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"reflect"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var candidateTestTime = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
// confirmed wraps a value as a confirmed decision.
func confirmed[V comparable](value V) *ProfileClaimInput[V] {
return &ProfileClaimInput[V]{Value: value, Status: ProfileClaimConfirmed}
}
func confirmedItems[V comparable](values ...V) []ProfileClaimInput[V] {
items := make([]ProfileClaimInput[V], 0, len(values))
for _, value := range values {
items = append(items, ProfileClaimInput[V]{Value: value, Status: ProfileClaimConfirmed})
}
return items
}
func completeCandidateProfileInput() CandidateProfileInput {
return CandidateProfileInput{
FullName: confirmed("Anna Sokolova"),
Email: confirmed("anna.sokolova@example.com"),
Phone: confirmed("+79000000000"),
Telegram: confirmed("@anna_sokolova"),
Stack: confirmedItems("PostgreSQL", "Kafka"),
Roles: confirmedItems(ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeMiddle}),
Experience: confirmedItems(ProfileExperience{
EmployerName: "Example Payments", Specialization: SpecializationBackend,
StartedOn: "2022-03", Summary: "Moved the payout service to an event model.",
}),
SoftSkills: confirmedItems("Mentoring"),
Location: confirmed("Kazan"),
Relocation: confirmed(false),
SalaryMinimum: confirmed(ProfileSalaryMinimum{Amount: 180000, TaxBasis: ProfileTaxNet}),
}
}
func mustCandidateContent(t *testing.T, stored CandidateProfileContent, input CandidateProfileInput, at time.Time) CandidateProfileContent {
t.Helper()
content, err := ResolveCandidateProfileContent(stored, input, at)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
return content
}
// suggestedContent builds stored content with imported, unconfirmed claims
// the way storage restores them, because no operation produces them yet.
func suggestedContent(t *testing.T) CandidateProfileContent {
t.Helper()
suggestion := func(kind string, ordinal int, value string) StoredProfileClaim {
return StoredProfileClaim{
Kind: kind, Ordinal: ordinal, Value: []byte(value), Status: "extracted", Origin: "extracted_from_resume",
Quote: "from the resume", ExtractionVersion: "resume-rules.2026-10.1",
}
}
content, err := RestoreCandidateProfileContent([]StoredProfileClaim{
suggestion(profileKindPhone, 0, `"+79000000000"`),
suggestion(profileKindStack, 0, `"Kafka"`),
suggestion(profileKindStack, 1, `"gRPC"`),
})
if err != nil {
t.Fatalf("RestoreCandidateProfileContent() error = %v", err)
}
return content
}
func TestResolveCandidateProfileContentStoresManualClaimsWithTrustLevelZero(t *testing.T) {
content := mustCandidateContent(t, CandidateProfileContent{}, completeCandidateProfileInput(), candidateTestTime)
name, ok := content.FullName()
if !ok || name.Value() != "Anna Sokolova" || name.Status() != ProfileClaimConfirmed {
t.Fatalf("full name = %v, %v, want a confirmed claim", name.Value(), ok)
}
source := name.Source()
if source.Origin() != ProfileOriginManual || source.TrustLevel() != 0 || source.Quote() != "" ||
source.ExtractionVersion() != "" || !source.ConfirmedAt().Equal(candidateTestTime) {
t.Fatalf("source = origin %s, trust %d, confirmed %v, want a manual claim at the save time", source.Origin(), source.TrustLevel(), source.ConfirmedAt())
}
salary, ok := content.SalaryMinimum()
if !ok || salary.Value() != (ProfileSalaryMinimum{Amount: 180000, TaxBasis: ProfileTaxNet}) {
t.Fatalf("salary minimum = %v, %v, want the given amount", salary.Value(), ok)
}
if roles := content.Roles(); len(roles) != 1 || roles[0].Value().SelfAssessedGrade != GradeMiddle {
t.Fatalf("roles = %d, want the self-assessed role", len(roles))
}
if len(content.Stack()) != 2 || len(content.SoftSkills()) != 1 || len(content.Experience()) != 1 {
t.Fatal("lists were not stored")
}
for _, claim := range content.Stack() {
if claim.Source().TrustLevel() != ProfileClaimTrustLevel {
t.Fatalf("trust level = %d, want %d for every claim", claim.Source().TrustLevel(), ProfileClaimTrustLevel)
}
}
}
func TestResolveCandidateProfileContentLeavesAbsentFieldsUnknown(t *testing.T) {
stored := mustCandidateContent(t, CandidateProfileContent{}, completeCandidateProfileInput(), candidateTestTime)
content := mustCandidateContent(t, stored, CandidateProfileInput{}, candidateTestTime.Add(time.Hour))
if _, ok := content.FullName(); ok {
t.Fatal("a field sent as null kept its value, want it removed")
}
if _, ok := content.SalaryMinimum(); ok {
t.Fatal("a salary sent as null kept its value, want it removed")
}
if len(content.Stack()) != 0 || len(content.Roles()) != 0 {
t.Fatal("an empty list kept its items, want the list replaced")
}
}
func TestSuggestionsStayUnconfirmedUntilTheCandidateConfirmsThem(t *testing.T) {
stored := suggestedContent(t)
phone, _ := stored.Phone()
if phone.Status() != ProfileClaimExtracted || phone.Source().TrustLevel() != 0 || !phone.Source().ConfirmedAt().IsZero() {
t.Fatalf("restored suggestion = %v, trust %d, want an unconfirmed claim of trust level 0", phone.Status(), phone.Source().TrustLevel())
}
later := candidateTestTime.Add(time.Hour)
t.Run("extracted keeps a stored suggestion unconfirmed and unchanged", func(t *testing.T) {
input := CandidateProfileInput{
Phone: &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted},
Stack: []ProfileClaimInput[string]{{Value: "Kafka", Status: ProfileClaimExtracted}, {Value: "gRPC", Status: ProfileClaimExtracted}},
}
content := mustCandidateContent(t, stored, input, later)
if !content.Equal(stored) {
t.Fatal("a form sent back unchanged altered the stored suggestions")
}
})
t.Run("confirmed confirms a suggestion and keeps its origin and quote", func(t *testing.T) {
input := CandidateProfileInput{Phone: confirmed("+79000000000"), Stack: confirmedItems("Kafka")}
content := mustCandidateContent(t, stored, input, later)
phone, _ := content.Phone()
source := phone.Source()
if phone.Status() != ProfileClaimConfirmed || source.Origin() != ProfileOriginExtractedFromResume ||
source.Quote() != "from the resume" || source.ExtractionVersion() != "resume-rules.2026-10.1" ||
!source.ConfirmedAt().Equal(later) || source.TrustLevel() != 0 {
t.Fatalf("confirmed suggestion = %s from %s, want confirmed at %v with the import provenance and trust level 0", phone.Status(), source.Origin(), later)
}
})
t.Run("confirmed with another value makes the claim manual", func(t *testing.T) {
content := mustCandidateContent(t, stored, CandidateProfileInput{Phone: confirmed("+79000000001")}, later)
phone, _ := content.Phone()
if phone.Source().Origin() != ProfileOriginManual || phone.Source().Quote() != "" {
t.Fatalf("changed suggestion origin = %s, want manual without the old quote", phone.Source().Origin())
}
})
t.Run("extracted for a value that is not a stored suggestion is refused", func(t *testing.T) {
input := CandidateProfileInput{
Stack: []ProfileClaimInput[string]{{Value: "Kafka", Status: ProfileClaimExtracted}, {Value: "Made up", Status: ProfileClaimExtracted}},
}
assertProfileFieldError(t, resolveErr(stored, input, later), "/stack/1/status")
})
t.Run("a confirmed value cannot go back to a suggestion", func(t *testing.T) {
confirmedStored := mustCandidateContent(t, stored, CandidateProfileInput{Phone: confirmed("+79000000000")}, later)
input := CandidateProfileInput{Phone: &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted}}
assertProfileFieldError(t, resolveErr(confirmedStored, input, later), "/contacts/phone/status")
})
}
func resolveErr(stored CandidateProfileContent, input CandidateProfileInput, at time.Time) error {
_, err := ResolveCandidateProfileContent(stored, input, at)
return err
}
func assertProfileFieldError(t *testing.T, err error, pointer string) {
t.Helper()
var fieldError *CandidateProfileFieldError
if !errors.Is(err, ErrInvalidCandidateProfile) || !errors.As(err, &fieldError) {
t.Fatalf("error = %v, want ErrInvalidCandidateProfile with a field pointer", err)
}
if fieldError.Pointer != pointer {
t.Fatalf("pointer = %q, want %q (reason %q)", fieldError.Pointer, pointer, fieldError.Reason)
}
}
func TestResolveCandidateProfileContentRejectsInvalidValuesWithPointers(t *testing.T) {
long := strings.Repeat("a", 201)
tests := []struct {
name string
mutate func(*CandidateProfileInput)
pointer string
}{
{"full name with surrounding whitespace", func(in *CandidateProfileInput) { in.FullName = confirmed(" Anna") }, "/full_name/value"},
{"full name too long", func(in *CandidateProfileInput) { in.FullName = confirmed(long) }, "/full_name/value"},
{"email without a domain", func(in *CandidateProfileInput) { in.Email = confirmed("anna") }, "/contacts/email/value"},
{"phone outside E.164", func(in *CandidateProfileInput) { in.Phone = confirmed("8 900 000 00 00") }, "/contacts/phone/value"},
{"telegram without the at sign", func(in *CandidateProfileInput) { in.Telegram = confirmed("anna_sokolova") }, "/contacts/telegram/value"},
{"status missing", func(in *CandidateProfileInput) { in.FullName = &ProfileClaimInput[string]{Value: "Anna"} }, "/full_name/status"},
{"location with a line break", func(in *CandidateProfileInput) { in.Location = confirmed("Kazan\nTatarstan") }, "/terms/location/value"},
{"salary below the step", func(in *CandidateProfileInput) {
in.SalaryMinimum = confirmed(ProfileSalaryMinimum{Amount: 180500, TaxBasis: ProfileTaxNet})
}, "/terms/salary_minimum/value/amount"},
{"salary above the bound", func(in *CandidateProfileInput) {
in.SalaryMinimum = confirmed(ProfileSalaryMinimum{Amount: 101_000_000, TaxBasis: ProfileTaxNet})
}, "/terms/salary_minimum/value/amount"},
{"salary without a tax basis", func(in *CandidateProfileInput) {
in.SalaryMinimum = confirmed(ProfileSalaryMinimum{Amount: 180000})
}, "/terms/salary_minimum/value/tax_basis"},
{"stack tag with surrounding whitespace", func(in *CandidateProfileInput) { in.Stack = confirmedItems("Go", "Kafka ") }, "/stack/1/tag"},
{"stack tag repeated without regard to case", func(in *CandidateProfileInput) { in.Stack = confirmedItems("Kafka", "go", "KAFKA") }, "/stack/2/tag"},
{"too many tags", func(in *CandidateProfileInput) {
in.Stack = confirmedItems(make([]string, maxProfileStackItems+1)...)
}, "/stack"},
{"soft skill repeated", func(in *CandidateProfileInput) { in.SoftSkills = confirmedItems("Mentoring", "mentoring") }, "/soft_skills/1/skill"},
{"role with an unknown specialization", func(in *CandidateProfileInput) {
in.Roles = confirmedItems(ProfileRole{Specialization: "go"})
}, "/roles/0/specialization"},
{"role with an unknown grade", func(in *CandidateProfileInput) {
in.Roles = confirmedItems(ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: "lead"})
}, "/roles/0/self_assessed_grade"},
{"role repeats a specialization", func(in *CandidateProfileInput) {
in.Roles = confirmedItems(ProfileRole{Specialization: SpecializationBackend}, ProfileRole{Specialization: SpecializationQA}, ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior})
}, "/roles/2/specialization"},
{"experience month in a wrong format", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-3"})
}, "/experience/0/started_on"},
{"experience ends before it starts", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-05", EndedOn: "2024-04"})
}, "/experience/0/ended_on"},
{"experience starts in the future", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2026-11"})
}, "/experience/0/started_on"},
{"experience summary too long", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-05", Summary: strings.Repeat("a", maxProfileSummaryRunes+1)})
}, "/experience/0/summary"},
{"employer with a line break", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{EmployerName: "A\nB", Specialization: SpecializationQA, StartedOn: "2024-05"})
}, "/experience/0/employer_name"},
{"too many roles", func(in *CandidateProfileInput) {
roles := make([]ProfileRole, len(specializationCodes)+1)
for index := range roles {
roles[index] = ProfileRole{Specialization: SpecializationBackend}
}
in.Roles = confirmedItems(roles...)
}, "/roles"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := completeCandidateProfileInput()
test.mutate(&input)
err := resolveErr(CandidateProfileContent{}, input, candidateTestTime)
assertProfileFieldError(t, err, test.pointer)
})
}
}
func TestProfileErrorsNeverQuoteSubmittedValues(t *testing.T) {
const secret = "secret-phone-9000000000"
input := completeCandidateProfileInput()
input.Phone = confirmed(secret)
err := resolveErr(CandidateProfileContent{}, input, candidateTestTime)
if err == nil || strings.Contains(err.Error(), secret) {
t.Fatalf("error = %v, want a failure that does not repeat the submitted value", err)
}
}
func TestResolveCandidateProfileContentNormalizesValues(t *testing.T) {
input := completeCandidateProfileInput()
input.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-05", Summary: "one\r\ntwo"})
content := mustCandidateContent(t, CandidateProfileContent{}, input, candidateTestTime)
if got := content.Experience()[0].Value().Summary; got != "one\ntwo" {
t.Fatalf("summary = %q, want CRLF normalized to LF", got)
}
}
func TestCandidateProfileReplaceTellsAChangeFromANoOp(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
empty, err := EmptyCandidateProfile(userID)
if err != nil || empty.Version() != 0 || !empty.CreatedAt().IsZero() {
t.Fatalf("EmptyCandidateProfile() = version %d, %v, want version 0", empty.Version(), err)
}
saved, changed, err := empty.Replace(completeCandidateProfileInput(), 0, candidateTestTime)
if err != nil || !changed {
t.Fatalf("Replace() = changed %v, %v, want a change", changed, err)
}
if saved.Version() != 0 || !saved.UpdatedAt().Equal(candidateTestTime) || !saved.CreatedAt().Equal(candidateTestTime) {
t.Fatalf("saved = version %d at %v, want the version left to storage", saved.Version(), saved.UpdatedAt())
}
// Sending the same decisions again changes nothing and keeps the
// confirmation time of the stored claims.
again, changed, err := saved.Replace(completeCandidateProfileInput(), 0, candidateTestTime.Add(time.Hour))
if err != nil || changed {
t.Fatalf("Replace(unchanged) = changed %v, %v, want a no-op", changed, err)
}
name, _ := again.Content().FullName()
if !name.Source().ConfirmedAt().Equal(candidateTestTime) || !again.UpdatedAt().Equal(candidateTestTime) {
t.Fatal("a no-op moved the confirmation or update time")
}
// A time before the last update, from clock skew, never moves it back.
edited := completeCandidateProfileInput()
edited.Location = confirmed("Moscow")
skewed, changed, err := saved.Replace(edited, 0, candidateTestTime.Add(-time.Minute))
if err != nil || !changed || !skewed.UpdatedAt().Equal(candidateTestTime) {
t.Fatalf("Replace(skewed clock) = changed %v, updated %v, %v, want the last update kept", changed, skewed.UpdatedAt(), err)
}
if _, _, err := (CandidateProfile{}).Replace(completeCandidateProfileInput(), 0, candidateTestTime); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Fatalf("Replace(zero profile) error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := EmptyCandidateProfile(uuid.Nil); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Fatalf("EmptyCandidateProfile(nil) error = %v, want ErrInvalidCandidateProfile", err)
}
}
func TestStoredClaimsRoundTripThroughRestore(t *testing.T) {
stored := suggestedContent(t)
input := completeCandidateProfileInput()
input.Phone = &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted}
input.Stack = append(confirmedItems("PostgreSQL"), ProfileClaimInput[string]{Value: "Kafka", Status: ProfileClaimExtracted})
content := mustCandidateContent(t, stored, input, candidateTestTime)
rows, err := content.StoredClaims()
if err != nil {
t.Fatalf("StoredClaims() error = %v", err)
}
for _, row := range rows {
if row.TrustLevel != 0 {
t.Fatalf("row %s has trust level %d, want 0", row.Kind, row.TrustLevel)
}
}
restored, err := RestoreCandidateProfileContent(rows)
if err != nil || !restored.Equal(content) {
t.Fatalf("RestoreCandidateProfileContent() = equal %v, %v, want the same content", restored.Equal(content), err)
}
reversed := slicesReversed(rows)
if again, err := RestoreCandidateProfileContent(reversed); err != nil || !again.Equal(content) {
t.Fatalf("restore of rows in another order = equal %v, %v, want the same content", again.Equal(content), err)
}
}
func slicesReversed(rows []StoredProfileClaim) []StoredProfileClaim {
reversed := make([]StoredProfileClaim, len(rows))
for index, row := range rows {
reversed[len(rows)-1-index] = row
}
return reversed
}
func TestRestoreCandidateProfileContentRefusesRowsThatBreakARule(t *testing.T) {
manual := func(kind string, ordinal int, value string) StoredProfileClaim {
return StoredProfileClaim{Kind: kind, Ordinal: ordinal, Value: []byte(value), Status: "confirmed", Origin: "manual", ConfirmedAt: candidateTestTime}
}
tests := []struct {
name string
rows []StoredProfileClaim
}{
{"unknown kind", []StoredProfileClaim{manual("confirmed_grade", 0, `"senior"`)}},
{"trust level above zero", []StoredProfileClaim{func() StoredProfileClaim {
row := manual(profileKindFullName, 0, `"Anna"`)
row.TrustLevel = 1
return row
}()}},
{"manual claim with a quote", []StoredProfileClaim{func() StoredProfileClaim {
row := manual(profileKindFullName, 0, `"Anna"`)
row.Quote = "quote"
return row
}()}},
{"suggestion without an extractor version", []StoredProfileClaim{{Kind: profileKindFullName, Value: []byte(`"Anna"`), Status: "extracted", Origin: "imported"}}},
{"confirmed claim without a time", []StoredProfileClaim{{Kind: profileKindFullName, Value: []byte(`"Anna"`), Status: "confirmed", Origin: "manual"}}},
{"role with a confirmed grade key", []StoredProfileClaim{manual(profileKindRole, 0, `{"specialization":"backend","self_assessed_grade":null,"confirmed_grade":"senior"}`)}},
{"role with an unknown specialization", []StoredProfileClaim{manual(profileKindRole, 0, `{"specialization":"go","self_assessed_grade":null}`)}},
{"value of a wrong type", []StoredProfileClaim{manual(profileKindRelocation, 0, `"yes"`)}},
{"value with trailing data", []StoredProfileClaim{manual(profileKindFullName, 0, `"Anna" "Anna"`)}},
{"single field twice", []StoredProfileClaim{manual(profileKindFullName, 0, `"Anna"`), manual(profileKindFullName, 0, `"Anna"`)}},
{"list with a gap", []StoredProfileClaim{manual(profileKindStack, 1, `"Go"`)}},
{"list repeats an item", []StoredProfileClaim{manual(profileKindStack, 0, `"Go"`), manual(profileKindStack, 1, `"go"`)}},
{"salary in another currency", []StoredProfileClaim{manual(profileKindSalaryMinimum, 0, `{"amount":180000,"currency":"USD","period":"month","tax_basis":"net"}`)}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := RestoreCandidateProfileContent(test.rows)
if !errors.Is(err, ErrInvalidCandidateProfile) {
t.Fatalf("RestoreCandidateProfileContent() error = %v, want ErrInvalidCandidateProfile", err)
}
if strings.Contains(err.Error(), "Anna") {
t.Fatalf("error = %v, want it not to quote a stored value", err)
}
})
}
}
func TestRestoreCandidateProfileValidatesTheRow(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
stored := StoredCandidateProfile{UserID: userID, Version: 2, CreatedAt: candidateTestTime, UpdatedAt: candidateTestTime.Add(time.Hour)}
profile, err := RestoreCandidateProfile(stored)
if err != nil || profile.Version() != 2 || profile.UserID() != userID {
t.Fatalf("RestoreCandidateProfile() = version %d, %v, want the stored profile", profile.Version(), err)
}
for name, mutate := range map[string]func(*StoredCandidateProfile){
"nil user": func(row *StoredCandidateProfile) { row.UserID = uuid.Nil },
"version zero": func(row *StoredCandidateProfile) { row.Version = 0 },
"update before it": func(row *StoredCandidateProfile) { row.UpdatedAt = row.CreatedAt.Add(-time.Second) },
} {
row := stored
mutate(&row)
if _, err := RestoreCandidateProfile(row); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("%s: error = %v, want ErrInvalidCandidateProfile", name, err)
}
}
}
// The profile types must offer no way to state a confirmed grade or a
// category: a confirmed category comes only from an assessment result.
func TestProfileTypesHaveNoConfirmedGradeOrCategory(t *testing.T) {
forbidden := []string{"confirmed", "category", "trust"}
for _, typ := range []reflect.Type{
reflect.TypeFor[ProfileRole](), reflect.TypeFor[ProfileExperience](), reflect.TypeFor[ProfileSalaryMinimum](),
reflect.TypeFor[CandidateProfileInput](), reflect.TypeFor[CandidateProfileContent](), reflect.TypeFor[CandidateProfile](),
} {
for index := range typ.NumField() {
name := strings.ToLower(typ.Field(index).Name)
for _, word := range forbidden {
if strings.Contains(name, word) {
t.Errorf("%s has a field %q, want none that names a confirmed grade, a category, or a trust level", typ.Name(), typ.Field(index).Name)
}
}
}
}
if got := reflect.TypeFor[ProfileRole]().NumField(); got != 2 {
t.Errorf("ProfileRole has %d fields, want the specialization and the self-assessed grade only", got)
}
}
func TestRestoreProfileClaimRefusesInconsistentStatus(t *testing.T) {
manual, err := NewManualProfileClaimSource(candidateTestTime)
if err != nil {
t.Fatalf("NewManualProfileClaimSource() error = %v", err)
}
if _, err := RestoreProfileClaim("x", ProfileClaimExtracted, manual); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("manual suggestion error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := RestoreProfileClaim("x", ProfileClaimStatus("unknown"), manual); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("unknown status error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := RestoreProfileClaim("x", ProfileClaimConfirmed, ProfileClaimSource{}); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("zero source error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := NewManualProfileClaimSource(time.Time{}); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("zero time error = %v, want ErrInvalidCandidateProfile", err)
}
}
func TestCandidateProfileValuesAreRedacted(t *testing.T) {
const name, summary, quote = "Anna Sokolova", "Moved the payout service", "from the resume"
userID := uuid.Must(uuid.NewV7())
empty, err := EmptyCandidateProfile(userID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
input := completeCandidateProfileInput()
profile, _, err := empty.Replace(input, 0, candidateTestTime)
if err != nil {
t.Fatalf("Replace() error = %v", err)
}
claim, _ := profile.Content().FullName()
experience := profile.Content().Experience()[0]
salary, _ := profile.Content().SalaryMinimum()
suggested, _ := suggestedContent(t).Phone()
type holder struct {
Profile CandidateProfile
Content CandidateProfileContent
Claim ProfileClaim[string]
Experience ProfileClaim[ProfileExperience]
Salary ProfileClaim[ProfileSalaryMinimum]
Suggestion ProfileClaim[string]
Source ProfileClaimSource
}
value := holder{profile, profile.Content(), claim, experience, salary, suggested, suggested.Source()}
var logged bytes.Buffer
slog.New(slog.NewTextHandler(&logged, nil)).Info("profile", "profile", profile, "claim", claim, "holder", value)
outputs := []string{
fmt.Sprintf("%v %+v %#v %s", value, value, value, value),
fmt.Sprintf("%v %+v %#v", profile, profile, profile),
fmt.Sprintf("%v %+v %#v", experience.Value(), salary.Value(), claim),
logged.String(),
}
for _, output := range outputs {
for _, secret := range []string{name, summary, quote, "+79000000000", "180000", "Kazan", "Example Payments"} {
if strings.Contains(output, secret) {
t.Errorf("output %q leaks %q", output, secret)
}
}
}
}
// A client holding an old version gets a version conflict, not a validation
// error, when its decision depends on claims that another save changed.
func TestCandidateProfileReplaceChecksTheVersionBeforeStateDependentRules(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
// Version 5 holds the phone confirmed by another tab.
stored, err := RestoreCandidateProfile(StoredCandidateProfile{
UserID: userID, Version: 5, CreatedAt: candidateTestTime, UpdatedAt: candidateTestTime,
Claims: []StoredProfileClaim{{
Kind: profileKindPhone, Value: []byte(`"+79000000000"`), Status: "confirmed", Origin: "extracted_from_resume",
Quote: "q", ExtractionVersion: "resume-rules.1", ConfirmedAt: candidateTestTime,
}},
})
if err != nil {
t.Fatalf("RestoreCandidateProfile() error = %v", err)
}
later := candidateTestTime.Add(time.Hour)
staleExtracted := CandidateProfileInput{Phone: &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted}}
t.Run("stale extracted decision is a conflict", func(t *testing.T) {
if _, _, err := stored.Replace(staleExtracted, 4, later); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("error = %v, want ErrCandidateProfileVersionConflict", err)
}
})
t.Run("current version keeps the validation error", func(t *testing.T) {
assertProfileFieldError(t, errOnly(stored.Replace(staleExtracted, 5, later)), "/contacts/phone/status")
})
t.Run("stale body rule stays a validation error", func(t *testing.T) {
bad := CandidateProfileInput{Phone: confirmed("8 900")}
assertProfileFieldError(t, errOnly(stored.Replace(bad, 4, later)), "/contacts/phone/value")
})
t.Run("stale unchanged body is a no-op", func(t *testing.T) {
unchanged := CandidateProfileInput{Phone: confirmed("+79000000000")}
got, changed, err := stored.Replace(unchanged, 4, later)
if err != nil || changed || got.Version() != 5 {
t.Fatalf("Replace() = changed %v, %v, want a no-op", changed, err)
}
})
t.Run("stale changed body is a conflict", func(t *testing.T) {
changedBody := CandidateProfileInput{Phone: confirmed("+79000000001")}
if _, _, err := stored.Replace(changedBody, 4, later); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("error = %v, want ErrCandidateProfileVersionConflict", err)
}
})
t.Run("a future version never existed", func(t *testing.T) {
unchanged := CandidateProfileInput{Phone: confirmed("+79000000000")}
for _, version := range []int64{6, 99, -1} {
if _, _, err := stored.Replace(unchanged, version, later); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("version %d error = %v, want ErrCandidateProfileVersionConflict", version, err)
}
}
})
}
func errOnly(_ CandidateProfile, _ bool, err error) error { return err }
+19
View File
@@ -751,6 +751,25 @@ What the ports guarantee (`outbound.OrganizationRepositories`, available on `Uni
- `GetForMember` reads the organization, its representatives (aggregated as JSON in the same statement), and the caller's active membership from one snapshot, and returns them or `ErrOrganizationNotFound` for an unknown organization, an account without a membership, and a `suspended`, `removed`, or `left` member alike. `ListForUser` pages the active organizations of one account, newest membership first, with the organization identifier as the tie-breaker. `UpdateProfile` is described above.
- `Memberships().Insert` returns `ErrMembershipExists` for a repeated pair in any state, `ErrOrganizationNotFound` for an unknown organization, and `ErrUserNotFound` for an unknown account; `Get` returns the membership in any state or `ErrMembershipNotFound`, and the caller checks `GrantsAccess`. There is no method that changes a role or a state yet.
### Candidate profile
Implemented as storage, domain, and the source contract (TASK-066): the migration `backend/db/migrations/00013_create_candidate_profiles.sql`, the queries in `backend/db/queries/candidate.sql`, the domain types in `backend/internal/domain/candidate.go`, the schemas in `api/core/components/schemas/candidate_schemas.yml`, and the operations `GetMyProfile` and `SaveMyProfile` in `api/core/routes/candidate_profile.yml`. There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter will come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`StoredClaims`, `RestoreCandidateProfile`) are ready and covered by an integration test.
Tables:
- `candidate_profiles`: `user_id` (the primary key and a foreign key to `users` with `ON DELETE CASCADE`), `version` (positive; the first save creates version 1, and the contract's version 0 is the absence of a row), and times. The profile is personal data of the account and goes with it; retention rules are an open legal question.
- `candidate_profile_claims`: one row per stored claim - a single field (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` at `ordinal` 0) or a list item (`stack` up to 30, `role` up to 9, `experience` up to 20, `soft_skill` up to 10, by position). Columns: `value` jsonb, `status` (`confirmed` or `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version`, and `confirmed_at`. A field without a value has no row, so the contract's `unknown` is the absence of a row. The foreign key points at `candidate_profiles` with `ON DELETE CASCADE`.
Decisions:
- Claims, not columns. Every value has a status, a source, and a confirmation time, so one claims table replaces fifty columns; jsonb holds the shape of the value (a string, a boolean, or an object), and each kind has its own CHECK for the format and bounds of the contract (E.164 for the phone, the `@` of a Telegram name, a multiple of 1000 for the salary, `YYYY-MM` and the order of the period for experience, the known specialization and grade codes). The domain validates a value in full before it is written, and `RestoreCandidateProfileContent` applies the same rules on read, so a row changed outside the application is rejected.
- Trust level 0 in the schema. `trust_level` is stored in a column with `CHECK (trust_level = 0)`, and the insert statement supplies 0 itself and takes no level from the caller. A confirmed value requires `confirmed_at`, an unconfirmed suggestion does not and is always an import (`extraction_version` is not NULL); a manual value is always confirmed and carries no quote. Raising trust is a property of evidence, which is not stored here.
- No confirmed category. The tables have no column for a confirmed grade or a category, and the value of a role admits only the keys `specialization` and `self_assessed_grade`, so neither a form nor an import can write a confirmed category; it is derived from assessment results when read (`confirmed_categories`).
- No mandatory link to a file, ML, or FSP. The tables have no column or foreign key to a resume file, the object storage, ML, or an FSP account, and the only foreign keys point at `users` and `candidate_profiles`. A profile typed by hand is complete; a future import adds its own columns or tables additively (`TestCandidateProfileStorage` checks the set of columns and foreign keys).
- Version. `AdvanceCandidateProfileVersion` is one statement that advances the version only when the stored one equals the one the caller read; for a stale version no row returns, and the caller answers 412 `version_conflict`. The update time is `GREATEST(stored, application clock)`, so an instance clock that runs behind never violates the CHECK `candidate_profiles_updated_after_creation` (which would be a 500). Version monotonicity is enforced by these queries only: there is no trigger, so no other code may write `version`. `InsertCandidateProfile` with `ON CONFLICT DO NOTHING` tells a lost first save apart (concurrent first saves: one wins, the rest get a version conflict). Replacing the set of claims (delete all, insert the new ones) runs in one transaction with the version advance. `domain.CandidateProfile.Replace(input, expectedVersion, at)` fixes the order: a version above the current one is a conflict; body rules are 400; a decision `extracted` that depends on the stored claims, against a stale version, is `ErrCandidateProfileVersionConflict` rather than 400; a body that changes nothing does not advance the version; any other change over a stale version is a conflict.
- Consistent read. `ReadCandidateProfile` reads the profile row and every claim in one statement (a LEFT JOIN), that is, from one snapshot; two separate queries could return version N with the claims of N+1 when a save commits between them. The adapter must use only this query and never replace it with two; a write reads the profile in the same transaction as the replacement, and the version condition protects against a lost edit.
- Privacy. The values are personal data of the candidate: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent`, and `CandidateProfile` hide themselves in `fmt` and `slog` output, `CandidateProfile` logs only the account identifier and the version, domain errors name the field and the rule but never the value, and metric labels are never taken from the profile. No query selects the profile of another account: every statement is scoped by `user_id`. The adapter must never log or wrap `pgconn.PgError.Detail` (it contains the failing row with names and phones) and reports only the SQLSTATE and the constraint name, as the organizations adapter does.
## Frontend
The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need.
+18
View File
@@ -352,6 +352,24 @@ Unit tests (`make -C backend test`) cover the organization rules without a datab
`TestPostgresMigrations` rolls migration 00010 back with the others, checks that its three tables and its function disappear while the identity tables stay, and checks them again after the second migration. The tests that truncate `users` name `usersDependentTables` (identity, delivery, consent, and organization tables), the one list to extend when a migration adds a table that references users. The suite does not cover the usecases, the handlers, the session and CSRF mapping, or the claim that the contract is enforced end to end, because none of them exists yet; the atomicity of the single-statement read of the organization with its representatives is not proven by a test, because the window between two statements cannot be reproduced deterministically.
## Candidate profile tests
Unit tests (`make -C backend test`) check the profile rules without a database:
- `internal/domain/candidate_test.go`: manual values get the source `manual`, trust level 0, and the save time; a field sent as null is removed and a list is replaced; an imported suggestion stays unconfirmed under `extracted` with the same value, is confirmed under `confirmed` while keeping its source and quote, becomes manual under another value, while `extracted` for a value that is not among the suggestions and moving a confirmed value back to a suggestion are rejected with the pointer `/stack/1/status`; a table of values names the field that broke the rule (a phone outside E.164, a Telegram name without `@`, a name with whitespace, a salary that is not a multiple of 1000, an unknown specialization or grade, a tag repeated without regard to case, a repeated role specialization, a month outside `YYYY-MM`, a period that ends before it starts or lies in the future, too many items); an error never contains the submitted value; a body that changes nothing leaves the profile and the confirmation time unchanged; the storage rows (`StoredClaims`) restore to the same content in any order, and a row with an unknown kind, a trust level above 0, a quote on a manual value, a value of another type, an extra `confirmed_grade` key, a gap in a list, or a repeat is rejected; the profile types have no field for a confirmed grade, a category, or a trust level; the values are hidden in `fmt` and `slog` output.
- `internal/adapter/primary/http/candidate_profile_contract_test.go`: by the contract bundle, the operations follow the conventions (session and CSRF for the save, the version in the body, no Idempotency-Key or If-Match, 412 rather than 409, `no-store`); a request carries no confirmed category, source, trust level, or confirmation time, and every profile schema closes its objects; each claim carries `status` and `source`, and `trust_level` is limited to zero; the full name uses `ContactFullName`; **no schema outside the profile family and no operation of an organization reaches a profile schema through references, and the profile refers to no organization, invitation, or need schema**; through the generated server the schema rejects a client-sent category, source, and unknown fields before the implementation, a valid profile answers 501, and a denied session answers 401.
- `frontend/src/shared/api/profile-contract.test.ts`: the generated Zod schemas accept a complete profile and a profile with no value at all (that is, without a file or FSP), require `expected_version`, reject each broken format and extra list items, let no confirmed grade, category, or source into the parsed body, require every claim to have a source with trust level 0, and the request types have none of these fields; the generated organization, invitation, and need files hold no profile keys, and vice versa.
`TestCandidateProfileStorage` in `backend/integration_test/candidate_profile_test.go` uses `bootstrap(t, postgresService)` with the migrated schema; `candidateProfileTables` belong to `usersDependentTables`, so the other tests truncate them together with `users`:
- Saving without a file, ML, or FSP: a profile with only a name, and a profile row with no claim at all, are saved and read back, and a complete profile returns the same content and sources through `StoredClaims` and `RestoreCandidateProfile`; a stored import suggestion reads back with its quote, extraction version, and level 0.
- Schema: the columns of the two tables equal the expected list (no file, FSP, confirmed grade, or category), and the only foreign keys lead to the account and to the profile row.
- Constraints through direct SQL: each rule refuses a row with its own constraint (a trust level above 0, an unknown kind, status, and origin, a single field with a position, a list past its limit, a confirmation without a time, a manual value with a quote, an import without an extraction version, wrong values of a tag, a phone, a Telegram name, relocation, a salary, a role with a `confirmed_grade` key, and experience); a repeated tag, skill, or role specialization, a profile without an account, version 0, and a claim without a profile are refused too, while the same valid row is accepted.
- Deleting the account deletes the profile and its claims; two accounts keep their profiles apart.
- Version: a lost second first save and a stale version return no row, eight advances from one version and eight concurrent first saves on their own connections give exactly one success, and an advance with an earlier application clock keeps the update time and violates no CHECK. Reading uses the single `ReadCandidateProfile` query.
`TestCandidateProfileMigrationRollsBack` rolls migration 00013 back on an isolated database and checks that both tables disappear while `users` stays.
## Assessment bank tests
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. With in-memory fakes of the repository and the unit of work, the usecase tests prove that a concurrent identical import reports the version as unchanged and a concurrent import with other content is refused, that the sentinels of database races become refusals with the matching reason, that publishing retires the older published version after taking the category lock and is refused when a newer one is published, that opening requires the policy version in force, that availability is refused when the published count falls below the opening's requirement or when the opening's policy version is no longer in force, and that an older approved draft is refused while a newer version exists as a draft, a published, or a retired one. `internal/adapter/secondary/postgres/assessment_bank_test.go` checks that the bank constraints map to their sentinels without the failing row, that a list page outside its limit fails before any statement, and that the category lock is refused outside a transaction.
+19
View File
@@ -751,6 +751,25 @@ contact_grant относится к паре кандидат-компания
- `GetForMember` читает организацию, ее представителей (собранных в JSON тем же оператором) и активное членство вызывающего из одного снимка и возвращает их либо `ErrOrganizationNotFound` одинаково для неизвестной организации, аккаунта без членства и участника в состоянии `suspended`, `removed` или `left`. `ListForUser` постранично отдает активные организации одного аккаунта от нового членства к старому с идентификатором организации как разрешением ничьей. `UpdateProfile` описан выше.
- `Memberships().Insert` возвращает `ErrMembershipExists` для повторной пары в любом состоянии, `ErrOrganizationNotFound` для неизвестной организации и `ErrUserNotFound` для неизвестного аккаунта; `Get` возвращает членство в любом состоянии или `ErrMembershipNotFound`, а вызывающий проверяет `GrantsAccess`. Метода, который меняет роль или состояние, пока нет.
### Профиль кандидата
Реализовано как хранение, домен и исходный контракт (TASK-066): миграция `backend/db/migrations/00013_create_candidate_profiles.sql`, запросы в `backend/db/queries/candidate.sql`, доменные типы в `backend/internal/domain/candidate.go`, схемы в `api/core/components/schemas/candidate_schemas.yml` и операции `GetMyProfile` и `SaveMyProfile` в `api/core/routes/candidate_profile.yml`. Порта, адаптера и обработчиков пока нет: операции отвечают 401 `unauthenticated`, пока сессий нет, и 501 `not_implemented` после валидации. Порт и адаптер придут с обработчиками и должны войти в `UnitOfWork`; запросы и доменное преобразование строк (`StoredClaims`, `RestoreCandidateProfile`) уже готовы и проверены интеграционным тестом.
Таблицы:
- `candidate_profiles`: `user_id` (первичный ключ и внешний ключ `ON DELETE CASCADE` на `users`), `version` (больше нуля; первое сохранение создает версию 1, а версия 0 контракта - отсутствие строки) и времена. Профиль - ПДн аккаунта и уходит вместе с ним; правила хранения - открытый юридический вопрос.
- `candidate_profile_claims`: по строке на сохраненное заявление - одиночное поле (`full_name`, `contact_email`, `contact_phone`, `contact_telegram`, `terms_location`, `terms_relocation`, `terms_salary_minimum` при `ordinal` 0) или элемент списка (`stack` до 30, `role` до 9, `experience` до 20, `soft_skill` до 10 по позиции). Столбцы: `value` jsonb, `status` (`confirmed` или `extracted`), `origin` (`manual`, `extracted_from_resume`, `imported`), `trust_level`, `quote`, `extraction_version` и `confirmed_at`. Поле без значения строки не имеет, поэтому `unknown` контракта - это отсутствие строки. Внешний ключ ведет на `candidate_profiles` с `ON DELETE CASCADE`.
Решения:
- Заявления, а не столбцы. У каждого значения есть статус, источник и время подтверждения, поэтому одна таблица заявлений вместо пятидесяти столбцов; форму значения (строка, булево или объект) держит jsonb, а у каждого вида есть свой CHECK формата и границ контракта (E.164 для телефона, `@` у Telegram, кратность 1000 у зарплаты, `YYYY-MM` и порядок периода у опыта, известные коды специализации и грейда). Домен проверяет значение полностью до записи, а `RestoreCandidateProfileContent` повторяет те же правила при чтении, поэтому строка, измененная вне приложения, отклоняется.
- Доверие 0 в схеме. `trust_level` хранится в столбце с `CHECK (trust_level = 0)`, а оператор вставки подставляет 0 сам и не принимает уровень от вызывающего. Подтвержденное значение требует `confirmed_at`, неподтвержденное предложение - нет и обязательно является импортом (`extraction_version` не NULL); ручное значение всегда подтверждено и не несет цитаты. Повышение доверия - свойство доказательств, которые хранятся не здесь.
- Нет подтвержденной категории. В таблицах нет столбца подтвержденного грейда или категории, а значение роли допускает только ключи `specialization` и `self_assessed_grade`, поэтому ни форма, ни импорт не могут записать подтвержденную категорию; она выводится из результатов оценки при чтении (`confirmed_categories`).
- Нет обязательной связи с файлом, ML или ФСП. В таблицах нет столбцов и внешних ключей к файлу резюме, хранилищу объектов, ML или аккаунту ФСП, а единственные внешние ключи - на `users` и на `candidate_profiles`. Профиль, набранный вручную, полон; будущий импорт добавит свои столбцы или таблицы аддитивно (`TestCandidateProfileStorage` проверяет набор столбцов и внешних ключей).
- Версия. `AdvanceCandidateProfileVersion` - один оператор, который увеличивает версию только когда сохраненная равна прочитанной вызывающим; для устаревшей версии строка не возвращается, и вызывающий отвечает 412 `version_conflict`. Время обновления считается как `GREATEST(сохраненное, текущее время приложения)`, поэтому отставшие часы экземпляра не нарушают CHECK `candidate_profiles_updated_after_creation` (иначе был бы 500). Монотонность версии обеспечивают только эти запросы: триггера нет, поэтому никакой другой код не должен писать `version`. `InsertCandidateProfile` с `ON CONFLICT DO NOTHING` отличает проигранное первое сохранение (параллельные первые сохранения: одно выигрывает, остальные - конфликт версии). Замена набора заявлений (удалить все и вставить новые) идет в одной транзакции вместе с продвижением версии. `domain.CandidateProfile.Replace(input, expectedVersion, at)` задает порядок: версия выше текущей - конфликт; правила тела - 400; решение `extracted`, зависящее от сохраненных заявлений, при устаревшей версии - `ErrCandidateProfileVersionConflict`, а не 400; тело без изменений - без продвижения версии; иное изменение по устаревшей версии - конфликт.
- Согласованное чтение. `ReadCandidateProfile` читает строку профиля и все заявления одним оператором (LEFT JOIN), то есть из одного снимка; два отдельных запроса могли бы вернуть версию N с заявлениями N+1 при сохранении между ними. Адаптер обязан использовать только этот запрос и не заменять его двумя; запись читает профиль в той же транзакции, что и замена, а защиту от потерянной правки дает условие версии.
- Приватность. Значения - ПДн кандидата: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent` и `CandidateProfile` скрывают себя в выводе `fmt` и `slog`, `CandidateProfile` логирует только идентификатор аккаунта и версию, ошибки домена называют поле и правило, но не значение, а метки метрик никогда не берутся из профиля. Ни один запрос не выбирает профиль чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер никогда не логирует и не оборачивает `pgconn.PgError.Detail` (там строка с именами и телефонами) и сообщает только SQLSTATE и имя ограничения, как адаптер организаций.
## Frontend
Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.
+18
View File
@@ -352,6 +352,24 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
`TestPostgresMigrations` откатывает миграцию 00010 вместе с остальными, проверяет, что три ее таблицы и функция исчезают, а таблицы identity остаются, и проверяет их снова после второго применения. Тесты, очищающие `users`, называют `usersDependentTables` (таблицы identity, доставок, согласий и организаций) - единственный список, который нужно расширять, когда миграция добавляет таблицу со ссылкой на users. Набор не покрывает usecase, обработчики, сопоставление сессии и CSRF и утверждение, что контракт соблюдается сквозным путем, потому что ничего из этого еще нет; атомарность чтения организации с представителями одним оператором тестом не доказана, потому что окно между двумя операторами нельзя воспроизвести детерминированно.
## Тесты профиля кандидата
Модульные тесты (`make -C backend test`) проверяют правила профиля без базы данных:
- `internal/domain/candidate_test.go`: ручные значения получают источник `manual`, уровень доверия 0 и время сохранения; поле, посланное как null, удаляется, а список заменяется; предложение импорта остается неподтвержденным при `extracted` с тем же значением, подтверждается при `confirmed` с сохранением источника и цитаты, становится ручным при другом значении, а `extracted` для значения, которого нет среди предложений, и возврат подтвержденного значения в предложение отклоняются с указателем `/stack/1/status`; таблица значений называет поле, которое нарушило правило (телефон вне E.164, Telegram без `@`, имя с пробелами, зарплата не кратна 1000, неизвестные специализация и грейд, повтор тега без учета регистра, повтор специализации роли, месяц не в формате `YYYY-MM`, период, который кончается раньше начала или лежит в будущем, слишком много элементов); ошибка не содержит присланного значения; тело без изменений не меняет профиль и время подтверждения; строки хранилища (`StoredClaims`) восстанавливаются в то же содержимое в любом порядке, а строка с неизвестным видом, уровнем доверия выше 0, цитатой у ручного значения, значением чужого типа, лишним ключом `confirmed_grade`, пропуском в списке или повтором отклоняется; типы профиля не имеют полей подтвержденного грейда, категории или уровня доверия; значения скрыты в выводе `fmt` и `slog`.
- `internal/adapter/primary/http/candidate_profile_contract_test.go`: по бандлу контракта операции следуют соглашениям (сессия и CSRF для сохранения, версия в теле, нет Idempotency-Key и If-Match, 412 вместо 409, `no-store`); запрос не несет подтвержденную категорию, источник, уровень доверия и время подтверждения, а все схемы профиля закрывают объекты; каждое заявление несет `status` и `source`, а `trust_level` ограничен нулем; имя использует `ContactFullName`; **ни одна схема вне семейства профиля, ни одна операция организации не достигает схемы профиля по ссылкам, и профиль не ссылается на схемы организации, приглашения или потребности**; через сгенерированный сервер схема отклоняет присланную клиентом категорию, источник и неизвестные поля до реализации, а допустимый профиль отвечает 501, при отклоненной сессии - 401.
- `frontend/src/shared/api/profile-contract.test.ts`: сгенерированные схемы Zod принимают полный профиль и профиль без единого значения (то есть без файла и ФСП), требуют `expected_version`, отклоняют каждый нарушенный формат и лишние элементы списков, не пропускают в разобранное тело подтвержденный грейд, категорию и источник, требуют у каждого заявления источник с уровнем доверия 0, а типы запросов не имеют этих полей; сгенерированные файлы организации, приглашения и потребности не содержат ключей профиля, и наоборот.
`TestCandidateProfileStorage` в `backend/integration_test/candidate_profile_test.go` использует `bootstrap(t, postgresService)` с мигрированной схемой; `candidateProfileTables` входят в `usersDependentTables`, поэтому остальные тесты очищают их вместе с `users`:
- Сохранение без файла, ML и ФСП: профиль только с именем, а также строка профиля без единого заявления сохраняются и читаются, а полный профиль возвращается с тем же содержимым и источником через `StoredClaims` и `RestoreCandidateProfile`; сохраненное предложение импорта читается с цитатой, версией извлечения и уровнем 0.
- Схема: столбцы двух таблиц равны ожидаемому списку (без файла, ФСП, подтвержденного грейда и категории), а единственные внешние ключи ведут на аккаунт и на строку профиля.
- Ограничения через прямой SQL: каждое правило отказывает строке с собственным ограничением (уровень доверия выше 0, неизвестные вид, статус и источник, одиночное поле с позицией, список за пределом, подтверждение без времени, ручное значение с цитатой, импорт без версии извлечения, неверные значения тега, телефона, Telegram, переезда, зарплаты, роли с ключом `confirmed_grade` и опыта); повтор тега, навыка и специализации роли, профиль без аккаунта, версия 0 и заявление без профиля тоже отклоняются, а такая же корректная строка принимается.
- Удаление аккаунта удаляет профиль и заявления; два аккаунта хранят профили независимо.
- Версия: проигравшее второе первое сохранение и устаревшая версия не возвращают строку, восемь продвижений от одной версии и восемь параллельных первых сохранений на своих соединениях дают ровно один успех, а продвижение с более ранним временем приложения сохраняет время обновления и не нарушает CHECK. Чтение идет одним запросом `ReadCandidateProfile`.
`TestCandidateProfileMigrationRollsBack` откатывает миграцию 00013 на изолированной базе, проверяет, что обе таблицы исчезают, а `users` остается.
## Тесты банка заданий
`backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. С in-memory подделками репозитория и единицы работы usecase-тесты доказывают: одновременный идентичный импорт сообщает версию как неизмененную, а одновременный импорт с другим содержимым отклоняется; sentinel-ошибки гонок базы становятся отказами с подходящей причиной; публикация после взятия блокировки категории выводит из обращения более старую опубликованную версию и отклоняется, если опубликована более новая; открытие требует действующую версию политики; доступность отклоняется, когда число опубликованных семейств падает ниже требования открытия или когда версия политики открытия больше не действует; более старый одобренный черновик отклоняется, пока существует более новая версия: черновик, опубликованная или выведенная из обращения. `internal/adapter/secondary/postgres/assessment_bank_test.go` проверяет, что ограничения банка преобразуются в свои sentinel-ошибки без строки с нарушением, что страница списка вне предела падает до любого запроса и что блокировка категории отклоняется вне транзакции.
+21 -4
View File
@@ -138,17 +138,34 @@ describe("rewriteMockSource", () => {
);
});
it("fails when the schemas disagree on the bounds", () => {
const ambiguous = buildPatternBoundsIndex({
it("uses the common bounds when schemas share a property name and a pattern", () => {
const shared = buildPatternBoundsIndex({
components: {
schemas: {
A: { properties: { id: { type: "string", maxLength: 8, pattern: "^a+$" } } },
A: {
properties: { id: { type: "string", minLength: 1, maxLength: 8, pattern: "^a+$" } },
},
B: { properties: { id: { type: "string", maxLength: 9, pattern: "^a+$" } } },
},
},
});
const source = `${header}\nexport const m = () => ({id: faker.helpers.fromRegExp("^a+$")})\n`;
expect(() => rewrite(source, ambiguous)).toThrow("so the mock bounds are ambiguous");
expect(rewrite(source, shared).text).toContain(
'fakeFromPattern("^a+$", {minLength: 1, maxLength: 8})',
);
});
it("fails when the bounds of schemas have no common value", () => {
const disjoint = buildPatternBoundsIndex({
components: {
schemas: {
A: { properties: { id: { type: "string", maxLength: 3, pattern: "^a+$" } } },
B: { properties: { id: { type: "string", minLength: 5, pattern: "^a+$" } } },
},
},
});
const source = `${header}\nexport const m = () => ({id: faker.helpers.fromRegExp("^a+$")})\n`;
expect(() => rewrite(source, disjoint)).toThrow("so the mock bounds are ambiguous");
});
it("fails on a call that it cannot attribute to a property", () => {
+21 -5
View File
@@ -13,7 +13,8 @@
// src/shared/api/mock-pattern.ts. The bounds come from the OpenAPI document:
// the call's enclosing object property and the pattern identify the schema.
// The rewrite fails when a call has an unexpected form, when no schema
// matches, or when schemas that match disagree on the bounds, so a contract
// matches, or when the bounds of schemas that match have no common value;
// schemas that match with different bounds share their intersection, so a contract
// change cannot silently produce invalid mocks. Running it again on its own
// output changes nothing.
//
@@ -207,14 +208,29 @@ function findBounds(
`${location}: no schema property "${property}" with pattern ${JSON.stringify(pattern)} in the OpenAPI document.`,
);
}
if (candidates.length > 1) {
if (candidates.length === 1) {
return bounds;
}
// The generated mock does not say which schema owns the call, so schemas
// that share a property name and a pattern share one set of bounds: the
// intersection. A value inside it satisfies every one of those schemas.
const minLength = Math.max(...candidates.map((item) => item.minLength ?? 0));
const maxima = candidates.flatMap((item) =>
item.maxLength === undefined ? [] : [item.maxLength],
);
const maxLength = maxima.length === 0 ? undefined : Math.min(...maxima);
if (maxLength !== undefined && minLength > maxLength) {
throw new Error(
`${location}: properties named "${property}" with pattern ${JSON.stringify(pattern)} have different length bounds (${candidates
`${location}: properties named "${property}" with pattern ${JSON.stringify(pattern)} have length bounds (${candidates
.map(describeBounds)
.join("; ")}), so the mock bounds are ambiguous.`,
.join("; ")}) that no value satisfies together, so the mock bounds are ambiguous.`,
);
}
return bounds;
const anyMin = candidates.some((item) => item.minLength !== undefined);
return {
...(anyMin ? { minLength } : {}),
...(maxLength === undefined ? {} : { maxLength }),
};
}
/**
@@ -22,7 +22,10 @@ import type {
import type {
CandidateExperience,
CandidateProfile,
CandidateQuestionnaire,
ProfileClaimSource,
ProfileSalaryMinimum,
WorkContext
} from '../../schemas';
@@ -39,6 +42,18 @@ export const getSaveMyQuestionnaireResponseWorkContextMock = (overrideResponse:
export const getSaveMyQuestionnaireResponseMock = (overrideResponse: Partial<Extract<CandidateQuestionnaire, object>> = {}): 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(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), task_languages: faker.helpers.arrayElements(['python','go'] as const), stack: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}))), 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 getGetMyProfileResponseProfileClaimSourceMock = (overrideResponse: Partial<ProfileClaimSource> = {}): ProfileClaimSource => ({...{origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}, ...overrideResponse});
export const getGetMyProfileResponseProfileSalaryMinimumMock = (overrideResponse: Partial<ProfileSalaryMinimum> = {}): ProfileSalaryMinimum => ({...{amount: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse});
export const getGetMyProfileResponseMock = (overrideResponse: Partial<Extract<CandidateProfile, object>> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {location: {stLine truncated
export const getSaveMyProfileResponseProfileClaimSourceMock = (overrideResponse: Partial<ProfileClaimSource> = {}): ProfileClaimSource => ({...{origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}, ...overrideResponse});
export const getSaveMyProfileResponseProfileSalaryMinimumMock = (overrideResponse: Partial<ProfileSalaryMinimum> = {}): ProfileSalaryMinimum => ({...{amount: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse});
export const getSaveMyProfileResponseMock = (overrideResponse: Partial<Extract<CandidateProfile, object>> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {locationLine truncated
export const getGetMyQuestionnaireMockHandler = (overrideResponse?: CandidateQuestionnaire | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<CandidateQuestionnaire> | CandidateQuestionnaire), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/questionnaire', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
@@ -63,7 +78,33 @@ export const getSaveMyQuestionnaireMockHandler = (overrideResponse?: CandidateQu
})
}, options)
}
export const getGetMyProfileMockHandler = (overrideResponse?: CandidateProfile | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<CandidateProfile> | CandidateProfile), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/profile', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetMyProfileResponseMock(),
{ status: 200
})
}, options)
}
export const getSaveMyProfileMockHandler = (overrideResponse?: CandidateProfile | ((info: Parameters<Parameters<typeof http.put>[1]>[0]) => Promise<CandidateProfile> | CandidateProfile), options?: RequestHandlerOptions) => {
return http.put('*/api/v1/me/profile', async (info: Parameters<Parameters<typeof http.put>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getSaveMyProfileResponseMock(),
{ status: 200
})
}, options)
}
export const getCandidateMock = () => [
getGetMyQuestionnaireMockHandler(),
getSaveMyQuestionnaireMockHandler()
getSaveMyQuestionnaireMockHandler(),
getGetMyProfileMockHandler(),
getSaveMyProfileMockHandler()
]
@@ -24,6 +24,8 @@ import type {
} from '@tanstack/react-query';
import type {
CandidateProfile,
CandidateProfileUpdate,
CandidateQuestionnaire,
CandidateQuestionnaireUpdate,
Problem
@@ -253,3 +255,210 @@ export const useSaveMyQuestionnaire = <TError = ErrorType<Problem>,
> => {
return useMutation(getSaveMyQuestionnaireMutationOptions(options), queryClient);
}
export const getGetMyProfileUrl = () => {
return `/api/v1/me/profile`
}
/**
* 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 profile yet gets 200 with version 0, every single field `unknown`, and empty lists rather than 404, so the client reads the version for the first save in the same way as for later ones and a missing profile is not an error state.
*
* The profile is personal data that only its owner reads: full name, contacts, work history, and the lowest salary. It is a private resource and never an organization-visible one; organizations see a candidate through the anonymous card and, after an accepted invitation, through the contact grant, and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and the server never writes its values to logs, metrics, URLs, or events.
*
* Every value carries its confirmation state and provenance, and every claim has trust level 0. The self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results establish and which no request writes. The profile needs no file, no ML extraction, and no FSP account.
*
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
* @summary Read the private profile of the current candidate.
*/
export const getMyProfile = async ( options?: Parameters<typeof apiRequest>[1]): Promise<CandidateProfile> => {
return apiRequest<CandidateProfile>(getGetMyProfileUrl(),
{
...options,
method: 'GET'
}
);}
export const getGetMyProfileQueryKey = () => {
return [
`/api/v1/me/profile`
] as const;
}
export const getGetMyProfileQueryOptions = <TData = Awaited<ReturnType<typeof getMyProfile>>, TError = ErrorType<Problem>>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyProfile>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetMyProfileQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof getMyProfile>>> = ({ signal }) => getMyProfile({ signal, ...requestOptions });
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getMyProfile>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetMyProfileQueryResult = NonNullable<Awaited<ReturnType<typeof getMyProfile>>>
export type GetMyProfileQueryError = ErrorType<Problem>
export function useGetMyProfile<TData = Awaited<ReturnType<typeof getMyProfile>>, TError = ErrorType<Problem>>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyProfile>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyProfile>>,
TError,
Awaited<ReturnType<typeof getMyProfile>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyProfile<TData = Awaited<ReturnType<typeof getMyProfile>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyProfile>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getMyProfile>>,
TError,
Awaited<ReturnType<typeof getMyProfile>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetMyProfile<TData = Awaited<ReturnType<typeof getMyProfile>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyProfile>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Read the private profile of the current candidate.
*/
export function useGetMyProfile<TData = Awaited<ReturnType<typeof getMyProfile>>, TError = ErrorType<Problem>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getMyProfile>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetMyProfileQueryOptions(options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
export const getSaveMyProfileUrl = () => {
return `/api/v1/me/profile`
}
/**
* 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 of every field and list; see CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole.
*
* Every field is optional in substance: a profile can be saved with any subset filled and the rest null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or link. Which fields are needed to leave the onboarding step candidate_profile is an open product question that this contract does not decide; a save on that step advancing the account to candidate_questionnaire is planned.
*
* Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level, confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed grade never becomes a confirmed grade or a category.
*
* 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, and the client reads the profile again and reapplies its edits, so a concurrent edit from another tab or device is never lost silently. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for the questionnaire; the status and code are the same as for a failed If-Match.
*
* The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose values equal the stored ones, with the same decisions, changes nothing, keeps the version, and answers 200 with the current profile even when `expected_version` is older, so a retry after a lost response of a successful save succeeds instead of failing with 412. A version above the current one never existed and always answers 412 version_conflict, even for an unchanged body.
*
* The save replaces the stored claims as a whole. A suggestion that an import stored and that the client did not render and send back with the decision `extracted` is dropped by the save; a client therefore sends every suggestion that it received, and a client that read an older version gets 412 instead of silently dropping a suggestion it never saw.
*
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), domain rules that depend on the body alone (400), then the rules that depend on the stored claims against the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when `expected_version` is stale, because another save may have confirmed that value, and 400 when it is current; an unchanged body (200); any other change over a stale version (412). The schema rejects an unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is not a positive multiple of 1000, and more items than a list allows. The server also rejects a repeated tag, skill, or role specialization, a period that ends before it starts or lies in the future, and a decision `extracted` for a value that is not a stored suggestion, with 400 validation_failed and pointers to the items, for example `/roles/1/specialization` or `/stack/1/status`. Error bodies never repeat a submitted value.
* @summary Replace the private profile of the current candidate.
*/
export const saveMyProfile = async (candidateProfileUpdate: CandidateProfileUpdate, options?: Parameters<typeof apiRequest>[1]): Promise<CandidateProfile> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
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<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<CandidateProfile>(getSaveMyProfileUrl(),
{
...options,
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) },
body: JSON.stringify(candidateProfileUpdate)
}
);}
export const getSaveMyProfileMutationKey = () => ['saveMyProfile'] as const;
export const getSaveMyProfileMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof saveMyProfile>>, TError,SaveMyProfileMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof saveMyProfile>>, TError,SaveMyProfileMutationVariables, TContext> => {
const mutationKey = getSaveMyProfileMutationKey();
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<Awaited<ReturnType<typeof saveMyProfile>>, SaveMyProfileMutationVariables> = (props) => {
const {data} = props ?? {};
return saveMyProfile(data,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type SaveMyProfileMutationResult = NonNullable<Awaited<ReturnType<typeof saveMyProfile>>>
export type SaveMyProfileMutationBody = CandidateProfileUpdate
export type SaveMyProfileMutationError = ErrorType<Problem>
export type SaveMyProfileMutationVariables = {data: CandidateProfileUpdate}
/**
* @summary Replace the private profile of the current candidate.
*/
export const useSaveMyProfile = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof saveMyProfile>>, TError,SaveMyProfileMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof saveMyProfile>>,
TError,
SaveMyProfileMutationVariables,
TContext
> => {
return useMutation(getSaveMyProfileMutationOptions(options), queryClient);
}
@@ -0,0 +1,406 @@
import { readFileSync, readdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, expectTypeOf, it } from "vitest";
import { saveMyProfile } from "./endpoints/candidate/candidate";
import {
CandidateProfile,
CandidateProfileUpdate,
ProfileClaimSource,
ProfileConfirmedCategory,
ProfileRoleItem,
ProfileRoleItemInput,
SaveMyProfileBody,
} from "./schemas";
// These tests pin the generated candidate profile contract (TASK-066) that
// the profile form consumes. They fail when regeneration drops a limit, lets a
// request carry a confirmed grade, a category, or provenance, loses the trust
// level of a claim, or mixes the private profile with organization DTOs.
const manual = (confirmedAt = "2026-10-05T09:30:00Z") => ({
origin: "manual",
trust_level: 0,
quote: null,
extraction_version: null,
confirmed_at: confirmedAt,
});
const suggestion = {
origin: "extracted_from_resume",
trust_level: 0,
quote: "Tel.: +7 900 000-00-00",
extraction_version: "resume-rules.2026-10.1",
confirmed_at: null,
};
// without returns a copy of an object that lacks one key.
function without<T extends object>(value: T, key: string): Record<string, unknown> {
return Object.fromEntries(Object.entries(value).filter(([name]) => name !== key));
}
const unknownClaim = { status: "unknown", value: null, source: null } as const;
const validUpdate = {
expected_version: 0,
full_name: { value: "Anna Sokolova", status: "confirmed" },
contacts: {
email: { value: "anna.sokolova@example.com", status: "confirmed" },
phone: { value: "+79000000000", status: "extracted" },
telegram: null,
},
stack: [
{ tag: "PostgreSQL", status: "confirmed" },
{ tag: "Kafka", status: "extracted" },
],
roles: [{ specialization: "backend", self_assessed_grade: "middle", status: "confirmed" }],
experience: [
{
employer_name: "Example Payments",
specialization: "backend",
started_on: "2022-03",
ended_on: null,
summary: "Moved the payout service to an event model.",
status: "confirmed",
},
],
soft_skills: [{ skill: "Mentoring", status: "confirmed" }],
terms: {
location: { value: "Kazan", status: "confirmed" },
relocation: { value: false, status: "confirmed" },
salary_minimum: {
value: { amount: 180000, currency: "RUB", period: "month", tax_basis: "net" },
status: "confirmed",
},
},
};
const emptyUpdate = {
expected_version: 3,
full_name: null,
contacts: { email: null, phone: null, telegram: null },
stack: [],
roles: [],
experience: [],
soft_skills: [],
terms: { location: null, relocation: null, salary_minimum: null },
};
const profile = {
version: 3,
full_name: { status: "confirmed", value: "Anna Sokolova", source: manual() },
contacts: {
email: unknownClaim,
phone: { status: "extracted", value: "+79000000000", source: suggestion },
telegram: unknownClaim,
},
stack: [{ tag: "PostgreSQL", status: "confirmed", source: manual() }],
roles: [
{
specialization: "backend",
self_assessed_grade: "middle",
status: "confirmed",
source: manual(),
},
],
experience: [],
soft_skills: [],
terms: { location: unknownClaim, relocation: unknownClaim, salary_minimum: unknownClaim },
confirmed_categories: [
{
specialization: "backend",
grade: "junior",
confirmed_at: "2026-10-04T18:10:00Z",
attempt_id: "0192b3c4-d5e6-7f80-9a1b-2c3d4e5f6a7b",
},
],
updated_at: "2026-10-05T09:30:00Z",
};
const bodySchemas = [
["CandidateProfileUpdate", CandidateProfileUpdate],
["SaveMyProfileBody", SaveMyProfileBody],
] as const;
describe.each(bodySchemas)("generated %s", (_name, schema) => {
it("accepts a manual profile with a kept suggestion", () => {
const parsed = schema.parse(validUpdate);
expect(parsed.contacts.phone?.status).toBe("extracted");
expect(parsed.roles[0]?.self_assessed_grade).toBe("middle");
});
it("accepts a profile with nothing set, so no file or FSP link is required", () => {
expect(schema.parse(emptyUpdate)).toEqual(emptyUpdate);
});
it("requires the version that the client read", () => {
const withoutVersion = without(validUpdate, "expected_version");
const result = schema.safeParse(withoutVersion);
expect(result.success).toBe(false);
expect(result.error?.issues).toEqual([expect.objectContaining({ path: ["expected_version"] })]);
});
it.each([
[
"a phone outside E.164",
{ contacts: { ...validUpdate.contacts, phone: { value: "8 900 000", status: "confirmed" } } },
["contacts", "phone", "value"],
],
[
"a Telegram name without @",
{ contacts: { ...validUpdate.contacts, telegram: { value: "anna", status: "confirmed" } } },
["contacts", "telegram", "value"],
],
[
"an email that is not an address",
{ contacts: { ...validUpdate.contacts, email: { value: "anna", status: "confirmed" } } },
["contacts", "email", "value"],
],
[
"a decision outside confirmed and extracted",
{ stack: [{ tag: "Go", status: "unknown" }] },
["stack", 0, "status"],
],
[
"a name with surrounding whitespace",
{ full_name: { value: " Anna", status: "confirmed" } },
["full_name", "value"],
],
[
"a grade outside the scale",
{ roles: [{ specialization: "backend", self_assessed_grade: "lead", status: "confirmed" }] },
["roles", 0, "self_assessed_grade"],
],
[
"a language used as a specialization",
{ roles: [{ specialization: "go", self_assessed_grade: null, status: "confirmed" }] },
["roles", 0, "specialization"],
],
[
"a month outside YYYY-MM",
{ experience: [{ ...validUpdate.experience[0], started_on: "2022-3" }] },
["experience", 0, "started_on"],
],
[
"a salary that is not a multiple of 1000",
{
terms: {
...validUpdate.terms,
salary_minimum: {
value: { amount: 180500, currency: "RUB", period: "month", tax_basis: "net" },
status: "confirmed",
},
},
},
["terms", "salary_minimum", "value", "amount"],
],
[
"a salary in another currency",
{
terms: {
...validUpdate.terms,
salary_minimum: {
value: { amount: 180000, currency: "USD", period: "month", tax_basis: "net" },
status: "confirmed",
},
},
},
["terms", "salary_minimum"],
],
])("rejects %s", (_label, change, path) => {
const result = schema.safeParse({ ...validUpdate, ...change });
expect(result.success).toBe(false);
expect(result.error?.issues).toContainEqual(expect.objectContaining({ path }));
});
it("rejects more items than a list allows instead of truncating it", () => {
const stack = Array.from({ length: 31 }, (_, index) => ({
tag: `Tag ${index}`,
status: "confirmed",
}));
const roles = Array.from({ length: 10 }, () => ({
specialization: "qa",
self_assessed_grade: null,
status: "confirmed",
}));
const tooManyTags = schema.safeParse({ ...validUpdate, stack });
const tooManyRoles = schema.safeParse({ ...validUpdate, roles });
expect(tooManyTags.error?.issues).toEqual([
expect.objectContaining({ code: "too_big", path: ["stack"] }),
]);
expect(tooManyRoles.error?.issues).toEqual([
expect.objectContaining({ code: "too_big", path: ["roles"] }),
]);
});
it("never carries a confirmed grade, a category, or provenance in the parsed body", () => {
const parsed = schema.parse({
...validUpdate,
confirmed_categories: [{ specialization: "backend", grade: "senior" }],
full_name: {
value: "Anna Sokolova",
status: "confirmed",
source: suggestion,
trust_level: 5,
},
roles: [
{
specialization: "backend",
self_assessed_grade: "senior",
status: "confirmed",
confirmed_grade: "senior",
category: "backend",
},
],
});
// Generated Zod strips unknown keys; the server rejects them with 400.
expect(parsed).not.toHaveProperty("confirmed_categories");
expect(parsed.full_name).not.toHaveProperty("source");
expect(parsed.full_name).not.toHaveProperty("trust_level");
expect(parsed.roles[0]).not.toHaveProperty("confirmed_grade");
expect(parsed.roles[0]).not.toHaveProperty("category");
});
});
describe("generated CandidateProfile", () => {
it("separates the self-assessed grade of a role from the confirmed category", () => {
const parsed = CandidateProfile.parse(profile);
expect(parsed.roles[0]?.self_assessed_grade).toBe("middle");
expect(parsed.confirmed_categories).toEqual([
expect.objectContaining({ specialization: "backend", grade: "junior" }),
]);
expect(parsed.roles[0]).not.toHaveProperty("confirmed_grade");
});
it("gives every claim a source with trust level 0", () => {
expect(ProfileClaimSource.safeParse(suggestion).success).toBe(true);
expect(ProfileClaimSource.safeParse(manual()).success).toBe(true);
expect(ProfileClaimSource.safeParse({ ...suggestion, trust_level: 1 }).success).toBe(false);
expect(ProfileClaimSource.safeParse({ ...manual(), origin: "verified" }).success).toBe(false);
const withoutSource = without(profile.stack[0] ?? {}, "source");
expect(CandidateProfile.safeParse({ ...profile, stack: [withoutSource] }).success).toBe(false);
});
it("keeps an unconfirmed suggestion apart from a confirmed value", () => {
const parsed = CandidateProfile.parse(profile);
expect(parsed.contacts.phone.status).toBe("extracted");
expect(parsed.contacts.phone.source?.confirmed_at).toBeNull();
expect(parsed.contacts.phone.source?.trust_level).toBe(0);
expect(parsed.full_name.source?.confirmed_at).toBe("2026-10-05T09:30:00Z");
});
it("represents a profile that was never saved as version 0 with unknown fields", () => {
const parsed = CandidateProfile.parse({
version: 0,
full_name: unknownClaim,
contacts: { email: unknownClaim, phone: unknownClaim, telegram: unknownClaim },
stack: [],
roles: [],
experience: [],
soft_skills: [],
terms: { location: unknownClaim, relocation: unknownClaim, salary_minimum: unknownClaim },
confirmed_categories: [],
updated_at: null,
});
expect(parsed.version).toBe(0);
expect(parsed.confirmed_categories).toEqual([]);
});
it("requires a confirmed category to name its assessment", () => {
const withoutAttempt = without(profile.confirmed_categories[0] ?? {}, "attempt_id");
expect(ProfileConfirmedCategory.safeParse(profile.confirmed_categories[0]).success).toBe(true);
expect(ProfileConfirmedCategory.safeParse(withoutAttempt).success).toBe(false);
});
});
it("exposes the profile DTOs without a confirmed grade or a category in requests", () => {
type UpdateRole = CandidateProfileUpdate["roles"][number];
expectTypeOf<CandidateProfileUpdate>().not.toHaveProperty("confirmed_categories");
expectTypeOf<CandidateProfileUpdate>().not.toHaveProperty("version");
expectTypeOf<UpdateRole>().not.toHaveProperty("confirmed_grade");
expectTypeOf<UpdateRole>().not.toHaveProperty("category");
expectTypeOf<UpdateRole>().not.toHaveProperty("source");
expectTypeOf<ProfileRoleItemInput>().not.toHaveProperty("trust_level");
expectTypeOf<ProfileRoleItem>().not.toHaveProperty("confirmed_grade");
expectTypeOf<ProfileRoleItem>().not.toHaveProperty("category");
expectTypeOf<CandidateProfile>().toHaveProperty("confirmed_categories");
expectTypeOf(saveMyProfile).parameter(0).toEqualTypeOf<CandidateProfileUpdate>();
});
// The private profile holds personal data that no organization may read. The
// generated Zod files inline every referenced schema, so a profile schema that
// an organization-visible schema referred to would leave its field names in
// that generated file. The check reads the generated files: the organization,
// invitation, and need schemas and endpoints carry no profile-only field, and
// the profile schemas carry no organization-only field.
describe("private profile schemas", () => {
const apiDirectory = resolve(dirname(fileURLToPath(import.meta.url)));
const sourcesIn = (directory: string) =>
readdirSync(join(apiDirectory, directory), { recursive: true, encoding: "utf8" })
.filter((name) => name.endsWith(".ts"))
.map((name) => ({
name: join(directory, name),
source: readFileSync(join(apiDirectory, directory, name), "utf8"),
}));
const organizationSide = ["organization", "invitation", "need"].flatMap((tag) => [
...sourcesIn(join("schemas", tag)),
...sourcesIn(join("endpoints", tag)),
]);
const profileSide = sourcesIn(join("schemas", "candidate")).filter((file) =>
/(^|\/)(profile|candidateProfile|saveMyProfile)[^/]*\.zod\.ts$/.test(file.name),
);
// Generated object keys that only the private profile has. They are matched
// as quoted keys, because endpoint comments quote contract prose.
const profileOnly = [
'"confirmed_categories":',
'"salary_minimum":',
'"soft_skills":',
'"relocation":',
];
// Generated object keys that only organization-visible DTOs have.
const organizationOnly = [
'"verification_level":',
'"candidate_card":',
'"representatives":',
'"membership":',
];
it("finds the generated files of both sides", () => {
expect(profileSide.length).toBeGreaterThan(20);
expect(organizationSide.length).toBeGreaterThan(20);
});
it("is not reachable from an organization, invitation, or need schema or endpoint", () => {
const leaks = organizationSide.flatMap((file) =>
profileOnly
.filter((marker) => file.source.includes(marker))
.map((marker) => `${file.name}: ${marker}`),
);
expect(leaks).toEqual([]);
});
it("refers to nothing of an organization, an invitation, or a need", () => {
const leaks = profileSide.flatMap((file) =>
organizationOnly
.filter((marker) => file.source.includes(marker))
.map((marker) => `${file.name}: ${marker}`),
);
expect(leaks).toEqual([]);
});
});
@@ -16,7 +16,7 @@ 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.')
}).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. The work history entries of the candidate profile (`ProfileExperienceItem`) are a different, detailed claim: the two are saved separately and the server neither adds the entries up nor fills them from these totals.')
export type CandidateExperience = zod.input<typeof CandidateExperience>;
export type CandidateExperienceOutput = zod.output<typeof CandidateExperience>;
@@ -0,0 +1,317 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const candidateProfileVersionMin = 0;
export const candidateProfileFullNameValueOneMax = 200;
export const candidateProfileFullNameValueOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileFullNameSourceOneTrustLevelMin = 0;
export const candidateProfileFullNameSourceOneTrustLevelMax = 0;
export const candidateProfileFullNameSourceOneQuoteOneMax = 300;
export const candidateProfileFullNameSourceOneExtractionVersionOneMax = 64;
export const candidateProfileFullNameSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileContactsEmailValueOneMin = 3;
export const candidateProfileContactsEmailValueOneMax = 254;
export const candidateProfileContactsEmailSourceOneTrustLevelMin = 0;
export const candidateProfileContactsEmailSourceOneTrustLevelMax = 0;
export const candidateProfileContactsEmailSourceOneQuoteOneMax = 300;
export const candidateProfileContactsEmailSourceOneExtractionVersionOneMax = 64;
export const candidateProfileContactsEmailSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileContactsPhoneValueOneMin = 8;
export const candidateProfileContactsPhoneValueOneMax = 16;
export const candidateProfileContactsPhoneValueOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
export const candidateProfileContactsPhoneSourceOneTrustLevelMin = 0;
export const candidateProfileContactsPhoneSourceOneTrustLevelMax = 0;
export const candidateProfileContactsPhoneSourceOneQuoteOneMax = 300;
export const candidateProfileContactsPhoneSourceOneExtractionVersionOneMax = 64;
export const candidateProfileContactsPhoneSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileContactsTelegramValueOneMin = 6;
export const candidateProfileContactsTelegramValueOneMax = 33;
export const candidateProfileContactsTelegramValueOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
export const candidateProfileContactsTelegramSourceOneTrustLevelMin = 0;
export const candidateProfileContactsTelegramSourceOneTrustLevelMax = 0;
export const candidateProfileContactsTelegramSourceOneQuoteOneMax = 300;
export const candidateProfileContactsTelegramSourceOneExtractionVersionOneMax = 64;
export const candidateProfileContactsTelegramSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileStackItemTagMax = 50;
export const candidateProfileStackItemTagRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileStackItemSourceTrustLevelMin = 0;
export const candidateProfileStackItemSourceTrustLevelMax = 0;
export const candidateProfileStackItemSourceQuoteOneMax = 300;
export const candidateProfileStackItemSourceExtractionVersionOneMax = 64;
export const candidateProfileStackItemSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileStackMax = 30;
export const candidateProfileRolesItemSourceTrustLevelMin = 0;
export const candidateProfileRolesItemSourceTrustLevelMax = 0;
export const candidateProfileRolesItemSourceQuoteOneMax = 300;
export const candidateProfileRolesItemSourceExtractionVersionOneMax = 64;
export const candidateProfileRolesItemSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileRolesMax = 9;
export const candidateProfileExperienceItemEmployerNameOneMax = 200;
export const candidateProfileExperienceItemEmployerNameOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileExperienceItemStartedOnMin = 7;
export const candidateProfileExperienceItemStartedOnMax = 7;
export const candidateProfileExperienceItemStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const candidateProfileExperienceItemEndedOnOneMin = 7;
export const candidateProfileExperienceItemEndedOnOneMax = 7;
export const candidateProfileExperienceItemEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const candidateProfileExperienceItemSummaryOneMax = 1000;
export const candidateProfileExperienceItemSourceTrustLevelMin = 0;
export const candidateProfileExperienceItemSourceTrustLevelMax = 0;
export const candidateProfileExperienceItemSourceQuoteOneMax = 300;
export const candidateProfileExperienceItemSourceExtractionVersionOneMax = 64;
export const candidateProfileExperienceItemSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileExperienceMax = 20;
export const candidateProfileSoftSkillsItemSkillMax = 50;
export const candidateProfileSoftSkillsItemSkillRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileSoftSkillsItemSourceTrustLevelMin = 0;
export const candidateProfileSoftSkillsItemSourceTrustLevelMax = 0;
export const candidateProfileSoftSkillsItemSourceQuoteOneMax = 300;
export const candidateProfileSoftSkillsItemSourceExtractionVersionOneMax = 64;
export const candidateProfileSoftSkillsItemSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileSoftSkillsMax = 10;
export const candidateProfileTermsLocationValueOneMax = 100;
export const candidateProfileTermsLocationValueOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileTermsLocationSourceOneTrustLevelMin = 0;
export const candidateProfileTermsLocationSourceOneTrustLevelMax = 0;
export const candidateProfileTermsLocationSourceOneQuoteOneMax = 300;
export const candidateProfileTermsLocationSourceOneExtractionVersionOneMax = 64;
export const candidateProfileTermsLocationSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileTermsRelocationSourceOneTrustLevelMin = 0;
export const candidateProfileTermsRelocationSourceOneTrustLevelMax = 0;
export const candidateProfileTermsRelocationSourceOneQuoteOneMax = 300;
export const candidateProfileTermsRelocationSourceOneExtractionVersionOneMax = 64;
export const candidateProfileTermsRelocationSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileTermsSalaryMinimumValueOneAmountMin = 1000;
export const candidateProfileTermsSalaryMinimumValueOneAmountMax = 100000000;
export const candidateProfileTermsSalaryMinimumValueOneAmountMultipleOf = 1000;
export const candidateProfileTermsSalaryMinimumSourceOneTrustLevelMin = 0;
export const candidateProfileTermsSalaryMinimumSourceOneTrustLevelMax = 0;
export const candidateProfileTermsSalaryMinimumSourceOneQuoteOneMax = 300;
export const candidateProfileTermsSalaryMinimumSourceOneExtractionVersionOneMax = 64;
export const candidateProfileTermsSalaryMinimumSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileConfirmedCategoriesMax = 9;
export const CandidateProfile = zod.object({
"version": zod.int().min(candidateProfileVersionMin).describe('Version of the candidate profile. A candidate who has not saved the profile has version 0; every save that changes the profile advances it by one. The client sends the version it read as `expected_version`.'),
"full_name": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(1).max(candidateProfileFullNameValueOneMax).regex(candidateProfileFullNameValueOneRegExp).describe('Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileFullNameSourceOneTrustLevelMin).max(candidateProfileFullNameSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileFullNameSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileFullNameSourceOneExtractionVersionOneMax).regex(candidateProfileFullNameSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Full name of the candidate with its confirmation state and provenance. The value is personal data. It is disclosed to one organization only through the contact grant of the consent C4 and never appears in an organization-visible schema. `value` and `source` are null exactly when `status` is `unknown`.'),
"contacts": zod.object({
"email": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.email().min(candidateProfileContactsEmailValueOneMin).max(candidateProfileContactsEmailValueOneMax).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.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileContactsEmailSourceOneTrustLevelMin).max(candidateProfileContactsEmailSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileContactsEmailSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileContactsEmailSourceOneExtractionVersionOneMax).regex(candidateProfileContactsEmailSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Contact email of the candidate with its confirmation state and provenance. It is personal data. It is a contact channel that the candidate gives, not the login of the account: the two may differ, the server never sends mail to it and never verifies it. `value` and `source` are null exactly when `status` is `unknown`.'),
"phone": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(candidateProfileContactsPhoneValueOneMin).max(candidateProfileContactsPhoneValueOneMax).regex(candidateProfileContactsPhoneValueOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileContactsPhoneSourceOneTrustLevelMin).max(candidateProfileContactsPhoneSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileContactsPhoneSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileContactsPhoneSourceOneExtractionVersionOneMax).regex(candidateProfileContactsPhoneSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Contact phone number of the candidate with its confirmation state and provenance. It is personal data, stored in the E.164 format of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`.'),
"telegram": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(candidateProfileContactsTelegramValueOneMin).max(candidateProfileContactsTelegramValueOneMax).regex(candidateProfileContactsTelegramValueOneRegExp).describe('Telegram username with the leading @.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileContactsTelegramSourceOneTrustLevelMin).max(candidateProfileContactsTelegramSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileContactsTelegramSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileContactsTelegramSourceOneExtractionVersionOneMax).regex(candidateProfileContactsTelegramSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Telegram username of the candidate with its confirmation state and provenance. It is personal data, stored with the leading @ of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`.')
}).describe('Contact channels of the candidate. Each channel is a claim of its own, and the candidate fills in any subset. The kinds are the ones that the contact disclosure (consent C4) can pass on, with the same value formats, so a disclosure never has to convert or drop a stored value; adding a kind, such as a link to a code repository, is a contract change in both places. Contacts leave the profile only through a contact grant, never in a card or a search result. All values are personal data.'),
"stack": zod.array(zod.object({
"tag": zod.string().min(1).max(candidateProfileStackItemTagMax).regex(candidateProfileStackItemTagRegExp).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.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.'),
"source": zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileStackItemSourceTrustLevelMin).max(candidateProfileStackItemSourceTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileStackItemSourceQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileStackItemSourceExtractionVersionOneMax).regex(candidateProfileStackItemSourceExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.')
}).describe('One technology tag of the candidate\'s stack with its confirmation state and provenance. The profile stack is one list for the whole profile; the questionnaire holds the tags of each chosen specialization with the same `StackTag` meaning, and the two lists are independent: the server never copies one into the other. A tag is a descriptive attribute and never forms a category.')).max(candidateProfileStackMax).describe('Technology tags in the order the candidate gave them, each tag at most once without regard to letter case.'),
"roles": 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.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that the candidate claims in the specialization, or null when the candidate names none.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.'),
"source": zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileRolesItemSourceTrustLevelMin).max(candidateProfileRolesItemSourceTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileRolesItemSourceQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileRolesItemSourceExtractionVersionOneMax).regex(candidateProfileRolesItemSourceExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.')
}).describe('One role of the candidate: a specialization of the catalog with the grade that the candidate claims for it. `self_assessed_grade` is a claim, the same one that the questionnaire calls `self_assessed_grade` for its at most two chosen specializations: it influences nothing but the display and never becomes a confirmed grade or a category. The questionnaire value starts the assessment and the profile value is what the profile shows; the two are saved separately and the server never copies one into the other. A confirmed grade comes only from an assessment result and appears in `confirmed_categories` of the profile, never in a role; unknown fields such as `confirmed_grade` or `category` are rejected.')).max(candidateProfileRolesMax).describe('Roles in the order the candidate gave them, each specialization at most once.'),
"experience": zod.array(zod.object({
"employer_name": zod.union([zod.string().min(1).max(candidateProfileExperienceItemEmployerNameOneMax).regex(candidateProfileExperienceItemEmployerNameOneRegExp).describe('Name of the employer in one experience entry, as the candidate wrote it. It is personal data of the candidate\'s career. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Employer of the entry, or null when the candidate gives none.'),
"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.'),
"started_on": zod.string().min(candidateProfileExperienceItemStartedOnMin).max(candidateProfileExperienceItemStartedOnMax).regex(candidateProfileExperienceItemStartedOnRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),
"ended_on": zod.union([zod.string().min(candidateProfileExperienceItemEndedOnOneMin).max(candidateProfileExperienceItemEndedOnOneMax).regex(candidateProfileExperienceItemEndedOnOneRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),zod.null()]).describe('Last month of the work, or null when the candidate still works there. It is not earlier than `started_on`.'),
"summary": zod.union([zod.string().min(1).max(candidateProfileExperienceItemSummaryOneMax).describe('Tasks and results of the candidate in one experience entry. It describes the work rather than a job title. It may contain line breaks and personal data of the candidate; it must not contain personal data of other people. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Tasks and results of the entry, or null when the candidate gives none.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.'),
"source": zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileExperienceItemSourceTrustLevelMin).max(candidateProfileExperienceItemSourceTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileExperienceItemSourceQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileExperienceItemSourceExtractionVersionOneMax).regex(candidateProfileExperienceItemSourceExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.')
}).describe('One entry of the candidate\'s work history with its confirmation state and provenance. An entry describes the work by its specialization and tasks rather than by a job title, and it is a claim of trust level 0. It is different from the `CandidateExperience` of the questionnaire, which holds only the total months of commercial and academic experience of a chosen specialization as a hint for the assessment: the two are saved separately, and the server neither adds the entries up for the questionnaire nor fills the entries from it. An entry is personal data.')).max(candidateProfileExperienceMax).describe('Work history entries in the order the candidate gave them.'),
"soft_skills": zod.array(zod.object({
"skill": zod.string().min(1).max(candidateProfileSoftSkillsItemSkillMax).regex(candidateProfileSoftSkillsItemSkillRegExp).describe('Soft skill as the candidate wrote it, for example "Mentoring" or "Negotiation". The platform has no soft skill taxonomy, so the text is free; it never changes a category or a grade. It has no leading or trailing whitespace and no line breaks. The server compares skills without regard to letter case. Plain text; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.'),
"source": zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileSoftSkillsItemSourceTrustLevelMin).max(candidateProfileSoftSkillsItemSourceTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileSoftSkillsItemSourceQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileSoftSkillsItemSourceExtractionVersionOneMax).regex(candidateProfileSoftSkillsItemSourceExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.')
}).describe('One soft skill of the candidate with its confirmation state and provenance. It is a claim; no assessment checks it.')).max(candidateProfileSoftSkillsMax).describe('Soft skills in the order the candidate gave them, each skill at most once without regard to letter case.'),
"terms": zod.object({
"location": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(1).max(candidateProfileTermsLocationValueOneMax).regex(candidateProfileTermsLocationValueOneRegExp).describe('City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileTermsLocationSourceOneTrustLevelMin).max(candidateProfileTermsLocationSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileTermsLocationSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileTermsLocationSourceOneExtractionVersionOneMax).regex(candidateProfileTermsLocationSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Place of the candidate with its confirmation state and provenance. It is personal data. `value` and `source` are null exactly when `status` is `unknown`.'),
"relocation": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.boolean().nullable(),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileTermsRelocationSourceOneTrustLevelMin).max(candidateProfileTermsRelocationSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileTermsRelocationSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileTermsRelocationSourceOneExtractionVersionOneMax).regex(candidateProfileTermsRelocationSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Whether the candidate is ready to relocate, with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; the server never assumes an answer.'),
"salary_minimum": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.object({
"amount": zod.int().min(candidateProfileTermsSalaryMinimumValueOneAmountMin).max(candidateProfileTermsSalaryMinimumValueOneAmountMax).multipleOf(candidateProfileTermsSalaryMinimumValueOneAmountMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(candidateProfileTermsSalaryMinimumSourceOneTrustLevelMin).max(candidateProfileTermsSalaryMinimumSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(candidateProfileTermsSalaryMinimumSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(candidateProfileTermsSalaryMinimumSourceOneExtractionVersionOneMax).regex(candidateProfileTermsSalaryMinimumSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Lowest acceptable salary with its confirmation state and provenance. It is personal data that no organization reads. `value` and `source` are null exactly when `status` is `unknown`; the server never substitutes zero or a market estimate.')
}).describe('Conditions that the candidate wants: the place, readiness to relocate, and the lowest salary. Acceptable work formats are not repeated here; they are the `work_formats` of the questionnaire `WorkContext`, the only place that holds them. These are the candidate\'s wishes, never the terms of an invitation, which an organization offers and which the invitation contract describes.'),
"confirmed_categories": zod.array(zod.object({
"specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),
"grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
"confirmed_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"attempt_id": zod.uuid().describe('Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate.')
}).describe('A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`.')).max(candidateProfileConfirmedCategoriesMax).describe('Categories that assessment results confirmed, at most one per specialization, in catalog order. Read-only and empty until an assessment confirms a grade.'),
"updated_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Time of the last change, or null before the first save.')
}).describe('The private profile of the current candidate: full name and contacts, stack, roles, work experience, soft skills, and desired terms, each value with its confirmation state and provenance. It is personal data that only the candidate reads. It is never an organization-visible schema: an organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant, and no organization schema refers to this one.\nEvery value is a claim of trust level 0. The `self_assessed_grade` of a role is what the candidate says; the `confirmed_categories` list is what assessment results established, and the two are never mixed. A candidate who has not saved the profile gets version 0, every single field `unknown`, empty lists, and null `updated_at`.\nThe profile is manual by nature and complete without a file: no field requires a resume, the ML service, or an FSP account, and a candidate with none of them has the same fields. Work formats live in the questionnaire; a candidate\'s assessment starts from the questionnaire, not from this profile.')
export type CandidateProfile = zod.input<typeof CandidateProfile>;
export type CandidateProfileOutput = zod.output<typeof CandidateProfile>;
@@ -0,0 +1,132 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const candidateProfileUpdateExpectedVersionMin = 0;
export const candidateProfileUpdateFullNameOneValueMax = 200;
export const candidateProfileUpdateFullNameOneValueRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileUpdateContactsEmailOneValueMin = 3;
export const candidateProfileUpdateContactsEmailOneValueMax = 254;
export const candidateProfileUpdateContactsPhoneOneValueMin = 8;
export const candidateProfileUpdateContactsPhoneOneValueMax = 16;
export const candidateProfileUpdateContactsPhoneOneValueRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
export const candidateProfileUpdateContactsTelegramOneValueMin = 6;
export const candidateProfileUpdateContactsTelegramOneValueMax = 33;
export const candidateProfileUpdateContactsTelegramOneValueRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
export const candidateProfileUpdateStackItemTagMax = 50;
export const candidateProfileUpdateStackItemTagRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileUpdateStackMax = 30;
export const candidateProfileUpdateRolesMax = 9;
export const candidateProfileUpdateExperienceItemEmployerNameOneMax = 200;
export const candidateProfileUpdateExperienceItemEmployerNameOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileUpdateExperienceItemStartedOnMin = 7;
export const candidateProfileUpdateExperienceItemStartedOnMax = 7;
export const candidateProfileUpdateExperienceItemStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const candidateProfileUpdateExperienceItemEndedOnOneMin = 7;
export const candidateProfileUpdateExperienceItemEndedOnOneMax = 7;
export const candidateProfileUpdateExperienceItemEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const candidateProfileUpdateExperienceItemSummaryOneMax = 1000;
export const candidateProfileUpdateExperienceMax = 20;
export const candidateProfileUpdateSoftSkillsItemSkillMax = 50;
export const candidateProfileUpdateSoftSkillsItemSkillRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileUpdateSoftSkillsMax = 10;
export const candidateProfileUpdateTermsLocationOneValueMax = 100;
export const candidateProfileUpdateTermsLocationOneValueRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateProfileUpdateTermsSalaryMinimumOneValueAmountMin = 1000;
export const candidateProfileUpdateTermsSalaryMinimumOneValueAmountMax = 100000000;
export const candidateProfileUpdateTermsSalaryMinimumOneValueAmountMultipleOf = 1000;
export const CandidateProfileUpdate = zod.object({
"expected_version": zod.int().min(candidateProfileUpdateExpectedVersionMin).describe('Version of the candidate profile. A candidate who has not saved the profile has version 0; every save that changes the profile advances it by one. The client sends the version it read as `expected_version`.'),
"full_name": zod.union([zod.object({
"value": zod.string().min(1).max(candidateProfileUpdateFullNameOneValueMax).regex(candidateProfileUpdateFullNameOneValueRegExp).describe('Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the full name in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"contacts": zod.object({
"email": zod.union([zod.object({
"value": zod.email().min(candidateProfileUpdateContactsEmailOneValueMin).max(candidateProfileUpdateContactsEmailOneValueMax).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.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the contact email in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"phone": zod.union([zod.object({
"value": zod.string().min(candidateProfileUpdateContactsPhoneOneValueMin).max(candidateProfileUpdateContactsPhoneOneValueMax).regex(candidateProfileUpdateContactsPhoneOneValueRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the contact phone number in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"telegram": zod.union([zod.object({
"value": zod.string().min(candidateProfileUpdateContactsTelegramOneValueMin).max(candidateProfileUpdateContactsTelegramOneValueMax).regex(candidateProfileUpdateContactsTelegramOneValueRegExp).describe('Telegram username with the leading @.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the Telegram username in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()])
}).describe('Decisions about the contact channels in a request. A channel sent as null is unknown: it is removed if it was set.'),
"stack": zod.array(zod.object({
"tag": zod.string().min(1).max(candidateProfileUpdateStackItemTagMax).regex(candidateProfileUpdateStackItemTagRegExp).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.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one stack tag in a request; see CandidateProfileUpdate for the rules of `status`.')).max(candidateProfileUpdateStackMax).describe('Technology tags. The schema limits the count; the server also answers 400 with the pointer of a tag that repeats an earlier one without regard to letter case, for example `/stack/2/tag`.'),
"roles": 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.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that the candidate claims, or null when the candidate names none.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one role in a request; see CandidateProfileUpdate for the rules of `status`. The object has no confirmed grade and no category: unknown fields are rejected.')).max(candidateProfileUpdateRolesMax).describe('Roles. The server answers 400 with the pointer of a role whose specialization repeats an earlier one, for example `/roles/1/specialization`.'),
"experience": zod.array(zod.object({
"employer_name": zod.union([zod.string().min(1).max(candidateProfileUpdateExperienceItemEmployerNameOneMax).regex(candidateProfileUpdateExperienceItemEmployerNameOneRegExp).describe('Name of the employer in one experience entry, as the candidate wrote it. It is personal data of the candidate\'s career. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"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.'),
"started_on": zod.string().min(candidateProfileUpdateExperienceItemStartedOnMin).max(candidateProfileUpdateExperienceItemStartedOnMax).regex(candidateProfileUpdateExperienceItemStartedOnRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),
"ended_on": zod.union([zod.string().min(candidateProfileUpdateExperienceItemEndedOnOneMin).max(candidateProfileUpdateExperienceItemEndedOnOneMax).regex(candidateProfileUpdateExperienceItemEndedOnOneRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),zod.null()]),
"summary": zod.union([zod.string().min(1).max(candidateProfileUpdateExperienceItemSummaryOneMax).describe('Tasks and results of the candidate in one experience entry. It describes the work rather than a job title. It may contain line breaks and personal data of the candidate; it must not contain personal data of other people. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one work history entry in a request; see CandidateProfileUpdate for the rules of `status`. The server also requires `ended_on` not to precede `started_on` and no month to lie in the future, and answers 400 with the pointer of the month.')).max(candidateProfileUpdateExperienceMax).describe('Work history entries.'),
"soft_skills": zod.array(zod.object({
"skill": zod.string().min(1).max(candidateProfileUpdateSoftSkillsItemSkillMax).regex(candidateProfileUpdateSoftSkillsItemSkillRegExp).describe('Soft skill as the candidate wrote it, for example "Mentoring" or "Negotiation". The platform has no soft skill taxonomy, so the text is free; it never changes a category or a grade. It has no leading or trailing whitespace and no line breaks. The server compares skills without regard to letter case. Plain text; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one soft skill in a request; see CandidateProfileUpdate for the rules of `status`.')).max(candidateProfileUpdateSoftSkillsMax).describe('Soft skills. The server answers 400 with the pointer of a skill that repeats an earlier one without regard to letter case.'),
"terms": zod.object({
"location": zod.union([zod.object({
"value": zod.string().min(1).max(candidateProfileUpdateTermsLocationOneValueMax).regex(candidateProfileUpdateTermsLocationOneValueRegExp).describe('City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the place in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"relocation": zod.union([zod.object({
"value": zod.boolean(),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about readiness to relocate in a request; see CandidateProfileUpdate for the rules of `status`.'),zod.null()]),
"salary_minimum": zod.union([zod.object({
"value": zod.object({
"amount": zod.int().min(candidateProfileUpdateTermsSalaryMinimumOneValueAmountMin).max(candidateProfileUpdateTermsSalaryMinimumOneValueAmountMax).multipleOf(candidateProfileUpdateTermsSalaryMinimumOneValueAmountMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the lowest salary in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()])
}).describe('Decisions about the desired terms in a request. A field sent as null is unknown: it is removed if it was set.')
}).describe('Complete new state of the candidate profile. It replaces every stored value as a whole: a single field sent as null is unknown and is removed, and a list replaces the stored list. The body is personal data.\nEach value carries a decision `status`. `confirmed` sets a manual value or confirms a stored suggestion; confirming a suggestion with exactly its stored value keeps its origin and quote, and any other value makes the claim manual. `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the stored value; any other use answers 400 with the pointer of that status, for example `/stack/1/status`. The provenance, the trust level, and the confirmed categories are not part of the request, and unknown fields are rejected, so a request can neither mark a claim as verified nor write a confirmed grade or a category.')
export type CandidateProfileUpdate = zod.input<typeof CandidateProfileUpdate>;
export type CandidateProfileUpdateOutput = zod.output<typeof CandidateProfileUpdate>;
@@ -37,11 +37,11 @@ export const CandidateQuestionnaire = zod.object({
"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.'),
}).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. The work history entries of the candidate profile (`ProfileExperienceItem`) are a different, detailed claim: the two are saved separately and the server neither adds the entries up nor fills them from these totals.'),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. The candidate profile states the same kind of claim in the `roles` of `CandidateProfile` (`ProfileRoleItem.self_assessed_grade`): the questionnaire value starts the assessment and the profile value is what the profile shows, the two are saved separately, and neither is ever a confirmed grade.')).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.'),
}).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 (`ProfileTerms`). The acceptable work formats live only here: the profile does not repeat them.'),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`.')
@@ -37,11 +37,11 @@ export const CandidateQuestionnaireUpdate = zod.object({
"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`.'),
}).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. The work history entries of the candidate profile (`ProfileExperienceItem`) are a different, detailed claim: the two are saved separately and the server neither adds the entries up nor fills them from these totals.'),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. The candidate profile states the same kind of claim in the `roles` of `CandidateProfile` (`ProfileRoleItem.self_assessed_grade`): the questionnaire value starts the assessment and the profile value is what the profile shows, the two are saved separately, and neither is ever a confirmed grade.')).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('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 (`ProfileTerms`). The acceptable work formats live only here: the profile does not repeat them.')
}).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<typeof CandidateQuestionnaireUpdate>;
@@ -6,10 +6,53 @@
*/
export * from './candidateExperience.zod';
export * from './candidateProfile.zod';
export * from './candidateProfileUpdate.zod';
export * from './candidateQuestionnaire.zod';
export * from './candidateQuestionnaireUpdate.zod';
export * from './profileClaimOrigin.zod';
export * from './profileClaimQuote.zod';
export * from './profileClaimSource.zod';
export * from './profileClaimStatus.zod';
export * from './profileClaimTrustLevel.zod';
export * from './profileConfirmedCategory.zod';
export * from './profileContacts.zod';
export * from './profileContactsInput.zod';
export * from './profileEmailClaim.zod';
export * from './profileEmailInput.zod';
export * from './profileEmployerName.zod';
export * from './profileExperienceItem.zod';
export * from './profileExperienceItemInput.zod';
export * from './profileExperienceSummary.zod';
export * from './profileFullNameClaim.zod';
export * from './profileFullNameInput.zod';
export * from './profileItemStatus.zod';
export * from './profileLocationClaim.zod';
export * from './profileLocationInput.zod';
export * from './profileLocationName.zod';
export * from './profilePhoneClaim.zod';
export * from './profilePhoneInput.zod';
export * from './profileRelocationClaim.zod';
export * from './profileRelocationInput.zod';
export * from './profileRoleItem.zod';
export * from './profileRoleItemInput.zod';
export * from './profileSalaryMinimum.zod';
export * from './profileSalaryMinimumClaim.zod';
export * from './profileSalaryMinimumInput.zod';
export * from './profileSoftSkill.zod';
export * from './profileSoftSkillItem.zod';
export * from './profileSoftSkillItemInput.zod';
export * from './profileStackItem.zod';
export * from './profileStackItemInput.zod';
export * from './profileTelegramClaim.zod';
export * from './profileTelegramInput.zod';
export * from './profileTerms.zod';
export * from './profileTermsInput.zod';
export * from './profileVersion.zod';
export * from './profileYearMonth.zod';
export * from './questionnaireSpecialization.zod';
export * from './questionnaireVersion.zod';
export * from './saveMyProfileBody.zod';
export * from './saveMyQuestionnaireBody.zod';
export * from './stackTag.zod';
export * from './workContext.zod';
@@ -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 ProfileClaimOrigin = zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.')
export type ProfileClaimOrigin = zod.input<typeof ProfileClaimOrigin>;
export type ProfileClaimOriginOutput = zod.output<typeof ProfileClaimOrigin>;
@@ -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 ProfileClaimQuoteMax = 300;
export const ProfileClaimQuote = zod.string().min(1).max(ProfileClaimQuoteMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.')
export type ProfileClaimQuote = zod.input<typeof ProfileClaimQuote>;
export type ProfileClaimQuoteOutput = zod.output<typeof ProfileClaimQuote>;
@@ -0,0 +1,28 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileClaimSourceTrustLevelMin = 0;
export const profileClaimSourceTrustLevelMax = 0;
export const profileClaimSourceQuoteOneMax = 300;
export const profileClaimSourceExtractionVersionOneMax = 64;
export const profileClaimSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileClaimSource = zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileClaimSourceTrustLevelMin).max(profileClaimSourceTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileClaimSourceQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileClaimSourceExtractionVersionOneMax).regex(profileClaimSourceExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.')
export type ProfileClaimSource = zod.input<typeof ProfileClaimSource>;
export type ProfileClaimSourceOutput = zod.output<typeof ProfileClaimSource>;
@@ -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 ProfileClaimStatus = zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.')
export type ProfileClaimStatus = zod.input<typeof ProfileClaimStatus>;
export type ProfileClaimStatusOutput = zod.output<typeof ProfileClaimStatus>;
@@ -0,0 +1,16 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ProfileClaimTrustLevelMin = 0;
export const ProfileClaimTrustLevelMax = 0;
export const ProfileClaimTrustLevel = zod.int().min(ProfileClaimTrustLevelMin).max(ProfileClaimTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.')
export type ProfileClaimTrustLevel = zod.input<typeof ProfileClaimTrustLevel>;
export type ProfileClaimTrustLevelOutput = zod.output<typeof ProfileClaimTrustLevel>;
@@ -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 ProfileConfirmedCategory = zod.object({
"specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),
"grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
"confirmed_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"attempt_id": zod.uuid().describe('Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate.')
}).describe('A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`.')
export type ProfileConfirmedCategory = zod.input<typeof ProfileConfirmedCategory>;
export type ProfileConfirmedCategoryOutput = zod.output<typeof ProfileConfirmedCategory>;
@@ -0,0 +1,87 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileContactsEmailValueOneMin = 3;
export const profileContactsEmailValueOneMax = 254;
export const profileContactsEmailSourceOneTrustLevelMin = 0;
export const profileContactsEmailSourceOneTrustLevelMax = 0;
export const profileContactsEmailSourceOneQuoteOneMax = 300;
export const profileContactsEmailSourceOneExtractionVersionOneMax = 64;
export const profileContactsEmailSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const profileContactsPhoneValueOneMin = 8;
export const profileContactsPhoneValueOneMax = 16;
export const profileContactsPhoneValueOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
export const profileContactsPhoneSourceOneTrustLevelMin = 0;
export const profileContactsPhoneSourceOneTrustLevelMax = 0;
export const profileContactsPhoneSourceOneQuoteOneMax = 300;
export const profileContactsPhoneSourceOneExtractionVersionOneMax = 64;
export const profileContactsPhoneSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const profileContactsTelegramValueOneMin = 6;
export const profileContactsTelegramValueOneMax = 33;
export const profileContactsTelegramValueOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
export const profileContactsTelegramSourceOneTrustLevelMin = 0;
export const profileContactsTelegramSourceOneTrustLevelMax = 0;
export const profileContactsTelegramSourceOneQuoteOneMax = 300;
export const profileContactsTelegramSourceOneExtractionVersionOneMax = 64;
export const profileContactsTelegramSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileContacts = zod.object({
"email": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.email().min(profileContactsEmailValueOneMin).max(profileContactsEmailValueOneMax).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.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileContactsEmailSourceOneTrustLevelMin).max(profileContactsEmailSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileContactsEmailSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileContactsEmailSourceOneExtractionVersionOneMax).regex(profileContactsEmailSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Contact email of the candidate with its confirmation state and provenance. It is personal data. It is a contact channel that the candidate gives, not the login of the account: the two may differ, the server never sends mail to it and never verifies it. `value` and `source` are null exactly when `status` is `unknown`.'),
"phone": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(profileContactsPhoneValueOneMin).max(profileContactsPhoneValueOneMax).regex(profileContactsPhoneValueOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileContactsPhoneSourceOneTrustLevelMin).max(profileContactsPhoneSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileContactsPhoneSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileContactsPhoneSourceOneExtractionVersionOneMax).regex(profileContactsPhoneSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Contact phone number of the candidate with its confirmation state and provenance. It is personal data, stored in the E.164 format of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`.'),
"telegram": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(profileContactsTelegramValueOneMin).max(profileContactsTelegramValueOneMax).regex(profileContactsTelegramValueOneRegExp).describe('Telegram username with the leading @.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileContactsTelegramSourceOneTrustLevelMin).max(profileContactsTelegramSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileContactsTelegramSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileContactsTelegramSourceOneExtractionVersionOneMax).regex(profileContactsTelegramSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Telegram username of the candidate with its confirmation state and provenance. It is personal data, stored with the leading @ of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`.')
}).describe('Contact channels of the candidate. Each channel is a claim of its own, and the candidate fills in any subset. The kinds are the ones that the contact disclosure (consent C4) can pass on, with the same value formats, so a disclosure never has to convert or drop a stored value; adding a kind, such as a link to a code repository, is a contract change in both places. Contacts leave the profile only through a contact grant, never in a card or a search result. All values are personal data.')
export type ProfileContacts = zod.input<typeof ProfileContacts>;
export type ProfileContactsOutput = zod.output<typeof ProfileContacts>;
@@ -0,0 +1,39 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileContactsInputEmailOneValueMin = 3;
export const profileContactsInputEmailOneValueMax = 254;
export const profileContactsInputPhoneOneValueMin = 8;
export const profileContactsInputPhoneOneValueMax = 16;
export const profileContactsInputPhoneOneValueRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
export const profileContactsInputTelegramOneValueMin = 6;
export const profileContactsInputTelegramOneValueMax = 33;
export const profileContactsInputTelegramOneValueRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
export const ProfileContactsInput = zod.object({
"email": zod.union([zod.object({
"value": zod.email().min(profileContactsInputEmailOneValueMin).max(profileContactsInputEmailOneValueMax).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.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the contact email in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"phone": zod.union([zod.object({
"value": zod.string().min(profileContactsInputPhoneOneValueMin).max(profileContactsInputPhoneOneValueMax).regex(profileContactsInputPhoneOneValueRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the contact phone number in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"telegram": zod.union([zod.object({
"value": zod.string().min(profileContactsInputTelegramOneValueMin).max(profileContactsInputTelegramOneValueMax).regex(profileContactsInputTelegramOneValueRegExp).describe('Telegram username with the leading @.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the Telegram username in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()])
}).describe('Decisions about the contact channels in a request. A channel sent as null is unknown: it is removed if it was set.')
export type ProfileContactsInput = zod.input<typeof ProfileContactsInput>;
export type ProfileContactsInputOutput = zod.output<typeof ProfileContactsInput>;
@@ -0,0 +1,35 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileEmailClaimValueOneMin = 3;
export const profileEmailClaimValueOneMax = 254;
export const profileEmailClaimSourceOneTrustLevelMin = 0;
export const profileEmailClaimSourceOneTrustLevelMax = 0;
export const profileEmailClaimSourceOneQuoteOneMax = 300;
export const profileEmailClaimSourceOneExtractionVersionOneMax = 64;
export const profileEmailClaimSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileEmailClaim = zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.email().min(profileEmailClaimValueOneMin).max(profileEmailClaimValueOneMax).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.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileEmailClaimSourceOneTrustLevelMin).max(profileEmailClaimSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileEmailClaimSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileEmailClaimSourceOneExtractionVersionOneMax).regex(profileEmailClaimSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Contact email of the candidate with its confirmation state and provenance. It is personal data. It is a contact channel that the candidate gives, not the login of the account: the two may differ, the server never sends mail to it and never verifies it. `value` and `source` are null exactly when `status` is `unknown`.')
export type ProfileEmailClaim = zod.input<typeof ProfileEmailClaim>;
export type ProfileEmailClaimOutput = zod.output<typeof ProfileEmailClaim>;
@@ -0,0 +1,19 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileEmailInputValueMin = 3;
export const profileEmailInputValueMax = 254;
export const ProfileEmailInput = zod.object({
"value": zod.email().min(profileEmailInputValueMin).max(profileEmailInputValueMax).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.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the contact email in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.')
export type ProfileEmailInput = zod.input<typeof ProfileEmailInput>;
export type ProfileEmailInputOutput = zod.output<typeof ProfileEmailInput>;
@@ -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 ProfileEmployerNameMax = 200;
export const ProfileEmployerNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const ProfileEmployerName = zod.string().min(1).max(ProfileEmployerNameMax).regex(ProfileEmployerNameRegExp).describe('Name of the employer in one experience entry, as the candidate wrote it. It is personal data of the candidate\'s career. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
export type ProfileEmployerName = zod.input<typeof ProfileEmployerName>;
export type ProfileEmployerNameOutput = zod.output<typeof ProfileEmployerName>;
@@ -0,0 +1,52 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileExperienceItemEmployerNameOneMax = 200;
export const profileExperienceItemEmployerNameOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const profileExperienceItemStartedOnMin = 7;
export const profileExperienceItemStartedOnMax = 7;
export const profileExperienceItemStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const profileExperienceItemEndedOnOneMin = 7;
export const profileExperienceItemEndedOnOneMax = 7;
export const profileExperienceItemEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const profileExperienceItemSummaryOneMax = 1000;
export const profileExperienceItemSourceTrustLevelMin = 0;
export const profileExperienceItemSourceTrustLevelMax = 0;
export const profileExperienceItemSourceQuoteOneMax = 300;
export const profileExperienceItemSourceExtractionVersionOneMax = 64;
export const profileExperienceItemSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileExperienceItem = zod.object({
"employer_name": zod.union([zod.string().min(1).max(profileExperienceItemEmployerNameOneMax).regex(profileExperienceItemEmployerNameOneRegExp).describe('Name of the employer in one experience entry, as the candidate wrote it. It is personal data of the candidate\'s career. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Employer of the entry, or null when the candidate gives none.'),
"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.'),
"started_on": zod.string().min(profileExperienceItemStartedOnMin).max(profileExperienceItemStartedOnMax).regex(profileExperienceItemStartedOnRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),
"ended_on": zod.union([zod.string().min(profileExperienceItemEndedOnOneMin).max(profileExperienceItemEndedOnOneMax).regex(profileExperienceItemEndedOnOneRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),zod.null()]).describe('Last month of the work, or null when the candidate still works there. It is not earlier than `started_on`.'),
"summary": zod.union([zod.string().min(1).max(profileExperienceItemSummaryOneMax).describe('Tasks and results of the candidate in one experience entry. It describes the work rather than a job title. It may contain line breaks and personal data of the candidate; it must not contain personal data of other people. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Tasks and results of the entry, or null when the candidate gives none.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.'),
"source": zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileExperienceItemSourceTrustLevelMin).max(profileExperienceItemSourceTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileExperienceItemSourceQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileExperienceItemSourceExtractionVersionOneMax).regex(profileExperienceItemSourceExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.')
}).describe('One entry of the candidate\'s work history with its confirmation state and provenance. An entry describes the work by its specialization and tasks rather than by a job title, and it is a claim of trust level 0. It is different from the `CandidateExperience` of the questionnaire, which holds only the total months of commercial and academic experience of a chosen specialization as a hint for the assessment: the two are saved separately, and the server neither adds the entries up for the questionnaire nor fills the entries from it. An entry is personal data.')
export type ProfileExperienceItem = zod.input<typeof ProfileExperienceItem>;
export type ProfileExperienceItemOutput = zod.output<typeof ProfileExperienceItem>;
@@ -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 profileExperienceItemInputEmployerNameOneMax = 200;
export const profileExperienceItemInputEmployerNameOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const profileExperienceItemInputStartedOnMin = 7;
export const profileExperienceItemInputStartedOnMax = 7;
export const profileExperienceItemInputStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const profileExperienceItemInputEndedOnOneMin = 7;
export const profileExperienceItemInputEndedOnOneMax = 7;
export const profileExperienceItemInputEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const profileExperienceItemInputSummaryOneMax = 1000;
export const ProfileExperienceItemInput = zod.object({
"employer_name": zod.union([zod.string().min(1).max(profileExperienceItemInputEmployerNameOneMax).regex(profileExperienceItemInputEmployerNameOneRegExp).describe('Name of the employer in one experience entry, as the candidate wrote it. It is personal data of the candidate\'s career. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"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.'),
"started_on": zod.string().min(profileExperienceItemInputStartedOnMin).max(profileExperienceItemInputStartedOnMax).regex(profileExperienceItemInputStartedOnRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),
"ended_on": zod.union([zod.string().min(profileExperienceItemInputEndedOnOneMin).max(profileExperienceItemInputEndedOnOneMax).regex(profileExperienceItemInputEndedOnOneRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),zod.null()]),
"summary": zod.union([zod.string().min(1).max(profileExperienceItemInputSummaryOneMax).describe('Tasks and results of the candidate in one experience entry. It describes the work rather than a job title. It may contain line breaks and personal data of the candidate; it must not contain personal data of other people. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one work history entry in a request; see CandidateProfileUpdate for the rules of `status`. The server also requires `ended_on` not to precede `started_on` and no month to lie in the future, and answers 400 with the pointer of the month.')
export type ProfileExperienceItemInput = zod.input<typeof ProfileExperienceItemInput>;
export type ProfileExperienceItemInputOutput = zod.output<typeof ProfileExperienceItemInput>;
@@ -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 ProfileExperienceSummaryMax = 1000;
export const ProfileExperienceSummary = zod.string().min(1).max(ProfileExperienceSummaryMax).describe('Tasks and results of the candidate in one experience entry. It describes the work rather than a job title. It may contain line breaks and personal data of the candidate; it must not contain personal data of other people. Plain text; clients show it as text, never as HTML.')
export type ProfileExperienceSummary = zod.input<typeof ProfileExperienceSummary>;
export type ProfileExperienceSummaryOutput = zod.output<typeof ProfileExperienceSummary>;
@@ -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 profileFullNameClaimValueOneMax = 200;
export const profileFullNameClaimValueOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const profileFullNameClaimSourceOneTrustLevelMin = 0;
export const profileFullNameClaimSourceOneTrustLevelMax = 0;
export const profileFullNameClaimSourceOneQuoteOneMax = 300;
export const profileFullNameClaimSourceOneExtractionVersionOneMax = 64;
export const profileFullNameClaimSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileFullNameClaim = zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(1).max(profileFullNameClaimValueOneMax).regex(profileFullNameClaimValueOneRegExp).describe('Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileFullNameClaimSourceOneTrustLevelMin).max(profileFullNameClaimSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileFullNameClaimSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileFullNameClaimSourceOneExtractionVersionOneMax).regex(profileFullNameClaimSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Full name of the candidate with its confirmation state and provenance. The value is personal data. It is disclosed to one organization only through the contact grant of the consent C4 and never appears in an organization-visible schema. `value` and `source` are null exactly when `status` is `unknown`.')
export type ProfileFullNameClaim = zod.input<typeof ProfileFullNameClaim>;
export type ProfileFullNameClaimOutput = zod.output<typeof ProfileFullNameClaim>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileFullNameInputValueMax = 200;
export const profileFullNameInputValueRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const ProfileFullNameInput = zod.object({
"value": zod.string().min(1).max(profileFullNameInputValueMax).regex(profileFullNameInputValueRegExp).describe('Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the full name in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.')
export type ProfileFullNameInput = zod.input<typeof ProfileFullNameInput>;
export type ProfileFullNameInputOutput = zod.output<typeof ProfileFullNameInput>;
@@ -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 ProfileItemStatus = zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
export type ProfileItemStatus = zod.input<typeof ProfileItemStatus>;
export type ProfileItemStatusOutput = zod.output<typeof ProfileItemStatus>;
@@ -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 profileLocationClaimValueOneMax = 100;
export const profileLocationClaimValueOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const profileLocationClaimSourceOneTrustLevelMin = 0;
export const profileLocationClaimSourceOneTrustLevelMax = 0;
export const profileLocationClaimSourceOneQuoteOneMax = 300;
export const profileLocationClaimSourceOneExtractionVersionOneMax = 64;
export const profileLocationClaimSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileLocationClaim = zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(1).max(profileLocationClaimValueOneMax).regex(profileLocationClaimValueOneRegExp).describe('City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileLocationClaimSourceOneTrustLevelMin).max(profileLocationClaimSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileLocationClaimSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileLocationClaimSourceOneExtractionVersionOneMax).regex(profileLocationClaimSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Place of the candidate with its confirmation state and provenance. It is personal data. `value` and `source` are null exactly when `status` is `unknown`.')
export type ProfileLocationClaim = zod.input<typeof ProfileLocationClaim>;
export type ProfileLocationClaimOutput = zod.output<typeof ProfileLocationClaim>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileLocationInputValueMax = 100;
export const profileLocationInputValueRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const ProfileLocationInput = zod.object({
"value": zod.string().min(1).max(profileLocationInputValueMax).regex(profileLocationInputValueRegExp).describe('City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the place in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.')
export type ProfileLocationInput = zod.input<typeof ProfileLocationInput>;
export type ProfileLocationInputOutput = zod.output<typeof ProfileLocationInput>;
@@ -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 ProfileLocationNameMax = 100;
export const ProfileLocationNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const ProfileLocationName = zod.string().min(1).max(ProfileLocationNameMax).regex(ProfileLocationNameRegExp).describe('City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
export type ProfileLocationName = zod.input<typeof ProfileLocationName>;
export type ProfileLocationNameOutput = zod.output<typeof ProfileLocationName>;
@@ -0,0 +1,37 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profilePhoneClaimValueOneMin = 8;
export const profilePhoneClaimValueOneMax = 16;
export const profilePhoneClaimValueOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
export const profilePhoneClaimSourceOneTrustLevelMin = 0;
export const profilePhoneClaimSourceOneTrustLevelMax = 0;
export const profilePhoneClaimSourceOneQuoteOneMax = 300;
export const profilePhoneClaimSourceOneExtractionVersionOneMax = 64;
export const profilePhoneClaimSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfilePhoneClaim = zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(profilePhoneClaimValueOneMin).max(profilePhoneClaimValueOneMax).regex(profilePhoneClaimValueOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profilePhoneClaimSourceOneTrustLevelMin).max(profilePhoneClaimSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profilePhoneClaimSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profilePhoneClaimSourceOneExtractionVersionOneMax).regex(profilePhoneClaimSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Contact phone number of the candidate with its confirmation state and provenance. It is personal data, stored in the E.164 format of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`.')
export type ProfilePhoneClaim = zod.input<typeof ProfilePhoneClaim>;
export type ProfilePhoneClaimOutput = zod.output<typeof ProfilePhoneClaim>;
@@ -0,0 +1,21 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profilePhoneInputValueMin = 8;
export const profilePhoneInputValueMax = 16;
export const profilePhoneInputValueRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
export const ProfilePhoneInput = zod.object({
"value": zod.string().min(profilePhoneInputValueMin).max(profilePhoneInputValueMax).regex(profilePhoneInputValueRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the contact phone number in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.')
export type ProfilePhoneInput = zod.input<typeof ProfilePhoneInput>;
export type ProfilePhoneInputOutput = zod.output<typeof ProfilePhoneInput>;
@@ -0,0 +1,32 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileRelocationClaimSourceOneTrustLevelMin = 0;
export const profileRelocationClaimSourceOneTrustLevelMax = 0;
export const profileRelocationClaimSourceOneQuoteOneMax = 300;
export const profileRelocationClaimSourceOneExtractionVersionOneMax = 64;
export const profileRelocationClaimSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileRelocationClaim = zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.boolean().nullable(),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileRelocationClaimSourceOneTrustLevelMin).max(profileRelocationClaimSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileRelocationClaimSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileRelocationClaimSourceOneExtractionVersionOneMax).regex(profileRelocationClaimSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Whether the candidate is ready to relocate, with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; the server never assumes an answer.')
export type ProfileRelocationClaim = zod.input<typeof ProfileRelocationClaim>;
export type ProfileRelocationClaimOutput = zod.output<typeof ProfileRelocationClaim>;
@@ -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 ProfileRelocationInput = zod.object({
"value": zod.boolean(),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about readiness to relocate in a request; see CandidateProfileUpdate for the rules of `status`.')
export type ProfileRelocationInput = zod.input<typeof ProfileRelocationInput>;
export type ProfileRelocationInputOutput = zod.output<typeof ProfileRelocationInput>;
@@ -0,0 +1,33 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileRoleItemSourceTrustLevelMin = 0;
export const profileRoleItemSourceTrustLevelMax = 0;
export const profileRoleItemSourceQuoteOneMax = 300;
export const profileRoleItemSourceExtractionVersionOneMax = 64;
export const profileRoleItemSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileRoleItem = 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.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that the candidate claims in the specialization, or null when the candidate names none.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.'),
"source": zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileRoleItemSourceTrustLevelMin).max(profileRoleItemSourceTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileRoleItemSourceQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileRoleItemSourceExtractionVersionOneMax).regex(profileRoleItemSourceExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.')
}).describe('One role of the candidate: a specialization of the catalog with the grade that the candidate claims for it. `self_assessed_grade` is a claim, the same one that the questionnaire calls `self_assessed_grade` for its at most two chosen specializations: it influences nothing but the display and never becomes a confirmed grade or a category. The questionnaire value starts the assessment and the profile value is what the profile shows; the two are saved separately and the server never copies one into the other. A confirmed grade comes only from an assessment result and appears in `confirmed_categories` of the profile, never in a role; unknown fields such as `confirmed_grade` or `category` are rejected.')
export type ProfileRoleItem = zod.input<typeof ProfileRoleItem>;
export type ProfileRoleItemOutput = zod.output<typeof ProfileRoleItem>;
@@ -0,0 +1,16 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ProfileRoleItemInput = 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.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that the candidate claims, or null when the candidate names none.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one role in a request; see CandidateProfileUpdate for the rules of `status`. The object has no confirmed grade and no category: unknown fields are rejected.')
export type ProfileRoleItemInput = zod.input<typeof ProfileRoleItemInput>;
export type ProfileRoleItemInputOutput = zod.output<typeof ProfileRoleItemInput>;
@@ -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 profileSalaryMinimumAmountMin = 1000;
export const profileSalaryMinimumAmountMax = 100000000;
export const profileSalaryMinimumAmountMultipleOf = 1000;
export const ProfileSalaryMinimum = zod.object({
"amount": zod.int().min(profileSalaryMinimumAmountMin).max(profileSalaryMinimumAmountMax).multipleOf(profileSalaryMinimumAmountMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.')
export type ProfileSalaryMinimum = zod.input<typeof ProfileSalaryMinimum>;
export type ProfileSalaryMinimumOutput = zod.output<typeof ProfileSalaryMinimum>;
@@ -0,0 +1,41 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileSalaryMinimumClaimValueOneAmountMin = 1000;
export const profileSalaryMinimumClaimValueOneAmountMax = 100000000;
export const profileSalaryMinimumClaimValueOneAmountMultipleOf = 1000;
export const profileSalaryMinimumClaimSourceOneTrustLevelMin = 0;
export const profileSalaryMinimumClaimSourceOneTrustLevelMax = 0;
export const profileSalaryMinimumClaimSourceOneQuoteOneMax = 300;
export const profileSalaryMinimumClaimSourceOneExtractionVersionOneMax = 64;
export const profileSalaryMinimumClaimSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileSalaryMinimumClaim = zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.object({
"amount": zod.int().min(profileSalaryMinimumClaimValueOneAmountMin).max(profileSalaryMinimumClaimValueOneAmountMax).multipleOf(profileSalaryMinimumClaimValueOneAmountMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileSalaryMinimumClaimSourceOneTrustLevelMin).max(profileSalaryMinimumClaimSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileSalaryMinimumClaimSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileSalaryMinimumClaimSourceOneExtractionVersionOneMax).regex(profileSalaryMinimumClaimSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Lowest acceptable salary with its confirmation state and provenance. It is personal data that no organization reads. `value` and `source` are null exactly when `status` is `unknown`; the server never substitutes zero or a market estimate.')
export type ProfileSalaryMinimumClaim = zod.input<typeof ProfileSalaryMinimumClaim>;
export type ProfileSalaryMinimumClaimOutput = zod.output<typeof ProfileSalaryMinimumClaim>;
@@ -0,0 +1,25 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileSalaryMinimumInputValueAmountMin = 1000;
export const profileSalaryMinimumInputValueAmountMax = 100000000;
export const profileSalaryMinimumInputValueAmountMultipleOf = 1000;
export const ProfileSalaryMinimumInput = zod.object({
"value": zod.object({
"amount": zod.int().min(profileSalaryMinimumInputValueAmountMin).max(profileSalaryMinimumInputValueAmountMax).multipleOf(profileSalaryMinimumInputValueAmountMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the lowest salary in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.')
export type ProfileSalaryMinimumInput = zod.input<typeof ProfileSalaryMinimumInput>;
export type ProfileSalaryMinimumInputOutput = zod.output<typeof ProfileSalaryMinimumInput>;
@@ -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 ProfileSoftSkillMax = 50;
export const ProfileSoftSkillRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const ProfileSoftSkill = zod.string().min(1).max(ProfileSoftSkillMax).regex(ProfileSoftSkillRegExp).describe('Soft skill as the candidate wrote it, for example "Mentoring" or "Negotiation". The platform has no soft skill taxonomy, so the text is free; it never changes a category or a grade. It has no leading or trailing whitespace and no line breaks. The server compares skills without regard to letter case. Plain text; clients show it as text, never as HTML.')
export type ProfileSoftSkill = zod.input<typeof ProfileSoftSkill>;
export type ProfileSoftSkillOutput = zod.output<typeof ProfileSoftSkill>;
@@ -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 profileSoftSkillItemSkillMax = 50;
export const profileSoftSkillItemSkillRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const profileSoftSkillItemSourceTrustLevelMin = 0;
export const profileSoftSkillItemSourceTrustLevelMax = 0;
export const profileSoftSkillItemSourceQuoteOneMax = 300;
export const profileSoftSkillItemSourceExtractionVersionOneMax = 64;
export const profileSoftSkillItemSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileSoftSkillItem = zod.object({
"skill": zod.string().min(1).max(profileSoftSkillItemSkillMax).regex(profileSoftSkillItemSkillRegExp).describe('Soft skill as the candidate wrote it, for example "Mentoring" or "Negotiation". The platform has no soft skill taxonomy, so the text is free; it never changes a category or a grade. It has no leading or trailing whitespace and no line breaks. The server compares skills without regard to letter case. Plain text; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.'),
"source": zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileSoftSkillItemSourceTrustLevelMin).max(profileSoftSkillItemSourceTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileSoftSkillItemSourceQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileSoftSkillItemSourceExtractionVersionOneMax).regex(profileSoftSkillItemSourceExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.')
}).describe('One soft skill of the candidate with its confirmation state and provenance. It is a claim; no assessment checks it.')
export type ProfileSoftSkillItem = zod.input<typeof ProfileSoftSkillItem>;
export type ProfileSoftSkillItemOutput = zod.output<typeof ProfileSoftSkillItem>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileSoftSkillItemInputSkillMax = 50;
export const profileSoftSkillItemInputSkillRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const ProfileSoftSkillItemInput = zod.object({
"skill": zod.string().min(1).max(profileSoftSkillItemInputSkillMax).regex(profileSoftSkillItemInputSkillRegExp).describe('Soft skill as the candidate wrote it, for example "Mentoring" or "Negotiation". The platform has no soft skill taxonomy, so the text is free; it never changes a category or a grade. It has no leading or trailing whitespace and no line breaks. The server compares skills without regard to letter case. Plain text; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one soft skill in a request; see CandidateProfileUpdate for the rules of `status`.')
export type ProfileSoftSkillItemInput = zod.input<typeof ProfileSoftSkillItemInput>;
export type ProfileSoftSkillItemInputOutput = zod.output<typeof ProfileSoftSkillItemInput>;
@@ -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 profileStackItemTagMax = 50;
export const profileStackItemTagRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const profileStackItemSourceTrustLevelMin = 0;
export const profileStackItemSourceTrustLevelMax = 0;
export const profileStackItemSourceQuoteOneMax = 300;
export const profileStackItemSourceExtractionVersionOneMax = 64;
export const profileStackItemSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileStackItem = zod.object({
"tag": zod.string().min(1).max(profileStackItemTagMax).regex(profileStackItemTagRegExp).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.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.'),
"source": zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileStackItemSourceTrustLevelMin).max(profileStackItemSourceTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileStackItemSourceQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileStackItemSourceExtractionVersionOneMax).regex(profileStackItemSourceExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.')
}).describe('One technology tag of the candidate\'s stack with its confirmation state and provenance. The profile stack is one list for the whole profile; the questionnaire holds the tags of each chosen specialization with the same `StackTag` meaning, and the two lists are independent: the server never copies one into the other. A tag is a descriptive attribute and never forms a category.')
export type ProfileStackItem = zod.input<typeof ProfileStackItem>;
export type ProfileStackItemOutput = zod.output<typeof ProfileStackItem>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileStackItemInputTagMax = 50;
export const profileStackItemInputTagRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const ProfileStackItemInput = zod.object({
"tag": zod.string().min(1).max(profileStackItemInputTagMax).regex(profileStackItemInputTagRegExp).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.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one stack tag in a request; see CandidateProfileUpdate for the rules of `status`.')
export type ProfileStackItemInput = zod.input<typeof ProfileStackItemInput>;
export type ProfileStackItemInputOutput = zod.output<typeof ProfileStackItemInput>;
@@ -0,0 +1,37 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileTelegramClaimValueOneMin = 6;
export const profileTelegramClaimValueOneMax = 33;
export const profileTelegramClaimValueOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
export const profileTelegramClaimSourceOneTrustLevelMin = 0;
export const profileTelegramClaimSourceOneTrustLevelMax = 0;
export const profileTelegramClaimSourceOneQuoteOneMax = 300;
export const profileTelegramClaimSourceOneExtractionVersionOneMax = 64;
export const profileTelegramClaimSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileTelegramClaim = zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(profileTelegramClaimValueOneMin).max(profileTelegramClaimValueOneMax).regex(profileTelegramClaimValueOneRegExp).describe('Telegram username with the leading @.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileTelegramClaimSourceOneTrustLevelMin).max(profileTelegramClaimSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileTelegramClaimSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileTelegramClaimSourceOneExtractionVersionOneMax).regex(profileTelegramClaimSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Telegram username of the candidate with its confirmation state and provenance. It is personal data, stored with the leading @ of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`.')
export type ProfileTelegramClaim = zod.input<typeof ProfileTelegramClaim>;
export type ProfileTelegramClaimOutput = zod.output<typeof ProfileTelegramClaim>;
@@ -0,0 +1,21 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileTelegramInputValueMin = 6;
export const profileTelegramInputValueMax = 33;
export const profileTelegramInputValueRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
export const ProfileTelegramInput = zod.object({
"value": zod.string().min(profileTelegramInputValueMin).max(profileTelegramInputValueMax).regex(profileTelegramInputValueRegExp).describe('Telegram username with the leading @.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the Telegram username in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.')
export type ProfileTelegramInput = zod.input<typeof ProfileTelegramInput>;
export type ProfileTelegramInputOutput = zod.output<typeof ProfileTelegramInput>;
@@ -0,0 +1,87 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileTermsLocationValueOneMax = 100;
export const profileTermsLocationValueOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const profileTermsLocationSourceOneTrustLevelMin = 0;
export const profileTermsLocationSourceOneTrustLevelMax = 0;
export const profileTermsLocationSourceOneQuoteOneMax = 300;
export const profileTermsLocationSourceOneExtractionVersionOneMax = 64;
export const profileTermsLocationSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const profileTermsRelocationSourceOneTrustLevelMin = 0;
export const profileTermsRelocationSourceOneTrustLevelMax = 0;
export const profileTermsRelocationSourceOneQuoteOneMax = 300;
export const profileTermsRelocationSourceOneExtractionVersionOneMax = 64;
export const profileTermsRelocationSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const profileTermsSalaryMinimumValueOneAmountMin = 1000;
export const profileTermsSalaryMinimumValueOneAmountMax = 100000000;
export const profileTermsSalaryMinimumValueOneAmountMultipleOf = 1000;
export const profileTermsSalaryMinimumSourceOneTrustLevelMin = 0;
export const profileTermsSalaryMinimumSourceOneTrustLevelMax = 0;
export const profileTermsSalaryMinimumSourceOneQuoteOneMax = 300;
export const profileTermsSalaryMinimumSourceOneExtractionVersionOneMax = 64;
export const profileTermsSalaryMinimumSourceOneExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ProfileTerms = zod.object({
"location": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.string().min(1).max(profileTermsLocationValueOneMax).regex(profileTermsLocationValueOneRegExp).describe('City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileTermsLocationSourceOneTrustLevelMin).max(profileTermsLocationSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileTermsLocationSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileTermsLocationSourceOneExtractionVersionOneMax).regex(profileTermsLocationSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Place of the candidate with its confirmation state and provenance. It is personal data. `value` and `source` are null exactly when `status` is `unknown`.'),
"relocation": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.boolean().nullable(),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileTermsRelocationSourceOneTrustLevelMin).max(profileTermsRelocationSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileTermsRelocationSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileTermsRelocationSourceOneExtractionVersionOneMax).regex(profileTermsRelocationSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Whether the candidate is ready to relocate, with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; the server never assumes an answer.'),
"salary_minimum": zod.object({
"status": zod.enum(['confirmed', 'extracted', 'unknown']).describe('Confirmation state of a single profile field.\n\n- confirmed: the candidate typed the value or confirmed a suggestion.\n- extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0.\n- unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.'),
"value": zod.union([zod.object({
"amount": zod.int().min(profileTermsSalaryMinimumValueOneAmountMin).max(profileTermsSalaryMinimumValueOneAmountMax).multipleOf(profileTermsSalaryMinimumValueOneAmountMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.'),zod.null()]),
"source": zod.union([zod.object({
"origin": zod.enum(['manual', 'extracted_from_resume', 'imported']).describe('Where the value of a profile field or item came from. The server sets it; a request never sends it.\n\n- manual: the candidate typed the value in the form. `quote` and `extraction_version` are null.\n- extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume.\n- imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link.\n\nConfirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.'),
"trust_level": zod.int().min(profileTermsSalaryMinimumSourceOneTrustLevelMin).max(profileTermsSalaryMinimumSourceOneTrustLevelMax).describe('Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.'),
"quote": zod.union([zod.string().min(1).max(profileTermsSalaryMinimumSourceOneQuoteOneMax).describe('Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt.'),
"extraction_version": zod.union([zod.string().min(1).max(profileTermsSalaryMinimumSourceOneExtractionVersionOneMax).regex(profileTermsSalaryMinimumSourceOneExtractionVersionOneRegExp).describe('Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it.'),zod.null()]).describe('Extractor version for an extracted or imported value, or null for a manual value.'),
"confirmed_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 the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion.')
}).describe('Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.'),zod.null()])
}).describe('Lowest acceptable salary with its confirmation state and provenance. It is personal data that no organization reads. `value` and `source` are null exactly when `status` is `unknown`; the server never substitutes zero or a market estimate.')
}).describe('Conditions that the candidate wants: the place, readiness to relocate, and the lowest salary. Acceptable work formats are not repeated here; they are the `work_formats` of the questionnaire `WorkContext`, the only place that holds them. These are the candidate\'s wishes, never the terms of an invitation, which an organization offers and which the invitation contract describes.')
export type ProfileTerms = zod.input<typeof ProfileTerms>;
export type ProfileTermsOutput = zod.output<typeof ProfileTerms>;
@@ -0,0 +1,39 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileTermsInputLocationOneValueMax = 100;
export const profileTermsInputLocationOneValueRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const profileTermsInputSalaryMinimumOneValueAmountMin = 1000;
export const profileTermsInputSalaryMinimumOneValueAmountMax = 100000000;
export const profileTermsInputSalaryMinimumOneValueAmountMultipleOf = 1000;
export const ProfileTermsInput = zod.object({
"location": zod.union([zod.object({
"value": zod.string().min(1).max(profileTermsInputLocationOneValueMax).regex(profileTermsInputLocationOneValueRegExp).describe('City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the place in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"relocation": zod.union([zod.object({
"value": zod.boolean(),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about readiness to relocate in a request; see CandidateProfileUpdate for the rules of `status`.'),zod.null()]),
"salary_minimum": zod.union([zod.object({
"value": zod.object({
"amount": zod.int().min(profileTermsInputSalaryMinimumOneValueAmountMin).max(profileTermsInputSalaryMinimumOneValueAmountMax).multipleOf(profileTermsInputSalaryMinimumOneValueAmountMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the lowest salary in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()])
}).describe('Decisions about the desired terms in a request. A field sent as null is unknown: it is removed if it was set.')
export type ProfileTermsInput = zod.input<typeof ProfileTermsInput>;
export type ProfileTermsInputOutput = zod.output<typeof ProfileTermsInput>;
@@ -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 ProfileVersionMin = 0;
export const ProfileVersion = zod.int().min(ProfileVersionMin).describe('Version of the candidate profile. A candidate who has not saved the profile has version 0; every save that changes the profile advances it by one. The client sends the version it read as `expected_version`.')
export type ProfileVersion = zod.input<typeof ProfileVersion>;
export type ProfileVersionOutput = zod.output<typeof ProfileVersion>;
@@ -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 ProfileYearMonthMin = 7;
export const ProfileYearMonthMax = 7;
export const ProfileYearMonthRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const ProfileYearMonth = zod.string().min(ProfileYearMonthMin).max(ProfileYearMonthMax).regex(ProfileYearMonthRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.')
export type ProfileYearMonth = zod.input<typeof ProfileYearMonth>;
export type ProfileYearMonthOutput = zod.output<typeof ProfileYearMonth>;
@@ -29,8 +29,8 @@ export const QuestionnaireSpecialization = zod.object({
"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.')
}).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. The work history entries of the candidate profile (`ProfileExperienceItem`) are a different, detailed claim: the two are saved separately and the server neither adds the entries up nor fills them from these totals.'),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. The candidate profile states the same kind of claim in the `roles` of `CandidateProfile` (`ProfileRoleItem.self_assessed_grade`): the questionnaire value starts the assessment and the profile value is what the profile shows, the two are saved separately, and neither is ever a confirmed grade.')
export type QuestionnaireSpecialization = zod.input<typeof QuestionnaireSpecialization>;
export type QuestionnaireSpecializationOutput = zod.output<typeof QuestionnaireSpecialization>;
@@ -0,0 +1,132 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const saveMyProfileBodyExpectedVersionMin = 0;
export const saveMyProfileBodyFullNameOneValueMax = 200;
export const saveMyProfileBodyFullNameOneValueRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const saveMyProfileBodyContactsEmailOneValueMin = 3;
export const saveMyProfileBodyContactsEmailOneValueMax = 254;
export const saveMyProfileBodyContactsPhoneOneValueMin = 8;
export const saveMyProfileBodyContactsPhoneOneValueMax = 16;
export const saveMyProfileBodyContactsPhoneOneValueRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
export const saveMyProfileBodyContactsTelegramOneValueMin = 6;
export const saveMyProfileBodyContactsTelegramOneValueMax = 33;
export const saveMyProfileBodyContactsTelegramOneValueRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
export const saveMyProfileBodyStackItemTagMax = 50;
export const saveMyProfileBodyStackItemTagRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const saveMyProfileBodyStackMax = 30;
export const saveMyProfileBodyRolesMax = 9;
export const saveMyProfileBodyExperienceItemEmployerNameOneMax = 200;
export const saveMyProfileBodyExperienceItemEmployerNameOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const saveMyProfileBodyExperienceItemStartedOnMin = 7;
export const saveMyProfileBodyExperienceItemStartedOnMax = 7;
export const saveMyProfileBodyExperienceItemStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const saveMyProfileBodyExperienceItemEndedOnOneMin = 7;
export const saveMyProfileBodyExperienceItemEndedOnOneMax = 7;
export const saveMyProfileBodyExperienceItemEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const saveMyProfileBodyExperienceItemSummaryOneMax = 1000;
export const saveMyProfileBodyExperienceMax = 20;
export const saveMyProfileBodySoftSkillsItemSkillMax = 50;
export const saveMyProfileBodySoftSkillsItemSkillRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const saveMyProfileBodySoftSkillsMax = 10;
export const saveMyProfileBodyTermsLocationOneValueMax = 100;
export const saveMyProfileBodyTermsLocationOneValueRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const saveMyProfileBodyTermsSalaryMinimumOneValueAmountMin = 1000;
export const saveMyProfileBodyTermsSalaryMinimumOneValueAmountMax = 100000000;
export const saveMyProfileBodyTermsSalaryMinimumOneValueAmountMultipleOf = 1000;
export const SaveMyProfileBody = zod.object({
"expected_version": zod.int().min(saveMyProfileBodyExpectedVersionMin).describe('Version of the candidate profile. A candidate who has not saved the profile has version 0; every save that changes the profile advances it by one. The client sends the version it read as `expected_version`.'),
"full_name": zod.union([zod.object({
"value": zod.string().min(1).max(saveMyProfileBodyFullNameOneValueMax).regex(saveMyProfileBodyFullNameOneValueRegExp).describe('Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the full name in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"contacts": zod.object({
"email": zod.union([zod.object({
"value": zod.email().min(saveMyProfileBodyContactsEmailOneValueMin).max(saveMyProfileBodyContactsEmailOneValueMax).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.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the contact email in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"phone": zod.union([zod.object({
"value": zod.string().min(saveMyProfileBodyContactsPhoneOneValueMin).max(saveMyProfileBodyContactsPhoneOneValueMax).regex(saveMyProfileBodyContactsPhoneOneValueRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the contact phone number in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"telegram": zod.union([zod.object({
"value": zod.string().min(saveMyProfileBodyContactsTelegramOneValueMin).max(saveMyProfileBodyContactsTelegramOneValueMax).regex(saveMyProfileBodyContactsTelegramOneValueRegExp).describe('Telegram username with the leading @.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the Telegram username in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()])
}).describe('Decisions about the contact channels in a request. A channel sent as null is unknown: it is removed if it was set.'),
"stack": zod.array(zod.object({
"tag": zod.string().min(1).max(saveMyProfileBodyStackItemTagMax).regex(saveMyProfileBodyStackItemTagRegExp).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.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one stack tag in a request; see CandidateProfileUpdate for the rules of `status`.')).max(saveMyProfileBodyStackMax).describe('Technology tags. The schema limits the count; the server also answers 400 with the pointer of a tag that repeats an earlier one without regard to letter case, for example `/stack/2/tag`.'),
"roles": 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.union([zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),zod.null()]).describe('Grade that the candidate claims, or null when the candidate names none.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one role in a request; see CandidateProfileUpdate for the rules of `status`. The object has no confirmed grade and no category: unknown fields are rejected.')).max(saveMyProfileBodyRolesMax).describe('Roles. The server answers 400 with the pointer of a role whose specialization repeats an earlier one, for example `/roles/1/specialization`.'),
"experience": zod.array(zod.object({
"employer_name": zod.union([zod.string().min(1).max(saveMyProfileBodyExperienceItemEmployerNameOneMax).regex(saveMyProfileBodyExperienceItemEmployerNameOneRegExp).describe('Name of the employer in one experience entry, as the candidate wrote it. It is personal data of the candidate\'s career. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"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.'),
"started_on": zod.string().min(saveMyProfileBodyExperienceItemStartedOnMin).max(saveMyProfileBodyExperienceItemStartedOnMax).regex(saveMyProfileBodyExperienceItemStartedOnRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),
"ended_on": zod.union([zod.string().min(saveMyProfileBodyExperienceItemEndedOnOneMin).max(saveMyProfileBodyExperienceItemEndedOnOneMax).regex(saveMyProfileBodyExperienceItemEndedOnOneRegExp).describe('Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future.'),zod.null()]),
"summary": zod.union([zod.string().min(1).max(saveMyProfileBodyExperienceItemSummaryOneMax).describe('Tasks and results of the candidate in one experience entry. It describes the work rather than a job title. It may contain line breaks and personal data of the candidate; it must not contain personal data of other people. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one work history entry in a request; see CandidateProfileUpdate for the rules of `status`. The server also requires `ended_on` not to precede `started_on` and no month to lie in the future, and answers 400 with the pointer of the month.')).max(saveMyProfileBodyExperienceMax).describe('Work history entries.'),
"soft_skills": zod.array(zod.object({
"skill": zod.string().min(1).max(saveMyProfileBodySoftSkillsItemSkillMax).regex(saveMyProfileBodySoftSkillsItemSkillRegExp).describe('Soft skill as the candidate wrote it, for example "Mentoring" or "Negotiation". The platform has no soft skill taxonomy, so the text is free; it never changes a category or a grade. It has no leading or trailing whitespace and no line breaks. The server compares skills without regard to letter case. Plain text; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about one soft skill in a request; see CandidateProfileUpdate for the rules of `status`.')).max(saveMyProfileBodySoftSkillsMax).describe('Soft skills. The server answers 400 with the pointer of a skill that repeats an earlier one without regard to letter case.'),
"terms": zod.object({
"location": zod.union([zod.object({
"value": zod.string().min(1).max(saveMyProfileBodyTermsLocationOneValueMax).regex(saveMyProfileBodyTermsLocationOneValueRegExp).describe('City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the place in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()]),
"relocation": zod.union([zod.object({
"value": zod.boolean(),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about readiness to relocate in a request; see CandidateProfileUpdate for the rules of `status`.'),zod.null()]),
"salary_minimum": zod.union([zod.object({
"value": zod.object({
"amount": zod.int().min(saveMyProfileBodyTermsSalaryMinimumOneValueAmountMin).max(saveMyProfileBodyTermsSalaryMinimumOneValueAmountMax).multipleOf(saveMyProfileBodyTermsSalaryMinimumOneValueAmountMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.'),
"status": zod.enum(['confirmed', 'extracted']).describe('Confirmation state of a profile list item, and the decision that a request sends for a field or an item.\n\n- confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure.\n- extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses.\n\nA request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.')
}).describe('Decision about the lowest salary in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data.'),zod.null()])
}).describe('Decisions about the desired terms in a request. A field sent as null is unknown: it is removed if it was set.')
}).describe('Complete new state of the candidate profile. It replaces every stored value as a whole: a single field sent as null is unknown and is removed, and a list replaces the stored list. The body is personal data.\nEach value carries a decision `status`. `confirmed` sets a manual value or confirms a stored suggestion; confirming a suggestion with exactly its stored value keeps its origin and quote, and any other value makes the claim manual. `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the stored value; any other use answers 400 with the pointer of that status, for example `/stack/1/status`. The provenance, the trust level, and the confirmed categories are not part of the request, and unknown fields are rejected, so a request can neither mark a claim as verified nor write a confirmed grade or a category.')
export type SaveMyProfileBody = zod.input<typeof SaveMyProfileBody>;
export type SaveMyProfileBodyOutput = zod.output<typeof SaveMyProfileBody>;
@@ -37,11 +37,11 @@ export const SaveMyQuestionnaireBody = zod.object({
"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`.'),
}).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. The work history entries of the candidate profile (`ProfileExperienceItem`) are a different, detailed claim: the two are saved separately and the server neither adds the entries up nor fills them from these totals.'),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. The candidate profile states the same kind of claim in the `roles` of `CandidateProfile` (`ProfileRoleItem.self_assessed_grade`): the questionnaire value starts the assessment and the profile value is what the profile shows, the two are saved separately, and neither is ever a confirmed grade.')).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('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 (`ProfileTerms`). The acceptable work formats live only here: the profile does not repeat them.')
}).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<typeof SaveMyQuestionnaireBody>;
@@ -11,7 +11,7 @@ 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.')
}).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 (`ProfileTerms`). The acceptable work formats live only here: the profile does not repeat them.')
export type WorkContext = zod.input<typeof WorkContext>;
export type WorkContextOutput = zod.output<typeof WorkContext>;
+2
View File
@@ -7,6 +7,7 @@
export * from './consentTextVersion.zod';
export * from './contactFieldKind.zod';
export * from './contactFullName.zod';
export * from './contactPhoneNumber.zod';
export * from './contactTelegramUsername.zod';
export * from './currencyCode.zod';
@@ -16,6 +17,7 @@ export * from './invitationTermsVersion.zod';
export * from './needLocationName.zod';
export * from './needTaskText.zod';
export * from './needVersion.zod';
export * from './needVersionLabel.zod';
export * from './pageInfo.zod';
export * from './problem.zod';
export * from './problemCode.zod';
@@ -18,7 +18,6 @@ export * from './contactConsentAcceptance.zod';
export * from './contactConsentOffer.zod';
export * from './contactConsentText.zod';
export * from './contactDisclosure.zod';
export * from './contactFullName.zod';
export * from './contactGrant.zod';
export * from './contactGrantState.zod';
export * from './contactRevocationReason.zod';
@@ -48,7 +48,6 @@ export * from './needUpdate.zod';
export * from './needValueOrigin.zod';
export * from './needValueSource.zod';
export * from './needValueStatus.zod';
export * from './needVersionLabel.zod';
export * from './needWorkFormats.zod';
export * from './needWorkFormatsInput.zod';
export * from './skillTaxonomyCode.zod';