diff --git a/api/README.en.md b/api/README.en.md index ecab7ae..8863dab 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -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`). diff --git a/api/README.md b/api/README.md index 0ee8cb1..c331e2f 100644 --- a/api/README.md +++ b/api/README.md @@ -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`). diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index 163a54a..aade093 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -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 diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index 99eda86..27c4a97 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -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 diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 1eb2275..e92092b 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -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 diff --git a/api/core/components/schemas/candidate_schemas.yml b/api/core/components/schemas/candidate_schemas.yml new file mode 100644 index 0000000..2a13949 --- /dev/null +++ b/api/core/components/schemas/candidate_schemas.yml @@ -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" diff --git a/api/core/components/schemas/questionnaire_schemas.yml b/api/core/components/schemas/questionnaire_schemas.yml index 5a45f8c..bb640d4 100644 --- a/api/core/components/schemas/questionnaire_schemas.yml +++ b/api/core/components/schemas/questionnaire_schemas.yml @@ -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 diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 78968c0..7ce5784 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -14,7 +14,7 @@ tags: - name: catalog description: 'Public reference data: directions, specializations with their assessment availability, and the grade scale.' - name: candidate - description: Data of the current candidate, such as the questionnaire with the chosen specializations and self-assessed grades. Confirmed grades and categories come only from assessment results. + description: '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 resume, answers and the code practice, finalization, and the result. Answers, keys, and attempt history are visible only to the candidate.' - name: organization @@ -495,6 +495,97 @@ paths: $ref: '#/components/responses/QuestionnaireVersionConflict' default: $ref: '#/components/responses/Problem' + /api/v1/me/profile: + 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/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateProfile' + examples: + new_candidate: + $ref: '#/components/examples/NewCandidateProfile' + backend_manual_with_suggestion: + $ref: '#/components/examples/BackendCandidateProfile' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/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/CandidateProfileUpdate' + examples: + backend_manual: + $ref: '#/components/examples/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/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateProfile' + examples: + backend_manual_with_suggestion: + $ref: '#/components/examples/BackendCandidateProfile' + '400': + $ref: '#/components/responses/ProfileValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '412': + $ref: '#/components/responses/ProfileVersionConflict' + default: + $ref: '#/components/responses/Problem' /api/v1/me/assessment-availability: get: operationId: GetMyAssessmentAvailability @@ -2795,7 +2886,7 @@ components: - 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 @@ -2810,7 +2901,7 @@ components: $ref: '#/components/schemas/WorkFormat' CandidateExperience: type: object - description: 'Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade.' + 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 @@ -2830,7 +2921,7 @@ components: 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 @@ -2910,6 +3001,723 @@ components: $ref: '#/components/schemas/QuestionnaireSpecialization' work_context: $ref: '#/components/schemas/WorkContext' + 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: '#/components/schemas/ProfileClaimOrigin' + trust_level: + $ref: '#/components/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: '#/components/schemas/ProfileClaimQuote' + - type: 'null' + extraction_version: + description: Extractor version for an extracted or imported value, or null for a manual value. + oneOf: + - $ref: '#/components/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: '#/components/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: '#/components/schemas/RubAmount' + currency: + $ref: '#/components/schemas/CurrencyCode' + period: + $ref: '#/components/schemas/SalaryPeriod' + tax_basis: + $ref: '#/components/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: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ContactFullName' + - type: 'null' + source: + oneOf: + - $ref: '#/components/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: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/EmailAddress' + - type: 'null' + source: + oneOf: + - $ref: '#/components/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: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ContactPhoneNumber' + - type: 'null' + source: + oneOf: + - $ref: '#/components/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: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ContactTelegramUsername' + - type: 'null' + source: + oneOf: + - $ref: '#/components/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: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ProfileLocationName' + - type: 'null' + source: + oneOf: + - $ref: '#/components/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: '#/components/schemas/ProfileClaimStatus' + value: + type: + - boolean + - 'null' + source: + oneOf: + - $ref: '#/components/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: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ProfileSalaryMinimum' + - type: 'null' + source: + oneOf: + - $ref: '#/components/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: '#/components/schemas/ProfileEmailClaim' + phone: + $ref: '#/components/schemas/ProfilePhoneClaim' + telegram: + $ref: '#/components/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: '#/components/schemas/ProfileLocationClaim' + relocation: + $ref: '#/components/schemas/ProfileRelocationClaim' + salary_minimum: + $ref: '#/components/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: '#/components/schemas/StackTag' + status: + $ref: '#/components/schemas/ProfileItemStatus' + source: + $ref: '#/components/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: '#/components/schemas/ProfileSoftSkill' + status: + $ref: '#/components/schemas/ProfileItemStatus' + source: + $ref: '#/components/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: '#/components/schemas/SpecializationCode' + self_assessed_grade: + description: Grade that the candidate claims in the specialization, or null when the candidate names none. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + status: + $ref: '#/components/schemas/ProfileItemStatus' + source: + $ref: '#/components/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: '#/components/schemas/ProfileEmployerName' + - type: 'null' + specialization: + $ref: '#/components/schemas/SpecializationCode' + started_on: + $ref: '#/components/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: '#/components/schemas/ProfileYearMonth' + - type: 'null' + summary: + description: Tasks and results of the entry, or null when the candidate gives none. + oneOf: + - $ref: '#/components/schemas/ProfileExperienceSummary' + - type: 'null' + status: + $ref: '#/components/schemas/ProfileItemStatus' + source: + $ref: '#/components/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: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + confirmed_at: + $ref: '#/components/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: '#/components/schemas/ProfileVersion' + full_name: + $ref: '#/components/schemas/ProfileFullNameClaim' + contacts: + $ref: '#/components/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: '#/components/schemas/ProfileStackItem' + roles: + type: array + maxItems: 9 + description: Roles in the order the candidate gave them, each specialization at most once. + items: + $ref: '#/components/schemas/ProfileRoleItem' + experience: + type: array + maxItems: 20 + description: Work history entries in the order the candidate gave them. + items: + $ref: '#/components/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: '#/components/schemas/ProfileSoftSkillItem' + terms: + $ref: '#/components/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: '#/components/schemas/ProfileConfirmedCategory' + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: '#/components/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: '#/components/schemas/ContactFullName' + status: + $ref: '#/components/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: '#/components/schemas/EmailAddress' + status: + $ref: '#/components/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: '#/components/schemas/ContactPhoneNumber' + status: + $ref: '#/components/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: '#/components/schemas/ContactTelegramUsername' + status: + $ref: '#/components/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: '#/components/schemas/ProfileLocationName' + status: + $ref: '#/components/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: '#/components/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: '#/components/schemas/ProfileSalaryMinimum' + status: + $ref: '#/components/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: '#/components/schemas/ProfileEmailInput' + - type: 'null' + phone: + oneOf: + - $ref: '#/components/schemas/ProfilePhoneInput' + - type: 'null' + telegram: + oneOf: + - $ref: '#/components/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: '#/components/schemas/ProfileLocationInput' + - type: 'null' + relocation: + oneOf: + - $ref: '#/components/schemas/ProfileRelocationInput' + - type: 'null' + salary_minimum: + oneOf: + - $ref: '#/components/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: '#/components/schemas/StackTag' + status: + $ref: '#/components/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: '#/components/schemas/ProfileSoftSkill' + status: + $ref: '#/components/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: '#/components/schemas/SpecializationCode' + self_assessed_grade: + description: Grade that the candidate claims, or null when the candidate names none. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + status: + $ref: '#/components/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: '#/components/schemas/ProfileEmployerName' + - type: 'null' + specialization: + $ref: '#/components/schemas/SpecializationCode' + started_on: + $ref: '#/components/schemas/ProfileYearMonth' + ended_on: + oneOf: + - $ref: '#/components/schemas/ProfileYearMonth' + - type: 'null' + summary: + oneOf: + - $ref: '#/components/schemas/ProfileExperienceSummary' + - type: 'null' + status: + $ref: '#/components/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: '#/components/schemas/ProfileVersion' + full_name: + oneOf: + - $ref: '#/components/schemas/ProfileFullNameInput' + - type: 'null' + contacts: + $ref: '#/components/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: '#/components/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: '#/components/schemas/ProfileRoleItemInput' + experience: + type: array + maxItems: 20 + description: Work history entries. + items: + $ref: '#/components/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: '#/components/schemas/ProfileSoftSkillItemInput' + terms: + $ref: '#/components/schemas/ProfileTermsInput' AssessmentMode: type: string description: |- @@ -7392,6 +8200,28 @@ components: examples: version_conflict: $ref: '#/components/examples/VersionConflict' + 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: '#/components/schemas/Problem' + examples: + phone_not_e164: + $ref: '#/components/examples/ProfilePhoneNotE164' + extracted_value_changed: + $ref: '#/components/examples/ProfileExtractedValueChanged' + repeated_role: + $ref: '#/components/examples/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: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/ProfileStaleVersion' AssessmentAttemptCreateValidationFailed: description: 'The body does not match the contract or violates an assessment rule: an unknown specialization, grade, or task language, an unknown field such as mode or seed, a specialization that is not in the questionnaire, or a task language that the published bank does not offer; code validation_failed with body pointers. Nothing was created, and the outcome is not stored under the Idempotency-Key.' content: @@ -8035,6 +8865,273 @@ components: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 3e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b + 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 AssessmentAvailability: summary: Backend open in demo_basic, Network Engineer blocked description: Illustrative values. Backend junior and middle can start in the demo_basic mode, with their limits shown before the start; intern and senior have no sufficient bank. Network Engineer junior waits for its same-grade retry interval after an unconfirmed attempt. diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 383ac45..77f55f3 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -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: diff --git a/api/core/routes/candidate_profile.yml b/api/core/routes/candidate_profile.yml new file mode 100644 index 0000000..28078c1 --- /dev/null +++ b/api/core/routes/candidate_profile.yml @@ -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 diff --git a/backend/db/migrations/00013_create_candidate_profiles.sql b/backend/db/migrations/00013_create_candidate_profiles.sql new file mode 100644 index 0000000..383c0cb --- /dev/null +++ b/backend/db/migrations/00013_create_candidate_profiles.sql @@ -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; diff --git a/backend/db/queries/candidate.sql b/backend/db/queries/candidate.sql new file mode 100644 index 0000000..17e12c7 --- /dev/null +++ b/backend/db/queries/candidate.sql @@ -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) +); diff --git a/backend/integration_test/candidate_profile_test.go b/backend/integration_test/candidate_profile_test.go new file mode 100644 index 0000000..c9ac18d --- /dev/null +++ b/backend/integration_test/candidate_profile_test.go @@ -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, "e, &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) + } +} diff --git a/backend/integration_test/organizations_test.go b/backend/integration_test/organizations_test.go index d4ffa1c..7cba410 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -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 diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index 229f618..84ec4ff 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -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_-]+$"), diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 4644d79..76597cf 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -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, diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index 51e8bca..80d8e12 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -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() } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index 065574b..867b707 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -5835,6 +5835,543 @@ func (s *CandidateOrganizationCard) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *CandidateProfile) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CandidateProfile) encodeFields(e *jx.Encoder) { + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("full_name") + s.FullName.Encode(e) + } + { + e.FieldStart("contacts") + s.Contacts.Encode(e) + } + { + e.FieldStart("stack") + e.ArrStart() + for _, elem := range s.Stack { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("roles") + e.ArrStart() + for _, elem := range s.Roles { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("experience") + e.ArrStart() + for _, elem := range s.Experience { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("soft_skills") + e.ArrStart() + for _, elem := range s.SoftSkills { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("terms") + s.Terms.Encode(e) + } + { + e.FieldStart("confirmed_categories") + e.ArrStart() + for _, elem := range s.ConfirmedCategories { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("updated_at") + s.UpdatedAt.Encode(e) + } +} + +var jsonFieldsNameOfCandidateProfile = [10]string{ + 0: "version", + 1: "full_name", + 2: "contacts", + 3: "stack", + 4: "roles", + 5: "experience", + 6: "soft_skills", + 7: "terms", + 8: "confirmed_categories", + 9: "updated_at", +} + +// Decode decodes CandidateProfile from json. +func (s *CandidateProfile) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateProfile to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "full_name": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.FullName.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"full_name\"") + } + case "contacts": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Contacts.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"contacts\"") + } + case "stack": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + s.Stack = make([]ProfileStackItem, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProfileStackItem + if err := elem.Decode(d); err != nil { + return err + } + s.Stack = append(s.Stack, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"stack\"") + } + case "roles": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + s.Roles = make([]ProfileRoleItem, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProfileRoleItem + if err := elem.Decode(d); err != nil { + return err + } + s.Roles = append(s.Roles, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"roles\"") + } + case "experience": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + s.Experience = make([]ProfileExperienceItem, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProfileExperienceItem + if err := elem.Decode(d); err != nil { + return err + } + s.Experience = append(s.Experience, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"experience\"") + } + case "soft_skills": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + s.SoftSkills = make([]ProfileSoftSkillItem, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProfileSoftSkillItem + if err := elem.Decode(d); err != nil { + return err + } + s.SoftSkills = append(s.SoftSkills, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"soft_skills\"") + } + case "terms": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.Terms.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms\"") + } + case "confirmed_categories": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + s.ConfirmedCategories = make([]ProfileConfirmedCategory, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProfileConfirmedCategory + if err := elem.Decode(d); err != nil { + return err + } + s.ConfirmedCategories = append(s.ConfirmedCategories, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmed_categories\"") + } + case "updated_at": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.UpdatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"updated_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CandidateProfile") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCandidateProfile) { + name = jsonFieldsNameOfCandidateProfile[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CandidateProfile) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateProfile) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CandidateProfileUpdate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CandidateProfileUpdate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + e.FieldStart("full_name") + s.FullName.Encode(e) + } + { + e.FieldStart("contacts") + s.Contacts.Encode(e) + } + { + e.FieldStart("stack") + e.ArrStart() + for _, elem := range s.Stack { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("roles") + e.ArrStart() + for _, elem := range s.Roles { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("experience") + e.ArrStart() + for _, elem := range s.Experience { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("soft_skills") + e.ArrStart() + for _, elem := range s.SoftSkills { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("terms") + s.Terms.Encode(e) + } +} + +var jsonFieldsNameOfCandidateProfileUpdate = [8]string{ + 0: "expected_version", + 1: "full_name", + 2: "contacts", + 3: "stack", + 4: "roles", + 5: "experience", + 6: "soft_skills", + 7: "terms", +} + +// Decode decodes CandidateProfileUpdate from json. +func (s *CandidateProfileUpdate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateProfileUpdate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "full_name": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.FullName.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"full_name\"") + } + case "contacts": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Contacts.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"contacts\"") + } + case "stack": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + s.Stack = make([]ProfileStackItemInput, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProfileStackItemInput + if err := elem.Decode(d); err != nil { + return err + } + s.Stack = append(s.Stack, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"stack\"") + } + case "roles": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + s.Roles = make([]ProfileRoleItemInput, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProfileRoleItemInput + if err := elem.Decode(d); err != nil { + return err + } + s.Roles = append(s.Roles, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"roles\"") + } + case "experience": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + s.Experience = make([]ProfileExperienceItemInput, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProfileExperienceItemInput + if err := elem.Decode(d); err != nil { + return err + } + s.Experience = append(s.Experience, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"experience\"") + } + case "soft_skills": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + s.SoftSkills = make([]ProfileSoftSkillItemInput, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ProfileSoftSkillItemInput + if err := elem.Decode(d); err != nil { + return err + } + s.SoftSkills = append(s.SoftSkills, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"soft_skills\"") + } + case "terms": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.Terms.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CandidateProfileUpdate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b11111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCandidateProfileUpdate) { + name = jsonFieldsNameOfCandidateProfileUpdate[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CandidateProfileUpdate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateProfileUpdate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *CandidateQuestionnaire) Encode(e *jx.Encoder) { e.ObjStart() @@ -12356,6 +12893,82 @@ func (s *GetMyInvitationUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GetMyProfileForbidden as json. +func (s *GetMyProfileForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyProfileForbidden from json. +func (s *GetMyProfileForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyProfileForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyProfileForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyProfileForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyProfileForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyProfileUnauthorized as json. +func (s *GetMyProfileUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyProfileUnauthorized from json. +func (s *GetMyProfileUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyProfileUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyProfileUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyProfileUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyProfileUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetMyQuestionnaireForbidden as json. func (s *GetMyQuestionnaireForbidden) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -24419,6 +25032,622 @@ func (s *NilPracticeVerdict) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ProfileClaimQuote as json. +func (o NilProfileClaimQuote) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileClaimQuote from json. +func (o *NilProfileClaimQuote) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileClaimQuote to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileClaimQuote + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileClaimQuote) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileClaimQuote) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileClaimSource as json. +func (o NilProfileClaimSource) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileClaimSource from json. +func (o *NilProfileClaimSource) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileClaimSource to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileClaimSource + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileClaimSource) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileClaimSource) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileEmailInput as json. +func (o NilProfileEmailInput) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileEmailInput from json. +func (o *NilProfileEmailInput) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileEmailInput to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileEmailInput + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileEmailInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileEmailInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileEmployerName as json. +func (o NilProfileEmployerName) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileEmployerName from json. +func (o *NilProfileEmployerName) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileEmployerName to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileEmployerName + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileEmployerName) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileEmployerName) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileExperienceSummary as json. +func (o NilProfileExperienceSummary) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileExperienceSummary from json. +func (o *NilProfileExperienceSummary) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileExperienceSummary to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileExperienceSummary + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileExperienceSummary) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileExperienceSummary) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileFullNameInput as json. +func (o NilProfileFullNameInput) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileFullNameInput from json. +func (o *NilProfileFullNameInput) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileFullNameInput to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileFullNameInput + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileFullNameInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileFullNameInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileLocationInput as json. +func (o NilProfileLocationInput) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileLocationInput from json. +func (o *NilProfileLocationInput) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileLocationInput to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileLocationInput + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileLocationInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileLocationInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileLocationName as json. +func (o NilProfileLocationName) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileLocationName from json. +func (o *NilProfileLocationName) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileLocationName to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileLocationName + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileLocationName) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileLocationName) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfilePhoneInput as json. +func (o NilProfilePhoneInput) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfilePhoneInput from json. +func (o *NilProfilePhoneInput) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfilePhoneInput to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfilePhoneInput + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfilePhoneInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfilePhoneInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileRelocationInput as json. +func (o NilProfileRelocationInput) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileRelocationInput from json. +func (o *NilProfileRelocationInput) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileRelocationInput to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileRelocationInput + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileRelocationInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileRelocationInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileSalaryMinimum as json. +func (o NilProfileSalaryMinimum) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileSalaryMinimum from json. +func (o *NilProfileSalaryMinimum) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileSalaryMinimum to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileSalaryMinimum + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileSalaryMinimum) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileSalaryMinimum) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileSalaryMinimumInput as json. +func (o NilProfileSalaryMinimumInput) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileSalaryMinimumInput from json. +func (o *NilProfileSalaryMinimumInput) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileSalaryMinimumInput to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileSalaryMinimumInput + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileSalaryMinimumInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileSalaryMinimumInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileTelegramInput as json. +func (o NilProfileTelegramInput) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileTelegramInput from json. +func (o *NilProfileTelegramInput) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileTelegramInput to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileTelegramInput + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileTelegramInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileTelegramInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileYearMonth as json. +func (o NilProfileYearMonth) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ProfileYearMonth from json. +func (o *NilProfileYearMonth) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilProfileYearMonth to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ProfileYearMonth + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilProfileYearMonth) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilProfileYearMonth) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes SalaryRange as json. func (o NilSalaryRange) Encode(e *jx.Encoder) { if o.Null { @@ -30952,6 +32181,4095 @@ func (s *ProblemFieldLocation) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ProfileClaimOrigin as json. +func (s ProfileClaimOrigin) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProfileClaimOrigin from json. +func (s *ProfileClaimOrigin) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileClaimOrigin to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProfileClaimOrigin(v) { + case ProfileClaimOriginManual: + *s = ProfileClaimOriginManual + case ProfileClaimOriginExtractedFromResume: + *s = ProfileClaimOriginExtractedFromResume + case ProfileClaimOriginImported: + *s = ProfileClaimOriginImported + default: + *s = ProfileClaimOrigin(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileClaimOrigin) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileClaimOrigin) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileClaimQuote as json. +func (s ProfileClaimQuote) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ProfileClaimQuote from json. +func (s *ProfileClaimQuote) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileClaimQuote to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ProfileClaimQuote(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileClaimQuote) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileClaimQuote) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileClaimSource) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileClaimSource) encodeFields(e *jx.Encoder) { + { + e.FieldStart("origin") + s.Origin.Encode(e) + } + { + e.FieldStart("trust_level") + s.TrustLevel.Encode(e) + } + { + e.FieldStart("quote") + s.Quote.Encode(e) + } + { + e.FieldStart("extraction_version") + s.ExtractionVersion.Encode(e) + } + { + e.FieldStart("confirmed_at") + s.ConfirmedAt.Encode(e) + } +} + +var jsonFieldsNameOfProfileClaimSource = [5]string{ + 0: "origin", + 1: "trust_level", + 2: "quote", + 3: "extraction_version", + 4: "confirmed_at", +} + +// Decode decodes ProfileClaimSource from json. +func (s *ProfileClaimSource) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileClaimSource to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "origin": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Origin.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"origin\"") + } + case "trust_level": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.TrustLevel.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"trust_level\"") + } + case "quote": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Quote.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"quote\"") + } + case "extraction_version": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.ExtractionVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"extraction_version\"") + } + case "confirmed_at": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.ConfirmedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmed_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileClaimSource") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00011111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileClaimSource) { + name = jsonFieldsNameOfProfileClaimSource[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileClaimSource) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileClaimSource) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileClaimStatus as json. +func (s ProfileClaimStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProfileClaimStatus from json. +func (s *ProfileClaimStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileClaimStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProfileClaimStatus(v) { + case ProfileClaimStatusConfirmed: + *s = ProfileClaimStatusConfirmed + case ProfileClaimStatusExtracted: + *s = ProfileClaimStatusExtracted + case ProfileClaimStatusUnknown: + *s = ProfileClaimStatusUnknown + default: + *s = ProfileClaimStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileClaimStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileClaimStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileClaimTrustLevel as json. +func (s ProfileClaimTrustLevel) Encode(e *jx.Encoder) { + unwrapped := int32(s) + + e.Int32(unwrapped) +} + +// Decode decodes ProfileClaimTrustLevel from json. +func (s *ProfileClaimTrustLevel) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileClaimTrustLevel to nil") + } + var unwrapped int32 + if err := func() error { + v, err := d.Int32() + unwrapped = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ProfileClaimTrustLevel(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileClaimTrustLevel) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileClaimTrustLevel) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileConfirmedCategory) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileConfirmedCategory) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("grade") + s.Grade.Encode(e) + } + { + e.FieldStart("confirmed_at") + s.ConfirmedAt.Encode(e) + } + { + e.FieldStart("attempt_id") + json.EncodeUUID(e, s.AttemptID) + } +} + +var jsonFieldsNameOfProfileConfirmedCategory = [4]string{ + 0: "specialization", + 1: "grade", + 2: "confirmed_at", + 3: "attempt_id", +} + +// Decode decodes ProfileConfirmedCategory from json. +func (s *ProfileConfirmedCategory) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileConfirmedCategory to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specialization": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "grade": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Grade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"grade\"") + } + case "confirmed_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.ConfirmedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmed_at\"") + } + case "attempt_id": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := json.DecodeUUID(d) + s.AttemptID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"attempt_id\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileConfirmedCategory") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileConfirmedCategory) { + name = jsonFieldsNameOfProfileConfirmedCategory[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileConfirmedCategory) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileConfirmedCategory) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileContacts) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileContacts) encodeFields(e *jx.Encoder) { + { + e.FieldStart("email") + s.Email.Encode(e) + } + { + e.FieldStart("phone") + s.Phone.Encode(e) + } + { + e.FieldStart("telegram") + s.Telegram.Encode(e) + } +} + +var jsonFieldsNameOfProfileContacts = [3]string{ + 0: "email", + 1: "phone", + 2: "telegram", +} + +// Decode decodes ProfileContacts from json. +func (s *ProfileContacts) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileContacts to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "email": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Email.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email\"") + } + case "phone": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Phone.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"phone\"") + } + case "telegram": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Telegram.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"telegram\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileContacts") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileContacts) { + name = jsonFieldsNameOfProfileContacts[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileContacts) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileContacts) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileContactsInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileContactsInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("email") + s.Email.Encode(e) + } + { + e.FieldStart("phone") + s.Phone.Encode(e) + } + { + e.FieldStart("telegram") + s.Telegram.Encode(e) + } +} + +var jsonFieldsNameOfProfileContactsInput = [3]string{ + 0: "email", + 1: "phone", + 2: "telegram", +} + +// Decode decodes ProfileContactsInput from json. +func (s *ProfileContactsInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileContactsInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "email": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Email.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email\"") + } + case "phone": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Phone.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"phone\"") + } + case "telegram": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Telegram.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"telegram\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileContactsInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileContactsInput) { + name = jsonFieldsNameOfProfileContactsInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileContactsInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileContactsInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileEmailClaim) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileEmailClaim) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileEmailClaim = [3]string{ + 0: "status", + 1: "value", + 2: "source", +} + +// Decode decodes ProfileEmailClaim from json. +func (s *ProfileEmailClaim) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileEmailClaim to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "value": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "source": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileEmailClaim") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileEmailClaim) { + name = jsonFieldsNameOfProfileEmailClaim[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileEmailClaim) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileEmailClaim) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileEmailInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileEmailInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileEmailInput = [2]string{ + 0: "value", + 1: "status", +} + +// Decode decodes ProfileEmailInput from json. +func (s *ProfileEmailInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileEmailInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "value": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileEmailInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileEmailInput) { + name = jsonFieldsNameOfProfileEmailInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileEmailInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileEmailInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileEmployerName as json. +func (s ProfileEmployerName) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ProfileEmployerName from json. +func (s *ProfileEmployerName) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileEmployerName to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ProfileEmployerName(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileEmployerName) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileEmployerName) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileExperienceItem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileExperienceItem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("employer_name") + s.EmployerName.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("started_on") + s.StartedOn.Encode(e) + } + { + e.FieldStart("ended_on") + s.EndedOn.Encode(e) + } + { + e.FieldStart("summary") + s.Summary.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileExperienceItem = [7]string{ + 0: "employer_name", + 1: "specialization", + 2: "started_on", + 3: "ended_on", + 4: "summary", + 5: "status", + 6: "source", +} + +// Decode decodes ProfileExperienceItem from json. +func (s *ProfileExperienceItem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileExperienceItem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "employer_name": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.EmployerName.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"employer_name\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "started_on": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.StartedOn.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"started_on\"") + } + case "ended_on": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.EndedOn.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ended_on\"") + } + case "summary": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Summary.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"summary\"") + } + case "status": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "source": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileExperienceItem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b01111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileExperienceItem) { + name = jsonFieldsNameOfProfileExperienceItem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileExperienceItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileExperienceItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileExperienceItemInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileExperienceItemInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("employer_name") + s.EmployerName.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("started_on") + s.StartedOn.Encode(e) + } + { + e.FieldStart("ended_on") + s.EndedOn.Encode(e) + } + { + e.FieldStart("summary") + s.Summary.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileExperienceItemInput = [6]string{ + 0: "employer_name", + 1: "specialization", + 2: "started_on", + 3: "ended_on", + 4: "summary", + 5: "status", +} + +// Decode decodes ProfileExperienceItemInput from json. +func (s *ProfileExperienceItemInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileExperienceItemInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "employer_name": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.EmployerName.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"employer_name\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "started_on": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.StartedOn.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"started_on\"") + } + case "ended_on": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.EndedOn.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"ended_on\"") + } + case "summary": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Summary.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"summary\"") + } + case "status": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileExperienceItemInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileExperienceItemInput) { + name = jsonFieldsNameOfProfileExperienceItemInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileExperienceItemInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileExperienceItemInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileExperienceSummary as json. +func (s ProfileExperienceSummary) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ProfileExperienceSummary from json. +func (s *ProfileExperienceSummary) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileExperienceSummary to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ProfileExperienceSummary(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileExperienceSummary) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileExperienceSummary) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileFullNameClaim) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileFullNameClaim) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileFullNameClaim = [3]string{ + 0: "status", + 1: "value", + 2: "source", +} + +// Decode decodes ProfileFullNameClaim from json. +func (s *ProfileFullNameClaim) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileFullNameClaim to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "value": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "source": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileFullNameClaim") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileFullNameClaim) { + name = jsonFieldsNameOfProfileFullNameClaim[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileFullNameClaim) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileFullNameClaim) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileFullNameInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileFullNameInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileFullNameInput = [2]string{ + 0: "value", + 1: "status", +} + +// Decode decodes ProfileFullNameInput from json. +func (s *ProfileFullNameInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileFullNameInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "value": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileFullNameInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileFullNameInput) { + name = jsonFieldsNameOfProfileFullNameInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileFullNameInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileFullNameInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileItemStatus as json. +func (s ProfileItemStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ProfileItemStatus from json. +func (s *ProfileItemStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileItemStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ProfileItemStatus(v) { + case ProfileItemStatusConfirmed: + *s = ProfileItemStatusConfirmed + case ProfileItemStatusExtracted: + *s = ProfileItemStatusExtracted + default: + *s = ProfileItemStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileItemStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileItemStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileLocationClaim) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileLocationClaim) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileLocationClaim = [3]string{ + 0: "status", + 1: "value", + 2: "source", +} + +// Decode decodes ProfileLocationClaim from json. +func (s *ProfileLocationClaim) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileLocationClaim to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "value": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "source": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileLocationClaim") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileLocationClaim) { + name = jsonFieldsNameOfProfileLocationClaim[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileLocationClaim) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileLocationClaim) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileLocationInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileLocationInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileLocationInput = [2]string{ + 0: "value", + 1: "status", +} + +// Decode decodes ProfileLocationInput from json. +func (s *ProfileLocationInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileLocationInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "value": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileLocationInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileLocationInput) { + name = jsonFieldsNameOfProfileLocationInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileLocationInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileLocationInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileLocationName as json. +func (s ProfileLocationName) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ProfileLocationName from json. +func (s *ProfileLocationName) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileLocationName to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ProfileLocationName(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileLocationName) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileLocationName) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfilePhoneClaim) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfilePhoneClaim) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfilePhoneClaim = [3]string{ + 0: "status", + 1: "value", + 2: "source", +} + +// Decode decodes ProfilePhoneClaim from json. +func (s *ProfilePhoneClaim) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfilePhoneClaim to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "value": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "source": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfilePhoneClaim") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfilePhoneClaim) { + name = jsonFieldsNameOfProfilePhoneClaim[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfilePhoneClaim) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfilePhoneClaim) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfilePhoneInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfilePhoneInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfilePhoneInput = [2]string{ + 0: "value", + 1: "status", +} + +// Decode decodes ProfilePhoneInput from json. +func (s *ProfilePhoneInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfilePhoneInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "value": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfilePhoneInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfilePhoneInput) { + name = jsonFieldsNameOfProfilePhoneInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfilePhoneInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfilePhoneInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileRelocationClaim) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileRelocationClaim) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileRelocationClaim = [3]string{ + 0: "status", + 1: "value", + 2: "source", +} + +// Decode decodes ProfileRelocationClaim from json. +func (s *ProfileRelocationClaim) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileRelocationClaim to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "value": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "source": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileRelocationClaim") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileRelocationClaim) { + name = jsonFieldsNameOfProfileRelocationClaim[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileRelocationClaim) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileRelocationClaim) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileRelocationInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileRelocationInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("value") + e.Bool(s.Value) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileRelocationInput = [2]string{ + 0: "value", + 1: "status", +} + +// Decode decodes ProfileRelocationInput from json. +func (s *ProfileRelocationInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileRelocationInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "value": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Bool() + s.Value = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileRelocationInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileRelocationInput) { + name = jsonFieldsNameOfProfileRelocationInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileRelocationInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileRelocationInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileRoleItem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileRoleItem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("self_assessed_grade") + s.SelfAssessedGrade.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileRoleItem = [4]string{ + 0: "specialization", + 1: "self_assessed_grade", + 2: "status", + 3: "source", +} + +// Decode decodes ProfileRoleItem from json. +func (s *ProfileRoleItem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileRoleItem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specialization": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "self_assessed_grade": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.SelfAssessedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"self_assessed_grade\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "source": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileRoleItem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileRoleItem) { + name = jsonFieldsNameOfProfileRoleItem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileRoleItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileRoleItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileRoleItemInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileRoleItemInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("self_assessed_grade") + s.SelfAssessedGrade.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileRoleItemInput = [3]string{ + 0: "specialization", + 1: "self_assessed_grade", + 2: "status", +} + +// Decode decodes ProfileRoleItemInput from json. +func (s *ProfileRoleItemInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileRoleItemInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specialization": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "self_assessed_grade": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.SelfAssessedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"self_assessed_grade\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileRoleItemInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileRoleItemInput) { + name = jsonFieldsNameOfProfileRoleItemInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileRoleItemInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileRoleItemInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileSalaryMinimum) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileSalaryMinimum) encodeFields(e *jx.Encoder) { + { + e.FieldStart("amount") + s.Amount.Encode(e) + } + { + e.FieldStart("currency") + s.Currency.Encode(e) + } + { + e.FieldStart("period") + s.Period.Encode(e) + } + { + e.FieldStart("tax_basis") + s.TaxBasis.Encode(e) + } +} + +var jsonFieldsNameOfProfileSalaryMinimum = [4]string{ + 0: "amount", + 1: "currency", + 2: "period", + 3: "tax_basis", +} + +// Decode decodes ProfileSalaryMinimum from json. +func (s *ProfileSalaryMinimum) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileSalaryMinimum to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "amount": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Amount.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"amount\"") + } + case "currency": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Currency.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"currency\"") + } + case "period": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Period.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"period\"") + } + case "tax_basis": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.TaxBasis.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tax_basis\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileSalaryMinimum") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileSalaryMinimum) { + name = jsonFieldsNameOfProfileSalaryMinimum[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileSalaryMinimum) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileSalaryMinimum) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileSalaryMinimumClaim) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileSalaryMinimumClaim) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileSalaryMinimumClaim = [3]string{ + 0: "status", + 1: "value", + 2: "source", +} + +// Decode decodes ProfileSalaryMinimumClaim from json. +func (s *ProfileSalaryMinimumClaim) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileSalaryMinimumClaim to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "value": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "source": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileSalaryMinimumClaim") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileSalaryMinimumClaim) { + name = jsonFieldsNameOfProfileSalaryMinimumClaim[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileSalaryMinimumClaim) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileSalaryMinimumClaim) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileSalaryMinimumInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileSalaryMinimumInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileSalaryMinimumInput = [2]string{ + 0: "value", + 1: "status", +} + +// Decode decodes ProfileSalaryMinimumInput from json. +func (s *ProfileSalaryMinimumInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileSalaryMinimumInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "value": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileSalaryMinimumInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileSalaryMinimumInput) { + name = jsonFieldsNameOfProfileSalaryMinimumInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileSalaryMinimumInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileSalaryMinimumInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileSoftSkill as json. +func (s ProfileSoftSkill) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ProfileSoftSkill from json. +func (s *ProfileSoftSkill) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileSoftSkill to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ProfileSoftSkill(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileSoftSkill) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileSoftSkill) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileSoftSkillItem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileSoftSkillItem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("skill") + s.Skill.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileSoftSkillItem = [3]string{ + 0: "skill", + 1: "status", + 2: "source", +} + +// Decode decodes ProfileSoftSkillItem from json. +func (s *ProfileSoftSkillItem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileSoftSkillItem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "skill": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Skill.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"skill\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "source": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileSoftSkillItem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileSoftSkillItem) { + name = jsonFieldsNameOfProfileSoftSkillItem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileSoftSkillItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileSoftSkillItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileSoftSkillItemInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileSoftSkillItemInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("skill") + s.Skill.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileSoftSkillItemInput = [2]string{ + 0: "skill", + 1: "status", +} + +// Decode decodes ProfileSoftSkillItemInput from json. +func (s *ProfileSoftSkillItemInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileSoftSkillItemInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "skill": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Skill.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"skill\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileSoftSkillItemInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileSoftSkillItemInput) { + name = jsonFieldsNameOfProfileSoftSkillItemInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileSoftSkillItemInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileSoftSkillItemInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileStackItem) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileStackItem) encodeFields(e *jx.Encoder) { + { + e.FieldStart("tag") + s.Tag.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileStackItem = [3]string{ + 0: "tag", + 1: "status", + 2: "source", +} + +// Decode decodes ProfileStackItem from json. +func (s *ProfileStackItem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileStackItem to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "tag": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Tag.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tag\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "source": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileStackItem") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileStackItem) { + name = jsonFieldsNameOfProfileStackItem[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileStackItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileStackItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileStackItemInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileStackItemInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("tag") + s.Tag.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileStackItemInput = [2]string{ + 0: "tag", + 1: "status", +} + +// Decode decodes ProfileStackItemInput from json. +func (s *ProfileStackItemInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileStackItemInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "tag": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Tag.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tag\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileStackItemInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileStackItemInput) { + name = jsonFieldsNameOfProfileStackItemInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileStackItemInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileStackItemInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileTelegramClaim) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileTelegramClaim) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } +} + +var jsonFieldsNameOfProfileTelegramClaim = [3]string{ + 0: "status", + 1: "value", + 2: "source", +} + +// Decode decodes ProfileTelegramClaim from json. +func (s *ProfileTelegramClaim) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileTelegramClaim to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "value": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "source": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileTelegramClaim") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileTelegramClaim) { + name = jsonFieldsNameOfProfileTelegramClaim[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileTelegramClaim) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileTelegramClaim) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileTelegramInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileTelegramInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfProfileTelegramInput = [2]string{ + 0: "value", + 1: "status", +} + +// Decode decodes ProfileTelegramInput from json. +func (s *ProfileTelegramInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileTelegramInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "value": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileTelegramInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileTelegramInput) { + name = jsonFieldsNameOfProfileTelegramInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileTelegramInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileTelegramInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileTerms) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileTerms) encodeFields(e *jx.Encoder) { + { + e.FieldStart("location") + s.Location.Encode(e) + } + { + e.FieldStart("relocation") + s.Relocation.Encode(e) + } + { + e.FieldStart("salary_minimum") + s.SalaryMinimum.Encode(e) + } +} + +var jsonFieldsNameOfProfileTerms = [3]string{ + 0: "location", + 1: "relocation", + 2: "salary_minimum", +} + +// Decode decodes ProfileTerms from json. +func (s *ProfileTerms) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileTerms to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "location": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Location.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"location\"") + } + case "relocation": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Relocation.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"relocation\"") + } + case "salary_minimum": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.SalaryMinimum.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"salary_minimum\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileTerms") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileTerms) { + name = jsonFieldsNameOfProfileTerms[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileTerms) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileTerms) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ProfileTermsInput) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ProfileTermsInput) encodeFields(e *jx.Encoder) { + { + e.FieldStart("location") + s.Location.Encode(e) + } + { + e.FieldStart("relocation") + s.Relocation.Encode(e) + } + { + e.FieldStart("salary_minimum") + s.SalaryMinimum.Encode(e) + } +} + +var jsonFieldsNameOfProfileTermsInput = [3]string{ + 0: "location", + 1: "relocation", + 2: "salary_minimum", +} + +// Decode decodes ProfileTermsInput from json. +func (s *ProfileTermsInput) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileTermsInput to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "location": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Location.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"location\"") + } + case "relocation": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Relocation.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"relocation\"") + } + case "salary_minimum": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.SalaryMinimum.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"salary_minimum\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ProfileTermsInput") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfProfileTermsInput) { + name = jsonFieldsNameOfProfileTermsInput[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ProfileTermsInput) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileTermsInput) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileVersion as json. +func (s ProfileVersion) Encode(e *jx.Encoder) { + unwrapped := int64(s) + + e.Int64(unwrapped) +} + +// Decode decodes ProfileVersion from json. +func (s *ProfileVersion) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileVersion to nil") + } + var unwrapped int64 + if err := func() error { + v, err := d.Int64() + unwrapped = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ProfileVersion(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ProfileYearMonth as json. +func (s ProfileYearMonth) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ProfileYearMonth from json. +func (s *ProfileYearMonth) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ProfileYearMonth to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ProfileYearMonth(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ProfileYearMonth) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ProfileYearMonth) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *QuestionnaireSpecialization) Encode(e *jx.Encoder) { e.ObjStart() @@ -32075,6 +37393,158 @@ func (s *SalaryTaxBasis) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes SaveMyProfileBadRequest as json. +func (s *SaveMyProfileBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SaveMyProfileBadRequest from json. +func (s *SaveMyProfileBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SaveMyProfileBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SaveMyProfileBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SaveMyProfileBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SaveMyProfileBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SaveMyProfileForbidden as json. +func (s *SaveMyProfileForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SaveMyProfileForbidden from json. +func (s *SaveMyProfileForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SaveMyProfileForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SaveMyProfileForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SaveMyProfileForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SaveMyProfileForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SaveMyProfilePreconditionFailed as json. +func (s *SaveMyProfilePreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SaveMyProfilePreconditionFailed from json. +func (s *SaveMyProfilePreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SaveMyProfilePreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SaveMyProfilePreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SaveMyProfilePreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SaveMyProfilePreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SaveMyProfileUnauthorized as json. +func (s *SaveMyProfileUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SaveMyProfileUnauthorized from json. +func (s *SaveMyProfileUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SaveMyProfileUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SaveMyProfileUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SaveMyProfileUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SaveMyProfileUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes SaveMyQuestionnaireBadRequest as json. func (s *SaveMyQuestionnaireBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index 350e24b..d4271e2 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -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" diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index 37ae587..2afb019 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -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, diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index bc11d38..fe985d7 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -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: diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index f66c345..f5f0910 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -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" { diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index e902c5e..6a5170b 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -2341,7 +2341,9 @@ type CancelMyInvitationUnprocessableEntity Problem func (*CancelMyInvitationUnprocessableEntity) cancelMyInvitationRes() {} // 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. +// 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. // Ref: #/components/schemas/CandidateExperience type CandidateExperience struct { // Months of commercial work in the specialization. @@ -2891,6 +2893,278 @@ func (s *CandidateOrganizationCard) SetVerificationLevel(val OrganizationVerific s.VerificationLevel = val } +// 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. +// Ref: #/components/schemas/CandidateProfile +type CandidateProfile struct { + Version ProfileVersion `json:"version"` + FullName ProfileFullNameClaim `json:"full_name"` + Contacts ProfileContacts `json:"contacts"` + // Technology tags in the order the candidate gave them, each tag at most once without regard to letter + // case. + Stack []ProfileStackItem `json:"stack"` + // Roles in the order the candidate gave them, each specialization at most once. + Roles []ProfileRoleItem `json:"roles"` + // Work history entries in the order the candidate gave them. + Experience []ProfileExperienceItem `json:"experience"` + // Soft skills in the order the candidate gave them, each skill at most once without regard to letter + // case. + SoftSkills []ProfileSoftSkillItem `json:"soft_skills"` + Terms ProfileTerms `json:"terms"` + // Categories that assessment results confirmed, at most one per specialization, in catalog order. + // Read-only and empty until an assessment confirms a grade. + ConfirmedCategories []ProfileConfirmedCategory `json:"confirmed_categories"` + // Time of the last change, or null before the first save. + UpdatedAt NilTimestamp `json:"updated_at"` +} + +// GetVersion returns the value of Version. +func (s *CandidateProfile) GetVersion() ProfileVersion { + return s.Version +} + +// GetFullName returns the value of FullName. +func (s *CandidateProfile) GetFullName() ProfileFullNameClaim { + return s.FullName +} + +// GetContacts returns the value of Contacts. +func (s *CandidateProfile) GetContacts() ProfileContacts { + return s.Contacts +} + +// GetStack returns the value of Stack. +func (s *CandidateProfile) GetStack() []ProfileStackItem { + return s.Stack +} + +// GetRoles returns the value of Roles. +func (s *CandidateProfile) GetRoles() []ProfileRoleItem { + return s.Roles +} + +// GetExperience returns the value of Experience. +func (s *CandidateProfile) GetExperience() []ProfileExperienceItem { + return s.Experience +} + +// GetSoftSkills returns the value of SoftSkills. +func (s *CandidateProfile) GetSoftSkills() []ProfileSoftSkillItem { + return s.SoftSkills +} + +// GetTerms returns the value of Terms. +func (s *CandidateProfile) GetTerms() ProfileTerms { + return s.Terms +} + +// GetConfirmedCategories returns the value of ConfirmedCategories. +func (s *CandidateProfile) GetConfirmedCategories() []ProfileConfirmedCategory { + return s.ConfirmedCategories +} + +// GetUpdatedAt returns the value of UpdatedAt. +func (s *CandidateProfile) GetUpdatedAt() NilTimestamp { + return s.UpdatedAt +} + +// SetVersion sets the value of Version. +func (s *CandidateProfile) SetVersion(val ProfileVersion) { + s.Version = val +} + +// SetFullName sets the value of FullName. +func (s *CandidateProfile) SetFullName(val ProfileFullNameClaim) { + s.FullName = val +} + +// SetContacts sets the value of Contacts. +func (s *CandidateProfile) SetContacts(val ProfileContacts) { + s.Contacts = val +} + +// SetStack sets the value of Stack. +func (s *CandidateProfile) SetStack(val []ProfileStackItem) { + s.Stack = val +} + +// SetRoles sets the value of Roles. +func (s *CandidateProfile) SetRoles(val []ProfileRoleItem) { + s.Roles = val +} + +// SetExperience sets the value of Experience. +func (s *CandidateProfile) SetExperience(val []ProfileExperienceItem) { + s.Experience = val +} + +// SetSoftSkills sets the value of SoftSkills. +func (s *CandidateProfile) SetSoftSkills(val []ProfileSoftSkillItem) { + s.SoftSkills = val +} + +// SetTerms sets the value of Terms. +func (s *CandidateProfile) SetTerms(val ProfileTerms) { + s.Terms = val +} + +// SetConfirmedCategories sets the value of ConfirmedCategories. +func (s *CandidateProfile) SetConfirmedCategories(val []ProfileConfirmedCategory) { + s.ConfirmedCategories = val +} + +// SetUpdatedAt sets the value of UpdatedAt. +func (s *CandidateProfile) SetUpdatedAt(val NilTimestamp) { + s.UpdatedAt = val +} + +// CandidateProfileHeaders wraps CandidateProfile with response headers. +type CandidateProfileHeaders struct { + CacheControl CacheControlNoStore + Response CandidateProfile +} + +// GetCacheControl returns the value of CacheControl. +func (s *CandidateProfileHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *CandidateProfileHeaders) GetResponse() CandidateProfile { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *CandidateProfileHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *CandidateProfileHeaders) SetResponse(val CandidateProfile) { + s.Response = val +} + +func (*CandidateProfileHeaders) getMyProfileRes() {} +func (*CandidateProfileHeaders) saveMyProfileRes() {} + +// 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. +// Ref: #/components/schemas/CandidateProfileUpdate +type CandidateProfileUpdate struct { + ExpectedVersion ProfileVersion `json:"expected_version"` + FullName NilProfileFullNameInput `json:"full_name"` + Contacts ProfileContactsInput `json:"contacts"` + // 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`. + Stack []ProfileStackItemInput `json:"stack"` + // Roles. The server answers 400 with the pointer of a role whose specialization repeats an earlier + // one, for example `/roles/1/specialization`. + Roles []ProfileRoleItemInput `json:"roles"` + // Work history entries. + Experience []ProfileExperienceItemInput `json:"experience"` + // Soft skills. The server answers 400 with the pointer of a skill that repeats an earlier one without + // regard to letter case. + SoftSkills []ProfileSoftSkillItemInput `json:"soft_skills"` + Terms ProfileTermsInput `json:"terms"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *CandidateProfileUpdate) GetExpectedVersion() ProfileVersion { + return s.ExpectedVersion +} + +// GetFullName returns the value of FullName. +func (s *CandidateProfileUpdate) GetFullName() NilProfileFullNameInput { + return s.FullName +} + +// GetContacts returns the value of Contacts. +func (s *CandidateProfileUpdate) GetContacts() ProfileContactsInput { + return s.Contacts +} + +// GetStack returns the value of Stack. +func (s *CandidateProfileUpdate) GetStack() []ProfileStackItemInput { + return s.Stack +} + +// GetRoles returns the value of Roles. +func (s *CandidateProfileUpdate) GetRoles() []ProfileRoleItemInput { + return s.Roles +} + +// GetExperience returns the value of Experience. +func (s *CandidateProfileUpdate) GetExperience() []ProfileExperienceItemInput { + return s.Experience +} + +// GetSoftSkills returns the value of SoftSkills. +func (s *CandidateProfileUpdate) GetSoftSkills() []ProfileSoftSkillItemInput { + return s.SoftSkills +} + +// GetTerms returns the value of Terms. +func (s *CandidateProfileUpdate) GetTerms() ProfileTermsInput { + return s.Terms +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *CandidateProfileUpdate) SetExpectedVersion(val ProfileVersion) { + s.ExpectedVersion = val +} + +// SetFullName sets the value of FullName. +func (s *CandidateProfileUpdate) SetFullName(val NilProfileFullNameInput) { + s.FullName = val +} + +// SetContacts sets the value of Contacts. +func (s *CandidateProfileUpdate) SetContacts(val ProfileContactsInput) { + s.Contacts = val +} + +// SetStack sets the value of Stack. +func (s *CandidateProfileUpdate) SetStack(val []ProfileStackItemInput) { + s.Stack = val +} + +// SetRoles sets the value of Roles. +func (s *CandidateProfileUpdate) SetRoles(val []ProfileRoleItemInput) { + s.Roles = val +} + +// SetExperience sets the value of Experience. +func (s *CandidateProfileUpdate) SetExperience(val []ProfileExperienceItemInput) { + s.Experience = val +} + +// SetSoftSkills sets the value of SoftSkills. +func (s *CandidateProfileUpdate) SetSoftSkills(val []ProfileSoftSkillItemInput) { + s.SoftSkills = val +} + +// SetTerms sets the value of Terms. +func (s *CandidateProfileUpdate) SetTerms(val ProfileTermsInput) { + s.Terms = val +} + // Questionnaire of the current candidate: the chosen specializations with self-assessed grades and the // working context. It never contains a confirmed grade or a category; those come only from assessment // results. A candidate who has not saved the questionnaire yet gets version 0, no specializations, and @@ -5228,6 +5502,14 @@ type GetMyInvitationUnauthorized Problem func (*GetMyInvitationUnauthorized) getMyInvitationRes() {} +type GetMyProfileForbidden Problem + +func (*GetMyProfileForbidden) getMyProfileRes() {} + +type GetMyProfileUnauthorized Problem + +func (*GetMyProfileUnauthorized) getMyProfileRes() {} + type GetMyQuestionnaireForbidden Problem func (*GetMyQuestionnaireForbidden) getMyQuestionnaireRes() {} @@ -11289,6 +11571,636 @@ func (o NilPracticeVerdict) Or(d PracticeVerdict) PracticeVerdict { return d } +// NewNilProfileClaimQuote returns new NilProfileClaimQuote with value set to v. +func NewNilProfileClaimQuote(v ProfileClaimQuote) NilProfileClaimQuote { + return NilProfileClaimQuote{ + Value: v, + } +} + +// NilProfileClaimQuote is nullable ProfileClaimQuote. +type NilProfileClaimQuote struct { + Value ProfileClaimQuote + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileClaimQuote) SetTo(v ProfileClaimQuote) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileClaimQuote) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileClaimQuote) SetToNull() { + o.Null = true + var v ProfileClaimQuote + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileClaimQuote) Get() (v ProfileClaimQuote, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileClaimQuote) Or(d ProfileClaimQuote) ProfileClaimQuote { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileClaimSource returns new NilProfileClaimSource with value set to v. +func NewNilProfileClaimSource(v ProfileClaimSource) NilProfileClaimSource { + return NilProfileClaimSource{ + Value: v, + } +} + +// NilProfileClaimSource is nullable ProfileClaimSource. +type NilProfileClaimSource struct { + Value ProfileClaimSource + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileClaimSource) SetTo(v ProfileClaimSource) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileClaimSource) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileClaimSource) SetToNull() { + o.Null = true + var v ProfileClaimSource + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileClaimSource) Get() (v ProfileClaimSource, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileClaimSource) Or(d ProfileClaimSource) ProfileClaimSource { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileEmailInput returns new NilProfileEmailInput with value set to v. +func NewNilProfileEmailInput(v ProfileEmailInput) NilProfileEmailInput { + return NilProfileEmailInput{ + Value: v, + } +} + +// NilProfileEmailInput is nullable ProfileEmailInput. +type NilProfileEmailInput struct { + Value ProfileEmailInput + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileEmailInput) SetTo(v ProfileEmailInput) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileEmailInput) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileEmailInput) SetToNull() { + o.Null = true + var v ProfileEmailInput + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileEmailInput) Get() (v ProfileEmailInput, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileEmailInput) Or(d ProfileEmailInput) ProfileEmailInput { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileEmployerName returns new NilProfileEmployerName with value set to v. +func NewNilProfileEmployerName(v ProfileEmployerName) NilProfileEmployerName { + return NilProfileEmployerName{ + Value: v, + } +} + +// NilProfileEmployerName is nullable ProfileEmployerName. +type NilProfileEmployerName struct { + Value ProfileEmployerName + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileEmployerName) SetTo(v ProfileEmployerName) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileEmployerName) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileEmployerName) SetToNull() { + o.Null = true + var v ProfileEmployerName + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileEmployerName) Get() (v ProfileEmployerName, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileEmployerName) Or(d ProfileEmployerName) ProfileEmployerName { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileExperienceSummary returns new NilProfileExperienceSummary with value set to v. +func NewNilProfileExperienceSummary(v ProfileExperienceSummary) NilProfileExperienceSummary { + return NilProfileExperienceSummary{ + Value: v, + } +} + +// NilProfileExperienceSummary is nullable ProfileExperienceSummary. +type NilProfileExperienceSummary struct { + Value ProfileExperienceSummary + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileExperienceSummary) SetTo(v ProfileExperienceSummary) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileExperienceSummary) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileExperienceSummary) SetToNull() { + o.Null = true + var v ProfileExperienceSummary + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileExperienceSummary) Get() (v ProfileExperienceSummary, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileExperienceSummary) Or(d ProfileExperienceSummary) ProfileExperienceSummary { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileFullNameInput returns new NilProfileFullNameInput with value set to v. +func NewNilProfileFullNameInput(v ProfileFullNameInput) NilProfileFullNameInput { + return NilProfileFullNameInput{ + Value: v, + } +} + +// NilProfileFullNameInput is nullable ProfileFullNameInput. +type NilProfileFullNameInput struct { + Value ProfileFullNameInput + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileFullNameInput) SetTo(v ProfileFullNameInput) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileFullNameInput) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileFullNameInput) SetToNull() { + o.Null = true + var v ProfileFullNameInput + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileFullNameInput) Get() (v ProfileFullNameInput, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileFullNameInput) Or(d ProfileFullNameInput) ProfileFullNameInput { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileLocationInput returns new NilProfileLocationInput with value set to v. +func NewNilProfileLocationInput(v ProfileLocationInput) NilProfileLocationInput { + return NilProfileLocationInput{ + Value: v, + } +} + +// NilProfileLocationInput is nullable ProfileLocationInput. +type NilProfileLocationInput struct { + Value ProfileLocationInput + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileLocationInput) SetTo(v ProfileLocationInput) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileLocationInput) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileLocationInput) SetToNull() { + o.Null = true + var v ProfileLocationInput + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileLocationInput) Get() (v ProfileLocationInput, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileLocationInput) Or(d ProfileLocationInput) ProfileLocationInput { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileLocationName returns new NilProfileLocationName with value set to v. +func NewNilProfileLocationName(v ProfileLocationName) NilProfileLocationName { + return NilProfileLocationName{ + Value: v, + } +} + +// NilProfileLocationName is nullable ProfileLocationName. +type NilProfileLocationName struct { + Value ProfileLocationName + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileLocationName) SetTo(v ProfileLocationName) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileLocationName) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileLocationName) SetToNull() { + o.Null = true + var v ProfileLocationName + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileLocationName) Get() (v ProfileLocationName, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileLocationName) Or(d ProfileLocationName) ProfileLocationName { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfilePhoneInput returns new NilProfilePhoneInput with value set to v. +func NewNilProfilePhoneInput(v ProfilePhoneInput) NilProfilePhoneInput { + return NilProfilePhoneInput{ + Value: v, + } +} + +// NilProfilePhoneInput is nullable ProfilePhoneInput. +type NilProfilePhoneInput struct { + Value ProfilePhoneInput + Null bool +} + +// SetTo sets value to v. +func (o *NilProfilePhoneInput) SetTo(v ProfilePhoneInput) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfilePhoneInput) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfilePhoneInput) SetToNull() { + o.Null = true + var v ProfilePhoneInput + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfilePhoneInput) Get() (v ProfilePhoneInput, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfilePhoneInput) Or(d ProfilePhoneInput) ProfilePhoneInput { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileRelocationInput returns new NilProfileRelocationInput with value set to v. +func NewNilProfileRelocationInput(v ProfileRelocationInput) NilProfileRelocationInput { + return NilProfileRelocationInput{ + Value: v, + } +} + +// NilProfileRelocationInput is nullable ProfileRelocationInput. +type NilProfileRelocationInput struct { + Value ProfileRelocationInput + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileRelocationInput) SetTo(v ProfileRelocationInput) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileRelocationInput) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileRelocationInput) SetToNull() { + o.Null = true + var v ProfileRelocationInput + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileRelocationInput) Get() (v ProfileRelocationInput, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileRelocationInput) Or(d ProfileRelocationInput) ProfileRelocationInput { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileSalaryMinimum returns new NilProfileSalaryMinimum with value set to v. +func NewNilProfileSalaryMinimum(v ProfileSalaryMinimum) NilProfileSalaryMinimum { + return NilProfileSalaryMinimum{ + Value: v, + } +} + +// NilProfileSalaryMinimum is nullable ProfileSalaryMinimum. +type NilProfileSalaryMinimum struct { + Value ProfileSalaryMinimum + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileSalaryMinimum) SetTo(v ProfileSalaryMinimum) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileSalaryMinimum) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileSalaryMinimum) SetToNull() { + o.Null = true + var v ProfileSalaryMinimum + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileSalaryMinimum) Get() (v ProfileSalaryMinimum, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileSalaryMinimum) Or(d ProfileSalaryMinimum) ProfileSalaryMinimum { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileSalaryMinimumInput returns new NilProfileSalaryMinimumInput with value set to v. +func NewNilProfileSalaryMinimumInput(v ProfileSalaryMinimumInput) NilProfileSalaryMinimumInput { + return NilProfileSalaryMinimumInput{ + Value: v, + } +} + +// NilProfileSalaryMinimumInput is nullable ProfileSalaryMinimumInput. +type NilProfileSalaryMinimumInput struct { + Value ProfileSalaryMinimumInput + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileSalaryMinimumInput) SetTo(v ProfileSalaryMinimumInput) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileSalaryMinimumInput) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileSalaryMinimumInput) SetToNull() { + o.Null = true + var v ProfileSalaryMinimumInput + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileSalaryMinimumInput) Get() (v ProfileSalaryMinimumInput, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileSalaryMinimumInput) Or(d ProfileSalaryMinimumInput) ProfileSalaryMinimumInput { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileTelegramInput returns new NilProfileTelegramInput with value set to v. +func NewNilProfileTelegramInput(v ProfileTelegramInput) NilProfileTelegramInput { + return NilProfileTelegramInput{ + Value: v, + } +} + +// NilProfileTelegramInput is nullable ProfileTelegramInput. +type NilProfileTelegramInput struct { + Value ProfileTelegramInput + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileTelegramInput) SetTo(v ProfileTelegramInput) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileTelegramInput) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileTelegramInput) SetToNull() { + o.Null = true + var v ProfileTelegramInput + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileTelegramInput) Get() (v ProfileTelegramInput, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileTelegramInput) Or(d ProfileTelegramInput) ProfileTelegramInput { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilProfileYearMonth returns new NilProfileYearMonth with value set to v. +func NewNilProfileYearMonth(v ProfileYearMonth) NilProfileYearMonth { + return NilProfileYearMonth{ + Value: v, + } +} + +// NilProfileYearMonth is nullable ProfileYearMonth. +type NilProfileYearMonth struct { + Value ProfileYearMonth + Null bool +} + +// SetTo sets value to v. +func (o *NilProfileYearMonth) SetTo(v ProfileYearMonth) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilProfileYearMonth) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilProfileYearMonth) SetToNull() { + o.Null = true + var v ProfileYearMonth + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilProfileYearMonth) Get() (v ProfileYearMonth, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilProfileYearMonth) Or(d ProfileYearMonth) ProfileYearMonth { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilSalaryRange returns new NilSalaryRange with value set to v. func NewNilSalaryRange(v SalaryRange) NilSalaryRange { return NilSalaryRange{ @@ -16005,12 +16917,1410 @@ func (s *ProblemStatusCode) SetResponse(val Problem) { s.Response = val } +// 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. +// Ref: #/components/schemas/ProfileClaimOrigin +type ProfileClaimOrigin string + +const ( + ProfileClaimOriginManual ProfileClaimOrigin = "manual" + ProfileClaimOriginExtractedFromResume ProfileClaimOrigin = "extracted_from_resume" + ProfileClaimOriginImported ProfileClaimOrigin = "imported" +) + +// AllValues returns all ProfileClaimOrigin values. +func (ProfileClaimOrigin) AllValues() []ProfileClaimOrigin { + return []ProfileClaimOrigin{ + ProfileClaimOriginManual, + ProfileClaimOriginExtractedFromResume, + ProfileClaimOriginImported, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProfileClaimOrigin) MarshalText() ([]byte, error) { + switch s { + case ProfileClaimOriginManual: + return []byte(s), nil + case ProfileClaimOriginExtractedFromResume: + return []byte(s), nil + case ProfileClaimOriginImported: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProfileClaimOrigin) UnmarshalText(data []byte) error { + switch ProfileClaimOrigin(data) { + case ProfileClaimOriginManual: + *s = ProfileClaimOriginManual + return nil + case ProfileClaimOriginExtractedFromResume: + *s = ProfileClaimOriginExtractedFromResume + return nil + case ProfileClaimOriginImported: + *s = ProfileClaimOriginImported + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type ProfileClaimQuote string + +// 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. +// Ref: #/components/schemas/ProfileClaimSource +type ProfileClaimSource struct { + Origin ProfileClaimOrigin `json:"origin"` + TrustLevel ProfileClaimTrustLevel `json:"trust_level"` + // 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. + Quote NilProfileClaimQuote `json:"quote"` + // Extractor version for an extracted or imported value, or null for a manual value. + ExtractionVersion NilNeedVersionLabel `json:"extraction_version"` + // Time the candidate typed or confirmed the value, or null while the value is an unconfirmed + // suggestion. + ConfirmedAt NilTimestamp `json:"confirmed_at"` +} + +// GetOrigin returns the value of Origin. +func (s *ProfileClaimSource) GetOrigin() ProfileClaimOrigin { + return s.Origin +} + +// GetTrustLevel returns the value of TrustLevel. +func (s *ProfileClaimSource) GetTrustLevel() ProfileClaimTrustLevel { + return s.TrustLevel +} + +// GetQuote returns the value of Quote. +func (s *ProfileClaimSource) GetQuote() NilProfileClaimQuote { + return s.Quote +} + +// GetExtractionVersion returns the value of ExtractionVersion. +func (s *ProfileClaimSource) GetExtractionVersion() NilNeedVersionLabel { + return s.ExtractionVersion +} + +// GetConfirmedAt returns the value of ConfirmedAt. +func (s *ProfileClaimSource) GetConfirmedAt() NilTimestamp { + return s.ConfirmedAt +} + +// SetOrigin sets the value of Origin. +func (s *ProfileClaimSource) SetOrigin(val ProfileClaimOrigin) { + s.Origin = val +} + +// SetTrustLevel sets the value of TrustLevel. +func (s *ProfileClaimSource) SetTrustLevel(val ProfileClaimTrustLevel) { + s.TrustLevel = val +} + +// SetQuote sets the value of Quote. +func (s *ProfileClaimSource) SetQuote(val NilProfileClaimQuote) { + s.Quote = val +} + +// SetExtractionVersion sets the value of ExtractionVersion. +func (s *ProfileClaimSource) SetExtractionVersion(val NilNeedVersionLabel) { + s.ExtractionVersion = val +} + +// SetConfirmedAt sets the value of ConfirmedAt. +func (s *ProfileClaimSource) SetConfirmedAt(val NilTimestamp) { + s.ConfirmedAt = val +} + +// 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. +// +// Ref: #/components/schemas/ProfileClaimStatus +type ProfileClaimStatus string + +const ( + ProfileClaimStatusConfirmed ProfileClaimStatus = "confirmed" + ProfileClaimStatusExtracted ProfileClaimStatus = "extracted" + ProfileClaimStatusUnknown ProfileClaimStatus = "unknown" +) + +// AllValues returns all ProfileClaimStatus values. +func (ProfileClaimStatus) AllValues() []ProfileClaimStatus { + return []ProfileClaimStatus{ + ProfileClaimStatusConfirmed, + ProfileClaimStatusExtracted, + ProfileClaimStatusUnknown, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProfileClaimStatus) MarshalText() ([]byte, error) { + switch s { + case ProfileClaimStatusConfirmed: + return []byte(s), nil + case ProfileClaimStatusExtracted: + return []byte(s), nil + case ProfileClaimStatusUnknown: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProfileClaimStatus) UnmarshalText(data []byte) error { + switch ProfileClaimStatus(data) { + case ProfileClaimStatusConfirmed: + *s = ProfileClaimStatusConfirmed + return nil + case ProfileClaimStatusExtracted: + *s = ProfileClaimStatusExtracted + return nil + case ProfileClaimStatusUnknown: + *s = ProfileClaimStatusUnknown + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type ProfileClaimTrustLevel int32 + +// 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`. +// Ref: #/components/schemas/ProfileConfirmedCategory +type ProfileConfirmedCategory struct { + Specialization SpecializationCode `json:"specialization"` + Grade GradeCode `json:"grade"` + ConfirmedAt Timestamp `json:"confirmed_at"` + // Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate. + AttemptID uuid.UUID `json:"attempt_id"` +} + +// GetSpecialization returns the value of Specialization. +func (s *ProfileConfirmedCategory) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetGrade returns the value of Grade. +func (s *ProfileConfirmedCategory) GetGrade() GradeCode { + return s.Grade +} + +// GetConfirmedAt returns the value of ConfirmedAt. +func (s *ProfileConfirmedCategory) GetConfirmedAt() Timestamp { + return s.ConfirmedAt +} + +// GetAttemptID returns the value of AttemptID. +func (s *ProfileConfirmedCategory) GetAttemptID() uuid.UUID { + return s.AttemptID +} + +// SetSpecialization sets the value of Specialization. +func (s *ProfileConfirmedCategory) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetGrade sets the value of Grade. +func (s *ProfileConfirmedCategory) SetGrade(val GradeCode) { + s.Grade = val +} + +// SetConfirmedAt sets the value of ConfirmedAt. +func (s *ProfileConfirmedCategory) SetConfirmedAt(val Timestamp) { + s.ConfirmedAt = val +} + +// SetAttemptID sets the value of AttemptID. +func (s *ProfileConfirmedCategory) SetAttemptID(val uuid.UUID) { + s.AttemptID = val +} + +// 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. +// Ref: #/components/schemas/ProfileContacts +type ProfileContacts struct { + Email ProfileEmailClaim `json:"email"` + Phone ProfilePhoneClaim `json:"phone"` + Telegram ProfileTelegramClaim `json:"telegram"` +} + +// GetEmail returns the value of Email. +func (s *ProfileContacts) GetEmail() ProfileEmailClaim { + return s.Email +} + +// GetPhone returns the value of Phone. +func (s *ProfileContacts) GetPhone() ProfilePhoneClaim { + return s.Phone +} + +// GetTelegram returns the value of Telegram. +func (s *ProfileContacts) GetTelegram() ProfileTelegramClaim { + return s.Telegram +} + +// SetEmail sets the value of Email. +func (s *ProfileContacts) SetEmail(val ProfileEmailClaim) { + s.Email = val +} + +// SetPhone sets the value of Phone. +func (s *ProfileContacts) SetPhone(val ProfilePhoneClaim) { + s.Phone = val +} + +// SetTelegram sets the value of Telegram. +func (s *ProfileContacts) SetTelegram(val ProfileTelegramClaim) { + s.Telegram = val +} + +// Decisions about the contact channels in a request. A channel sent as null is unknown: it is removed +// if it was set. +// Ref: #/components/schemas/ProfileContactsInput +type ProfileContactsInput struct { + Email NilProfileEmailInput `json:"email"` + Phone NilProfilePhoneInput `json:"phone"` + Telegram NilProfileTelegramInput `json:"telegram"` +} + +// GetEmail returns the value of Email. +func (s *ProfileContactsInput) GetEmail() NilProfileEmailInput { + return s.Email +} + +// GetPhone returns the value of Phone. +func (s *ProfileContactsInput) GetPhone() NilProfilePhoneInput { + return s.Phone +} + +// GetTelegram returns the value of Telegram. +func (s *ProfileContactsInput) GetTelegram() NilProfileTelegramInput { + return s.Telegram +} + +// SetEmail sets the value of Email. +func (s *ProfileContactsInput) SetEmail(val NilProfileEmailInput) { + s.Email = val +} + +// SetPhone sets the value of Phone. +func (s *ProfileContactsInput) SetPhone(val NilProfilePhoneInput) { + s.Phone = val +} + +// SetTelegram sets the value of Telegram. +func (s *ProfileContactsInput) SetTelegram(val NilProfileTelegramInput) { + s.Telegram = val +} + +// 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`. +// Ref: #/components/schemas/ProfileEmailClaim +type ProfileEmailClaim struct { + Status ProfileClaimStatus `json:"status"` + Value NilEmailAddress `json:"value"` + Source NilProfileClaimSource `json:"source"` +} + +// GetStatus returns the value of Status. +func (s *ProfileEmailClaim) GetStatus() ProfileClaimStatus { + return s.Status +} + +// GetValue returns the value of Value. +func (s *ProfileEmailClaim) GetValue() NilEmailAddress { + return s.Value +} + +// GetSource returns the value of Source. +func (s *ProfileEmailClaim) GetSource() NilProfileClaimSource { + return s.Source +} + +// SetStatus sets the value of Status. +func (s *ProfileEmailClaim) SetStatus(val ProfileClaimStatus) { + s.Status = val +} + +// SetValue sets the value of Value. +func (s *ProfileEmailClaim) SetValue(val NilEmailAddress) { + s.Value = val +} + +// SetSource sets the value of Source. +func (s *ProfileEmailClaim) SetSource(val NilProfileClaimSource) { + s.Source = val +} + +// Decision about the contact email in a request; see CandidateProfileUpdate for the rules of `status`. +// The value is personal data. +// Ref: #/components/schemas/ProfileEmailInput +type ProfileEmailInput struct { + Value EmailAddress `json:"value"` + Status ProfileItemStatus `json:"status"` +} + +// GetValue returns the value of Value. +func (s *ProfileEmailInput) GetValue() EmailAddress { + return s.Value +} + +// GetStatus returns the value of Status. +func (s *ProfileEmailInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetValue sets the value of Value. +func (s *ProfileEmailInput) SetValue(val EmailAddress) { + s.Value = val +} + +// SetStatus sets the value of Status. +func (s *ProfileEmailInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +type ProfileEmployerName string + +// 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. +// Ref: #/components/schemas/ProfileExperienceItem +type ProfileExperienceItem struct { + // Employer of the entry, or null when the candidate gives none. + EmployerName NilProfileEmployerName `json:"employer_name"` + Specialization SpecializationCode `json:"specialization"` + StartedOn ProfileYearMonth `json:"started_on"` + // Last month of the work, or null when the candidate still works there. It is not earlier than + // `started_on`. + EndedOn NilProfileYearMonth `json:"ended_on"` + // Tasks and results of the entry, or null when the candidate gives none. + Summary NilProfileExperienceSummary `json:"summary"` + Status ProfileItemStatus `json:"status"` + Source ProfileClaimSource `json:"source"` +} + +// GetEmployerName returns the value of EmployerName. +func (s *ProfileExperienceItem) GetEmployerName() NilProfileEmployerName { + return s.EmployerName +} + +// GetSpecialization returns the value of Specialization. +func (s *ProfileExperienceItem) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetStartedOn returns the value of StartedOn. +func (s *ProfileExperienceItem) GetStartedOn() ProfileYearMonth { + return s.StartedOn +} + +// GetEndedOn returns the value of EndedOn. +func (s *ProfileExperienceItem) GetEndedOn() NilProfileYearMonth { + return s.EndedOn +} + +// GetSummary returns the value of Summary. +func (s *ProfileExperienceItem) GetSummary() NilProfileExperienceSummary { + return s.Summary +} + +// GetStatus returns the value of Status. +func (s *ProfileExperienceItem) GetStatus() ProfileItemStatus { + return s.Status +} + +// GetSource returns the value of Source. +func (s *ProfileExperienceItem) GetSource() ProfileClaimSource { + return s.Source +} + +// SetEmployerName sets the value of EmployerName. +func (s *ProfileExperienceItem) SetEmployerName(val NilProfileEmployerName) { + s.EmployerName = val +} + +// SetSpecialization sets the value of Specialization. +func (s *ProfileExperienceItem) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetStartedOn sets the value of StartedOn. +func (s *ProfileExperienceItem) SetStartedOn(val ProfileYearMonth) { + s.StartedOn = val +} + +// SetEndedOn sets the value of EndedOn. +func (s *ProfileExperienceItem) SetEndedOn(val NilProfileYearMonth) { + s.EndedOn = val +} + +// SetSummary sets the value of Summary. +func (s *ProfileExperienceItem) SetSummary(val NilProfileExperienceSummary) { + s.Summary = val +} + +// SetStatus sets the value of Status. +func (s *ProfileExperienceItem) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// SetSource sets the value of Source. +func (s *ProfileExperienceItem) SetSource(val ProfileClaimSource) { + s.Source = val +} + +// 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. +// Ref: #/components/schemas/ProfileExperienceItemInput +type ProfileExperienceItemInput struct { + EmployerName NilProfileEmployerName `json:"employer_name"` + Specialization SpecializationCode `json:"specialization"` + StartedOn ProfileYearMonth `json:"started_on"` + EndedOn NilProfileYearMonth `json:"ended_on"` + Summary NilProfileExperienceSummary `json:"summary"` + Status ProfileItemStatus `json:"status"` +} + +// GetEmployerName returns the value of EmployerName. +func (s *ProfileExperienceItemInput) GetEmployerName() NilProfileEmployerName { + return s.EmployerName +} + +// GetSpecialization returns the value of Specialization. +func (s *ProfileExperienceItemInput) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetStartedOn returns the value of StartedOn. +func (s *ProfileExperienceItemInput) GetStartedOn() ProfileYearMonth { + return s.StartedOn +} + +// GetEndedOn returns the value of EndedOn. +func (s *ProfileExperienceItemInput) GetEndedOn() NilProfileYearMonth { + return s.EndedOn +} + +// GetSummary returns the value of Summary. +func (s *ProfileExperienceItemInput) GetSummary() NilProfileExperienceSummary { + return s.Summary +} + +// GetStatus returns the value of Status. +func (s *ProfileExperienceItemInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetEmployerName sets the value of EmployerName. +func (s *ProfileExperienceItemInput) SetEmployerName(val NilProfileEmployerName) { + s.EmployerName = val +} + +// SetSpecialization sets the value of Specialization. +func (s *ProfileExperienceItemInput) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetStartedOn sets the value of StartedOn. +func (s *ProfileExperienceItemInput) SetStartedOn(val ProfileYearMonth) { + s.StartedOn = val +} + +// SetEndedOn sets the value of EndedOn. +func (s *ProfileExperienceItemInput) SetEndedOn(val NilProfileYearMonth) { + s.EndedOn = val +} + +// SetSummary sets the value of Summary. +func (s *ProfileExperienceItemInput) SetSummary(val NilProfileExperienceSummary) { + s.Summary = val +} + +// SetStatus sets the value of Status. +func (s *ProfileExperienceItemInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +type ProfileExperienceSummary string + +// 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`. +// Ref: #/components/schemas/ProfileFullNameClaim +type ProfileFullNameClaim struct { + Status ProfileClaimStatus `json:"status"` + Value NilContactFullName `json:"value"` + Source NilProfileClaimSource `json:"source"` +} + +// GetStatus returns the value of Status. +func (s *ProfileFullNameClaim) GetStatus() ProfileClaimStatus { + return s.Status +} + +// GetValue returns the value of Value. +func (s *ProfileFullNameClaim) GetValue() NilContactFullName { + return s.Value +} + +// GetSource returns the value of Source. +func (s *ProfileFullNameClaim) GetSource() NilProfileClaimSource { + return s.Source +} + +// SetStatus sets the value of Status. +func (s *ProfileFullNameClaim) SetStatus(val ProfileClaimStatus) { + s.Status = val +} + +// SetValue sets the value of Value. +func (s *ProfileFullNameClaim) SetValue(val NilContactFullName) { + s.Value = val +} + +// SetSource sets the value of Source. +func (s *ProfileFullNameClaim) SetSource(val NilProfileClaimSource) { + s.Source = val +} + +// Decision about the full name in a request; see CandidateProfileUpdate for the rules of `status`. The +// value is personal data. +// Ref: #/components/schemas/ProfileFullNameInput +type ProfileFullNameInput struct { + Value ContactFullName `json:"value"` + Status ProfileItemStatus `json:"status"` +} + +// GetValue returns the value of Value. +func (s *ProfileFullNameInput) GetValue() ContactFullName { + return s.Value +} + +// GetStatus returns the value of Status. +func (s *ProfileFullNameInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetValue sets the value of Value. +func (s *ProfileFullNameInput) SetValue(val ContactFullName) { + s.Value = val +} + +// SetStatus sets the value of Status. +func (s *ProfileFullNameInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// 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. +// Ref: #/components/schemas/ProfileItemStatus +type ProfileItemStatus string + +const ( + ProfileItemStatusConfirmed ProfileItemStatus = "confirmed" + ProfileItemStatusExtracted ProfileItemStatus = "extracted" +) + +// AllValues returns all ProfileItemStatus values. +func (ProfileItemStatus) AllValues() []ProfileItemStatus { + return []ProfileItemStatus{ + ProfileItemStatusConfirmed, + ProfileItemStatusExtracted, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ProfileItemStatus) MarshalText() ([]byte, error) { + switch s { + case ProfileItemStatusConfirmed: + return []byte(s), nil + case ProfileItemStatusExtracted: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ProfileItemStatus) UnmarshalText(data []byte) error { + switch ProfileItemStatus(data) { + case ProfileItemStatusConfirmed: + *s = ProfileItemStatusConfirmed + return nil + case ProfileItemStatusExtracted: + *s = ProfileItemStatusExtracted + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Place of the candidate with its confirmation state and provenance. It is personal data. `value` and +// `source` are null exactly when `status` is `unknown`. +// Ref: #/components/schemas/ProfileLocationClaim +type ProfileLocationClaim struct { + Status ProfileClaimStatus `json:"status"` + Value NilProfileLocationName `json:"value"` + Source NilProfileClaimSource `json:"source"` +} + +// GetStatus returns the value of Status. +func (s *ProfileLocationClaim) GetStatus() ProfileClaimStatus { + return s.Status +} + +// GetValue returns the value of Value. +func (s *ProfileLocationClaim) GetValue() NilProfileLocationName { + return s.Value +} + +// GetSource returns the value of Source. +func (s *ProfileLocationClaim) GetSource() NilProfileClaimSource { + return s.Source +} + +// SetStatus sets the value of Status. +func (s *ProfileLocationClaim) SetStatus(val ProfileClaimStatus) { + s.Status = val +} + +// SetValue sets the value of Value. +func (s *ProfileLocationClaim) SetValue(val NilProfileLocationName) { + s.Value = val +} + +// SetSource sets the value of Source. +func (s *ProfileLocationClaim) SetSource(val NilProfileClaimSource) { + s.Source = val +} + +// Decision about the place in a request; see CandidateProfileUpdate for the rules of `status`. The +// value is personal data. +// Ref: #/components/schemas/ProfileLocationInput +type ProfileLocationInput struct { + Value ProfileLocationName `json:"value"` + Status ProfileItemStatus `json:"status"` +} + +// GetValue returns the value of Value. +func (s *ProfileLocationInput) GetValue() ProfileLocationName { + return s.Value +} + +// GetStatus returns the value of Status. +func (s *ProfileLocationInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetValue sets the value of Value. +func (s *ProfileLocationInput) SetValue(val ProfileLocationName) { + s.Value = val +} + +// SetStatus sets the value of Status. +func (s *ProfileLocationInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +type ProfileLocationName string + +// 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`. +// Ref: #/components/schemas/ProfilePhoneClaim +type ProfilePhoneClaim struct { + Status ProfileClaimStatus `json:"status"` + Value NilContactPhoneNumber `json:"value"` + Source NilProfileClaimSource `json:"source"` +} + +// GetStatus returns the value of Status. +func (s *ProfilePhoneClaim) GetStatus() ProfileClaimStatus { + return s.Status +} + +// GetValue returns the value of Value. +func (s *ProfilePhoneClaim) GetValue() NilContactPhoneNumber { + return s.Value +} + +// GetSource returns the value of Source. +func (s *ProfilePhoneClaim) GetSource() NilProfileClaimSource { + return s.Source +} + +// SetStatus sets the value of Status. +func (s *ProfilePhoneClaim) SetStatus(val ProfileClaimStatus) { + s.Status = val +} + +// SetValue sets the value of Value. +func (s *ProfilePhoneClaim) SetValue(val NilContactPhoneNumber) { + s.Value = val +} + +// SetSource sets the value of Source. +func (s *ProfilePhoneClaim) SetSource(val NilProfileClaimSource) { + s.Source = val +} + +// Decision about the contact phone number in a request; see CandidateProfileUpdate for the rules of +// `status`. The value is personal data. +// Ref: #/components/schemas/ProfilePhoneInput +type ProfilePhoneInput struct { + Value ContactPhoneNumber `json:"value"` + Status ProfileItemStatus `json:"status"` +} + +// GetValue returns the value of Value. +func (s *ProfilePhoneInput) GetValue() ContactPhoneNumber { + return s.Value +} + +// GetStatus returns the value of Status. +func (s *ProfilePhoneInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetValue sets the value of Value. +func (s *ProfilePhoneInput) SetValue(val ContactPhoneNumber) { + s.Value = val +} + +// SetStatus sets the value of Status. +func (s *ProfilePhoneInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// 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. +// Ref: #/components/schemas/ProfileRelocationClaim +type ProfileRelocationClaim struct { + Status ProfileClaimStatus `json:"status"` + Value NilBool `json:"value"` + Source NilProfileClaimSource `json:"source"` +} + +// GetStatus returns the value of Status. +func (s *ProfileRelocationClaim) GetStatus() ProfileClaimStatus { + return s.Status +} + +// GetValue returns the value of Value. +func (s *ProfileRelocationClaim) GetValue() NilBool { + return s.Value +} + +// GetSource returns the value of Source. +func (s *ProfileRelocationClaim) GetSource() NilProfileClaimSource { + return s.Source +} + +// SetStatus sets the value of Status. +func (s *ProfileRelocationClaim) SetStatus(val ProfileClaimStatus) { + s.Status = val +} + +// SetValue sets the value of Value. +func (s *ProfileRelocationClaim) SetValue(val NilBool) { + s.Value = val +} + +// SetSource sets the value of Source. +func (s *ProfileRelocationClaim) SetSource(val NilProfileClaimSource) { + s.Source = val +} + +// Decision about readiness to relocate in a request; see CandidateProfileUpdate for the rules of +// `status`. +// Ref: #/components/schemas/ProfileRelocationInput +type ProfileRelocationInput struct { + Value bool `json:"value"` + Status ProfileItemStatus `json:"status"` +} + +// GetValue returns the value of Value. +func (s *ProfileRelocationInput) GetValue() bool { + return s.Value +} + +// GetStatus returns the value of Status. +func (s *ProfileRelocationInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetValue sets the value of Value. +func (s *ProfileRelocationInput) SetValue(val bool) { + s.Value = val +} + +// SetStatus sets the value of Status. +func (s *ProfileRelocationInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// 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. +// Ref: #/components/schemas/ProfileRoleItem +type ProfileRoleItem struct { + Specialization SpecializationCode `json:"specialization"` + // Grade that the candidate claims in the specialization, or null when the candidate names none. + SelfAssessedGrade NilGradeCode `json:"self_assessed_grade"` + Status ProfileItemStatus `json:"status"` + Source ProfileClaimSource `json:"source"` +} + +// GetSpecialization returns the value of Specialization. +func (s *ProfileRoleItem) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetSelfAssessedGrade returns the value of SelfAssessedGrade. +func (s *ProfileRoleItem) GetSelfAssessedGrade() NilGradeCode { + return s.SelfAssessedGrade +} + +// GetStatus returns the value of Status. +func (s *ProfileRoleItem) GetStatus() ProfileItemStatus { + return s.Status +} + +// GetSource returns the value of Source. +func (s *ProfileRoleItem) GetSource() ProfileClaimSource { + return s.Source +} + +// SetSpecialization sets the value of Specialization. +func (s *ProfileRoleItem) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetSelfAssessedGrade sets the value of SelfAssessedGrade. +func (s *ProfileRoleItem) SetSelfAssessedGrade(val NilGradeCode) { + s.SelfAssessedGrade = val +} + +// SetStatus sets the value of Status. +func (s *ProfileRoleItem) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// SetSource sets the value of Source. +func (s *ProfileRoleItem) SetSource(val ProfileClaimSource) { + s.Source = val +} + +// 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. +// Ref: #/components/schemas/ProfileRoleItemInput +type ProfileRoleItemInput struct { + Specialization SpecializationCode `json:"specialization"` + // Grade that the candidate claims, or null when the candidate names none. + SelfAssessedGrade NilGradeCode `json:"self_assessed_grade"` + Status ProfileItemStatus `json:"status"` +} + +// GetSpecialization returns the value of Specialization. +func (s *ProfileRoleItemInput) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetSelfAssessedGrade returns the value of SelfAssessedGrade. +func (s *ProfileRoleItemInput) GetSelfAssessedGrade() NilGradeCode { + return s.SelfAssessedGrade +} + +// GetStatus returns the value of Status. +func (s *ProfileRoleItemInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetSpecialization sets the value of Specialization. +func (s *ProfileRoleItemInput) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetSelfAssessedGrade sets the value of SelfAssessedGrade. +func (s *ProfileRoleItemInput) SetSelfAssessedGrade(val NilGradeCode) { + s.SelfAssessedGrade = val +} + +// SetStatus sets the value of Status. +func (s *ProfileRoleItemInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// 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. +// Ref: #/components/schemas/ProfileSalaryMinimum +type ProfileSalaryMinimum struct { + Amount RubAmount `json:"amount"` + Currency CurrencyCode `json:"currency"` + Period SalaryPeriod `json:"period"` + TaxBasis SalaryTaxBasis `json:"tax_basis"` +} + +// GetAmount returns the value of Amount. +func (s *ProfileSalaryMinimum) GetAmount() RubAmount { + return s.Amount +} + +// GetCurrency returns the value of Currency. +func (s *ProfileSalaryMinimum) GetCurrency() CurrencyCode { + return s.Currency +} + +// GetPeriod returns the value of Period. +func (s *ProfileSalaryMinimum) GetPeriod() SalaryPeriod { + return s.Period +} + +// GetTaxBasis returns the value of TaxBasis. +func (s *ProfileSalaryMinimum) GetTaxBasis() SalaryTaxBasis { + return s.TaxBasis +} + +// SetAmount sets the value of Amount. +func (s *ProfileSalaryMinimum) SetAmount(val RubAmount) { + s.Amount = val +} + +// SetCurrency sets the value of Currency. +func (s *ProfileSalaryMinimum) SetCurrency(val CurrencyCode) { + s.Currency = val +} + +// SetPeriod sets the value of Period. +func (s *ProfileSalaryMinimum) SetPeriod(val SalaryPeriod) { + s.Period = val +} + +// SetTaxBasis sets the value of TaxBasis. +func (s *ProfileSalaryMinimum) SetTaxBasis(val SalaryTaxBasis) { + s.TaxBasis = val +} + +// 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. +// Ref: #/components/schemas/ProfileSalaryMinimumClaim +type ProfileSalaryMinimumClaim struct { + Status ProfileClaimStatus `json:"status"` + Value NilProfileSalaryMinimum `json:"value"` + Source NilProfileClaimSource `json:"source"` +} + +// GetStatus returns the value of Status. +func (s *ProfileSalaryMinimumClaim) GetStatus() ProfileClaimStatus { + return s.Status +} + +// GetValue returns the value of Value. +func (s *ProfileSalaryMinimumClaim) GetValue() NilProfileSalaryMinimum { + return s.Value +} + +// GetSource returns the value of Source. +func (s *ProfileSalaryMinimumClaim) GetSource() NilProfileClaimSource { + return s.Source +} + +// SetStatus sets the value of Status. +func (s *ProfileSalaryMinimumClaim) SetStatus(val ProfileClaimStatus) { + s.Status = val +} + +// SetValue sets the value of Value. +func (s *ProfileSalaryMinimumClaim) SetValue(val NilProfileSalaryMinimum) { + s.Value = val +} + +// SetSource sets the value of Source. +func (s *ProfileSalaryMinimumClaim) SetSource(val NilProfileClaimSource) { + s.Source = val +} + +// Decision about the lowest salary in a request; see CandidateProfileUpdate for the rules of `status`. +// The value is personal data. +// Ref: #/components/schemas/ProfileSalaryMinimumInput +type ProfileSalaryMinimumInput struct { + Value ProfileSalaryMinimum `json:"value"` + Status ProfileItemStatus `json:"status"` +} + +// GetValue returns the value of Value. +func (s *ProfileSalaryMinimumInput) GetValue() ProfileSalaryMinimum { + return s.Value +} + +// GetStatus returns the value of Status. +func (s *ProfileSalaryMinimumInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetValue sets the value of Value. +func (s *ProfileSalaryMinimumInput) SetValue(val ProfileSalaryMinimum) { + s.Value = val +} + +// SetStatus sets the value of Status. +func (s *ProfileSalaryMinimumInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +type ProfileSoftSkill string + +// One soft skill of the candidate with its confirmation state and provenance. It is a claim; no +// assessment checks it. +// Ref: #/components/schemas/ProfileSoftSkillItem +type ProfileSoftSkillItem struct { + Skill ProfileSoftSkill `json:"skill"` + Status ProfileItemStatus `json:"status"` + Source ProfileClaimSource `json:"source"` +} + +// GetSkill returns the value of Skill. +func (s *ProfileSoftSkillItem) GetSkill() ProfileSoftSkill { + return s.Skill +} + +// GetStatus returns the value of Status. +func (s *ProfileSoftSkillItem) GetStatus() ProfileItemStatus { + return s.Status +} + +// GetSource returns the value of Source. +func (s *ProfileSoftSkillItem) GetSource() ProfileClaimSource { + return s.Source +} + +// SetSkill sets the value of Skill. +func (s *ProfileSoftSkillItem) SetSkill(val ProfileSoftSkill) { + s.Skill = val +} + +// SetStatus sets the value of Status. +func (s *ProfileSoftSkillItem) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// SetSource sets the value of Source. +func (s *ProfileSoftSkillItem) SetSource(val ProfileClaimSource) { + s.Source = val +} + +// Decision about one soft skill in a request; see CandidateProfileUpdate for the rules of `status`. +// Ref: #/components/schemas/ProfileSoftSkillItemInput +type ProfileSoftSkillItemInput struct { + Skill ProfileSoftSkill `json:"skill"` + Status ProfileItemStatus `json:"status"` +} + +// GetSkill returns the value of Skill. +func (s *ProfileSoftSkillItemInput) GetSkill() ProfileSoftSkill { + return s.Skill +} + +// GetStatus returns the value of Status. +func (s *ProfileSoftSkillItemInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetSkill sets the value of Skill. +func (s *ProfileSoftSkillItemInput) SetSkill(val ProfileSoftSkill) { + s.Skill = val +} + +// SetStatus sets the value of Status. +func (s *ProfileSoftSkillItemInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// 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. +// Ref: #/components/schemas/ProfileStackItem +type ProfileStackItem struct { + Tag StackTag `json:"tag"` + Status ProfileItemStatus `json:"status"` + Source ProfileClaimSource `json:"source"` +} + +// GetTag returns the value of Tag. +func (s *ProfileStackItem) GetTag() StackTag { + return s.Tag +} + +// GetStatus returns the value of Status. +func (s *ProfileStackItem) GetStatus() ProfileItemStatus { + return s.Status +} + +// GetSource returns the value of Source. +func (s *ProfileStackItem) GetSource() ProfileClaimSource { + return s.Source +} + +// SetTag sets the value of Tag. +func (s *ProfileStackItem) SetTag(val StackTag) { + s.Tag = val +} + +// SetStatus sets the value of Status. +func (s *ProfileStackItem) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// SetSource sets the value of Source. +func (s *ProfileStackItem) SetSource(val ProfileClaimSource) { + s.Source = val +} + +// Decision about one stack tag in a request; see CandidateProfileUpdate for the rules of `status`. +// Ref: #/components/schemas/ProfileStackItemInput +type ProfileStackItemInput struct { + Tag StackTag `json:"tag"` + Status ProfileItemStatus `json:"status"` +} + +// GetTag returns the value of Tag. +func (s *ProfileStackItemInput) GetTag() StackTag { + return s.Tag +} + +// GetStatus returns the value of Status. +func (s *ProfileStackItemInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetTag sets the value of Tag. +func (s *ProfileStackItemInput) SetTag(val StackTag) { + s.Tag = val +} + +// SetStatus sets the value of Status. +func (s *ProfileStackItemInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// 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`. +// Ref: #/components/schemas/ProfileTelegramClaim +type ProfileTelegramClaim struct { + Status ProfileClaimStatus `json:"status"` + Value NilContactTelegramUsername `json:"value"` + Source NilProfileClaimSource `json:"source"` +} + +// GetStatus returns the value of Status. +func (s *ProfileTelegramClaim) GetStatus() ProfileClaimStatus { + return s.Status +} + +// GetValue returns the value of Value. +func (s *ProfileTelegramClaim) GetValue() NilContactTelegramUsername { + return s.Value +} + +// GetSource returns the value of Source. +func (s *ProfileTelegramClaim) GetSource() NilProfileClaimSource { + return s.Source +} + +// SetStatus sets the value of Status. +func (s *ProfileTelegramClaim) SetStatus(val ProfileClaimStatus) { + s.Status = val +} + +// SetValue sets the value of Value. +func (s *ProfileTelegramClaim) SetValue(val NilContactTelegramUsername) { + s.Value = val +} + +// SetSource sets the value of Source. +func (s *ProfileTelegramClaim) SetSource(val NilProfileClaimSource) { + s.Source = val +} + +// Decision about the Telegram username in a request; see CandidateProfileUpdate for the rules of +// `status`. The value is personal data. +// Ref: #/components/schemas/ProfileTelegramInput +type ProfileTelegramInput struct { + Value ContactTelegramUsername `json:"value"` + Status ProfileItemStatus `json:"status"` +} + +// GetValue returns the value of Value. +func (s *ProfileTelegramInput) GetValue() ContactTelegramUsername { + return s.Value +} + +// GetStatus returns the value of Status. +func (s *ProfileTelegramInput) GetStatus() ProfileItemStatus { + return s.Status +} + +// SetValue sets the value of Value. +func (s *ProfileTelegramInput) SetValue(val ContactTelegramUsername) { + s.Value = val +} + +// SetStatus sets the value of Status. +func (s *ProfileTelegramInput) SetStatus(val ProfileItemStatus) { + s.Status = val +} + +// 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. +// Ref: #/components/schemas/ProfileTerms +type ProfileTerms struct { + Location ProfileLocationClaim `json:"location"` + Relocation ProfileRelocationClaim `json:"relocation"` + SalaryMinimum ProfileSalaryMinimumClaim `json:"salary_minimum"` +} + +// GetLocation returns the value of Location. +func (s *ProfileTerms) GetLocation() ProfileLocationClaim { + return s.Location +} + +// GetRelocation returns the value of Relocation. +func (s *ProfileTerms) GetRelocation() ProfileRelocationClaim { + return s.Relocation +} + +// GetSalaryMinimum returns the value of SalaryMinimum. +func (s *ProfileTerms) GetSalaryMinimum() ProfileSalaryMinimumClaim { + return s.SalaryMinimum +} + +// SetLocation sets the value of Location. +func (s *ProfileTerms) SetLocation(val ProfileLocationClaim) { + s.Location = val +} + +// SetRelocation sets the value of Relocation. +func (s *ProfileTerms) SetRelocation(val ProfileRelocationClaim) { + s.Relocation = val +} + +// SetSalaryMinimum sets the value of SalaryMinimum. +func (s *ProfileTerms) SetSalaryMinimum(val ProfileSalaryMinimumClaim) { + s.SalaryMinimum = val +} + +// Decisions about the desired terms in a request. A field sent as null is unknown: it is removed if it +// was set. +// Ref: #/components/schemas/ProfileTermsInput +type ProfileTermsInput struct { + Location NilProfileLocationInput `json:"location"` + Relocation NilProfileRelocationInput `json:"relocation"` + SalaryMinimum NilProfileSalaryMinimumInput `json:"salary_minimum"` +} + +// GetLocation returns the value of Location. +func (s *ProfileTermsInput) GetLocation() NilProfileLocationInput { + return s.Location +} + +// GetRelocation returns the value of Relocation. +func (s *ProfileTermsInput) GetRelocation() NilProfileRelocationInput { + return s.Relocation +} + +// GetSalaryMinimum returns the value of SalaryMinimum. +func (s *ProfileTermsInput) GetSalaryMinimum() NilProfileSalaryMinimumInput { + return s.SalaryMinimum +} + +// SetLocation sets the value of Location. +func (s *ProfileTermsInput) SetLocation(val NilProfileLocationInput) { + s.Location = val +} + +// SetRelocation sets the value of Relocation. +func (s *ProfileTermsInput) SetRelocation(val NilProfileRelocationInput) { + s.Relocation = val +} + +// SetSalaryMinimum sets the value of SalaryMinimum. +func (s *ProfileTermsInput) SetSalaryMinimum(val NilProfileSalaryMinimumInput) { + s.SalaryMinimum = val +} + +type ProfileVersion int64 + +type ProfileYearMonth string + // 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. +// 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. // Ref: #/components/schemas/QuestionnaireSpecialization type QuestionnaireSpecialization struct { Specialization SpecializationCode `json:"specialization"` @@ -16329,6 +18639,22 @@ func (s *SalaryTaxBasis) UnmarshalText(data []byte) error { } } +type SaveMyProfileBadRequest Problem + +func (*SaveMyProfileBadRequest) saveMyProfileRes() {} + +type SaveMyProfileForbidden Problem + +func (*SaveMyProfileForbidden) saveMyProfileRes() {} + +type SaveMyProfilePreconditionFailed Problem + +func (*SaveMyProfilePreconditionFailed) saveMyProfileRes() {} + +type SaveMyProfileUnauthorized Problem + +func (*SaveMyProfileUnauthorized) saveMyProfileRes() {} + type SaveMyQuestionnaireBadRequest Problem func (*SaveMyQuestionnaireBadRequest) saveMyQuestionnaireRes() {} @@ -19039,7 +21365,8 @@ type WithdrawOrganizationInvitationUnprocessableEntity Problem func (*WithdrawOrganizationInvitationUnprocessableEntity) withdrawOrganizationInvitationRes() {} // 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. +// location, relocation, and salary expectations belong to the candidate profile (`ProfileTerms`). The +// acceptable work formats live only here: the profile does not repeat them. // Ref: #/components/schemas/WorkContext type WorkContext struct { // Acceptable work formats. diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index 3bd2560..e763b1b 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -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{}, diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index b61b710..c551de0 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -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, diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 2d7e0b9..26aa476 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -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, diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index 05c1507..06e4392 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -2798,6 +2798,483 @@ func (s *CandidateOrganizationCard) Validate() error { return nil } +func (s *CandidateProfile) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if err := s.FullName.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "full_name", + Error: err, + }) + } + if err := func() error { + if err := s.Contacts.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "contacts", + Error: err, + }) + } + if err := func() error { + if s.Stack == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 30, + MaxLengthSet: true, + }).ValidateLength(len(s.Stack)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Stack { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "stack", + Error: err, + }) + } + if err := func() error { + if s.Roles == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 9, + MaxLengthSet: true, + }).ValidateLength(len(s.Roles)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Roles { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "roles", + Error: err, + }) + } + if err := func() error { + if s.Experience == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Experience)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Experience { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "experience", + Error: err, + }) + } + if err := func() error { + if s.SoftSkills == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.SoftSkills)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.SoftSkills { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "soft_skills", + Error: err, + }) + } + if err := func() error { + if err := s.Terms.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms", + Error: err, + }) + } + if err := func() error { + if s.ConfirmedCategories == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 9, + MaxLengthSet: true, + }).ValidateLength(len(s.ConfirmedCategories)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.ConfirmedCategories { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "confirmed_categories", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CandidateProfileHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CandidateProfileUpdate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if value, ok := s.FullName.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "full_name", + Error: err, + }) + } + if err := func() error { + if err := s.Contacts.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "contacts", + Error: err, + }) + } + if err := func() error { + if s.Stack == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 30, + MaxLengthSet: true, + }).ValidateLength(len(s.Stack)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Stack { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "stack", + Error: err, + }) + } + if err := func() error { + if s.Roles == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 9, + MaxLengthSet: true, + }).ValidateLength(len(s.Roles)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Roles { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "roles", + Error: err, + }) + } + if err := func() error { + if s.Experience == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Experience)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Experience { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "experience", + Error: err, + }) + } + if err := func() error { + if s.SoftSkills == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.SoftSkills)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.SoftSkills { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "soft_skills", + Error: err, + }) + } + if err := func() error { + if err := s.Terms.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *CandidateQuestionnaire) Validate() error { if s == nil { return validate.ErrNilPointer @@ -5361,6 +5838,22 @@ func (s *GetMyInvitationUnauthorized) Validate() error { return nil } +func (s *GetMyProfileForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyProfileUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetMyQuestionnaireForbidden) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -12268,6 +12761,1685 @@ func (s *ProblemStatusCode) Validate() error { return nil } +func (s ProfileClaimOrigin) Validate() error { + switch s { + case "manual": + return nil + case "extracted_from_resume": + return nil + case "imported": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s ProfileClaimQuote) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 300, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *ProfileClaimSource) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Origin.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "origin", + Error: err, + }) + } + if err := func() error { + if err := s.TrustLevel.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "trust_level", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Quote.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "quote", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ExtractionVersion.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "extraction_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProfileClaimStatus) Validate() error { + switch s { + case "confirmed": + return nil + case "extracted": + return nil + case "unknown": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s ProfileClaimTrustLevel) Validate() error { + alias := (int32)(s) + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(alias)); err != nil { + return errors.Wrap(err, "int") + } + return nil +} + +func (s *ProfileConfirmedCategory) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.Grade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "grade", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileContacts) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Email.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "email", + Error: err, + }) + } + if err := func() error { + if err := s.Phone.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "phone", + Error: err, + }) + } + if err := func() error { + if err := s.Telegram.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "telegram", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileContactsInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if value, ok := s.Email.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "email", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Phone.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "phone", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Telegram.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "telegram", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileEmailClaim) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Value.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Source.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileEmailInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProfileEmployerName) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *ProfileExperienceItem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if value, ok := s.EmployerName.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "employer_name", + Error: err, + }) + } + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.StartedOn.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "started_on", + Error: err, + }) + } + if err := func() error { + if value, ok := s.EndedOn.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "ended_on", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Summary.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "summary", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Source.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileExperienceItemInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if value, ok := s.EmployerName.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "employer_name", + Error: err, + }) + } + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.StartedOn.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "started_on", + Error: err, + }) + } + if err := func() error { + if value, ok := s.EndedOn.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "ended_on", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Summary.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "summary", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProfileExperienceSummary) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 1000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *ProfileFullNameClaim) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Value.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Source.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileFullNameInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProfileItemStatus) Validate() error { + switch s { + case "confirmed": + return nil + case "extracted": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ProfileLocationClaim) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Value.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Source.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileLocationInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProfileLocationName) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 100, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *ProfilePhoneClaim) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Value.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Source.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfilePhoneInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileRelocationClaim) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Source.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileRelocationInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileRoleItem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if value, ok := s.SelfAssessedGrade.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "self_assessed_grade", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Source.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileRoleItemInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if value, ok := s.SelfAssessedGrade.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "self_assessed_grade", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileSalaryMinimum) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Amount.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "amount", + Error: err, + }) + } + if err := func() error { + if err := s.Currency.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "currency", + Error: err, + }) + } + if err := func() error { + if err := s.Period.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "period", + Error: err, + }) + } + if err := func() error { + if err := s.TaxBasis.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "tax_basis", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileSalaryMinimumClaim) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Value.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Source.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileSalaryMinimumInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProfileSoftSkill) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 50, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *ProfileSoftSkillItem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Skill.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "skill", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Source.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileSoftSkillItemInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Skill.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "skill", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileStackItem) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Tag.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "tag", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Source.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileStackItemInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Tag.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "tag", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileTelegramClaim) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Value.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Source.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileTelegramInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileTerms) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Location.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "location", + Error: err, + }) + } + if err := func() error { + if err := s.Relocation.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "relocation", + Error: err, + }) + } + if err := func() error { + if err := s.SalaryMinimum.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "salary_minimum", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ProfileTermsInput) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if value, ok := s.Location.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "location", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Relocation.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "relocation", + Error: err, + }) + } + if err := func() error { + if value, ok := s.SalaryMinimum.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "salary_minimum", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ProfileVersion) Validate() error { + alias := (int64)(s) + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(alias)); err != nil { + return errors.Wrap(err, "int") + } + return nil +} + +func (s ProfileYearMonth) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 7, + MinLengthSet: true, + MaxLength: 7, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[0-9]{4}-(0[1-9]|1[0-2])$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + func (s *QuestionnaireSpecialization) Validate() error { if s == nil { return validate.ErrNilPointer @@ -12681,6 +14853,38 @@ func (s SalaryTaxBasis) Validate() error { } } +func (s *SaveMyProfileBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SaveMyProfileForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SaveMyProfilePreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SaveMyProfileUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *SaveMyQuestionnaireBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { diff --git a/backend/internal/adapter/primary/http/candidate_profile_contract_test.go b/backend/internal/adapter/primary/http/candidate_profile_contract_test.go new file mode 100644 index 0000000..f91a2af --- /dev/null +++ b/backend/internal/adapter/primary/http/candidate_profile_contract_test.go @@ -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) + }) + } +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/candidate.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/candidate.sql.go new file mode 100644 index 0000000..2bd3ba2 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/candidate.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 79bcab1..c88e8bf 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -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 diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 8a669e5..4a128e2 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -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 diff --git a/backend/internal/domain/candidate.go b/backend/internal/domain/candidate.go new file mode 100644 index 0000000..61adcea --- /dev/null +++ b/backend/internal/domain/candidate.go @@ -0,0 +1,1235 @@ +package domain + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "log/slog" + "regexp" + "slices" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +// ErrCandidateProfileVersionConflict reports that the expected version of a +// profile is not the current one: another save advanced it, or the client +// named a version that does not exist. Nothing was changed; the client reads +// the profile again. +var ErrCandidateProfileVersionConflict = errors.New("candidate profile changed concurrently") + +// ErrInvalidCandidateProfile reports a candidate profile value, decision, or +// stored profile that breaks a rule. +var ErrInvalidCandidateProfile = errors.New("invalid candidate profile") + +// CandidateProfileFieldError reports the request field of a candidate profile +// that broke a rule. It matches ErrInvalidCandidateProfile with errors.Is, and +// an HTTP adapter reads Pointer with errors.As to answer 400 with the pointer +// of the field. Reason is fixed text; neither field quotes the submitted +// value, which is personal data. +type CandidateProfileFieldError struct { + // Pointer is the JSON Pointer of the field in the request body, such as + // "/contacts/phone/value" or "/roles/1/specialization". + Pointer string + // Reason says which rule the field broke. + Reason string + // stateDependent marks a rule that is judged against the stored claims, + // such as a decision extracted: against a stale version the verdict is + // meaningless, so Replace answers a version conflict instead. + stateDependent bool +} + +func (err *CandidateProfileFieldError) Error() string { + return "candidate profile field " + err.Pointer + " " + err.Reason +} + +func (err *CandidateProfileFieldError) Unwrap() error { return ErrInvalidCandidateProfile } + +func invalidStateDependentProfileField(location, pointer, reason string) error { + return fmt.Errorf("%s - %w", location, &CandidateProfileFieldError{Pointer: pointer, Reason: reason, stateDependent: true}) +} + +func invalidProfileField(location, pointer, reason string) error { + return fmt.Errorf("%s - %w", location, &CandidateProfileFieldError{Pointer: pointer, Reason: reason}) +} + +const ( + // The bounds match the schemas of the public contract and the CHECK + // constraints of candidate_profile_claims. The full name bound is the one + // of ContactFullName, so a contact disclosure never has to cut it. + maxProfileFullNameRunes = 200 + maxProfileLocationRunes = 100 + maxProfileTagRunes = 50 + maxProfileEmployerRunes = 200 + maxProfileSummaryRunes = 1000 + maxProfileQuoteRunes = 300 + maxProfileStackItems = 30 + maxProfileExperienceItems = 20 + maxProfileSoftSkills = 10 + // minProfileSalaryAmount is also the step of an amount: PRD FR13 sets 1000 + // roubles for the bounds of a salary. + minProfileSalaryAmount = 1000 + maxProfileSalaryAmount = 100_000_000 + // profileCurrency and profilePeriod are the only values of the MVP. + profileCurrency = "RUB" + profilePeriod = "month" + + // ProfileClaimTrustLevel is the trust level of every profile claim. + // Whatever its origin, a claim is an unverified statement; a candidate + // confirming a suggestion changes its status, never its level. Higher + // levels belong to evidence, such as an assessment result, which is + // stored elsewhere and never written into a claim. + ProfileClaimTrustLevel = 0 +) + +var ( + // profileMonthPattern is the YYYY-MM format of ProfileYearMonth. + profileMonthPattern = regexp.MustCompile(`^[0-9]{4}-(0[1-9]|1[0-2])$`) + // profileExtractionLabelPattern is the format of an extractor version. + profileExtractionLabelPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`) +) + +// SpecializationCode is the stable code of a catalog specialization. A +// category is a specialization together with a confirmed grade; the code +// values match the SpecializationCode schema of the public contract. +type SpecializationCode string + +const ( + SpecializationBackend SpecializationCode = "backend" + SpecializationFrontend SpecializationCode = "frontend" + SpecializationMobile SpecializationCode = "mobile" + SpecializationNetworkEngineer SpecializationCode = "network_engineer" + SpecializationDevopsSRE SpecializationCode = "devops_sre" + SpecializationDataAnalyst SpecializationCode = "data_analyst" + SpecializationDSML SpecializationCode = "ds_ml" + SpecializationInformationSecurity SpecializationCode = "information_security" + SpecializationQA SpecializationCode = "qa" +) + +// specializationCodes lists the catalog in catalog order. +var specializationCodes = []SpecializationCode{ + SpecializationBackend, SpecializationFrontend, SpecializationMobile, SpecializationNetworkEngineer, + SpecializationDevopsSRE, SpecializationDataAnalyst, SpecializationDSML, SpecializationInformationSecurity, + SpecializationQA, +} + +// IsKnown reports whether code is a specialization of the catalog. +func (code SpecializationCode) IsKnown() bool { return slices.Contains(specializationCodes, code) } + +// GradeCode is a grade of the MVP scale. The same codes describe a +// self-assessed grade, which the candidate states, and a confirmed grade, +// which only an assessment result establishes; a profile stores only the +// first. The values match the GradeCode schema of the public contract. +type GradeCode string + +const ( + GradeIntern GradeCode = "intern" + GradeJunior GradeCode = "junior" + GradeMiddle GradeCode = "middle" + GradeSenior GradeCode = "senior" +) + +// IsKnown reports whether code is a grade of the scale. +func (code GradeCode) IsKnown() bool { + switch code { + case GradeIntern, GradeJunior, GradeMiddle, GradeSenior: + return true + default: + return false + } +} + +// ProfileClaimStatus is the confirmation state of a stored profile value. A +// value that does not exist has no claim at all, which is the contract's +// `unknown` state. Values match the ProfileItemStatus schema. +type ProfileClaimStatus string + +const ( + // ProfileClaimConfirmed means the candidate typed the value or confirmed + // a suggestion. + ProfileClaimConfirmed ProfileClaimStatus = "confirmed" + // ProfileClaimExtracted means the value is a suggestion from an imported + // document or source that nobody has confirmed yet. + ProfileClaimExtracted ProfileClaimStatus = "extracted" +) + +// ProfileClaimOrigin says where a claim came from. Values match the +// ProfileClaimOrigin schema. Only manual claims exist before an import is +// built; the import origins are planned. +type ProfileClaimOrigin string + +const ( + ProfileOriginManual ProfileClaimOrigin = "manual" + ProfileOriginExtractedFromResume ProfileClaimOrigin = "extracted_from_resume" + ProfileOriginImported ProfileClaimOrigin = "imported" +) + +// ProfileClaimSource is the provenance of one claim: its origin, the excerpt +// and extractor version of an import, and the time the candidate confirmed +// it. It holds no reference to a file, the ML service, or an FSP account: a +// profile never requires one. The quote can hold personal data, so String, +// GoString, Format, and LogValue redact the source. +type ProfileClaimSource struct { + origin ProfileClaimOrigin + quote string + extractionVersion string + confirmedAt time.Time +} + +const redactedProfile = "[redacted candidate profile]" + +// NewManualProfileClaimSource returns the source of a value that the +// candidate typed at the given time. +func NewManualProfileClaimSource(confirmedAt time.Time) (ProfileClaimSource, error) { + const location = "domain.NewManualProfileClaimSource" + if confirmedAt.IsZero() { + return ProfileClaimSource{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidCandidateProfile) + } + return ProfileClaimSource{origin: ProfileOriginManual, confirmedAt: confirmedAt}, nil +} + +// RestoreProfileClaimSource validates the provenance columns of a stored +// claim. confirmedAt is the zero time for an unconfirmed suggestion. A row +// that breaks the provenance rules fails with ErrInvalidCandidateProfile. +func RestoreProfileClaimSource( + origin ProfileClaimOrigin, trustLevel int, quote, extractionVersion string, confirmedAt time.Time, +) (ProfileClaimSource, error) { + const location = "domain.RestoreProfileClaimSource" + fail := func(reason string) (ProfileClaimSource, error) { + return ProfileClaimSource{}, fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidCandidateProfile) + } + if trustLevel != ProfileClaimTrustLevel { + return fail("every claim has trust level 0") + } + switch origin { + case ProfileOriginManual: + if quote != "" || extractionVersion != "" || confirmedAt.IsZero() { + return fail("a manual claim is confirmed and has no import data") + } + case ProfileOriginExtractedFromResume, ProfileOriginImported: + if !profileExtractionLabelPattern.MatchString(extractionVersion) { + return fail("an imported claim must name its extractor version") + } + if quote != "" && !validProfileQuote(quote) { + return fail("quote must be 1 to 300 characters without control characters") + } + default: + return fail("origin is unknown") + } + return ProfileClaimSource{origin: origin, quote: quote, extractionVersion: extractionVersion, confirmedAt: confirmedAt}, nil +} + +func validProfileQuote(quote string) bool { + return utf8.ValidString(quote) && utf8.RuneCountInString(quote) <= maxProfileQuoteRunes && + !strings.ContainsFunc(quote, func(character rune) bool { return character != '\n' && isForbiddenTextRune(character) }) +} + +func (source ProfileClaimSource) Origin() ProfileClaimOrigin { return source.origin } + +// TrustLevel returns the trust level of the claim, always +// ProfileClaimTrustLevel. +func (source ProfileClaimSource) TrustLevel() int { return ProfileClaimTrustLevel } + +// Quote returns the excerpt of the imported document, or "" for a manual +// value or an import without an excerpt. +func (source ProfileClaimSource) Quote() string { return source.quote } + +// ExtractionVersion returns the extractor version of an imported claim, or "" +// for a manual one. +func (source ProfileClaimSource) ExtractionVersion() string { return source.extractionVersion } + +// ConfirmedAt returns the time the candidate typed or confirmed the value, or +// the zero time while it is an unconfirmed suggestion. +func (source ProfileClaimSource) ConfirmedAt() time.Time { return source.confirmedAt } + +func (source ProfileClaimSource) confirm(at time.Time) ProfileClaimSource { + source.confirmedAt = at + return source +} + +func (source ProfileClaimSource) String() string { return redactedProfile } +func (source ProfileClaimSource) GoString() string { return redactedProfile } +func (source ProfileClaimSource) LogValue() slog.Value { + return slog.StringValue(redactedProfile) +} +func (source ProfileClaimSource) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedProfile) +} + +// ProfileClaim is one stored profile value with its status and provenance. +// The value is personal data of the candidate, so String, GoString, Format, +// and LogValue redact the claim. +type ProfileClaim[V comparable] struct { + value V + status ProfileClaimStatus + source ProfileClaimSource +} + +// RestoreProfileClaim returns a claim from a stored value. The status must +// agree with the source: a confirmed claim has a confirmation time and an +// unconfirmed suggestion has none and is an import. +func RestoreProfileClaim[V comparable](value V, status ProfileClaimStatus, source ProfileClaimSource) (ProfileClaim[V], error) { + const location = "domain.RestoreProfileClaim" + switch { + case source.origin == "": + return ProfileClaim[V]{}, fmt.Errorf("%s - source must be built by a source constructor: %w", location, ErrInvalidCandidateProfile) + case status == ProfileClaimConfirmed && source.confirmedAt.IsZero(): + return ProfileClaim[V]{}, fmt.Errorf("%s - a confirmed claim needs its confirmation time: %w", location, ErrInvalidCandidateProfile) + case status == ProfileClaimExtracted && (!source.confirmedAt.IsZero() || source.origin == ProfileOriginManual): + return ProfileClaim[V]{}, fmt.Errorf("%s - a suggestion is an unconfirmed import: %w", location, ErrInvalidCandidateProfile) + case status != ProfileClaimConfirmed && status != ProfileClaimExtracted: + return ProfileClaim[V]{}, fmt.Errorf("%s - status is unknown: %w", location, ErrInvalidCandidateProfile) + } + return ProfileClaim[V]{value: value, status: status, source: source}, nil +} + +func (claim ProfileClaim[V]) Value() V { return claim.value } +func (claim ProfileClaim[V]) Status() ProfileClaimStatus { return claim.status } +func (claim ProfileClaim[V]) Source() ProfileClaimSource { return claim.source } + +func (claim ProfileClaim[V]) String() string { return redactedProfile } +func (claim ProfileClaim[V]) GoString() string { return redactedProfile } +func (claim ProfileClaim[V]) LogValue() slog.Value { + return slog.StringValue(redactedProfile) +} +func (claim ProfileClaim[V]) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedProfile) +} + +func claimsEqual[V comparable](left, right ProfileClaim[V]) bool { + return left.value == right.value && left.status == right.status && + left.source.origin == right.source.origin && left.source.quote == right.source.quote && + left.source.extractionVersion == right.source.extractionVersion && + left.source.confirmedAt.Equal(right.source.confirmedAt) +} + +func optionalClaimsEqual[V comparable](left, right *ProfileClaim[V]) bool { + if left == nil || right == nil { + return left == right + } + return claimsEqual(*left, *right) +} + +// ProfileRole is a role of the candidate: a specialization with the grade the +// candidate claims for it. SelfAssessedGrade is "" when the candidate names +// none. It is a claim, the same one that the questionnaire calls the +// self-assessed grade: it never becomes a confirmed grade or a category. The +// type has no field for a confirmed grade on purpose. +type ProfileRole struct { + Specialization SpecializationCode + SelfAssessedGrade GradeCode +} + +// ProfileExperience is one entry of the work history. It describes the work +// by its specialization and tasks rather than by a job title. EmployerName +// and Summary are "" when not given; StartedOn and EndedOn are YYYY-MM months +// and EndedOn is "" for a job that continues. The entry is personal data: +// String, GoString, Format, and LogValue redact it. +type ProfileExperience struct { + EmployerName string + Specialization SpecializationCode + StartedOn string + EndedOn string + Summary string +} + +func (ProfileExperience) String() string { return redactedProfile } +func (ProfileExperience) GoString() string { return redactedProfile } +func (ProfileExperience) LogValue() slog.Value { + return slog.StringValue(redactedProfile) +} +func (ProfileExperience) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) } + +// ProfileTaxBasis is the tax basis of a salary amount. +type ProfileTaxBasis string + +const ( + ProfileTaxNet ProfileTaxBasis = "net" + ProfileTaxGross ProfileTaxBasis = "gross" +) + +// ProfileSalaryMinimum is the lowest salary that the candidate accepts, in +// whole roubles per month with an explicit tax basis. It is private to the +// candidate: no organization reads it. It is personal data: String, +// GoString, Format, and LogValue redact it. +type ProfileSalaryMinimum struct { + Amount int64 + TaxBasis ProfileTaxBasis +} + +func (ProfileSalaryMinimum) String() string { return redactedProfile } +func (ProfileSalaryMinimum) GoString() string { return redactedProfile } +func (ProfileSalaryMinimum) LogValue() slog.Value { + return slog.StringValue(redactedProfile) +} +func (ProfileSalaryMinimum) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) } + +// ProfileClaimInput is the decision of a request about one value: the value +// and whether the candidate confirms it or keeps it as an unconfirmed +// suggestion. +type ProfileClaimInput[V comparable] struct { + Value V + Status ProfileClaimStatus +} + +// CandidateProfileInput is the complete new state of a profile as a request +// gave it. A nil single field is unknown and removes the stored value; a list +// replaces the stored list. It holds personal data: never log it. +type CandidateProfileInput struct { + FullName *ProfileClaimInput[string] + Email *ProfileClaimInput[string] + Phone *ProfileClaimInput[string] + Telegram *ProfileClaimInput[string] + Stack []ProfileClaimInput[string] + Roles []ProfileClaimInput[ProfileRole] + Experience []ProfileClaimInput[ProfileExperience] + SoftSkills []ProfileClaimInput[string] + Location *ProfileClaimInput[string] + Relocation *ProfileClaimInput[bool] + SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum] +} + +// CandidateProfileContent is the validated content of a profile: every claim +// that exists. A field that is not set has no claim. It holds no confirmed +// grade or category, so no request and no import can write one through it, +// and no reference to a file, the ML service, or an FSP account. It is +// personal data: String, GoString, Format, and LogValue redact it. +type CandidateProfileContent struct { + fullName *ProfileClaim[string] + email *ProfileClaim[string] + phone *ProfileClaim[string] + telegram *ProfileClaim[string] + stack []ProfileClaim[string] + roles []ProfileClaim[ProfileRole] + experience []ProfileClaim[ProfileExperience] + softSkills []ProfileClaim[string] + location *ProfileClaim[string] + relocation *ProfileClaim[bool] + salaryMinimum *ProfileClaim[ProfileSalaryMinimum] +} + +func optionalClaim[V comparable](claim *ProfileClaim[V]) (ProfileClaim[V], bool) { + if claim == nil { + return ProfileClaim[V]{}, false + } + return *claim, true +} + +// FullName returns the claim of the full name and whether it is set. +func (content CandidateProfileContent) FullName() (ProfileClaim[string], bool) { + return optionalClaim(content.fullName) +} + +// Email returns the claim of the contact email and whether it is set. +func (content CandidateProfileContent) Email() (ProfileClaim[string], bool) { + return optionalClaim(content.email) +} + +// Phone returns the claim of the E.164 phone number and whether it is set. +func (content CandidateProfileContent) Phone() (ProfileClaim[string], bool) { + return optionalClaim(content.phone) +} + +// Telegram returns the claim of the Telegram username and whether it is set. +func (content CandidateProfileContent) Telegram() (ProfileClaim[string], bool) { + return optionalClaim(content.telegram) +} + +// Location returns the claim of the place and whether it is set. +func (content CandidateProfileContent) Location() (ProfileClaim[string], bool) { + return optionalClaim(content.location) +} + +// Relocation returns the claim of readiness to relocate and whether it is set. +func (content CandidateProfileContent) Relocation() (ProfileClaim[bool], bool) { + return optionalClaim(content.relocation) +} + +// SalaryMinimum returns the claim of the lowest salary and whether it is set. +func (content CandidateProfileContent) SalaryMinimum() (ProfileClaim[ProfileSalaryMinimum], bool) { + return optionalClaim(content.salaryMinimum) +} + +// Stack returns a copy of the stack tags in the order the candidate gave them. +func (content CandidateProfileContent) Stack() []ProfileClaim[string] { + return slices.Clone(content.stack) +} + +// Roles returns a copy of the roles in the order the candidate gave them. +func (content CandidateProfileContent) Roles() []ProfileClaim[ProfileRole] { + return slices.Clone(content.roles) +} + +// Experience returns a copy of the work history in the order the candidate +// gave it. +func (content CandidateProfileContent) Experience() []ProfileClaim[ProfileExperience] { + return slices.Clone(content.experience) +} + +// SoftSkills returns a copy of the soft skills in the order the candidate +// gave them. +func (content CandidateProfileContent) SoftSkills() []ProfileClaim[string] { + return slices.Clone(content.softSkills) +} + +// Equal reports whether both contents hold the same claims with the same +// provenance, which tells a change from a body that changes nothing. +func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool { + return optionalClaimsEqual(content.fullName, other.fullName) && + optionalClaimsEqual(content.email, other.email) && + optionalClaimsEqual(content.phone, other.phone) && + optionalClaimsEqual(content.telegram, other.telegram) && + optionalClaimsEqual(content.location, other.location) && + optionalClaimsEqual(content.relocation, other.relocation) && + optionalClaimsEqual(content.salaryMinimum, other.salaryMinimum) && + slices.EqualFunc(content.stack, other.stack, claimsEqual) && + slices.EqualFunc(content.roles, other.roles, claimsEqual) && + slices.EqualFunc(content.experience, other.experience, claimsEqual) && + slices.EqualFunc(content.softSkills, other.softSkills, claimsEqual) +} + +func (CandidateProfileContent) String() string { return redactedProfile } +func (CandidateProfileContent) GoString() string { return redactedProfile } +func (CandidateProfileContent) LogValue() slog.Value { + return slog.StringValue(redactedProfile) +} +func (CandidateProfileContent) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) } + +// claimRules holds what the resolution of one kind of value needs. The +// validate function returns the normalized value, the pointer of the part +// that broke a rule relative to the value (empty for the value itself), and +// the rule, or an empty rule when the value is valid. +type claimRules[V comparable] struct { + validate func(V) (normalized V, subPointer, reason string) + // valueRoot is the pointer of the value inside a decision: "/value" for + // a single field, and "/tag" or "/skill" for the scalar item that carries + // it in the contract. A structured item has its fields next to `status`, + // so its root is empty. + valueRoot string + // key identifies an item for the repeat rule, with keyPointer as the + // pointer of the repeated part of the item. A nil key allows repeats. + key func(V) string + keyPointer string +} + +// resolve decides what a request does to one value. The value is normalized +// and validated first. A confirmed decision for a stored suggestion with the +// same value confirms it and keeps its origin and quote; any other confirmed +// decision is a manual value, except that re-sending a confirmed value +// unchanged keeps the stored claim and its confirmation time. An extracted +// decision keeps a stored suggestion unconfirmed and is accepted only for the +// same value, because a client must not mark a value it made up as imported. +func (rules claimRules[V]) resolve( + location, pointer string, input ProfileClaimInput[V], stored []ProfileClaim[V], at time.Time, +) (ProfileClaim[V], error) { + value, subPointer, reason := rules.validate(input.Value) + if reason != "" { + return ProfileClaim[V]{}, invalidProfileField(location, pointer+rules.valueRoot+subPointer, reason) + } + index := slices.IndexFunc(stored, func(claim ProfileClaim[V]) bool { return claim.value == value }) + switch input.Status { + case ProfileClaimConfirmed: + if index >= 0 { + existing := stored[index] + if existing.status == ProfileClaimConfirmed { + return existing, nil + } + return ProfileClaim[V]{value: value, status: ProfileClaimConfirmed, source: existing.source.confirm(at)}, nil + } + source, err := NewManualProfileClaimSource(at) + if err != nil { + return ProfileClaim[V]{}, fmt.Errorf("%s - %w", location, err) + } + return ProfileClaim[V]{value: value, status: ProfileClaimConfirmed, source: source}, nil + case ProfileClaimExtracted: + if index >= 0 && stored[index].status == ProfileClaimExtracted { + return stored[index], nil + } + return ProfileClaim[V]{}, invalidStateDependentProfileField(location, pointer+"/status", "must be extracted only for a stored suggestion with the same value") + default: + return ProfileClaim[V]{}, invalidProfileField(location, pointer+"/status", "must be confirmed or extracted") + } +} + +// resolveOptional resolves a single field. A nil decision is an unknown +// field and returns nil. +func resolveOptional[V comparable]( + rules claimRules[V], location, pointer string, input *ProfileClaimInput[V], stored *ProfileClaim[V], at time.Time, +) (*ProfileClaim[V], error) { + if input == nil { + return nil, nil + } + var existing []ProfileClaim[V] + if stored != nil { + existing = []ProfileClaim[V]{*stored} + } + claim, err := rules.resolve(location, pointer, *input, existing, at) + if err != nil { + return nil, err + } + return &claim, nil +} + +// resolveItems resolves a list. It rejects a list over limit and, when the +// rules have a key, an item that repeats an earlier one. +func resolveItems[V comparable]( + rules claimRules[V], location, pointer string, inputs []ProfileClaimInput[V], stored []ProfileClaim[V], limit int, at time.Time, +) ([]ProfileClaim[V], error) { + if len(inputs) > limit { + return nil, invalidProfileField(location, pointer, fmt.Sprintf("must have at most %d items", limit)) + } + claims := make([]ProfileClaim[V], 0, len(inputs)) + seen := make(map[string]struct{}, len(inputs)) + for index, input := range inputs { + itemPointer := fmt.Sprintf("%s/%d", pointer, index) + claim, err := rules.resolve(location, itemPointer, input, stored, at) + if err != nil { + return nil, err + } + if rules.key != nil { + key := rules.key(claim.value) + if _, repeated := seen[key]; repeated { + return nil, invalidProfileField(location, itemPointer+rules.keyPointer, "must not repeat an earlier item") + } + seen[key] = struct{}{} + } + claims = append(claims, claim) + } + return claims, nil +} + +func singleLineRules(maxRunes int) func(string) (string, string, string) { + return func(value string) (string, string, string) { + return value, "", singleLineTextProblem(value, maxRunes) + } +} + +func patternRules(pattern *regexp.Regexp, reason string) func(string) (string, string, string) { + return func(value string) (string, string, string) { + if !pattern.MatchString(value) { + return value, "", reason + } + return value, "", "" + } +} + +func emailRules(value string) (string, string, string) { + email, err := NewEmailAddress(value) + if err != nil { + return value, "", "must be an email address" + } + return email.Address(), "", "" +} + +func caseInsensitiveKey(value string) string { return strings.ToLower(value) } + +func relocationRules(value bool) (bool, string, string) { return value, "", "" } + +func salaryRules(value ProfileSalaryMinimum) (ProfileSalaryMinimum, string, string) { + switch { + case value.Amount < minProfileSalaryAmount || value.Amount > maxProfileSalaryAmount || value.Amount%minProfileSalaryAmount != 0: + return value, "/amount", fmt.Sprintf("must be a multiple of %d from %d to %d", minProfileSalaryAmount, minProfileSalaryAmount, maxProfileSalaryAmount) + case value.TaxBasis != ProfileTaxNet && value.TaxBasis != ProfileTaxGross: + return value, "/tax_basis", "must be net or gross" + default: + return value, "", "" + } +} + +func roleRules(value ProfileRole) (ProfileRole, string, string) { + switch { + case !value.Specialization.IsKnown(): + return value, "/specialization", "must be a specialization of the catalog" + case value.SelfAssessedGrade != "" && !value.SelfAssessedGrade.IsKnown(): + return value, "/self_assessed_grade", "must be a grade of the scale" + default: + return value, "", "" + } +} + +// experienceRules checks one work history entry. A month later than the month +// of now is in the future; a zero now disables that check, which a restore +// uses because a stored entry never becomes a future one. +func experienceRules(now time.Time) func(ProfileExperience) (ProfileExperience, string, string) { + latest := "" + if !now.IsZero() { + latest = now.UTC().Format("2006-01") + } + problemOfMonth := func(month string) string { + switch { + case !profileMonthPattern.MatchString(month): + return "must be a month in the YYYY-MM format" + case latest != "" && month > latest: + return "must not be in the future" + default: + return "" + } + } + return func(value ProfileExperience) (ProfileExperience, string, string) { + value.Summary = strings.ReplaceAll(value.Summary, "\r\n", "\n") + switch { + case value.EmployerName != "" && singleLineTextProblem(value.EmployerName, maxProfileEmployerRunes) != "": + return value, "/employer_name", singleLineTextProblem(value.EmployerName, maxProfileEmployerRunes) + case !value.Specialization.IsKnown(): + return value, "/specialization", "must be a specialization of the catalog" + case problemOfMonth(value.StartedOn) != "": + return value, "/started_on", problemOfMonth(value.StartedOn) + case value.EndedOn != "" && problemOfMonth(value.EndedOn) != "": + return value, "/ended_on", problemOfMonth(value.EndedOn) + case value.EndedOn != "" && value.EndedOn < value.StartedOn: + return value, "/ended_on", "must not be earlier than started_on" + case value.Summary != "" && multiLineTextProblem(value.Summary, maxProfileSummaryRunes) != "": + return value, "/summary", multiLineTextProblem(value.Summary, maxProfileSummaryRunes) + default: + return value, "", "" + } + } +} + +// profileRules gathers the rules of every kind of value. +type profileRules struct { + fullName claimRules[string] + email claimRules[string] + phone claimRules[string] + telegram claimRules[string] + location claimRules[string] + relocation claimRules[bool] + salaryMinimum claimRules[ProfileSalaryMinimum] + stack claimRules[string] + softSkills claimRules[string] + roles claimRules[ProfileRole] + experience claimRules[ProfileExperience] +} + +func newProfileRules(now time.Time) profileRules { + return profileRules{ + fullName: claimRules[string]{validate: singleLineRules(maxProfileFullNameRunes), valueRoot: "/value"}, + email: claimRules[string]{validate: emailRules, valueRoot: "/value"}, + phone: claimRules[string]{ + validate: patternRules(organizationPhonePattern, "must be an E.164 phone number"), valueRoot: "/value", + }, + telegram: claimRules[string]{ + validate: patternRules(organizationTelegramPattern, "must be a Telegram username with the leading @"), valueRoot: "/value", + }, + location: claimRules[string]{validate: singleLineRules(maxProfileLocationRunes), valueRoot: "/value"}, + relocation: claimRules[bool]{validate: relocationRules, valueRoot: "/value"}, + salaryMinimum: claimRules[ProfileSalaryMinimum]{validate: salaryRules, valueRoot: "/value"}, + stack: claimRules[string]{ + validate: singleLineRules(maxProfileTagRunes), valueRoot: "/tag", key: caseInsensitiveKey, keyPointer: "/tag", + }, + softSkills: claimRules[string]{ + validate: singleLineRules(maxProfileTagRunes), valueRoot: "/skill", key: caseInsensitiveKey, keyPointer: "/skill", + }, + roles: claimRules[ProfileRole]{ + validate: roleRules, key: func(role ProfileRole) string { return string(role.Specialization) }, keyPointer: "/specialization", + }, + experience: claimRules[ProfileExperience]{validate: experienceRules(now)}, + } +} + +// ResolveCandidateProfileContent applies a request to the stored content and +// returns the new content. It validates every value, resolves each decision +// against the stored claim (see claimRules.resolve), and keeps a stored claim +// whose value is sent again unchanged. The first rule that fails returns an +// error matching ErrInvalidCandidateProfile with a *CandidateProfileFieldError +// that names the field. The zero CandidateProfileContent is the empty stored +// state of a first save. Every new claim has trust level 0. +func ResolveCandidateProfileContent(stored CandidateProfileContent, input CandidateProfileInput, at time.Time) (CandidateProfileContent, error) { + const location = "domain.ResolveCandidateProfileContent" + if at.IsZero() { + return CandidateProfileContent{}, fmt.Errorf("%s - time must be set: %w", location, ErrInvalidCandidateProfile) + } + rules := newProfileRules(at) + var ( + content CandidateProfileContent + err error + ) + steps := []func() error{ + func() (err error) { + content.fullName, err = resolveOptional(rules.fullName, location, "/full_name", input.FullName, stored.fullName, at) + return err + }, + func() (err error) { + content.email, err = resolveOptional(rules.email, location, "/contacts/email", input.Email, stored.email, at) + return err + }, + func() (err error) { + content.phone, err = resolveOptional(rules.phone, location, "/contacts/phone", input.Phone, stored.phone, at) + return err + }, + func() (err error) { + content.telegram, err = resolveOptional(rules.telegram, location, "/contacts/telegram", input.Telegram, stored.telegram, at) + return err + }, + func() (err error) { + content.stack, err = resolveItems(rules.stack, location, "/stack", input.Stack, stored.stack, maxProfileStackItems, at) + return err + }, + func() (err error) { + content.roles, err = resolveItems(rules.roles, location, "/roles", input.Roles, stored.roles, len(specializationCodes), at) + return err + }, + func() (err error) { + content.experience, err = resolveItems(rules.experience, location, "/experience", input.Experience, stored.experience, maxProfileExperienceItems, at) + return err + }, + func() (err error) { + content.softSkills, err = resolveItems(rules.softSkills, location, "/soft_skills", input.SoftSkills, stored.softSkills, maxProfileSoftSkills, at) + return err + }, + func() (err error) { + content.location, err = resolveOptional(rules.location, location, "/terms/location", input.Location, stored.location, at) + return err + }, + func() (err error) { + content.relocation, err = resolveOptional(rules.relocation, location, "/terms/relocation", input.Relocation, stored.relocation, at) + return err + }, + func() (err error) { + content.salaryMinimum, err = resolveOptional(rules.salaryMinimum, location, "/terms/salary_minimum", input.SalaryMinimum, stored.salaryMinimum, at) + return err + }, + } + for _, step := range steps { + if err = step(); err != nil { + return CandidateProfileContent{}, err + } + } + return content, nil +} + +// CandidateProfile is the private profile of one candidate account: its +// content and the optimistic concurrency version. Version 0 is the profile +// that was never saved. It is personal data: String, GoString, Format, and +// LogValue redact the content; LogValue logs only the account and the +// version. +type CandidateProfile struct { + userID uuid.UUID + // version is the optimistic concurrency version. Storage checks it as the + // expected version and advances it in the same statement, so a domain + // method never changes it. + version int64 + content CandidateProfileContent + createdAt time.Time + updatedAt time.Time +} + +// EmptyCandidateProfile returns the profile of an account that has not saved +// one: version 0, no claim, and no times. +func EmptyCandidateProfile(userID uuid.UUID) (CandidateProfile, error) { + if userID == uuid.Nil { + return CandidateProfile{}, fmt.Errorf("domain.EmptyCandidateProfile - user ID must not be nil: %w", ErrInvalidCandidateProfile) + } + return CandidateProfile{userID: userID}, nil +} + +func (profile CandidateProfile) UserID() uuid.UUID { return profile.userID } +func (profile CandidateProfile) Version() int64 { return profile.version } +func (profile CandidateProfile) Content() CandidateProfileContent { return profile.content } +func (profile CandidateProfile) CreatedAt() time.Time { return profile.createdAt } +func (profile CandidateProfile) UpdatedAt() time.Time { return profile.updatedAt } + +// IsZero reports a CandidateProfile not built by EmptyCandidateProfile or +// RestoreCandidateProfile. +func (profile CandidateProfile) IsZero() bool { return profile.userID == uuid.Nil } + +// Replace applies a request to the profile and reports whether anything +// changed. expectedVersion is the version the client read. The order is: +// +// 1. A version above the current one never existed, so it is a conflict. +// 2. A rule that depends on the body alone fails with +// ErrInvalidCandidateProfile whatever the version. +// 3. A decision rule that depends on the stored claims, such as extracted, +// judged against a stale version is a conflict: another save may have +// confirmed the value, and the client must read the profile again. +// 4. A request that leaves every claim as stored changes nothing and +// returns the profile as it is, even with an older version, so a retry +// of a save that already succeeded is harmless. +// 5. Any other change over a stale version is a conflict. +// +// A change returns the new content and the update time with the version +// unchanged, because storage advances it. A time before the last update, +// from clock skew between instances, is stored as the last update. +func (profile CandidateProfile) Replace(input CandidateProfileInput, expectedVersion int64, at time.Time) (CandidateProfile, bool, error) { + const location = "CandidateProfile.Replace" + if profile.IsZero() { + return CandidateProfile{}, false, fmt.Errorf("%s - profile was not built by EmptyCandidateProfile: %w", location, ErrInvalidCandidateProfile) + } + conflict := fmt.Errorf("%s - expected version is not current: %w", location, ErrCandidateProfileVersionConflict) + if expectedVersion > profile.version || expectedVersion < 0 { + return CandidateProfile{}, false, conflict + } + content, err := ResolveCandidateProfileContent(profile.content, input, at) + if err != nil { + var fieldError *CandidateProfileFieldError + if expectedVersion != profile.version && errors.As(err, &fieldError) && fieldError.stateDependent { + return CandidateProfile{}, false, conflict + } + return CandidateProfile{}, false, fmt.Errorf("%s - resolve content: %w", location, err) + } + if content.Equal(profile.content) { + return profile, false, nil + } + if expectedVersion != profile.version { + return CandidateProfile{}, false, conflict + } + updated := profile + updated.content = content + updated.updatedAt = at + if at.Before(profile.updatedAt) { + updated.updatedAt = profile.updatedAt + } + if updated.createdAt.IsZero() { + updated.createdAt = updated.updatedAt + } + return updated, true, nil +} + +func (CandidateProfile) String() string { return redactedProfile } +func (CandidateProfile) GoString() string { return redactedProfile } +func (CandidateProfile) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedProfile) +} + +// LogValue logs the account identifier and the version only. +func (profile CandidateProfile) LogValue() slog.Value { + return slog.GroupValue( + slog.String("user_id", profile.userID.String()), + slog.Int64("version", profile.version), + ) +} + +// Stored claim kinds. They are the values of candidate_profile_claims.kind +// and are fixed by its CHECK constraints. +const ( + profileKindFullName = "full_name" + profileKindEmail = "contact_email" + profileKindPhone = "contact_phone" + profileKindTelegram = "contact_telegram" + profileKindStack = "stack" + profileKindRole = "role" + profileKindExperience = "experience" + profileKindSoftSkill = "soft_skill" + profileKindLocation = "terms_location" + profileKindRelocation = "terms_relocation" + profileKindSalaryMinimum = "terms_salary_minimum" +) + +// StoredProfileClaim is a claim as the claims table holds it: the kind, the +// position, the canonical JSON of the value, and the provenance columns. The +// value and the quote are personal data: never log the struct. The zero +// ConfirmedAt is a NULL column, and an empty Quote or ExtractionVersion is a +// NULL one. +type StoredProfileClaim struct { + Kind string + Ordinal int + Value []byte + Status string + Origin string + TrustLevel int + Quote string + ExtractionVersion string + ConfirmedAt time.Time +} + +// The JSON shapes of structured values. Their keys are the ones that the +// CHECK constraints of candidate_profile_claims require, and a nullable part +// is JSON null, never absent. +type ( + storedRoleValue struct { + Specialization string `json:"specialization"` + SelfAssessedGrade *string `json:"self_assessed_grade"` + } + storedExperienceValue struct { + EmployerName *string `json:"employer_name"` + Specialization string `json:"specialization"` + StartedOn string `json:"started_on"` + EndedOn *string `json:"ended_on"` + Summary *string `json:"summary"` + } + storedSalaryValue struct { + Amount int64 `json:"amount"` + Currency string `json:"currency"` + Period string `json:"period"` + TaxBasis string `json:"tax_basis"` + } +) + +func optionalString(value string) *string { + if value == "" { + return nil + } + return &value +} + +func stringOrEmpty(value *string) string { + if value == nil { + return "" + } + return *value +} + +// claimEntry is one claim on its way to a stored row: the value is already +// in the JSON shape that the CHECK constraints require. +type claimEntry struct { + kind string + ordinal int + value any + status ProfileClaimStatus + source ProfileClaimSource +} + +func plainValue[V any](value V) any { return value } + +func roleStoredValue(role ProfileRole) any { + return storedRoleValue{Specialization: string(role.Specialization), SelfAssessedGrade: optionalString(string(role.SelfAssessedGrade))} +} + +func experienceStoredValue(entry ProfileExperience) any { + return storedExperienceValue{ + EmployerName: optionalString(entry.EmployerName), Specialization: string(entry.Specialization), + StartedOn: entry.StartedOn, EndedOn: optionalString(entry.EndedOn), Summary: optionalString(entry.Summary), + } +} + +func salaryStoredValue(salary ProfileSalaryMinimum) any { + return storedSalaryValue{Amount: salary.Amount, Currency: profileCurrency, Period: profilePeriod, TaxBasis: string(salary.TaxBasis)} +} + +func appendSingle[V comparable](entries []claimEntry, kind string, claim *ProfileClaim[V], encode func(V) any) []claimEntry { + if claim == nil { + return entries + } + return append(entries, claimEntry{kind: kind, value: encode(claim.value), status: claim.status, source: claim.source}) +} + +func appendList[V comparable](entries []claimEntry, kind string, claims []ProfileClaim[V], encode func(V) any) []claimEntry { + for index, claim := range claims { + entries = append(entries, claimEntry{kind: kind, ordinal: index, value: encode(claim.value), status: claim.status, source: claim.source}) + } + return entries +} + +// StoredClaims returns every claim of the content as rows of the claims +// table, in a stable order: single fields first, then each list in position +// order. The rows hold personal data. +func (content CandidateProfileContent) StoredClaims() ([]StoredProfileClaim, error) { + const location = "CandidateProfileContent.StoredClaims" + var entries []claimEntry + entries = appendSingle(entries, profileKindFullName, content.fullName, plainValue[string]) + entries = appendSingle(entries, profileKindEmail, content.email, plainValue[string]) + entries = appendSingle(entries, profileKindPhone, content.phone, plainValue[string]) + entries = appendSingle(entries, profileKindTelegram, content.telegram, plainValue[string]) + entries = appendSingle(entries, profileKindLocation, content.location, plainValue[string]) + entries = appendSingle(entries, profileKindRelocation, content.relocation, plainValue[bool]) + entries = appendSingle(entries, profileKindSalaryMinimum, content.salaryMinimum, salaryStoredValue) + entries = appendList(entries, profileKindStack, content.stack, plainValue[string]) + entries = appendList(entries, profileKindRole, content.roles, roleStoredValue) + entries = appendList(entries, profileKindExperience, content.experience, experienceStoredValue) + entries = appendList(entries, profileKindSoftSkill, content.softSkills, plainValue[string]) + + rows := make([]StoredProfileClaim, 0, len(entries)) + for _, entry := range entries { + encoded, err := json.Marshal(entry.value) + if err != nil { + return nil, fmt.Errorf("%s - encode %s: %w", location, entry.kind, err) + } + rows = append(rows, StoredProfileClaim{ + Kind: entry.kind, Ordinal: entry.ordinal, Value: encoded, Status: string(entry.status), Origin: string(entry.source.origin), + TrustLevel: ProfileClaimTrustLevel, Quote: entry.source.quote, ExtractionVersion: entry.source.extractionVersion, + ConfirmedAt: entry.source.confirmedAt, + }) + } + return rows, nil +} + +// RestoreCandidateProfileContent builds the content from stored rows. It +// validates each value with the rules of ResolveCandidateProfileContent and +// each provenance with RestoreProfileClaimSource, so a row changed outside +// the application fails with ErrInvalidCandidateProfile. The rows may come in +// any order; a list is ordered by Ordinal and must have no gap, and a single +// field must appear once. The error never quotes a value. +func RestoreCandidateProfileContent(rows []StoredProfileClaim) (CandidateProfileContent, error) { + const location = "domain.RestoreCandidateProfileContent" + rules := newProfileRules(time.Time{}) + fail := func(row StoredProfileClaim, reason string) error { + return fmt.Errorf("%s - claim %s/%d %s: %w", location, row.Kind, row.Ordinal, reason, ErrInvalidCandidateProfile) + } + var ( + content CandidateProfileContent + err error + ) + sorted := slices.Clone(rows) + slices.SortStableFunc(sorted, func(left, right StoredProfileClaim) int { return left.Ordinal - right.Ordinal }) + for _, row := range sorted { + source, sourceErr := RestoreProfileClaimSource(ProfileClaimOrigin(row.Origin), row.TrustLevel, row.Quote, row.ExtractionVersion, row.ConfirmedAt) + if sourceErr != nil { + return CandidateProfileContent{}, fail(row, "has invalid provenance") + } + status := ProfileClaimStatus(row.Status) + switch row.Kind { + case profileKindFullName: + err = restoreSingle(&content.fullName, rules.fullName, row, status, source) + case profileKindEmail: + err = restoreSingle(&content.email, rules.email, row, status, source) + case profileKindPhone: + err = restoreSingle(&content.phone, rules.phone, row, status, source) + case profileKindTelegram: + err = restoreSingle(&content.telegram, rules.telegram, row, status, source) + case profileKindLocation: + err = restoreSingle(&content.location, rules.location, row, status, source) + case profileKindRelocation: + err = restoreSingle(&content.relocation, rules.relocation, row, status, source) + case profileKindSalaryMinimum: + err = restoreSingle(&content.salaryMinimum, rules.salaryMinimum, row, status, source) + case profileKindStack: + err = restoreItem(&content.stack, rules.stack, row, status, source) + case profileKindSoftSkill: + err = restoreItem(&content.softSkills, rules.softSkills, row, status, source) + case profileKindRole: + err = restoreItem(&content.roles, rules.roles, row, status, source) + case profileKindExperience: + err = restoreItem(&content.experience, rules.experience, row, status, source) + default: + err = errors.New("kind is unknown") + } + if err != nil { + return CandidateProfileContent{}, fail(row, err.Error()) + } + } + return content, nil +} + +// decodeStoredValue decodes the canonical JSON of a stored value into V. +func decodeStoredValue[V comparable](row StoredProfileClaim) (V, error) { + var value V + switch target := any(&value).(type) { + case *ProfileRole: + var stored storedRoleValue + if err := decodeStrictJSON(row.Value, &stored); err != nil { + return value, err + } + *target = ProfileRole{Specialization: SpecializationCode(stored.Specialization), SelfAssessedGrade: GradeCode(stringOrEmpty(stored.SelfAssessedGrade))} + case *ProfileExperience: + var stored storedExperienceValue + if err := decodeStrictJSON(row.Value, &stored); err != nil { + return value, err + } + *target = ProfileExperience{ + EmployerName: stringOrEmpty(stored.EmployerName), Specialization: SpecializationCode(stored.Specialization), + StartedOn: stored.StartedOn, EndedOn: stringOrEmpty(stored.EndedOn), Summary: stringOrEmpty(stored.Summary), + } + case *ProfileSalaryMinimum: + var stored storedSalaryValue + if err := decodeStrictJSON(row.Value, &stored); err != nil { + return value, err + } + if stored.Currency != profileCurrency || stored.Period != profilePeriod { + return value, errors.New("value has an unsupported currency or period") + } + *target = ProfileSalaryMinimum{Amount: stored.Amount, TaxBasis: ProfileTaxBasis(stored.TaxBasis)} + default: + if err := decodeStrictJSON(row.Value, &value); err != nil { + return value, err + } + } + return value, nil +} + +func decodeStrictJSON(data []byte, target any) error { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(target); err != nil { + return errors.New("value has an unexpected shape") + } + if decoder.More() { + return errors.New("value has an unexpected shape") + } + return nil +} + +func restoreClaim[V comparable](rules claimRules[V], row StoredProfileClaim, status ProfileClaimStatus, source ProfileClaimSource) (ProfileClaim[V], error) { + value, err := decodeStoredValue[V](row) + if err != nil { + return ProfileClaim[V]{}, err + } + normalized, _, reason := rules.validate(value) + if reason != "" || normalized != value { + return ProfileClaim[V]{}, errors.New("value breaks a rule of the contract") + } + claim, err := RestoreProfileClaim(value, status, source) + if err != nil { + return ProfileClaim[V]{}, errors.New("status does not agree with the provenance") + } + return claim, nil +} + +func restoreSingle[V comparable]( + target **ProfileClaim[V], rules claimRules[V], row StoredProfileClaim, status ProfileClaimStatus, source ProfileClaimSource, +) error { + if *target != nil || row.Ordinal != 0 { + return errors.New("single field appears more than once or has a position") + } + claim, err := restoreClaim(rules, row, status, source) + if err != nil { + return err + } + *target = &claim + return nil +} + +func restoreItem[V comparable]( + target *[]ProfileClaim[V], rules claimRules[V], row StoredProfileClaim, status ProfileClaimStatus, source ProfileClaimSource, +) error { + if row.Ordinal != len(*target) { + return errors.New("list has a gap or a repeated position") + } + claim, err := restoreClaim(rules, row, status, source) + if err != nil { + return err + } + if rules.key != nil { + for _, existing := range *target { + if rules.key(existing.value) == rules.key(claim.value) { + return errors.New("list repeats an item") + } + } + } + *target = append(*target, claim) + return nil +} + +// StoredCandidateProfile carries the profile row and its claims. +type StoredCandidateProfile struct { + UserID uuid.UUID + Version int64 + CreatedAt time.Time + UpdatedAt time.Time + Claims []StoredProfileClaim +} + +// RestoreCandidateProfile validates a stored profile with the rules of the +// contract, so a row changed outside the application fails with +// ErrInvalidCandidateProfile. +func RestoreCandidateProfile(stored StoredCandidateProfile) (CandidateProfile, error) { + const location = "domain.RestoreCandidateProfile" + switch { + case stored.UserID == uuid.Nil: + return CandidateProfile{}, fmt.Errorf("%s - user ID must not be nil: %w", location, ErrInvalidCandidateProfile) + case stored.Version < 1: + return CandidateProfile{}, fmt.Errorf("%s - version must be positive: %w", location, ErrInvalidCandidateProfile) + case stored.CreatedAt.IsZero() || stored.UpdatedAt.Before(stored.CreatedAt): + return CandidateProfile{}, fmt.Errorf("%s - times must be set and ordered: %w", location, ErrInvalidCandidateProfile) + } + content, err := RestoreCandidateProfileContent(stored.Claims) + if err != nil { + return CandidateProfile{}, fmt.Errorf("%s - restore content: %w", location, err) + } + return CandidateProfile{ + userID: stored.UserID, version: stored.Version, content: content, + createdAt: stored.CreatedAt, updatedAt: stored.UpdatedAt, + }, nil +} diff --git a/backend/internal/domain/candidate_test.go b/backend/internal/domain/candidate_test.go new file mode 100644 index 0000000..8a0f30a --- /dev/null +++ b/backend/internal/domain/candidate_test.go @@ -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 } diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index e186887..d6baf44 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -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. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index c4881f8..47cce93 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -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. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 89f7297..4e2a0c8 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -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 добавляется только при конкретной потребности. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index c3472fe..d0da2a1 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -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-ошибки без строки с нарушением, что страница списка вне предела падает до любого запроса и что блокировка категории отклоняется вне транзакции. diff --git a/frontend/codegen/mock-patterns.test.ts b/frontend/codegen/mock-patterns.test.ts index a6150de..e9fd8f9 100644 --- a/frontend/codegen/mock-patterns.test.ts +++ b/frontend/codegen/mock-patterns.test.ts @@ -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", () => { diff --git a/frontend/codegen/mock-patterns.ts b/frontend/codegen/mock-patterns.ts index 8ee1979..72047b1 100644 --- a/frontend/codegen/mock-patterns.ts +++ b/frontend/codegen/mock-patterns.ts @@ -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 }), + }; } /** diff --git a/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts b/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts index f3fde30..b3c5771 100644 --- a/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts +++ b/frontend/src/shared/api/endpoints/candidate/candidate.msw.ts @@ -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> = {}): 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 => ({...{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 => ({...{amount: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse}); + +export const getGetMyProfileResponseMock = (overrideResponse: Partial> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {location: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, relocation: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.datatype.boolean(), null]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, salary_minimum: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileSalaryMinimumMock()},null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}}, confirmed_categories: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), confirmed_at: faker.date.past().toISOString().slice(0, 19) + 'Z', attempt_id: faker.string.uuid()})), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) + +export const getSaveMyProfileResponseProfileClaimSourceMock = (overrideResponse: Partial = {}): ProfileClaimSource => ({...{origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}, ...overrideResponse}); + +export const getSaveMyProfileResponseProfileSalaryMinimumMock = (overrideResponse: Partial = {}): ProfileSalaryMinimum => ({...{amount: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse}); + +export const getSaveMyProfileResponseMock = (overrideResponse: Partial> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {location: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, relocation: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.datatype.boolean(), null]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, salary_minimum: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileSalaryMinimumMock()},null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}}, confirmed_categories: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), confirmed_at: faker.date.past().toISOString().slice(0, 19) + 'Z', attempt_id: faker.string.uuid()})), updated_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse}) + export const getGetMyQuestionnaireMockHandler = (overrideResponse?: CandidateQuestionnaire | ((info: Parameters[1]>[0]) => Promise | CandidateQuestionnaire), options?: RequestHandlerOptions) => { return http.get('*/api/v1/me/questionnaire', async (info: Parameters[1]>[0]) => { @@ -63,7 +78,33 @@ export const getSaveMyQuestionnaireMockHandler = (overrideResponse?: CandidateQu }) }, options) } + +export const getGetMyProfileMockHandler = (overrideResponse?: CandidateProfile | ((info: Parameters[1]>[0]) => Promise | CandidateProfile), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/profile', async (info: Parameters[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[1]>[0]) => Promise | CandidateProfile), options?: RequestHandlerOptions) => { + return http.put('*/api/v1/me/profile', async (info: Parameters[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() ] diff --git a/frontend/src/shared/api/endpoints/candidate/candidate.ts b/frontend/src/shared/api/endpoints/candidate/candidate.ts index 16793db..d686fd8 100644 --- a/frontend/src/shared/api/endpoints/candidate/candidate.ts +++ b/frontend/src/shared/api/endpoints/candidate/candidate.ts @@ -24,6 +24,8 @@ import type { } from '@tanstack/react-query'; import type { + CandidateProfile, + CandidateProfileUpdate, CandidateQuestionnaire, CandidateQuestionnaireUpdate, Problem @@ -253,3 +255,210 @@ export const useSaveMyQuestionnaire = , > => { 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[1]): Promise => { + + return apiRequest(getGetMyProfileUrl(), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyProfileQueryKey = () => { + return [ + `/api/v1/me/profile` + ] as const; + } + + +export const getGetMyProfileQueryOptions = >, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyProfileQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyProfile({ signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyProfileQueryResult = NonNullable>> +export type GetMyProfileQueryError = ErrorType + + +export function useGetMyProfile>, TError = ErrorType>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyProfile>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyProfile>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the private profile of the current candidate. + */ + +export function useGetMyProfile>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyProfileQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + 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[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(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 = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SaveMyProfileMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, 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>, SaveMyProfileMutationVariables> = (props) => { + const {data} = props ?? {}; + + return saveMyProfile(data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type SaveMyProfileMutationResult = NonNullable>> + export type SaveMyProfileMutationBody = CandidateProfileUpdate + export type SaveMyProfileMutationError = ErrorType + export type SaveMyProfileMutationVariables = {data: CandidateProfileUpdate} + + /** + * @summary Replace the private profile of the current candidate. + */ +export const useSaveMyProfile = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SaveMyProfileMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + SaveMyProfileMutationVariables, + TContext + > => { + return useMutation(getSaveMyProfileMutationOptions(options), queryClient); + } diff --git a/frontend/src/shared/api/profile-contract.test.ts b/frontend/src/shared/api/profile-contract.test.ts new file mode 100644 index 0000000..fa5ef3c --- /dev/null +++ b/frontend/src/shared/api/profile-contract.test.ts @@ -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(value: T, key: string): Record { + 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().not.toHaveProperty("confirmed_categories"); + expectTypeOf().not.toHaveProperty("version"); + expectTypeOf().not.toHaveProperty("confirmed_grade"); + expectTypeOf().not.toHaveProperty("category"); + expectTypeOf().not.toHaveProperty("source"); + expectTypeOf().not.toHaveProperty("trust_level"); + expectTypeOf().not.toHaveProperty("confirmed_grade"); + expectTypeOf().not.toHaveProperty("category"); + expectTypeOf().toHaveProperty("confirmed_categories"); + expectTypeOf(saveMyProfile).parameter(0).toEqualTypeOf(); +}); + +// 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([]); + }); +}); diff --git a/frontend/src/shared/api/schemas/candidate/candidateExperience.zod.ts b/frontend/src/shared/api/schemas/candidate/candidateExperience.zod.ts index 16d9305..700996f 100644 --- a/frontend/src/shared/api/schemas/candidate/candidateExperience.zod.ts +++ b/frontend/src/shared/api/schemas/candidate/candidateExperience.zod.ts @@ -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; export type CandidateExperienceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/candidateProfile.zod.ts b/frontend/src/shared/api/schemas/candidate/candidateProfile.zod.ts new file mode 100644 index 0000000..7fb4261 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/candidateProfile.zod.ts @@ -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; +export type CandidateProfileOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/candidateProfileUpdate.zod.ts b/frontend/src/shared/api/schemas/candidate/candidateProfileUpdate.zod.ts new file mode 100644 index 0000000..93e8846 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/candidateProfileUpdate.zod.ts @@ -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; +export type CandidateProfileUpdateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/candidateQuestionnaire.zod.ts b/frontend/src/shared/api/schemas/candidate/candidateQuestionnaire.zod.ts index 92ea6e7..c154c2d 100644 --- a/frontend/src/shared/api/schemas/candidate/candidateQuestionnaire.zod.ts +++ b/frontend/src/shared/api/schemas/candidate/candidateQuestionnaire.zod.ts @@ -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`.') diff --git a/frontend/src/shared/api/schemas/candidate/candidateQuestionnaireUpdate.zod.ts b/frontend/src/shared/api/schemas/candidate/candidateQuestionnaireUpdate.zod.ts index 033833d..dd537b7 100644 --- a/frontend/src/shared/api/schemas/candidate/candidateQuestionnaireUpdate.zod.ts +++ b/frontend/src/shared/api/schemas/candidate/candidateQuestionnaireUpdate.zod.ts @@ -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; diff --git a/frontend/src/shared/api/schemas/candidate/index.ts b/frontend/src/shared/api/schemas/candidate/index.ts index b974317..df9ebb9 100644 --- a/frontend/src/shared/api/schemas/candidate/index.ts +++ b/frontend/src/shared/api/schemas/candidate/index.ts @@ -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'; diff --git a/frontend/src/shared/api/schemas/candidate/profileClaimOrigin.zod.ts b/frontend/src/shared/api/schemas/candidate/profileClaimOrigin.zod.ts new file mode 100644 index 0000000..e208d80 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileClaimOrigin.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileClaimOriginOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileClaimQuote.zod.ts b/frontend/src/shared/api/schemas/candidate/profileClaimQuote.zod.ts new file mode 100644 index 0000000..f909441 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileClaimQuote.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileClaimQuoteOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileClaimSource.zod.ts b/frontend/src/shared/api/schemas/candidate/profileClaimSource.zod.ts new file mode 100644 index 0000000..df90f65 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileClaimSource.zod.ts @@ -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; +export type ProfileClaimSourceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileClaimStatus.zod.ts b/frontend/src/shared/api/schemas/candidate/profileClaimStatus.zod.ts new file mode 100644 index 0000000..d6403be --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileClaimStatus.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileClaimStatusOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileClaimTrustLevel.zod.ts b/frontend/src/shared/api/schemas/candidate/profileClaimTrustLevel.zod.ts new file mode 100644 index 0000000..1e48ee6 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileClaimTrustLevel.zod.ts @@ -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; +export type ProfileClaimTrustLevelOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileConfirmedCategory.zod.ts b/frontend/src/shared/api/schemas/candidate/profileConfirmedCategory.zod.ts new file mode 100644 index 0000000..b64315e --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileConfirmedCategory.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileConfirmedCategoryOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileContacts.zod.ts b/frontend/src/shared/api/schemas/candidate/profileContacts.zod.ts new file mode 100644 index 0000000..49088e3 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileContacts.zod.ts @@ -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; +export type ProfileContactsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileContactsInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileContactsInput.zod.ts new file mode 100644 index 0000000..d26093f --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileContactsInput.zod.ts @@ -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; +export type ProfileContactsInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileEmailClaim.zod.ts b/frontend/src/shared/api/schemas/candidate/profileEmailClaim.zod.ts new file mode 100644 index 0000000..b24b3d8 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileEmailClaim.zod.ts @@ -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; +export type ProfileEmailClaimOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileEmailInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileEmailInput.zod.ts new file mode 100644 index 0000000..e9fa303 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileEmailInput.zod.ts @@ -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; +export type ProfileEmailInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileEmployerName.zod.ts b/frontend/src/shared/api/schemas/candidate/profileEmployerName.zod.ts new file mode 100644 index 0000000..899ed3b --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileEmployerName.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileEmployerNameOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileExperienceItem.zod.ts b/frontend/src/shared/api/schemas/candidate/profileExperienceItem.zod.ts new file mode 100644 index 0000000..b9c7c75 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileExperienceItem.zod.ts @@ -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; +export type ProfileExperienceItemOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileExperienceItemInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileExperienceItemInput.zod.ts new file mode 100644 index 0000000..2eba793 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileExperienceItemInput.zod.ts @@ -0,0 +1,36 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileExperienceItemInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileExperienceSummary.zod.ts b/frontend/src/shared/api/schemas/candidate/profileExperienceSummary.zod.ts new file mode 100644 index 0000000..c1bd688 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileExperienceSummary.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileExperienceSummaryOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileFullNameClaim.zod.ts b/frontend/src/shared/api/schemas/candidate/profileFullNameClaim.zod.ts new file mode 100644 index 0000000..a966069 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileFullNameClaim.zod.ts @@ -0,0 +1,36 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileFullNameClaimOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileFullNameInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileFullNameInput.zod.ts new file mode 100644 index 0000000..f27a527 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileFullNameInput.zod.ts @@ -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; +export type ProfileFullNameInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileItemStatus.zod.ts b/frontend/src/shared/api/schemas/candidate/profileItemStatus.zod.ts new file mode 100644 index 0000000..0b79ef6 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileItemStatus.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileItemStatusOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileLocationClaim.zod.ts b/frontend/src/shared/api/schemas/candidate/profileLocationClaim.zod.ts new file mode 100644 index 0000000..36f7a58 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileLocationClaim.zod.ts @@ -0,0 +1,36 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileLocationClaimOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileLocationInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileLocationInput.zod.ts new file mode 100644 index 0000000..fe8d013 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileLocationInput.zod.ts @@ -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; +export type ProfileLocationInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileLocationName.zod.ts b/frontend/src/shared/api/schemas/candidate/profileLocationName.zod.ts new file mode 100644 index 0000000..ce4c342 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileLocationName.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileLocationNameOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profilePhoneClaim.zod.ts b/frontend/src/shared/api/schemas/candidate/profilePhoneClaim.zod.ts new file mode 100644 index 0000000..0b5c179 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profilePhoneClaim.zod.ts @@ -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; +export type ProfilePhoneClaimOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profilePhoneInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profilePhoneInput.zod.ts new file mode 100644 index 0000000..484da4f --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profilePhoneInput.zod.ts @@ -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; +export type ProfilePhoneInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileRelocationClaim.zod.ts b/frontend/src/shared/api/schemas/candidate/profileRelocationClaim.zod.ts new file mode 100644 index 0000000..2a3aa01 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileRelocationClaim.zod.ts @@ -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; +export type ProfileRelocationClaimOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileRelocationInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileRelocationInput.zod.ts new file mode 100644 index 0000000..d285065 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileRelocationInput.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileRelocationInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileRoleItem.zod.ts b/frontend/src/shared/api/schemas/candidate/profileRoleItem.zod.ts new file mode 100644 index 0000000..f8ec7c6 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileRoleItem.zod.ts @@ -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; +export type ProfileRoleItemOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileRoleItemInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileRoleItemInput.zod.ts new file mode 100644 index 0000000..e19802c --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileRoleItemInput.zod.ts @@ -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; +export type ProfileRoleItemInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileSalaryMinimum.zod.ts b/frontend/src/shared/api/schemas/candidate/profileSalaryMinimum.zod.ts new file mode 100644 index 0000000..88e963b --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileSalaryMinimum.zod.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileSalaryMinimumOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileSalaryMinimumClaim.zod.ts b/frontend/src/shared/api/schemas/candidate/profileSalaryMinimumClaim.zod.ts new file mode 100644 index 0000000..802e937 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileSalaryMinimumClaim.zod.ts @@ -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; +export type ProfileSalaryMinimumClaimOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileSalaryMinimumInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileSalaryMinimumInput.zod.ts new file mode 100644 index 0000000..d892826 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileSalaryMinimumInput.zod.ts @@ -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; +export type ProfileSalaryMinimumInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileSoftSkill.zod.ts b/frontend/src/shared/api/schemas/candidate/profileSoftSkill.zod.ts new file mode 100644 index 0000000..b9f152e --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileSoftSkill.zod.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileSoftSkillOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileSoftSkillItem.zod.ts b/frontend/src/shared/api/schemas/candidate/profileSoftSkillItem.zod.ts new file mode 100644 index 0000000..8ab2576 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileSoftSkillItem.zod.ts @@ -0,0 +1,36 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileSoftSkillItemOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileSoftSkillItemInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileSoftSkillItemInput.zod.ts new file mode 100644 index 0000000..8f363e7 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileSoftSkillItemInput.zod.ts @@ -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; +export type ProfileSoftSkillItemInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileStackItem.zod.ts b/frontend/src/shared/api/schemas/candidate/profileStackItem.zod.ts new file mode 100644 index 0000000..83a26a7 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileStackItem.zod.ts @@ -0,0 +1,36 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileStackItemOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileStackItemInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileStackItemInput.zod.ts new file mode 100644 index 0000000..1e5311f --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileStackItemInput.zod.ts @@ -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; +export type ProfileStackItemInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileTelegramClaim.zod.ts b/frontend/src/shared/api/schemas/candidate/profileTelegramClaim.zod.ts new file mode 100644 index 0000000..f802c90 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileTelegramClaim.zod.ts @@ -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; +export type ProfileTelegramClaimOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileTelegramInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileTelegramInput.zod.ts new file mode 100644 index 0000000..b652735 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileTelegramInput.zod.ts @@ -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; +export type ProfileTelegramInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileTerms.zod.ts b/frontend/src/shared/api/schemas/candidate/profileTerms.zod.ts new file mode 100644 index 0000000..b4617a4 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileTerms.zod.ts @@ -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; +export type ProfileTermsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileTermsInput.zod.ts b/frontend/src/shared/api/schemas/candidate/profileTermsInput.zod.ts new file mode 100644 index 0000000..c79fd93 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileTermsInput.zod.ts @@ -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; +export type ProfileTermsInputOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileVersion.zod.ts b/frontend/src/shared/api/schemas/candidate/profileVersion.zod.ts new file mode 100644 index 0000000..3315de4 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileVersion.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileVersionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/profileYearMonth.zod.ts b/frontend/src/shared/api/schemas/candidate/profileYearMonth.zod.ts new file mode 100644 index 0000000..d3760e3 --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/profileYearMonth.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const 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; +export type ProfileYearMonthOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/questionnaireSpecialization.zod.ts b/frontend/src/shared/api/schemas/candidate/questionnaireSpecialization.zod.ts index f10a650..1820982 100644 --- a/frontend/src/shared/api/schemas/candidate/questionnaireSpecialization.zod.ts +++ b/frontend/src/shared/api/schemas/candidate/questionnaireSpecialization.zod.ts @@ -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; export type QuestionnaireSpecializationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/saveMyProfileBody.zod.ts b/frontend/src/shared/api/schemas/candidate/saveMyProfileBody.zod.ts new file mode 100644 index 0000000..a814b0a --- /dev/null +++ b/frontend/src/shared/api/schemas/candidate/saveMyProfileBody.zod.ts @@ -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; +export type SaveMyProfileBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/candidate/saveMyQuestionnaireBody.zod.ts b/frontend/src/shared/api/schemas/candidate/saveMyQuestionnaireBody.zod.ts index 7dc151b..71f8945 100644 --- a/frontend/src/shared/api/schemas/candidate/saveMyQuestionnaireBody.zod.ts +++ b/frontend/src/shared/api/schemas/candidate/saveMyQuestionnaireBody.zod.ts @@ -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; diff --git a/frontend/src/shared/api/schemas/candidate/workContext.zod.ts b/frontend/src/shared/api/schemas/candidate/workContext.zod.ts index 5d70b2d..dc30ae9 100644 --- a/frontend/src/shared/api/schemas/candidate/workContext.zod.ts +++ b/frontend/src/shared/api/schemas/candidate/workContext.zod.ts @@ -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; export type WorkContextOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactFullName.zod.ts b/frontend/src/shared/api/schemas/contactFullName.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/invitation/contactFullName.zod.ts rename to frontend/src/shared/api/schemas/contactFullName.zod.ts diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index 2d3c5fe..8e5091b 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -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'; diff --git a/frontend/src/shared/api/schemas/invitation/index.ts b/frontend/src/shared/api/schemas/invitation/index.ts index 17c9aaf..c2584e6 100644 --- a/frontend/src/shared/api/schemas/invitation/index.ts +++ b/frontend/src/shared/api/schemas/invitation/index.ts @@ -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'; diff --git a/frontend/src/shared/api/schemas/need/index.ts b/frontend/src/shared/api/schemas/need/index.ts index 806bb5c..f1d36b8 100644 --- a/frontend/src/shared/api/schemas/need/index.ts +++ b/frontend/src/shared/api/schemas/need/index.ts @@ -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'; diff --git a/frontend/src/shared/api/schemas/need/needVersionLabel.zod.ts b/frontend/src/shared/api/schemas/needVersionLabel.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/needVersionLabel.zod.ts rename to frontend/src/shared/api/schemas/needVersionLabel.zod.ts