feat(profile): persist candidate edits and enforce company access

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 14:15:16 +03:00
1 parent 3ab6bd91a3
commit 73c7caa225
67 files changed
+5286 -229

No files matched your search

+6 -4
View File
@@ -180,7 +180,7 @@ Questionnaire:
### Candidate profile
The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD). The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin.
The `candidate` tag includes implemented `GetMyProfile` and `SaveMyProfile` operations for the private manual profile. A verified candidate reads and edits only their own profile; an employer receives 403 and a guest receives 401. PUT requires the session CSRF token and exact Origin. Data, version, overlap confirmations, history, and the step transition commit in one transaction. Without DATABASE_URL, the operations retain their 501 fallback.
| Method and path | operationId | Protection | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -189,6 +189,8 @@ The `candidate` tag also describes the private candidate profile that the candid
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`.
`experience_overlaps` lists intersecting inclusive month ranges and their decision state. A changed save requires explicit `confirmed_parallel_periods` with indices and exact dates for that version; an earlier decision survives only for the same indices and dates. A stored unconfirmed overlap permits an exact no-op, but no other edit without a decision. History is appended only on change. A successful PUT advances only `candidate_profile` to `candidate_questionnaire`; the earlier `candidate_consents` and later steps stay unchanged. Consent-step completion has no separate operation yet.
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.
@@ -228,7 +230,7 @@ Open questions for the product owner and legal:
- 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.
- The minimum for the onboarding step `candidate_profile`: the current contract requires no field, so any successful PUT completes that step, including an empty no-op. Requiring fields later needs a separate product decision and contract change.
- 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, not this one.
@@ -557,7 +559,7 @@ No new problem code is added: the contract uses `validation_failed`, `unauthenti
### Organizations
The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. The storage behind them exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned as part of organization management and access control.
The `organization` tag includes implemented creation, reading, editing, and the current account's organization directory. A verified employer creates an organization with an active owner; organization-scoped operations require an active owner on each request. Unsafe operations require the session CSRF token and exact Origin. The common middleware also protects unimplemented need and invitation operations before their 501 fallback. See [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships).
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -577,7 +579,7 @@ Active organization context:
Access:
- An employer account only. A candidate account answers 403 `forbidden` on all four operations, and an account without a session answers 401.
- `GetOrganization` and `UpdateOrganization` answer 404 `not_found` for an account without an active membership in `org_id` and for an unknown organization alike, and also for a `suspended`, `removed`, or `left` member, so organizations cannot be enumerated and a revoked member loses the next read at once. A member whose role does not manage the organization answers 403 `forbidden` on `UpdateOrganization`; the FR07 matrix gives managing the company and its staff to the owner only. In the MVP every member is an owner, because the operations that add members are planned.
- `GetOrganization` and `UpdateOrganization` answer 404 `not_found` for an account without an active membership in `org_id` and for an unknown organization alike, and also for a `suspended`, `removed`, or `left` member, so organizations cannot be enumerated and a revoked member loses the next read at once. A member whose role does not manage the organization answers 403 `forbidden` on `GetOrganization` and `UpdateOrganization`; the FR07 matrix gives managing the company and its staff to the owner only. In the MVP every member is an owner, because the operations that add members are planned.
- `CreateOrganization` creates the organization and the owner membership of the caller in one transaction (role `owner`, state `active`), so an organization never exists without an owner; the database refuses to commit one that has none. The body has no owner, role, membership, or verification field.
Memberships:
+6 -4
View File
@@ -180,7 +180,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Профиль кандидата
Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin.
Тег `candidate` включает реализованные `GetMyProfile` и `SaveMyProfile` для приватного ручного профиля. Подтвержденный кандидат читает и меняет только свой профиль; работодатель получает 403, гость - 401. PUT требует CSRF-токен сессии и точный Origin. Данные, версия, подтверждения пересечений, история и переход шага сохраняются одной транзакцией. Без DATABASE_URL остается ответ 501.
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -189,6 +189,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Каждая операция также объявляет problem-ответ `default`. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed` и `version_conflict`.
`experience_overlaps` перечисляет пересекающиеся включительные месяцы и состояние решения. Перед измененным сохранением требуется явное `confirmed_parallel_periods` с индексами и точными датами этой версии; прежнее решение переносится только при тех же индексах и датах. Сохраненный неподтвержденный overlap допускает точный no-op, но не изменение других полей без решения. История добавляется только при изменении. Успешный PUT переводит только `candidate_profile` в `candidate_questionnaire`; ранний `candidate_consents` и поздние шаги не меняются. Завершение шага согласий пока не имеет отдельной операции.
Состав профиля:
- Полное имя и контакты (`full_name`, `contacts.email`, `contacts.phone`, `contacts.telegram`), стек (`stack`, теги `StackTag`), роли (`roles`: специализация каталога и самооценка грейда), опыт работы (`experience`: записи с периодом по месяцам `YYYY-MM`, специализацией и описанием задач, а не названием должности), софт-скиллы (`soft_skills`, свободный текст) и условия (`terms`: место, готовность к переезду и минимальная зарплата с валютой, периодом и налоговой базой). Это ПДн кандидата; каждое такое поле в описании схемы помечено как персональные данные, а значения не попадают в логи, метрики, URL и события.
@@ -228,7 +230,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- Основание по 152-ФЗ: какое согласие покрывает хранение профиля (C1 при регистрации или отдельное), нужны ли отдельные согласия для имени и контактов, сроки хранения и порядок удаления. Сейчас удаление аккаунта каскадно удаляет профиль, а правил хранения нет.
- Порядок версии и доменных правил: выбрано проверять версию раньше правил, зависящих от сохраненных заявлений (устаревшая вкладка получает 412, а не 400); нужно подтверждение владельца продукта.
- Полная замена: `PUT` удаляет сохраненные предложения импорта, которых клиент не показал и не вернул со статусом `extracted`; допустимо ли это или сервер должен сохранять непоказанные предложения.
- Минимум для шага онбординга `candidate_profile`: контракт не требует ни одного поля; какие поля нужны, чтобы шаг считался пройденным, решает владелец продукта.
- Минимум для шага онбординга `candidate_profile`: текущий контракт не требует ни одного поля, поэтому любой успешный PUT завершает этот шаг, включая пустой no-op. Введение обязательных полей потребует отдельного решения владельца продукта и изменения контракта.
- Единый источник между анкетой и профилем: оставить самооценку и стек независимыми или хранить одно заявление и показывать в обоих местах.
- Софт-скиллы: таксономии нет, свободный текст до 10 штук по 50 символов; нужен ли справочник.
- Опыт: названия работодателей и описания - ПДн; как анонимная карточка их обобщает (PRD: отрасль и размер), решает контракт карточки, а не этот.
@@ -557,7 +559,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
### Организации
Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. Хранение за ними уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в управлении организациями и контроле доступа.
Тег `organization` включает реализованные создание, чтение, редактирование и список своих организаций. Подтвержденный работодатель создает организацию с активным владельцем; операции в области организации требуют активного владельца на каждом запросе. Небезопасные операции требуют CSRF-токен сессии и точный Origin. Общий middleware защищает также пока не реализованные потребности и приглашения до ответа 501. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства).
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
@@ -577,7 +579,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Доступ:
- Только аккаунт работодателя. Аккаунт кандидата получает 403 `forbidden` на всех четырех операциях, аккаунт без сессии - 401.
- `GetOrganization` и `UpdateOrganization` одинаково отвечают 404 `not_found` аккаунту без активного членства в `org_id` и на неизвестную организацию, а также участнику в состоянии `suspended`, `removed` или `left`, поэтому организации нельзя перечислить, а отозванный участник теряет следующее чтение сразу. Участник, чья роль не управляет организацией, получает 403 `forbidden` на `UpdateOrganization`; матрица FR07 отдает управление компанией и сотрудниками только владельцу. В MVP каждый участник - владелец, потому что операции добавления участников запланированы.
- `GetOrganization` и `UpdateOrganization` одинаково отвечают 404 `not_found` аккаунту без активного членства в `org_id` и на неизвестную организацию, а также участнику в состоянии `suspended`, `removed` или `left`, поэтому организации нельзя перечислить, а отозванный участник теряет следующее чтение сразу. Участник, чья роль не управляет организацией, получает 403 `forbidden` на `GetOrganization` и `UpdateOrganization`; матрица FR07 отдает управление компанией и сотрудниками только владельцу. В MVP каждый участник - владелец, потому что операции добавления участников запланированы.
- `CreateOrganization` создает организацию и членство владельца для вызывающего в одной транзакции (роль `owner`, состояние `active`), поэтому организации без владельца не существует; база отказывается фиксировать такую. В теле нет поля владельца, роли, членства или уровня проверки.
Членства:
+2
View File
@@ -3993,6 +3993,7 @@ NewCandidateProfile:
stack: []
roles: []
experience: []
experience_overlaps: []
soft_skills: []
terms:
location:
@@ -4093,6 +4094,7 @@ BackendCandidateProfile:
quote: null
extraction_version: null
confirmed_at: "2026-10-05T09:30:00Z"
experience_overlaps: []
soft_skills:
- skill: Mentoring
status: confirmed
+2 -1
View File
@@ -599,7 +599,8 @@ ProfileValidationFailed:
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
value that is not a stored suggestion, an overlapping experience period
without an explicit date-pair acknowledgement, 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:
+75
View File
@@ -1988,6 +1988,68 @@ ProfileExperienceItem:
$ref: '#/ProfileItemStatus'
source:
$ref: '#/ProfileClaimSource'
ProfileExperienceOverlapStatus:
type: string
description: Whether the candidate confirmed that two overlapping periods are genuine parallel work.
enum:
- needs_confirmation
- confirmed
ProfileExperienceOverlap:
type: object
description: One pair of work history entries whose inclusive month ranges overlap. The indices refer to the experience array in this profile version. `confirmed` records an explicit acknowledgement for this pair of dates; otherwise the pair needs confirmation before a changed profile can be saved.
additionalProperties: false
required:
- first_index
- second_index
- status
properties:
first_index:
type: integer
minimum: 0
maximum: 19
second_index:
type: integer
minimum: 1
maximum: 19
status:
$ref: '#/ProfileExperienceOverlapStatus'
ProfileExperiencePeriod:
type: object
description: The exact month range of an experience entry, copied into a confirmation.
additionalProperties: false
required:
- started_on
- ended_on
properties:
started_on:
$ref: '#/ProfileYearMonth'
ended_on:
description: Last month of work, or null when the period is open-ended.
oneOf:
- $ref: '#/ProfileYearMonth'
- type: 'null'
ProfileParallelPeriodConfirmation:
type: object
description: Explicit acknowledgement that the two indexed experience periods are genuine parallel work. The indices and exact ranges must match the submitted experience array; expected_version binds the acknowledgement to the profile version the candidate read.
additionalProperties: false
required:
- first_index
- second_index
- first_period
- second_period
properties:
first_index:
type: integer
minimum: 0
maximum: 19
second_index:
type: integer
minimum: 1
maximum: 19
first_period:
$ref: '#/ProfileExperiencePeriod'
second_period:
$ref: '#/ProfileExperiencePeriod'
ProfileConfirmedCategory:
type: object
description: 'A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`.'
@@ -2023,6 +2085,7 @@ CandidateProfile:
- stack
- roles
- experience
- experience_overlaps
- soft_skills
- terms
- confirmed_categories
@@ -2052,6 +2115,12 @@ CandidateProfile:
description: Work history entries in the order the candidate gave them.
items:
$ref: '#/ProfileExperienceItem'
experience_overlaps:
type: array
maxItems: 190
description: Every pair of overlapping experience periods, with its confirmation status. The indices refer to this version's experience array.
items:
$ref: '#/ProfileExperienceOverlap'
soft_skills:
type: array
maxItems: 10
@@ -2311,6 +2380,12 @@ CandidateProfileUpdate:
description: Work history entries.
items:
$ref: '#/ProfileExperienceItemInput'
confirmed_parallel_periods:
type: array
maxItems: 190
description: Explicit acknowledgements for overlapping periods. Each pair must use distinct in-range indices and repeat the exact normalized started_on and ended_on values of those entries in this body. A changed or reordered period needs a new acknowledgement. The server retains a previous acknowledgement only for the same indices and dates. Duplicate pairs and pairs that do not overlap are rejected.
items:
$ref: '#/ProfileParallelPeriodConfirmation'
soft_skills:
type: array
maxItems: 10
@@ -515,6 +515,76 @@ schemas:
$ref: "#/schemas/ProfileItemStatus"
source:
$ref: "#/schemas/ProfileClaimSource"
ProfileExperienceOverlapStatus:
type: string
description: Whether the candidate confirmed that two overlapping periods are genuine parallel work.
enum:
- needs_confirmation
- confirmed
ProfileExperienceOverlap:
type: object
description: >-
One pair of work history entries whose inclusive month ranges overlap.
The indices refer to the experience array in this profile version.
`confirmed` records an explicit acknowledgement for this pair of dates;
otherwise the pair needs confirmation before a changed profile can be saved.
additionalProperties: false
required:
- first_index
- second_index
- status
properties:
first_index:
type: integer
minimum: 0
maximum: 19
second_index:
type: integer
minimum: 1
maximum: 19
status:
$ref: "#/schemas/ProfileExperienceOverlapStatus"
ProfileExperiencePeriod:
type: object
description: The exact month range of an experience entry, copied into a confirmation.
additionalProperties: false
required:
- started_on
- ended_on
properties:
started_on:
$ref: "#/schemas/ProfileYearMonth"
ended_on:
description: Last month of work, or null when the period is open-ended.
oneOf:
- $ref: "#/schemas/ProfileYearMonth"
- type: "null"
ProfileParallelPeriodConfirmation:
type: object
description: >-
Explicit acknowledgement that the two indexed experience periods are
genuine parallel work. The indices and exact ranges must match the
submitted experience array; expected_version binds the acknowledgement
to the profile version the candidate read.
additionalProperties: false
required:
- first_index
- second_index
- first_period
- second_period
properties:
first_index:
type: integer
minimum: 0
maximum: 19
second_index:
type: integer
minimum: 1
maximum: 19
first_period:
$ref: "#/schemas/ProfileExperiencePeriod"
second_period:
$ref: "#/schemas/ProfileExperiencePeriod"
ProfileConfirmedCategory:
type: object
description: >-
@@ -573,6 +643,7 @@ schemas:
- stack
- roles
- experience
- experience_overlaps
- soft_skills
- terms
- confirmed_categories
@@ -606,6 +677,14 @@ schemas:
description: Work history entries in the order the candidate gave them.
items:
$ref: "#/schemas/ProfileExperienceItem"
experience_overlaps:
type: array
maxItems: 190
description: >-
Every pair of overlapping experience periods, with its confirmation
status. The indices refer to this version's experience array.
items:
$ref: "#/schemas/ProfileExperienceOverlap"
soft_skills:
type: array
maxItems: 10
@@ -921,6 +1000,18 @@ schemas:
description: Work history entries.
items:
$ref: "#/schemas/ProfileExperienceItemInput"
confirmed_parallel_periods:
type: array
maxItems: 190
description: >-
Explicit acknowledgements for overlapping periods. Each pair must
use distinct in-range indices and repeat the exact normalized
started_on and ended_on values of those entries in this body. A
changed or reordered period needs a new acknowledgement. The server
retains a previous acknowledgement only for the same indices and
dates. Duplicate pairs and pairs that do not overlap are rejected.
items:
$ref: "#/schemas/ProfileParallelPeriodConfirmation"
soft_skills:
type: array
maxItems: 10
+87 -8
View File
@@ -552,6 +552,8 @@ paths:
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.
`experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices refer to this response's `experience` array and are scoped to the same `version`; each pair is either `needs_confirmation` or `confirmed`.
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
security:
- sessionCookie: []
@@ -584,7 +586,7 @@ paths:
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.
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. A successful save advances an account whose current onboarding step is candidate_profile to candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update is atomic with the profile and its history.
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.
@@ -594,7 +596,9 @@ paths:
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.
Experience periods use inclusive calendar months. An overlap is allowed only when `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel work. Each acknowledgement names two distinct experience indices and repeats their exact normalized `started_on` and `ended_on` values; both indices and periods must match the submitted array and `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries an earlier acknowledgement only when the same two indices still contain the same dates; reordering or changing either date requires a new acknowledgement. Editing other experience fields does not invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping acknowledgements are invalid.
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, a changed overlap without explicit confirmation, 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: []
@@ -1152,15 +1156,13 @@ paths:
/api/v1/organizations/{org_id}:
get:
operationId: GetOrganization
summary: Read an organization of which the caller is a member.
summary: Read an organization managed by the caller.
description: |-
Requires the session cookie of an employer account with an active membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing.
Requires the session cookie of a verified employer account with an active owner membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing.
Returns the profile with its current `version`, the verification level (`verification`), and the card as a candidate sees it (`candidate_card`). The verification level is always the one the server holds: it never rises because the profile is complete, because the organization has members, or because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations returns it with the membership.
In the MVP the profile is readable by any active member; every member is an owner, because the operations that add members are planned. The roles of PRD FR07 that read a company card without managing it change no field of this contract.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed with the path pointer.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer.
security:
- sessionCookie: []
tags:
@@ -4067,6 +4069,68 @@ components:
$ref: '#/components/schemas/ProfileItemStatus'
source:
$ref: '#/components/schemas/ProfileClaimSource'
ProfileExperienceOverlapStatus:
type: string
description: Whether the candidate confirmed that two overlapping periods are genuine parallel work.
enum:
- needs_confirmation
- confirmed
ProfileExperienceOverlap:
type: object
description: One pair of work history entries whose inclusive month ranges overlap. The indices refer to the experience array in this profile version. `confirmed` records an explicit acknowledgement for this pair of dates; otherwise the pair needs confirmation before a changed profile can be saved.
additionalProperties: false
required:
- first_index
- second_index
- status
properties:
first_index:
type: integer
minimum: 0
maximum: 19
second_index:
type: integer
minimum: 1
maximum: 19
status:
$ref: '#/components/schemas/ProfileExperienceOverlapStatus'
ProfileExperiencePeriod:
type: object
description: The exact month range of an experience entry, copied into a confirmation.
additionalProperties: false
required:
- started_on
- ended_on
properties:
started_on:
$ref: '#/components/schemas/ProfileYearMonth'
ended_on:
description: Last month of work, or null when the period is open-ended.
oneOf:
- $ref: '#/components/schemas/ProfileYearMonth'
- type: 'null'
ProfileParallelPeriodConfirmation:
type: object
description: Explicit acknowledgement that the two indexed experience periods are genuine parallel work. The indices and exact ranges must match the submitted experience array; expected_version binds the acknowledgement to the profile version the candidate read.
additionalProperties: false
required:
- first_index
- second_index
- first_period
- second_period
properties:
first_index:
type: integer
minimum: 0
maximum: 19
second_index:
type: integer
minimum: 1
maximum: 19
first_period:
$ref: '#/components/schemas/ProfileExperiencePeriod'
second_period:
$ref: '#/components/schemas/ProfileExperiencePeriod'
ProfileConfirmedCategory:
type: object
description: 'A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`.'
@@ -4101,6 +4165,7 @@ components:
- stack
- roles
- experience
- experience_overlaps
- soft_skills
- terms
- confirmed_categories
@@ -4130,6 +4195,12 @@ components:
description: Work history entries in the order the candidate gave them.
items:
$ref: '#/components/schemas/ProfileExperienceItem'
experience_overlaps:
type: array
maxItems: 190
description: Every pair of overlapping experience periods, with its confirmation status. The indices refer to this version's experience array.
items:
$ref: '#/components/schemas/ProfileExperienceOverlap'
soft_skills:
type: array
maxItems: 10
@@ -4389,6 +4460,12 @@ components:
description: Work history entries.
items:
$ref: '#/components/schemas/ProfileExperienceItemInput'
confirmed_parallel_periods:
type: array
maxItems: 190
description: Explicit acknowledgements for overlapping periods. Each pair must use distinct in-range indices and repeat the exact normalized started_on and ended_on values of those entries in this body. A changed or reordered period needs a new acknowledgement. The server retains a previous acknowledgement only for the same indices and dates. Duplicate pairs and pairs that do not overlap are rejected.
items:
$ref: '#/components/schemas/ProfileParallelPeriodConfirmation'
soft_skills:
type: array
maxItems: 10
@@ -9756,7 +9833,7 @@ components:
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.'
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, an overlapping experience period without an explicit date-pair acknowledgement, 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:
@@ -10480,6 +10557,7 @@ components:
stack: []
roles: []
experience: []
experience_overlaps: []
soft_skills: []
terms:
location:
@@ -10573,6 +10651,7 @@ components:
quote: null
extraction_version: null
confirmed_at: '2026-10-05T09:30:00Z'
experience_overlaps: []
soft_skills:
- skill: Mentoring
status: confirmed
+8
View File
@@ -321,6 +321,14 @@ components:
$ref: ./components/schemas.yml#/ProfileRoleItem
ProfileExperienceItem:
$ref: ./components/schemas.yml#/ProfileExperienceItem
ProfileExperienceOverlapStatus:
$ref: ./components/schemas.yml#/ProfileExperienceOverlapStatus
ProfileExperienceOverlap:
$ref: ./components/schemas.yml#/ProfileExperienceOverlap
ProfileExperiencePeriod:
$ref: ./components/schemas.yml#/ProfileExperiencePeriod
ProfileParallelPeriodConfirmation:
$ref: ./components/schemas.yml#/ProfileParallelPeriodConfirmation
ProfileConfirmedCategory:
$ref: ./components/schemas.yml#/ProfileConfirmedCategory
CandidateProfile:
+6 -2
View File
@@ -8,6 +8,8 @@ get:
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.
`experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices refer to this response's `experience` array and are scoped to the same `version`; each pair is either `needs_confirmation` or `confirmed`.
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
security:
- sessionCookie: []
@@ -40,7 +42,7 @@ put:
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.
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. A successful save advances an account whose current onboarding step is candidate_profile to candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update is atomic with the profile and its history.
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.
@@ -50,7 +52,9 @@ put:
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.
Experience periods use inclusive calendar months. An overlap is allowed only when `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel work. Each acknowledgement names two distinct experience indices and repeats their exact normalized `started_on` and `ended_on` values; both indices and periods must match the submitted array and `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries an earlier acknowledgement only when the same two indices still contain the same dates; reordering or changing either date requires a new acknowledgement. Editing other experience fields does not invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping acknowledgements are invalid.
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, a changed overlap without explicit confirmation, 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: []
+3 -5
View File
@@ -1,14 +1,12 @@
get:
operationId: GetOrganization
summary: Read an organization of which the caller is a member.
summary: Read an organization managed by the caller.
description: |-
Requires the session cookie of an employer account with an active membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing.
Requires the session cookie of a verified employer account with an active owner membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing.
Returns the profile with its current `version`, the verification level (`verification`), and the card as a candidate sees it (`candidate_card`). The verification level is always the one the server holds: it never rises because the profile is complete, because the organization has members, or because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations returns it with the membership.
In the MVP the profile is readable by any active member; every member is an owner, because the operations that add members are planned. The roles of PRD FR07 that read a company card without managing it change no field of this contract.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed with the path pointer.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer.
security:
- sessionCookie: []
tags:
+4 -2
View File
@@ -32,10 +32,12 @@ Revoking C2 makes the publication effectively closed and hides its fields throug
## Organizations
`POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}`, and `PATCH /api/v1/organizations/{org_id}` are implemented. A verified employer creates the organization and its active owner membership in one transaction, starting at `e0` with basis `confirmed_email`. Every read checks active membership. Only the active owner can edit; the version advances on change and the verification level is preserved.
`POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}`, and `PATCH /api/v1/organizations/{org_id}` are implemented. A verified employer creates the organization and its active owner membership in one transaction, starting at `e0` with basis `confirmed_email`. Every read checks active owner membership. Only the active owner can edit; the version advances on change and the verification level is preserved.
The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `ListMyOrganizations`, needs, and invitations remain unimplemented.
The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Needs and invitations remain unimplemented, but their routes already enforce the common owner check before the 501 fallback.
`TestOrganizationCreationAndOwnerEditingOverHTTP` checks concurrent replay, rollback on owner insertion failure, cross-account denial, persisted reads after rebuilding the API, and reuse of an expired key against PostgreSQL.
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` covers company isolation, candidate denial even with a manually inserted membership, denial for other roles, pagination, and owner revocation with the same cookie. A company in the active-membership directory does not grant owner authority; the server checks the role on every request.
See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md).
+4 -2
View File
@@ -32,10 +32,12 @@
## Организации
Реализованы `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}` и `PATCH /api/v1/organizations/{org_id}`. Подтвержденный работодатель создает организацию и активное членство владельца одной транзакцией; начальный уровень - `e0` с основанием `confirmed_email`. Каждое чтение проверяет активное членство. Изменять профиль может только активный владелец; версия повышается при изменении, уровень проверки сохраняется.
Реализованы `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}` и `PATCH /api/v1/organizations/{org_id}`. Подтвержденный работодатель создает организацию и активное членство владельца одной транзакцией; начальный уровень - `e0` с основанием `confirmed_email`. Каждое чтение проверяет активное членство владельца. Изменять профиль может только активный владелец; версия повышается при изменении, уровень проверки сохраняется.
Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `ListMyOrganizations`, потребности и приглашения пока не реализованы.
Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Потребности и приглашения пока не реализованы, но их пути уже защищены общей проверкой владельца до ответа 501.
`TestOrganizationCreationAndOwnerEditingOverHTTP` проверяет в PostgreSQL параллельный повтор, откат при ошибке вставки владельца, запрет чужого доступа, сохранение данных после пересоздания API и повторное использование истекшего ключа.
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяет изоляцию компаний, отказ кандидату даже с вручную добавленным членством, отказ другим ролям, пагинацию и отзыв доступа владельца с той же cookie. Компания в справочнике активных членств не дает права владельца; сервер проверяет роль на каждом запросе.
Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md).
@@ -0,0 +1,74 @@
-- +goose Up
-- Each row in candidate_profile_overlap_confirmations represents the
-- candidate's acknowledgement of one exact pair of periods in the current
-- profile. Replacing a profile replaces these rows in the same transaction.
CREATE TABLE candidate_profile_overlap_confirmations (
user_id uuid NOT NULL,
first_index smallint NOT NULL,
second_index smallint NOT NULL,
first_started_on text NOT NULL,
first_ended_on text,
second_started_on text NOT NULL,
second_ended_on text,
CONSTRAINT candidate_profile_overlap_confirmations_pkey PRIMARY KEY (
user_id, first_index, second_index
),
CONSTRAINT candidate_profile_overlap_confirmations_profile_fkey FOREIGN KEY (
user_id
) REFERENCES candidate_profiles (user_id) ON DELETE CASCADE,
CONSTRAINT candidate_profile_overlap_confirmations_indices CHECK (
first_index BETWEEN 0 AND 18
AND second_index > first_index
AND second_index BETWEEN 1 AND 19
),
CONSTRAINT candidate_profile_overlap_confirmations_months CHECK (
first_started_on ~ '^[0-9]{4}-(0[1-9]|1[0-2])$'
AND (first_ended_on IS NULL OR first_ended_on ~ '^[0-9]{4}-(0[1-9]|1[0-2])$')
AND second_started_on ~ '^[0-9]{4}-(0[1-9]|1[0-2])$'
AND (second_ended_on IS NULL OR second_ended_on ~ '^[0-9]{4}-(0[1-9]|1[0-2])$')
AND (first_ended_on IS NULL OR first_ended_on >= first_started_on)
AND (second_ended_on IS NULL OR second_ended_on >= second_started_on)
AND (first_ended_on IS NULL OR second_started_on <= first_ended_on)
AND (second_ended_on IS NULL OR first_started_on <= second_ended_on)
)
);
-- The snapshots are private, append-only application records of every
-- changed profile version. They go with the owning account and have no
-- automatic retention limit. Each individual snapshot is bounded by the
-- complete public profile schema.
CREATE TABLE candidate_profile_history (
user_id uuid NOT NULL,
version bigint NOT NULL,
changed_at timestamptz NOT NULL,
snapshot jsonb NOT NULL,
CONSTRAINT candidate_profile_history_pkey PRIMARY KEY (user_id, version),
CONSTRAINT candidate_profile_history_profile_fkey FOREIGN KEY (
user_id
) REFERENCES candidate_profiles (user_id) ON DELETE CASCADE,
CONSTRAINT candidate_profile_history_version_positive CHECK (version > 0),
CONSTRAINT candidate_profile_history_snapshot_bounded CHECK (
jsonb_typeof(snapshot) = 'object'
AND octet_length(snapshot::text) <= 262144
)
);
-- +goose StatementBegin
CREATE FUNCTION reject_candidate_profile_history_update() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'candidate profile history does not allow updates'
USING ERRCODE = 'integrity_constraint_violation';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER candidate_profile_history_no_update
BEFORE UPDATE ON candidate_profile_history
FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_history_update();
-- +goose Down
DROP TRIGGER candidate_profile_history_no_update ON candidate_profile_history;
DROP FUNCTION reject_candidate_profile_history_update();
DROP TABLE candidate_profile_history;
DROP TABLE candidate_profile_overlap_confirmations;
+76 -1
View File
@@ -60,7 +60,28 @@ SELECT
candidate_profile_claims.trust_level,
candidate_profile_claims.quote,
candidate_profile_claims.extraction_version,
candidate_profile_claims.confirmed_at
candidate_profile_claims.confirmed_at,
COALESCE(
(
SELECT jsonb_agg(
jsonb_build_object(
'first_index', confirmations.first_index,
'second_index', confirmations.second_index,
'first_period', jsonb_build_object(
'started_on', confirmations.first_started_on,
'ended_on', confirmations.first_ended_on
),
'second_period', jsonb_build_object(
'started_on', confirmations.second_started_on,
'ended_on', confirmations.second_ended_on
)
) ORDER BY confirmations.first_index, confirmations.second_index
)::text
FROM candidate_profile_overlap_confirmations AS confirmations
WHERE confirmations.user_id = candidate_profiles.user_id
),
'[]'::text
)::text AS parallel_period_acknowledgements
FROM candidate_profiles
LEFT JOIN candidate_profile_claims
ON candidate_profile_claims.user_id = candidate_profiles.user_id
@@ -100,3 +121,57 @@ INSERT INTO candidate_profile_claims (
sqlc.narg(extraction_version),
sqlc.narg(confirmed_at)
);
-- Replaces the current explicit decisions with those in the new profile.
-- The versioned profile row is advanced first in this same transaction.
-- name: DeleteCandidateProfileOverlapConfirmations :exec
DELETE FROM candidate_profile_overlap_confirmations
WHERE user_id = sqlc.arg(user_id);
-- name: InsertCandidateProfileOverlapConfirmation :exec
INSERT INTO candidate_profile_overlap_confirmations (
user_id,
first_index,
second_index,
first_started_on,
first_ended_on,
second_started_on,
second_ended_on
) VALUES (
sqlc.arg(user_id),
sqlc.arg(first_index),
sqlc.arg(second_index),
sqlc.arg(first_started_on),
sqlc.narg(first_ended_on),
sqlc.arg(second_started_on),
sqlc.narg(second_ended_on)
);
-- Every changed version appends exactly one private snapshot. The unique
-- key prevents a second snapshot for the same profile version.
-- name: AppendCandidateProfileHistory :exec
INSERT INTO candidate_profile_history (
user_id,
version,
changed_at,
snapshot
) VALUES (
sqlc.arg(user_id),
sqlc.arg(version),
sqlc.arg(changed_at),
sqlc.arg(snapshot)::jsonb
);
-- Saving a profile advances onboarding only from that exact step. A retry or
-- a save after a later step is already stored never regresses onboarding.
-- name: AdvanceCandidateOnboardingAfterProfile :exec
UPDATE users
SET
onboarding_step = 'candidate_questionnaire',
version = users.version + 1,
updated_at = GREATEST(users.updated_at, sqlc.arg(at)::timestamptz)
WHERE
users.id = sqlc.arg(user_id)
AND users.scenario = 'candidate'
AND users.email_verified_at IS NOT NULL
AND users.onboarding_step = 'candidate_profile';
@@ -0,0 +1,538 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/uuid"
httpadapter "lincodex/backend/internal/adapter/primary/http"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/argon2id"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
profileusecase "lincodex/backend/internal/usecase/profile"
)
const candidateProfileHTTPTestTimeout = 5 * time.Minute
func TestCandidateProfileOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), candidateProfileHTTPTestTimeout)
defer cancel()
harness := newCandidateProfileHTTPHarness(ctx, t, env)
truncateTables(ctx, t, harness.pool, usersDependentTables...)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
now := harness.clock.Now()
candidate := createSessionHTTPUser(ctx, t, harness, "profile-owner@example.test", passwordHash, true)
otherCandidate := createSessionHTTPUser(ctx, t, harness, "profile-other@example.test", passwordHash, true)
employer := createOrganizationHTTPUser(ctx, t, harness, "profile-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now)
for _, user := range []domain.User{candidate, otherCandidate} {
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_profile' WHERE id = $1", user.ID); err != nil {
t.Fatalf("set candidate profile onboarding step: %v", err)
}
}
candidateCookie, candidateCSRF := loginCandidateProfileHTTP(t, harness, candidate.Email.Address())
otherCookie, otherCSRF := loginCandidateProfileHTTP(t, harness, otherCandidate.Email.Address())
employerCookie, _ := loginCandidateProfileHTTP(t, harness, employer.Email.Address())
initial := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.101:1234")
if initial.Code != http.StatusOK || initial.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("empty profile = %d Cache-Control=%q, want 200 no-store: %s", initial.Code, initial.Header().Get("Cache-Control"), initial.Body.String())
}
var emptyResponse candidateProfileHTTPResponse
if err := json.Unmarshal(initial.Body.Bytes(), &emptyResponse); err != nil {
t.Fatalf("decode empty profile: %v", err)
}
if emptyResponse.Version != 0 || emptyResponse.FullName.Status != "unknown" || len(emptyResponse.ExperienceOverlaps) != 0 {
t.Fatalf("empty profile = %+v, want version 0 and no overlapping periods", emptyResponse)
}
missingAcknowledgement := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 0, "Private Profile Owner", false), candidateCookie, candidateCSRF, "192.0.2.102:1234")
if missingAcknowledgement.Code != http.StatusBadRequest || !strings.Contains(missingAcknowledgement.Body.String(), "/experience/1/started_on") {
t.Fatalf("overlapping periods without acknowledgement = %d %s, want field validation", missingAcknowledgement.Code, missingAcknowledgement.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 0, 0)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile")
firstSave := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 0, "Private Profile Owner", true), candidateCookie, candidateCSRF, "192.0.2.103:1234")
if firstSave.Code != http.StatusOK || firstSave.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("save profile = %d Cache-Control=%q: %s", firstSave.Code, firstSave.Header().Get("Cache-Control"), firstSave.Body.String())
}
var saved candidateProfileHTTPResponse
if err := json.Unmarshal(firstSave.Body.Bytes(), &saved); err != nil {
t.Fatalf("decode saved profile: %v", err)
}
if saved.Version != 1 || saved.FullName.Value == nil || *saved.FullName.Value != "Private Profile Owner" ||
len(saved.ExperienceOverlaps) != 1 || saved.ExperienceOverlaps[0].Status != "confirmed" ||
len(saved.ConfirmedCategories) != 0 {
t.Fatalf("saved profile = %+v, want version 1 with confirmed period overlap", saved)
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire")
assertCandidateProfileHistoryCannotBeUpdated(t, ctx, harness, candidate.ID)
reversedPeriod := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateWithExperience(t, 1, "Private Profile Owner", 0, "2021-01", "2020-12"),
candidateCookie, candidateCSRF, "192.0.2.111:1234")
if reversedPeriod.Code != http.StatusBadRequest || !strings.Contains(reversedPeriod.Body.String(), "/experience/0/ended_on") {
t.Fatalf("reversed experience period = %d %s, want a fixed ended_on validation error", reversedPeriod.Code, reversedPeriod.Body.String())
}
futurePeriod := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateWithExperience(t, 1, "Private Profile Owner", 1, "2999-01", nil),
candidateCookie, candidateCSRF, "192.0.2.112:1234")
if futurePeriod.Code != http.StatusBadRequest || !strings.Contains(futurePeriod.Body.String(), "/experience/1/started_on") {
t.Fatalf("future experience period = %d %s, want a fixed started_on validation error", futurePeriod.Code, futurePeriod.Body.String())
}
for _, forbiddenField := range []struct {
name string
value any
}{
{name: "confirmed_categories", value: []any{map[string]any{"specialization": "backend", "grade": "senior"}}},
{name: "user_id", value: uuid.NewString()},
} {
body := candidateProfileUpdateWithUnknownField(t,
candidateProfileUpdateBody(t, 1, "Private Profile Owner", true), forbiddenField.name, forbiddenField.value)
response := candidateProfileHTTPRequest(t, harness, http.MethodPut, body, candidateCookie, candidateCSRF, "192.0.2.113:1234")
if response.Code != http.StatusBadRequest {
t.Fatalf("profile update with %s = %d %s, want 400", forbiddenField.name, response.Code, response.Body.String())
}
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire")
stale := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 0, "Stale Profile Name", true), candidateCookie, candidateCSRF, "192.0.2.104:1234")
requireSessionProblem(t, stale, http.StatusPreconditionFailed, "version_conflict")
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
noOp := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 1, "Private Profile Owner", true), candidateCookie, candidateCSRF, "192.0.2.105:1234")
if noOp.Code != http.StatusOK {
t.Fatalf("no-op profile save = %d %s, want 200", noOp.Code, noOp.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
otherRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", otherCookie, "", "192.0.2.106:1234")
var otherProfile candidateProfileHTTPResponse
if otherRead.Code != http.StatusOK || json.Unmarshal(otherRead.Body.Bytes(), &otherProfile) != nil ||
otherProfile.Version != 0 || otherProfile.FullName.Value != nil {
t.Fatalf("another candidate's profile = %d %s, want an empty version-0 profile", otherRead.Code, otherRead.Body.String())
}
employerRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", employerCookie, "", "192.0.2.107:1234")
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
for _, foreignPath := range []string{
"/api/v1/me/profile/" + otherCandidate.ID.String(),
"/api/v1/me/profile/" + uuid.NewString(),
} {
foreignRead := harness.request(t, http.MethodGet, foreignPath, "", sessionHTTPTestOrigin, candidateCookie, "", "192.0.2.114:1234")
if foreignRead.Code != http.StatusNotFound || strings.Contains(foreignRead.Body.String(), "Private Profile Owner") {
t.Fatalf("foreign profile path %s = %d %s, want a non-disclosing 404", foreignPath, foreignRead.Code, foreignRead.Body.String())
}
}
// A no-op on an unsaved profile advances onboarding without inventing a
// profile version or a history row.
emptySave := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateEmptyProfileUpdateBody(t), otherCookie, otherCSRF, "192.0.2.108:1234")
if emptySave.Code != http.StatusOK {
t.Fatalf("empty profile save = %d %s, want 200", emptySave.Code, emptySave.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, otherCandidate.ID, 0, 0)
assertCandidateProfileOnboarding(t, ctx, harness, otherCandidate.ID, "candidate_questionnaire")
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_profile' WHERE id = $1", candidate.ID); err != nil {
t.Fatalf("reset candidate onboarding for rollback test: %v", err)
}
removeHistoryFailure := installCandidateProfileHistoryInsertFailure(t, ctx, harness)
historyFailure := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 1, "Failed History Write", true), candidateCookie, candidateCSRF, "192.0.2.115:1234")
if historyFailure.Code != http.StatusInternalServerError {
t.Fatalf("profile save with history failure = %d %s, want 500", historyFailure.Code, historyFailure.Body.String())
}
removeHistoryFailure()
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile")
// Failure after history insertion must also roll back the profile and
// history when the onboarding transition fails in the same transaction.
removeOnboardingFailure := installCandidateProfileOnboardingFailure(t, ctx, harness)
rollbackAttempt := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 1, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.116:1234")
if rollbackAttempt.Code != http.StatusInternalServerError {
t.Fatalf("profile save with onboarding failure = %d %s, want 500", rollbackAttempt.Code, rollbackAttempt.Body.String())
}
removeOnboardingFailure()
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile")
unchanged := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.117:1234")
var unchangedProfile candidateProfileHTTPResponse
if unchanged.Code != http.StatusOK || json.Unmarshal(unchanged.Body.Bytes(), &unchangedProfile) != nil ||
unchangedProfile.FullName.Value == nil || *unchangedProfile.FullName.Value != "Private Profile Owner" {
t.Fatalf("profile after failed transaction = %d %s, want old claims", unchanged.Code, unchanged.Body.String())
}
updated := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 1, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.118:1234")
var updatedProfile candidateProfileHTTPResponse
if updated.Code != http.StatusOK || json.Unmarshal(updated.Body.Bytes(), &updatedProfile) != nil ||
updatedProfile.Version != 2 || updatedProfile.FullName.Value == nil || *updatedProfile.FullName.Value != "Private Profile Owner Updated" {
t.Fatalf("profile save after rolled-back attempt = %d %s, want version 2", updated.Code, updated.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 2, 2)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire")
// Once onboarding has moved past the profile step, saving again does not
// move it back or override its current step.
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_assessment' WHERE id = $1", candidate.ID); err != nil {
t.Fatalf("move onboarding to a later step: %v", err)
}
if response := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 2, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.109:1234"); response.Code != http.StatusOK {
t.Fatalf("profile save after later onboarding step = %d %s", response.Code, response.Body.String())
}
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_assessment")
for _, privateValue := range []string{
candidate.Email.Address(), otherCandidate.Email.Address(), employer.Email.Address(),
"Private Profile Owner", "Private Profile Owner Updated", "Stale Profile Name", "Failed History Write",
"Example Private Employer", "Private career history",
} {
if strings.Contains(harness.logs.String(), privateValue) {
t.Fatalf("profile HTTP logs contain private value %q", privateValue)
}
}
// Rebuild the handlers and pool while retaining the session cookie. The
// profile and append-only history remain in PostgreSQL across restarts.
harness.pool.Close()
harness = newCandidateProfileHTTPHarness(ctx, t, env)
restartedRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.110:1234")
var restarted candidateProfileHTTPResponse
if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restarted) != nil ||
restarted.Version != 2 || restarted.FullName.Value == nil || *restarted.FullName.Value != "Private Profile Owner Updated" ||
len(restarted.ExperienceOverlaps) != 1 || restarted.ExperienceOverlaps[0].Status != "confirmed" {
t.Fatalf("profile after handler restart = %d %s, want version 2 and stored confirmation", restartedRead.Code, restartedRead.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 2, 2)
}
type candidateProfileHTTPResponse struct {
Version int64 `json:"version"`
FullName struct {
Status string `json:"status"`
Value *string `json:"value"`
} `json:"full_name"`
ExperienceOverlaps []struct {
FirstIndex int `json:"first_index"`
SecondIndex int `json:"second_index"`
Status string `json:"status"`
} `json:"experience_overlaps"`
ConfirmedCategories []json.RawMessage `json:"confirmed_categories"`
}
func newCandidateProfileHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness {
t.Helper()
pool := env.newPool(ctx, t)
store := postgresadapter.NewIdentityStore(pool)
hasher, err := argon2id.NewHasher(1)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
credentials := identity.NewCredentials(hasher)
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
sessions, err := identity.NewSessionService(identity.SessionDependencies{
Transactor: postgresadapter.NewTransactor(pool), Users: store.Users(), Sessions: store.Sessions(),
Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now,
}, identity.SessionSettings{
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
})
if err != nil {
t.Fatalf("NewSessionService() error = %v", err)
}
logs := &strings.Builder{}
logger := slog.New(slog.NewJSONHandler(logs, nil))
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
identityHandler := v1.NewIdentityHandler(nil,
v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL),
)
profileHandler := v1.NewProfileHandler(profileusecase.NewService(postgresadapter.NewTransactor(pool), clock.Now))
handler := v1.NewHandler(healthHandler, responder,
v1.WithIdentity(identityHandler), v1.WithProfile(profileHandler),
)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
prometheus.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
}
func loginCandidateProfileHTTP(t *testing.T, harness *sessionHTTPHarness, email string) (string, string) {
t.Helper()
response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.100:1234")
if response.Code != http.StatusCreated {
t.Fatalf("login profile account = %d %s", response.Code, response.Body.String())
}
cookie := requireSessionCookie(t, response)
var body struct {
CSRFToken string `json:"csrf_token"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" {
t.Fatalf("decode login CSRF token: %v", err)
}
return cookie.Value, body.CSRFToken
}
func candidateProfileHTTPRequest(
t *testing.T,
harness *sessionHTTPHarness,
method, body, cookie, csrf, remoteAddr string,
) *httptest.ResponseRecorder {
t.Helper()
return harness.request(t, method, "/api/v1/me/profile", body, sessionHTTPTestOrigin, cookie, csrf, remoteAddr)
}
func candidateProfileUpdateBody(t *testing.T, version int64, name string, confirmOverlap bool) string {
t.Helper()
experience := []map[string]any{
{
"employer_name": "Example Private Employer", "specialization": "backend", "started_on": "2021-01",
"ended_on": "2022-06", "summary": "Private career history", "status": "confirmed",
},
{
"employer_name": "Second Private Employer", "specialization": "backend", "started_on": "2022-01",
"ended_on": "2023-04", "summary": "Another private result", "status": "confirmed",
},
}
acknowledgements := []map[string]any{}
if confirmOverlap {
acknowledgements = append(acknowledgements, map[string]any{
"first_index": 0, "second_index": 1,
"first_period": map[string]any{"started_on": "2021-01", "ended_on": "2022-06"},
"second_period": map[string]any{"started_on": "2022-01", "ended_on": "2023-04"},
})
}
body, err := json.Marshal(map[string]any{
"expected_version": version,
"full_name": map[string]any{"value": name, "status": "confirmed"},
"contacts": map[string]any{"email": nil, "phone": nil, "telegram": nil},
"stack": []any{},
"roles": []any{},
"experience": experience,
"confirmed_parallel_periods": acknowledgements,
"soft_skills": []any{},
"terms": map[string]any{"location": nil, "relocation": nil, "salary_minimum": nil},
})
if err != nil {
t.Fatalf("marshal profile update: %v", err)
}
return string(body)
}
func candidateProfileUpdateWithExperience(
t *testing.T,
version int64,
name string,
index int,
startedOn string,
endedOn any,
) string {
t.Helper()
var body map[string]any
if err := json.Unmarshal([]byte(candidateProfileUpdateBody(t, version, name, true)), &body); err != nil {
t.Fatalf("decode profile update fixture: %v", err)
}
experience, ok := body["experience"].([]any)
if !ok || index < 0 || index >= len(experience) {
t.Fatalf("profile update fixture has no experience at index %d", index)
}
item, ok := experience[index].(map[string]any)
if !ok {
t.Fatalf("profile update fixture experience at index %d has the wrong type", index)
}
item["started_on"] = startedOn
item["ended_on"] = endedOn
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal profile update fixture: %v", err)
}
return string(encoded)
}
func candidateProfileUpdateWithUnknownField(t *testing.T, requestBody, field string, value any) string {
t.Helper()
var body map[string]any
if err := json.Unmarshal([]byte(requestBody), &body); err != nil {
t.Fatalf("decode profile update fixture: %v", err)
}
body[field] = value
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal profile update with %s: %v", field, err)
}
return string(encoded)
}
func candidateEmptyProfileUpdateBody(t *testing.T) string {
t.Helper()
body, err := json.Marshal(map[string]any{
"expected_version": 0,
"full_name": nil,
"contacts": map[string]any{"email": nil, "phone": nil, "telegram": nil},
"stack": []any{}, "roles": []any{}, "experience": []any{},
"confirmed_parallel_periods": []any{}, "soft_skills": []any{},
"terms": map[string]any{"location": nil, "relocation": nil, "salary_minimum": nil},
})
if err != nil {
t.Fatalf("marshal empty profile update: %v", err)
}
return string(body)
}
func assertCandidateProfileRows(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, version, history int64) {
t.Helper()
var profileCount, historyCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_profiles WHERE user_id = $1", userID).Scan(&profileCount); err != nil {
t.Fatalf("count stored profiles: %v", err)
}
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_profile_history WHERE user_id = $1", userID).Scan(&historyCount); err != nil {
t.Fatalf("count profile history: %v", err)
}
wantProfileCount := int64(0)
if version > 0 {
wantProfileCount = 1
}
if profileCount != wantProfileCount || historyCount != history {
t.Fatalf("profile rows = %d, history rows = %d; want %d and %d", profileCount, historyCount, wantProfileCount, history)
}
if version > 0 {
var storedVersion int64
if err := harness.pool.QueryRow(ctx, "SELECT version FROM candidate_profiles WHERE user_id = $1", userID).Scan(&storedVersion); err != nil {
t.Fatalf("read stored profile version: %v", err)
}
if storedVersion != version {
t.Fatalf("stored profile version = %d, want %d", storedVersion, version)
}
}
}
func assertCandidateProfileOnboarding(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, want string) {
t.Helper()
var step string
if err := harness.pool.QueryRow(ctx, "SELECT onboarding_step FROM users WHERE id = $1", userID).Scan(&step); err != nil {
t.Fatalf("read onboarding step: %v", err)
}
if step != want {
t.Fatalf("onboarding step = %q, want %q", step, want)
}
}
func assertCandidateProfileHistoryCannotBeUpdated(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID) {
t.Helper()
if _, err := harness.pool.Exec(ctx, "UPDATE candidate_profile_history SET snapshot = snapshot WHERE user_id = $1", userID); err == nil {
t.Fatal("candidate profile history accepted an UPDATE")
}
}
func installCandidateProfileHistoryInsertFailure(t *testing.T, ctx context.Context, harness *sessionHTTPHarness) func() {
t.Helper()
const functionName = "reject_candidate_profile_history_insert_for_http_test"
const triggerName = "candidate_profile_http_reject_history_insert"
if _, err := harness.pool.Exec(ctx, `
CREATE FUNCTION reject_candidate_profile_history_insert_for_http_test() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'candidate profile history HTTP test failure';
END;
$$`); err != nil {
t.Fatalf("create history failure function: %v", err)
}
removed := false
remove := func() {
if removed {
return
}
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := harness.pool.Exec(cleanupCtx, "DROP TRIGGER IF EXISTS "+triggerName+" ON candidate_profile_history"); err != nil {
t.Errorf("drop history failure trigger: %v", err)
}
if _, err := harness.pool.Exec(cleanupCtx, "DROP FUNCTION IF EXISTS "+functionName+"()"); err != nil {
t.Errorf("drop history failure function: %v", err)
}
removed = true
}
t.Cleanup(remove)
if _, err := harness.pool.Exec(ctx, `
CREATE TRIGGER candidate_profile_http_reject_history_insert
BEFORE INSERT ON candidate_profile_history
FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_history_insert_for_http_test()`); err != nil {
t.Fatalf("create history failure trigger: %v", err)
}
return remove
}
func installCandidateProfileOnboardingFailure(t *testing.T, ctx context.Context, harness *sessionHTTPHarness) func() {
t.Helper()
const functionName = "reject_candidate_profile_onboarding_advance_for_http_test"
const triggerName = "candidate_profile_http_reject_onboarding_advance"
if _, err := harness.pool.Exec(ctx, `
CREATE FUNCTION reject_candidate_profile_onboarding_advance_for_http_test() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF OLD.onboarding_step = 'candidate_profile' AND NEW.onboarding_step = 'candidate_questionnaire' THEN
RAISE EXCEPTION 'candidate profile HTTP test failure';
END IF;
RETURN NEW;
END;
$$`); err != nil {
t.Fatalf("create onboarding failure function: %v", err)
}
removed := false
remove := func() {
if removed {
return
}
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := harness.pool.Exec(cleanupCtx, "DROP TRIGGER IF EXISTS "+triggerName+" ON users"); err != nil {
t.Errorf("drop onboarding failure trigger: %v", err)
}
if _, err := harness.pool.Exec(cleanupCtx, "DROP FUNCTION IF EXISTS "+functionName+"()"); err != nil {
t.Errorf("drop onboarding failure function: %v", err)
}
removed = true
}
t.Cleanup(remove)
if _, err := harness.pool.Exec(ctx, `
CREATE TRIGGER candidate_profile_http_reject_onboarding_advance
BEFORE UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_onboarding_advance_for_http_test()`); err != nil {
t.Fatalf("create onboarding failure trigger: %v", err)
}
return remove
}
@@ -35,7 +35,12 @@ var (
candidateProfileClaimsTable = pgx.Identifier{"candidate_profile_claims"}
// candidateProfileTables reference users, so a TRUNCATE of users names
// them through usersDependentTables.
candidateProfileTables = []pgx.Identifier{candidateProfileClaimsTable, candidateProfilesTable}
candidateProfileTables = []pgx.Identifier{
{"candidate_profile_overlap_confirmations"},
{"candidate_profile_history"},
candidateProfileClaimsTable,
candidateProfilesTable,
}
)
// candidateProfileFixture works on the bootstrap database. The tables are
@@ -0,0 +1,265 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"lincodex/backend/internal/domain"
)
func TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout)
defer cancel()
harness := newOrganizationHTTPHarness(ctx, t, env)
resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"})
truncateTables(ctx, t, harness.pool, resetTables...)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
now := harness.clock.Now()
owner := createOrganizationHTTPUser(ctx, t, harness, "company-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
foreignOwner := createOrganizationHTTPUser(ctx, t, harness, "company-foreign-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
recruiter := createOrganizationHTTPUser(ctx, t, harness, "company-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now)
candidate := createOrganizationHTTPUser(ctx, t, harness, "company-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address())
foreignSession := loginOrganizationHTTP(t, harness, foreignOwner.Email.Address())
recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address())
candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address())
organizationA := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "company-context-a")
organizationA2 := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "company-context-a2")
organizationB := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, foreignSession, "company-context-b")
insertOrganizationHTTPMembership(ctx, t, harness, organizationA, recruiter.ID, "recruiter", "active", now)
insertOrganizationHTTPMembership(ctx, t, harness, organizationA, candidate.ID, "owner", "active", now)
ownerRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", ownerSession, "")
if ownerRead.Code != http.StatusOK {
t.Fatalf("owner read = %d %s, want 200", ownerRead.Code, ownerRead.Body.String())
}
for _, test := range []struct {
name string
session organizationHTTPSession
want int
}{
{name: "foreign company", session: foreignSession, want: http.StatusNotFound},
{name: "recruiter membership", session: recruiterSession, want: http.StatusForbidden},
{name: "candidate with manually inserted owner membership", session: candidateSession, want: http.StatusForbidden},
} {
t.Run(test.name, func(t *testing.T) {
response := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", test.session, "")
if response.Code != test.want {
t.Fatalf("company read = %d %s, want %d", response.Code, response.Body.String(), test.want)
}
assertNoCompanyDetails(t, response)
})
}
childForeign := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String()+"/needs", "", "", foreignSession, "")
if childForeign.Code != http.StatusNotFound {
t.Fatalf("foreign owner on tenant needs route = %d %s, want 404 before fallback", childForeign.Code, childForeign.Body.String())
}
assertNoCompanyDetails(t, childForeign)
childOwner := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String()+"/needs", "", "", ownerSession, "")
if childOwner.Code != http.StatusNotImplemented {
t.Fatalf("owner on currently unimplemented needs route = %d %s, want guarded 501 fallback", childOwner.Code, childOwner.Body.String())
}
candidateHide := organizationHTTPRequest(t, harness, http.MethodPut,
"/api/v1/me/privacy/hidden-organizations/"+organizationA.String(), "", env.Config.AppPublicURL, candidateSession, "")
if candidateHide.Code != http.StatusNotImplemented {
t.Fatalf("candidate-owned hiding route = %d %s, want its own 501 fallback", candidateHide.Code, candidateHide.Body.String())
}
assertNoCompanyDetails(t, candidateHide)
firstPage := readOrganizationDirectory(t, harness, ownerSession, "/api/v1/me/organizations?limit=1", http.StatusOK)
if len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" {
t.Fatalf("first organization page = %+v, want one item and a next cursor", firstPage)
}
if firstPage.Items[0].Membership.Role != "owner" || firstPage.Items[0].Membership.State != "active" {
t.Fatalf("owner directory membership = %+v, want active owner", firstPage.Items[0].Membership)
}
secondPage := readOrganizationDirectory(t, harness, ownerSession,
"/api/v1/me/organizations?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), http.StatusOK)
if len(secondPage.Items) != 1 || secondPage.Page.HasMore || secondPage.Page.NextCursor != nil {
t.Fatalf("second organization page = %+v, want one last item", secondPage)
}
if firstPage.Items[0].Organization.ID == secondPage.Items[0].Organization.ID {
t.Fatal("organization directory repeated an item across pages")
}
for _, item := range []organizationDirectoryItem{firstPage.Items[0], secondPage.Items[0]} {
if item.Organization.ID != organizationA.String() && item.Organization.ID != organizationA2.String() {
t.Fatalf("owner directory exposed another account's organization %s", item.Organization.ID)
}
}
foreignCursor := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/me/organizations?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", "", foreignSession, "")
requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed")
foreignDirectory := readOrganizationDirectory(t, harness, foreignSession, "/api/v1/me/organizations", http.StatusOK)
if len(foreignDirectory.Items) != 1 || foreignDirectory.Items[0].Organization.ID != organizationB.String() {
t.Fatalf("foreign owner's directory = %+v, want only %s", foreignDirectory.Items, organizationB)
}
recruiterDirectory := readOrganizationDirectory(t, harness, recruiterSession, "/api/v1/me/organizations", http.StatusOK)
if len(recruiterDirectory.Items) != 1 || recruiterDirectory.Items[0].Membership.Role != "recruiter" {
t.Fatalf("recruiter's directory = %+v, want its active recruiter membership", recruiterDirectory.Items)
}
candidateDirectory := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/organizations", "", "", candidateSession, "")
requireSessionProblem(t, candidateDirectory, http.StatusForbidden, "forbidden")
assertNoCompanyDetails(t, candidateDirectory)
if _, err := harness.pool.Exec(ctx,
"UPDATE memberships SET state = 'removed', updated_at = $1 WHERE organization_id = $2 AND user_id = $3",
now.Add(time.Second), organizationA, recruiter.ID,
); err != nil {
t.Fatalf("revoke recruiter membership: %v", err)
}
revokedRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", recruiterSession, "")
requireSessionProblem(t, revokedRead, http.StatusNotFound, "not_found")
revokedDirectory := readOrganizationDirectory(t, harness, recruiterSession, "/api/v1/me/organizations", http.StatusOK)
if len(revokedDirectory.Items) != 0 {
t.Fatalf("directory with the same cookie after revocation = %+v, want empty", revokedDirectory.Items)
}
if _, err := harness.pool.Exec(ctx,
"UPDATE memberships SET state = 'removed', updated_at = $1 WHERE organization_id = $2 AND user_id = $3",
now.Add(2*time.Second), organizationA, owner.ID,
); err != nil {
t.Fatalf("revoke owner membership: %v", err)
}
revokedOwnerRead := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationA.String(), "", "", ownerSession, "")
requireSessionProblem(t, revokedOwnerRead, http.StatusNotFound, "not_found")
assertNoCompanyDetails(t, revokedOwnerRead)
revokedOwnerChild := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationA.String()+"/needs", "", "", ownerSession, "")
if revokedOwnerChild.Code != http.StatusNotFound {
t.Fatalf("same owner cookie after revocation on tenant route = %d %s, want 404", revokedOwnerChild.Code, revokedOwnerChild.Body.String())
}
assertNoCompanyDetails(t, revokedOwnerChild)
remainingOwnerRead := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationA2.String(), "", "", ownerSession, "")
if remainingOwnerRead.Code != http.StatusOK {
t.Fatalf("same owner cookie for its remaining organization = %d %s, want 200", remainingOwnerRead.Code, remainingOwnerRead.Body.String())
}
remainingOwnerDirectory := readOrganizationDirectory(t, harness, ownerSession, "/api/v1/me/organizations", http.StatusOK)
if len(remainingOwnerDirectory.Items) != 1 || remainingOwnerDirectory.Items[0].Organization.ID != organizationA2.String() {
t.Fatalf("owner directory after membership revocation = %+v, want only %s", remainingOwnerDirectory.Items, organizationA2)
}
for _, marker := range []string{
owner.Email.Address(), foreignOwner.Email.Address(), recruiter.Email.Address(), candidate.Email.Address(),
"ООО Тестовая компания",
} {
if strings.Contains(harness.logs.String(), marker) {
t.Fatalf("company context logs contain account or profile data %q", marker)
}
}
}
func createCompanyForContextTest(
t *testing.T,
harness *sessionHTTPHarness,
origin string,
session organizationHTTPSession,
idempotencyKey string,
) uuid.UUID {
t.Helper()
response := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations",
"{\"name\":\"ООО Тестовая компания\",\"contacts\":{\"website\":\"https://company-context.example.test\",\"email\":\"careers@company-context.example.test\",\"phone\":\"+12025550123\",\"telegram\":\"@companycontext\"}}",
origin, session, idempotencyKey)
if response.Code != http.StatusCreated {
t.Fatalf("create test company = %d %s, want 201", response.Code, response.Body.String())
}
var company struct {
ID uuid.UUID `json:"id"`
}
if err := json.Unmarshal(response.Body.Bytes(), &company); err != nil {
t.Fatalf("decode test company: %v", err)
}
return company.ID
}
func assertNoCompanyDetails(t *testing.T, response *httptest.ResponseRecorder) {
t.Helper()
body := response.Body.String()
for _, marker := range []string{
"ООО Тестовая компания",
"company-context.example.test",
"careers@company-context.example.test",
"+12025550123",
"@companycontext",
} {
if strings.Contains(body, marker) {
t.Fatalf("denied company response contains company profile data %q", marker)
}
}
}
func insertOrganizationHTTPMembership(
ctx context.Context,
t *testing.T,
harness *sessionHTTPHarness,
organizationID uuid.UUID,
userID uuid.UUID,
role, state string,
at time.Time,
) {
t.Helper()
membershipID, err := uuid.NewV7()
if err != nil {
t.Fatalf("NewV7 membership ID: %v", err)
}
if _, err := harness.pool.Exec(ctx, `
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $6)
`, membershipID, organizationID, userID, role, state, at); err != nil {
t.Fatalf("insert test company membership: %v", err)
}
}
type organizationDirectoryResponse struct {
Items []organizationDirectoryItem `json:"items"`
Page struct {
HasMore bool `json:"has_more"`
NextCursor *string `json:"next_cursor"`
} `json:"page"`
}
type organizationDirectoryItem struct {
Organization struct {
ID string `json:"id"`
} `json:"organization"`
Membership struct {
Role string `json:"role"`
State string `json:"state"`
} `json:"membership"`
}
func readOrganizationDirectory(
t *testing.T,
harness *sessionHTTPHarness,
session organizationHTTPSession,
path string,
wantStatus int,
) organizationDirectoryResponse {
t.Helper()
response := organizationHTTPRequest(t, harness, http.MethodGet, path, "", "", session, "")
if response.Code != wantStatus {
t.Fatalf("organization directory = %d %s, want %d", response.Code, response.Body.String(), wantStatus)
}
var directory organizationDirectoryResponse
if err := json.Unmarshal(response.Body.Bytes(), &directory); err != nil {
t.Fatalf("decode organization directory: %v", err)
}
return directory
}
@@ -1149,6 +1149,23 @@ func TestServiceMailSending(t *testing.T) {
if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 {
t.Fatalf("audited decisions = %d, %v; want exactly one", decisions, err)
}
scheduled := harness.delivery(ctx, t, deliveryID)
if scheduled.Status() != domain.DeliveryStatusUnknown || scheduled.NextAttemptAt().IsZero() {
t.Fatalf("authorized delivery is %s due %s; want scheduled unknown work", scheduled.Status(), scheduled.NextAttemptAt())
}
dueAfterAuthorization := scheduled.NextAttemptAt().Add(time.Second)
var databaseNow time.Time
if err := pool.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&databaseNow); err != nil {
t.Fatalf("read database clock after manual retry: %v", err)
}
databaseDueAt := databaseNow.Add(time.Second)
if databaseDueAt.After(dueAfterAuthorization) {
dueAfterAuthorization = databaseDueAt
}
// The CLI uses the real clock; the worker uses the test clock. Align the
// worker with the persisted due time before scripting the next provider
// response, or this subtest leaves that response queued for the next one.
harness.clock.Set(dueAfterAuthorization)
fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "300"})
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry {
@@ -299,7 +299,7 @@ func newOrganizationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvi
v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler),
)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
prometheus.New(), logger, nil)
prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler))
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -4903,6 +4903,10 @@ func (s *Server) handleGetMyPrivacySettingsRequest(args [0]string, argsEscaped b
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices
// refer to this response's `experience` array and are scoped to the same `version`; each pair is
// either `needs_confirmation` or `confirmed`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
@@ -5497,9 +5501,9 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool,
// handleGetOrganizationRequest handles GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
// Requires the session cookie of a verified employer account with an active owner membership in
// `org_id`. The organization comes from the path and is checked against the membership that the server
// holds for the session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
@@ -5507,15 +5511,11 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool,
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
// not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers
// 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
@@ -5653,7 +5653,7 @@ func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool,
mreq := middleware.Request{
Context: ctx,
OperationName: GetOrganizationOperation,
OperationSummary: "Read an organization of which the caller is a member.",
OperationSummary: "Read an organization managed by the caller.",
OperationID: "GetOrganization",
Body: nil,
RawBody: rawBody,
@@ -10710,9 +10710,9 @@ func (s *Server) handleRevokeMyOrganizationContactConsentRequest(args [1]string,
//
// 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.
// link. A successful save advances an account whose current onboarding step is candidate_profile to
// candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update
// is atomic with the profile and its history.
//
// 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,
@@ -10737,6 +10737,17 @@ func (s *Server) handleRevokeMyOrganizationContactConsentRequest(args [1]string,
// 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.
//
// Experience periods use inclusive calendar months. An overlap is allowed only when
// `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel
// work. Each acknowledgement names two distinct experience indices and repeats their exact normalized
// `started_on` and `ended_on` values; both indices and periods must match the submitted array and
// `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries
// an earlier acknowledgement only when the same two indices still contain the same dates; reordering
// or changing either date requires a new acknowledgement. Editing other experience fields does not
// invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers
// to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping
// acknowledgements are invalid.
//
// 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
@@ -10747,9 +10758,9 @@ func (s *Server) handleRevokeMyOrganizationContactConsentRequest(args [1]string,
// 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.
// future, a changed overlap without explicit confirmation, 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) {
@@ -9819,6 +9819,14 @@ func (s *CandidateProfile) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
e.FieldStart("experience_overlaps")
e.ArrStart()
for _, elem := range s.ExperienceOverlaps {
elem.Encode(e)
}
e.ArrEnd()
}
{
e.FieldStart("soft_skills")
e.ArrStart()
@@ -9845,17 +9853,18 @@ func (s *CandidateProfile) encodeFields(e *jx.Encoder) {
}
}
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",
var jsonFieldsNameOfCandidateProfile = [11]string{
0: "version",
1: "full_name",
2: "contacts",
3: "stack",
4: "roles",
5: "experience",
6: "experience_overlaps",
7: "soft_skills",
8: "terms",
9: "confirmed_categories",
10: "updated_at",
}
// Decode decodes CandidateProfile from json.
@@ -9951,8 +9960,26 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"experience\"")
}
case "soft_skills":
case "experience_overlaps":
requiredBitSet[0] |= 1 << 6
if err := func() error {
s.ExperienceOverlaps = make([]ProfileExperienceOverlap, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem ProfileExperienceOverlap
if err := elem.Decode(d); err != nil {
return err
}
s.ExperienceOverlaps = append(s.ExperienceOverlaps, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"experience_overlaps\"")
}
case "soft_skills":
requiredBitSet[0] |= 1 << 7
if err := func() error {
s.SoftSkills = make([]ProfileSoftSkillItem, 0)
if err := d.Arr(func(d *jx.Decoder) error {
@@ -9970,7 +9997,7 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
return errors.Wrap(err, "decode field \"soft_skills\"")
}
case "terms":
requiredBitSet[0] |= 1 << 7
requiredBitSet[1] |= 1 << 0
if err := func() error {
if err := s.Terms.Decode(d); err != nil {
return err
@@ -9980,7 +10007,7 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
return errors.Wrap(err, "decode field \"terms\"")
}
case "confirmed_categories":
requiredBitSet[1] |= 1 << 0
requiredBitSet[1] |= 1 << 1
if err := func() error {
s.ConfirmedCategories = make([]ProfileConfirmedCategory, 0)
if err := d.Arr(func(d *jx.Decoder) error {
@@ -9998,7 +10025,7 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
return errors.Wrap(err, "decode field \"confirmed_categories\"")
}
case "updated_at":
requiredBitSet[1] |= 1 << 1
requiredBitSet[1] |= 1 << 2
if err := func() error {
if err := s.UpdatedAt.Decode(d); err != nil {
return err
@@ -10018,7 +10045,7 @@ func (s *CandidateProfile) Decode(d *jx.Decoder) error {
var failures []validate.FieldError
for i, mask := range [2]uint8{
0b11111111,
0b00000011,
0b00000111,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
@@ -10109,6 +10136,16 @@ func (s *CandidateProfileUpdate) encodeFields(e *jx.Encoder) {
}
e.ArrEnd()
}
{
if s.ConfirmedParallelPeriods != nil {
e.FieldStart("confirmed_parallel_periods")
e.ArrStart()
for _, elem := range s.ConfirmedParallelPeriods {
elem.Encode(e)
}
e.ArrEnd()
}
}
{
e.FieldStart("soft_skills")
e.ArrStart()
@@ -10123,15 +10160,16 @@ func (s *CandidateProfileUpdate) encodeFields(e *jx.Encoder) {
}
}
var jsonFieldsNameOfCandidateProfileUpdate = [8]string{
var jsonFieldsNameOfCandidateProfileUpdate = [9]string{
0: "expected_version",
1: "full_name",
2: "contacts",
3: "stack",
4: "roles",
5: "experience",
6: "soft_skills",
7: "terms",
6: "confirmed_parallel_periods",
7: "soft_skills",
8: "terms",
}
// Decode decodes CandidateProfileUpdate from json.
@@ -10139,7 +10177,7 @@ 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
var requiredBitSet [2]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
@@ -10227,8 +10265,25 @@ func (s *CandidateProfileUpdate) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "decode field \"experience\"")
}
case "confirmed_parallel_periods":
if err := func() error {
s.ConfirmedParallelPeriods = make([]ProfileParallelPeriodConfirmation, 0)
if err := d.Arr(func(d *jx.Decoder) error {
var elem ProfileParallelPeriodConfirmation
if err := elem.Decode(d); err != nil {
return err
}
s.ConfirmedParallelPeriods = append(s.ConfirmedParallelPeriods, elem)
return nil
}); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"confirmed_parallel_periods\"")
}
case "soft_skills":
requiredBitSet[0] |= 1 << 6
requiredBitSet[0] |= 1 << 7
if err := func() error {
s.SoftSkills = make([]ProfileSoftSkillItemInput, 0)
if err := d.Arr(func(d *jx.Decoder) error {
@@ -10246,7 +10301,7 @@ func (s *CandidateProfileUpdate) Decode(d *jx.Decoder) error {
return errors.Wrap(err, "decode field \"soft_skills\"")
}
case "terms":
requiredBitSet[0] |= 1 << 7
requiredBitSet[1] |= 1 << 0
if err := func() error {
if err := s.Terms.Decode(d); err != nil {
return err
@@ -10264,8 +10319,9 @@ func (s *CandidateProfileUpdate) Decode(d *jx.Decoder) error {
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b11111111,
for i, mask := range [2]uint8{
0b10111111,
0b00000001,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
@@ -40269,6 +40325,283 @@ func (s *ProfileExperienceItemInput) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ProfileExperienceOverlap) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ProfileExperienceOverlap) encodeFields(e *jx.Encoder) {
{
e.FieldStart("first_index")
e.Int(s.FirstIndex)
}
{
e.FieldStart("second_index")
e.Int(s.SecondIndex)
}
{
e.FieldStart("status")
s.Status.Encode(e)
}
}
var jsonFieldsNameOfProfileExperienceOverlap = [3]string{
0: "first_index",
1: "second_index",
2: "status",
}
// Decode decodes ProfileExperienceOverlap from json.
func (s *ProfileExperienceOverlap) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProfileExperienceOverlap to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "first_index":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Int()
s.FirstIndex = int(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"first_index\"")
}
case "second_index":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Int()
s.SecondIndex = int(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"second_index\"")
}
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 ProfileExperienceOverlap")
}
// 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(jsonFieldsNameOfProfileExperienceOverlap) {
name = jsonFieldsNameOfProfileExperienceOverlap[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 *ProfileExperienceOverlap) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ProfileExperienceOverlap) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ProfileExperienceOverlapStatus as json.
func (s ProfileExperienceOverlapStatus) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes ProfileExperienceOverlapStatus from json.
func (s *ProfileExperienceOverlapStatus) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProfileExperienceOverlapStatus to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch ProfileExperienceOverlapStatus(v) {
case ProfileExperienceOverlapStatusNeedsConfirmation:
*s = ProfileExperienceOverlapStatusNeedsConfirmation
case ProfileExperienceOverlapStatusConfirmed:
*s = ProfileExperienceOverlapStatusConfirmed
default:
*s = ProfileExperienceOverlapStatus(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s ProfileExperienceOverlapStatus) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ProfileExperienceOverlapStatus) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ProfileExperiencePeriod) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ProfileExperiencePeriod) encodeFields(e *jx.Encoder) {
{
e.FieldStart("started_on")
s.StartedOn.Encode(e)
}
{
e.FieldStart("ended_on")
s.EndedOn.Encode(e)
}
}
var jsonFieldsNameOfProfileExperiencePeriod = [2]string{
0: "started_on",
1: "ended_on",
}
// Decode decodes ProfileExperiencePeriod from json.
func (s *ProfileExperiencePeriod) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProfileExperiencePeriod to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "started_on":
requiredBitSet[0] |= 1 << 0
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 << 1
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\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ProfileExperiencePeriod")
}
// 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(jsonFieldsNameOfProfileExperiencePeriod) {
name = jsonFieldsNameOfProfileExperiencePeriod[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 *ProfileExperiencePeriod) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ProfileExperiencePeriod) 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)
@@ -40855,6 +41188,149 @@ func (s *ProfileLocationName) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *ProfileParallelPeriodConfirmation) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *ProfileParallelPeriodConfirmation) encodeFields(e *jx.Encoder) {
{
e.FieldStart("first_index")
e.Int(s.FirstIndex)
}
{
e.FieldStart("second_index")
e.Int(s.SecondIndex)
}
{
e.FieldStart("first_period")
s.FirstPeriod.Encode(e)
}
{
e.FieldStart("second_period")
s.SecondPeriod.Encode(e)
}
}
var jsonFieldsNameOfProfileParallelPeriodConfirmation = [4]string{
0: "first_index",
1: "second_index",
2: "first_period",
3: "second_period",
}
// Decode decodes ProfileParallelPeriodConfirmation from json.
func (s *ProfileParallelPeriodConfirmation) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ProfileParallelPeriodConfirmation to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "first_index":
requiredBitSet[0] |= 1 << 0
if err := func() error {
v, err := d.Int()
s.FirstIndex = int(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"first_index\"")
}
case "second_index":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Int()
s.SecondIndex = int(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"second_index\"")
}
case "first_period":
requiredBitSet[0] |= 1 << 2
if err := func() error {
if err := s.FirstPeriod.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"first_period\"")
}
case "second_period":
requiredBitSet[0] |= 1 << 3
if err := func() error {
if err := s.SecondPeriod.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"second_period\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode ProfileParallelPeriodConfirmation")
}
// 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(jsonFieldsNameOfProfileParallelPeriodConfirmation) {
name = jsonFieldsNameOfProfileParallelPeriodConfirmation[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 *ProfileParallelPeriodConfirmation) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ProfileParallelPeriodConfirmation) 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()
@@ -3261,7 +3261,7 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
switch method {
case "GET":
r.name = GetOrganizationOperation
r.summary = "Read an organization of which the caller is a member."
r.summary = "Read an organization managed by the caller."
r.operationID = "GetOrganization"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}"
@@ -5097,6 +5097,9 @@ type CandidateProfile struct {
Roles []ProfileRoleItem `json:"roles"`
// Work history entries in the order the candidate gave them.
Experience []ProfileExperienceItem `json:"experience"`
// Every pair of overlapping experience periods, with its confirmation status. The indices refer to
// this version's experience array.
ExperienceOverlaps []ProfileExperienceOverlap `json:"experience_overlaps"`
// Soft skills in the order the candidate gave them, each skill at most once without regard to letter
// case.
SoftSkills []ProfileSoftSkillItem `json:"soft_skills"`
@@ -5138,6 +5141,11 @@ func (s *CandidateProfile) GetExperience() []ProfileExperienceItem {
return s.Experience
}
// GetExperienceOverlaps returns the value of ExperienceOverlaps.
func (s *CandidateProfile) GetExperienceOverlaps() []ProfileExperienceOverlap {
return s.ExperienceOverlaps
}
// GetSoftSkills returns the value of SoftSkills.
func (s *CandidateProfile) GetSoftSkills() []ProfileSoftSkillItem {
return s.SoftSkills
@@ -5188,6 +5196,11 @@ func (s *CandidateProfile) SetExperience(val []ProfileExperienceItem) {
s.Experience = val
}
// SetExperienceOverlaps sets the value of ExperienceOverlaps.
func (s *CandidateProfile) SetExperienceOverlaps(val []ProfileExperienceOverlap) {
s.ExperienceOverlaps = val
}
// SetSoftSkills sets the value of SoftSkills.
func (s *CandidateProfile) SetSoftSkills(val []ProfileSoftSkillItem) {
s.SoftSkills = val
@@ -5259,6 +5272,11 @@ type CandidateProfileUpdate struct {
Roles []ProfileRoleItemInput `json:"roles"`
// Work history entries.
Experience []ProfileExperienceItemInput `json:"experience"`
// Explicit acknowledgements for overlapping periods. Each pair must use distinct in-range indices and
// repeat the exact normalized started_on and ended_on values of those entries in this body. A changed
// or reordered period needs a new acknowledgement. The server retains a previous acknowledgement only
// for the same indices and dates. Duplicate pairs and pairs that do not overlap are rejected.
ConfirmedParallelPeriods []ProfileParallelPeriodConfirmation `json:"confirmed_parallel_periods"`
// 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"`
@@ -5295,6 +5313,11 @@ func (s *CandidateProfileUpdate) GetExperience() []ProfileExperienceItemInput {
return s.Experience
}
// GetConfirmedParallelPeriods returns the value of ConfirmedParallelPeriods.
func (s *CandidateProfileUpdate) GetConfirmedParallelPeriods() []ProfileParallelPeriodConfirmation {
return s.ConfirmedParallelPeriods
}
// GetSoftSkills returns the value of SoftSkills.
func (s *CandidateProfileUpdate) GetSoftSkills() []ProfileSoftSkillItemInput {
return s.SoftSkills
@@ -5335,6 +5358,11 @@ func (s *CandidateProfileUpdate) SetExperience(val []ProfileExperienceItemInput)
s.Experience = val
}
// SetConfirmedParallelPeriods sets the value of ConfirmedParallelPeriods.
func (s *CandidateProfileUpdate) SetConfirmedParallelPeriods(val []ProfileParallelPeriodConfirmation) {
s.ConfirmedParallelPeriods = val
}
// SetSoftSkills sets the value of SoftSkills.
func (s *CandidateProfileUpdate) SetSoftSkills(val []ProfileSoftSkillItemInput) {
s.SoftSkills = val
@@ -21066,6 +21094,117 @@ func (s *ProfileExperienceItemInput) SetStatus(val ProfileItemStatus) {
s.Status = val
}
// One pair of work history entries whose inclusive month ranges overlap. The indices refer to the
// experience array in this profile version. `confirmed` records an explicit acknowledgement for this
// pair of dates; otherwise the pair needs confirmation before a changed profile can be saved.
// Ref: #/components/schemas/ProfileExperienceOverlap
type ProfileExperienceOverlap struct {
FirstIndex int `json:"first_index"`
SecondIndex int `json:"second_index"`
Status ProfileExperienceOverlapStatus `json:"status"`
}
// GetFirstIndex returns the value of FirstIndex.
func (s *ProfileExperienceOverlap) GetFirstIndex() int {
return s.FirstIndex
}
// GetSecondIndex returns the value of SecondIndex.
func (s *ProfileExperienceOverlap) GetSecondIndex() int {
return s.SecondIndex
}
// GetStatus returns the value of Status.
func (s *ProfileExperienceOverlap) GetStatus() ProfileExperienceOverlapStatus {
return s.Status
}
// SetFirstIndex sets the value of FirstIndex.
func (s *ProfileExperienceOverlap) SetFirstIndex(val int) {
s.FirstIndex = val
}
// SetSecondIndex sets the value of SecondIndex.
func (s *ProfileExperienceOverlap) SetSecondIndex(val int) {
s.SecondIndex = val
}
// SetStatus sets the value of Status.
func (s *ProfileExperienceOverlap) SetStatus(val ProfileExperienceOverlapStatus) {
s.Status = val
}
// Whether the candidate confirmed that two overlapping periods are genuine parallel work.
// Ref: #/components/schemas/ProfileExperienceOverlapStatus
type ProfileExperienceOverlapStatus string
const (
ProfileExperienceOverlapStatusNeedsConfirmation ProfileExperienceOverlapStatus = "needs_confirmation"
ProfileExperienceOverlapStatusConfirmed ProfileExperienceOverlapStatus = "confirmed"
)
// AllValues returns all ProfileExperienceOverlapStatus values.
func (ProfileExperienceOverlapStatus) AllValues() []ProfileExperienceOverlapStatus {
return []ProfileExperienceOverlapStatus{
ProfileExperienceOverlapStatusNeedsConfirmation,
ProfileExperienceOverlapStatusConfirmed,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s ProfileExperienceOverlapStatus) MarshalText() ([]byte, error) {
switch s {
case ProfileExperienceOverlapStatusNeedsConfirmation:
return []byte(s), nil
case ProfileExperienceOverlapStatusConfirmed:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *ProfileExperienceOverlapStatus) UnmarshalText(data []byte) error {
switch ProfileExperienceOverlapStatus(data) {
case ProfileExperienceOverlapStatusNeedsConfirmation:
*s = ProfileExperienceOverlapStatusNeedsConfirmation
return nil
case ProfileExperienceOverlapStatusConfirmed:
*s = ProfileExperienceOverlapStatusConfirmed
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// The exact month range of an experience entry, copied into a confirmation.
// Ref: #/components/schemas/ProfileExperiencePeriod
type ProfileExperiencePeriod struct {
StartedOn ProfileYearMonth `json:"started_on"`
// Last month of work, or null when the period is open-ended.
EndedOn NilProfileYearMonth `json:"ended_on"`
}
// GetStartedOn returns the value of StartedOn.
func (s *ProfileExperiencePeriod) GetStartedOn() ProfileYearMonth {
return s.StartedOn
}
// GetEndedOn returns the value of EndedOn.
func (s *ProfileExperiencePeriod) GetEndedOn() NilProfileYearMonth {
return s.EndedOn
}
// SetStartedOn sets the value of StartedOn.
func (s *ProfileExperiencePeriod) SetStartedOn(val ProfileYearMonth) {
s.StartedOn = val
}
// SetEndedOn sets the value of EndedOn.
func (s *ProfileExperiencePeriod) SetEndedOn(val NilProfileYearMonth) {
s.EndedOn = val
}
type ProfileExperienceSummary string
// Full name of the candidate with its confirmation state and provenance. The value is personal data.
@@ -21260,6 +21399,57 @@ func (s *ProfileLocationInput) SetStatus(val ProfileItemStatus) {
type ProfileLocationName string
// Explicit acknowledgement that the two indexed experience periods are genuine parallel work. The
// indices and exact ranges must match the submitted experience array; expected_version binds the
// acknowledgement to the profile version the candidate read.
// Ref: #/components/schemas/ProfileParallelPeriodConfirmation
type ProfileParallelPeriodConfirmation struct {
FirstIndex int `json:"first_index"`
SecondIndex int `json:"second_index"`
FirstPeriod ProfileExperiencePeriod `json:"first_period"`
SecondPeriod ProfileExperiencePeriod `json:"second_period"`
}
// GetFirstIndex returns the value of FirstIndex.
func (s *ProfileParallelPeriodConfirmation) GetFirstIndex() int {
return s.FirstIndex
}
// GetSecondIndex returns the value of SecondIndex.
func (s *ProfileParallelPeriodConfirmation) GetSecondIndex() int {
return s.SecondIndex
}
// GetFirstPeriod returns the value of FirstPeriod.
func (s *ProfileParallelPeriodConfirmation) GetFirstPeriod() ProfileExperiencePeriod {
return s.FirstPeriod
}
// GetSecondPeriod returns the value of SecondPeriod.
func (s *ProfileParallelPeriodConfirmation) GetSecondPeriod() ProfileExperiencePeriod {
return s.SecondPeriod
}
// SetFirstIndex sets the value of FirstIndex.
func (s *ProfileParallelPeriodConfirmation) SetFirstIndex(val int) {
s.FirstIndex = val
}
// SetSecondIndex sets the value of SecondIndex.
func (s *ProfileParallelPeriodConfirmation) SetSecondIndex(val int) {
s.SecondIndex = val
}
// SetFirstPeriod sets the value of FirstPeriod.
func (s *ProfileParallelPeriodConfirmation) SetFirstPeriod(val ProfileExperiencePeriod) {
s.FirstPeriod = val
}
// SetSecondPeriod sets the value of SecondPeriod.
func (s *ProfileParallelPeriodConfirmation) SetSecondPeriod(val ProfileExperiencePeriod) {
s.SecondPeriod = val
}
// 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`.
@@ -700,6 +700,10 @@ type Handler interface {
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices
// refer to this response's `experience` array and are scoped to the same `version`; each pair is
// either `needs_confirmation` or `confirmed`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
@@ -742,9 +746,9 @@ type Handler interface {
GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error)
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
// Requires the session cookie of a verified employer account with an active owner membership in
// `org_id`. The organization comes from the path and is checked against the membership that the server
// holds for the session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
@@ -752,15 +756,11 @@ type Handler interface {
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
// not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers
// 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer.
//
// GET /api/v1/organizations/{org_id}
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
@@ -1293,9 +1293,9 @@ type Handler interface {
//
// 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.
// link. A successful save advances an account whose current onboarding step is candidate_profile to
// candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update
// is atomic with the profile and its history.
//
// 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,
@@ -1320,6 +1320,17 @@ type Handler interface {
// 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.
//
// Experience periods use inclusive calendar months. An overlap is allowed only when
// `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel
// work. Each acknowledgement names two distinct experience indices and repeats their exact normalized
// `started_on` and `ended_on` values; both indices and periods must match the submitted array and
// `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries
// an earlier acknowledgement only when the same two indices still contain the same dates; reordering
// or changing either date requires a new acknowledgement. Editing other experience fields does not
// invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers
// to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping
// acknowledgements are invalid.
//
// 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
@@ -1330,9 +1341,9 @@ type Handler interface {
// 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.
// future, a changed overlap without explicit confirmation, 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)
@@ -768,6 +768,10 @@ func (UnimplementedHandler) GetMyPrivacySettings(ctx context.Context) (r GetMyPr
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices
// refer to this response's `experience` array and are scoped to the same `version`; each pair is
// either `needs_confirmation` or `confirmed`.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
@@ -819,9 +823,9 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
// Requires the session cookie of a verified employer account with an active owner membership in
// `org_id`. The organization comes from the path and is checked against the membership that the server
// holds for the session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
@@ -829,15 +833,11 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
// not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers
// 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrganizationParams) (r GetOrganizationRes, _ error) {
@@ -1442,9 +1442,9 @@ func (UnimplementedHandler) RevokeMyOrganizationContactConsent(ctx context.Conte
//
// 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.
// link. A successful save advances an account whose current onboarding step is candidate_profile to
// candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update
// is atomic with the profile and its history.
//
// 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,
@@ -1469,6 +1469,17 @@ func (UnimplementedHandler) RevokeMyOrganizationContactConsent(ctx context.Conte
// 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.
//
// Experience periods use inclusive calendar months. An overlap is allowed only when
// `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel
// work. Each acknowledgement names two distinct experience indices and repeats their exact normalized
// `started_on` and `ended_on` values; both indices and periods must match the submitted array and
// `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries
// an earlier acknowledgement only when the same two indices still contain the same dates; reordering
// or changing either date requires a new acknowledgement. Editing other experience fields does not
// invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers
// to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping
// acknowledgements are invalid.
//
// 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
@@ -1479,9 +1490,9 @@ func (UnimplementedHandler) RevokeMyOrganizationContactConsent(ctx context.Conte
// 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.
// future, a changed overlap without explicit confirmation, 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) {
@@ -4553,6 +4553,42 @@ func (s *CandidateProfile) Validate() error {
Error: err,
})
}
if err := func() error {
if s.ExperienceOverlaps == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 190,
MaxLengthSet: true,
}).ValidateLength(len(s.ExperienceOverlaps)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.ExperienceOverlaps {
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_overlaps",
Error: err,
})
}
if err := func() error {
if s.SoftSkills == nil {
return errors.New("nil is invalid value")
@@ -4830,6 +4866,42 @@ func (s *CandidateProfileUpdate) Validate() error {
Error: err,
})
}
if err := func() error {
if s.ConfirmedParallelPeriods == nil {
return nil // optional
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 190,
MaxLengthSet: true,
}).ValidateLength(len(s.ConfirmedParallelPeriods)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.ConfirmedParallelPeriods {
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_parallel_periods",
Error: err,
})
}
if err := func() error {
if s.SoftSkills == nil {
return errors.New("nil is invalid value")
@@ -16144,6 +16216,123 @@ func (s *ProfileExperienceItemInput) Validate() error {
return nil
}
func (s *ProfileExperienceOverlap) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: true,
Max: 19,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.FirstIndex)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "first_index",
Error: err,
})
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 19,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.SecondIndex)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "second_index",
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 ProfileExperienceOverlapStatus) Validate() error {
switch s {
case "needs_confirmation":
return nil
case "confirmed":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *ProfileExperiencePeriod) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
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 len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ProfileExperienceSummary) Validate() error {
alias := (string)(s)
if err := (validate.String{
@@ -16381,6 +16570,82 @@ func (s ProfileLocationName) Validate() error {
return nil
}
func (s *ProfileParallelPeriodConfirmation) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 0,
MaxSet: true,
Max: 19,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.FirstIndex)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "first_index",
Error: err,
})
}
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 19,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.SecondIndex)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "second_index",
Error: err,
})
}
if err := func() error {
if err := s.FirstPeriod.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "first_period",
Error: err,
})
}
if err := func() error {
if err := s.SecondPeriod.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "second_period",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ProfilePhoneClaim) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -106,10 +106,18 @@ func TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory(t *test
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"}
wantUpdate := []string{"confirmed_parallel_periods", "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)
}
profile = resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfile"})
if !slices.Contains(profile.Required, "experience_overlaps") {
t.Error("CandidateProfile does not report every overlapping experience pair")
}
confirmation := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileParallelPeriodConfirmation"})
if got := propertyNames(confirmation); !slices.Equal(got, []string{"first_index", "first_period", "second_index", "second_period"}) {
t.Errorf("ProfileParallelPeriodConfirmation properties = %v, want indices and exact periods only", got)
}
role := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileRoleItemInput"})
if got := propertyNames(role); !slices.Equal(got, []string{"self_assessed_grade", "specialization", "status"}) {
@@ -0,0 +1,97 @@
package httpadapter
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
ogenmiddleware "github.com/ogen-go/ogen/middleware"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/organization"
)
// CompanyAuthorizer checks the current authenticated account against a
// company's active owner membership.
type CompanyAuthorizer interface {
AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (organization.CompanyAccess, error)
}
var ownerCompanyOperations = map[apiadapter.OperationName]struct{}{
apiadapter.GetOrganizationOperation: {},
apiadapter.UpdateOrganizationOperation: {},
apiadapter.ListOrganizationNeedsOperation: {},
apiadapter.CreateOrganizationNeedOperation: {},
apiadapter.GetOrganizationNeedOperation: {},
apiadapter.UpdateOrganizationNeedOperation: {},
apiadapter.ListOrganizationInvitationsOperation: {},
apiadapter.CreateOrganizationInvitationOperation: {},
apiadapter.GetOrganizationInvitationOperation: {},
apiadapter.UpdateOrganizationInvitationOperation: {},
apiadapter.SendOrganizationInvitationOperation: {},
apiadapter.GetOrganizationInvitationContactsOperation: {},
apiadapter.WithdrawOrganizationInvitationOperation: {},
apiadapter.RaiseOrganizationInvitationSalaryOperation: {},
}
// NewCompanyContextMiddleware verifies every owner-scoped company operation
// after generated security and parameter decoding, then attaches the request
// capability. Operations outside the explicit map pass through unchanged.
func NewCompanyContextMiddleware(authorizer CompanyAuthorizer) apiadapter.Middleware {
return func(request ogenmiddleware.Request, next ogenmiddleware.Next) (ogenmiddleware.Response, error) {
if _, required := ownerCompanyOperations[request.OperationName]; !required {
return next(request)
}
if authorizer == nil {
return ogenmiddleware.Response{}, errors.New("httpadapter.NewCompanyContextMiddleware - company authorizer is not configured")
}
principal, ok := v1.PrincipalFromContext(request.Context)
if !ok {
return ogenmiddleware.Response{}, problem.New(request.Context, apiadapter.ProblemCodeUnauthenticated)
}
organizationID, ok := companyPathID(request)
if !ok {
return ogenmiddleware.Response{}, errors.New("httpadapter.NewCompanyContextMiddleware - decoded organization identifier has an unexpected type")
}
access, err := authorizer.AuthorizeCompany(request.Context, principal.UserID, organizationID)
if err != nil {
if response := companyAuthorizationProblem(request.Context, err); response != nil {
return ogenmiddleware.Response{}, response
}
return ogenmiddleware.Response{}, fmt.Errorf("httpadapter.NewCompanyContextMiddleware - authorize company: %w", err)
}
if !access.Matches(principal.UserID, organizationID) {
return ogenmiddleware.Response{}, errors.New("httpadapter.NewCompanyContextMiddleware - authorizer returned a mismatched company capability")
}
request.SetContext(organization.WithCompanyAccess(request.Context, access))
return next(request)
}
}
func companyPathID(request ogenmiddleware.Request) (uuid.UUID, bool) {
value, ok := request.Params.Path("org_id")
if !ok {
return uuid.Nil, false
}
organizationID, ok := value.(uuid.UUID)
return organizationID, ok && organizationID != uuid.Nil
}
func companyAuthorizationProblem(ctx context.Context, err error) *apiadapter.ProblemStatusCode {
switch {
case errors.Is(err, organization.ErrEmailNotVerified):
return problem.New(ctx, apiadapter.ProblemCodeEmailNotVerified)
case errors.Is(err, organization.ErrForbidden), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return problem.New(ctx, apiadapter.ProblemCodeForbidden)
case errors.Is(err, outbound.ErrOrganizationNotFound):
return problem.New(ctx, apiadapter.ProblemCodeNotFound)
default:
return nil
}
}
var _ CompanyAuthorizer = (*v1.OrganizationHandler)(nil)
@@ -0,0 +1,205 @@
package httpadapter
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/google/uuid"
ogenmiddleware "github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/openapi"
"go.yaml.in/yaml/v3"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/organization"
)
type companyAuthorizerFunc func(context.Context, uuid.UUID, uuid.UUID) (organization.CompanyAccess, error)
type requestContextRecorder struct {
context context.Context
}
func (recorder *requestContextRecorder) ServeHTTP(_ http.ResponseWriter, request *http.Request) {
recorder.context = request.Context()
}
func (authorizer companyAuthorizerFunc) AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (organization.CompanyAccess, error) {
return authorizer(ctx, actorID, organizationID)
}
func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testing.T) {
organizationID := uuid.New()
request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, organizationID)
if _, err := NewCompanyContextMiddleware(nil)(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
t.Fatal("owner operation reached next without an authorizer")
return ogenmiddleware.Response{}, nil
}); err == nil {
t.Fatal("owner operation passed without an authorizer")
}
for _, operation := range []apiadapter.OperationName{
apiadapter.HideOrganizationOperation,
apiadapter.UnhideOrganizationOperation,
apiadapter.RevokeMyOrganizationContactConsentOperation,
apiadapter.ListMyOrganizationsOperation,
} {
t.Run(operation, func(t *testing.T) {
called := false
_, err := NewCompanyContextMiddleware(nil)(ownerCompanyMiddlewareRequest(t, uuid.New(), operation, organizationID),
func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
called = true
return ogenmiddleware.Response{}, nil
})
if err != nil || !called {
t.Fatalf("candidate/self-scoped operation: called=%v err=%v; want pass-through", called, err)
}
})
}
}
func TestCompanyContextMiddlewareMapsMembershipFailuresToPublicProblems(t *testing.T) {
for _, test := range []struct {
name string
err error
code apiadapter.ProblemCode
}{
{name: "candidate", err: organization.ErrForbidden, code: apiadapter.ProblemCodeForbidden},
{name: "unverified employer", err: organization.ErrEmailNotVerified, code: apiadapter.ProblemCodeEmailNotVerified},
{name: "other role", err: outbound.ErrOrganizationManagerRequired, code: apiadapter.ProblemCodeForbidden},
{name: "missing or inactive membership", err: outbound.ErrOrganizationNotFound, code: apiadapter.ProblemCodeNotFound},
} {
t.Run(test.name, func(t *testing.T) {
request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, uuid.New())
authorizer := companyAuthorizerFunc(func(context.Context, uuid.UUID, uuid.UUID) (organization.CompanyAccess, error) {
return organization.CompanyAccess{}, test.err
})
called := false
_, err := NewCompanyContextMiddleware(authorizer)(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
called = true
return ogenmiddleware.Response{}, nil
})
var response *apiadapter.ProblemStatusCode
if !errors.As(err, &response) || response.Response.Code != test.code || called {
t.Fatalf("middleware error=%v response=%+v called=%v; want %s and no next call", err, response, called, test.code)
}
})
}
request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, uuid.New())
if _, err := NewCompanyContextMiddleware(companyAuthorizerFunc(func(context.Context, uuid.UUID, uuid.UUID) (organization.CompanyAccess, error) {
return organization.CompanyAccess{}, nil
}))(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
t.Fatal("mismatched capability reached next")
return ogenmiddleware.Response{}, nil
}); err == nil {
t.Fatal("mismatched capability was accepted")
}
}
func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
const bundlePath = "../../../../../api/core/openapi.bundle.yml"
data, err := os.ReadFile(bundlePath)
if err != nil {
t.Fatalf("read OpenAPI bundle: %v", err)
}
var document struct {
Paths map[string]map[string]struct {
OperationID string `yaml:"operationId"`
} `yaml:"paths"`
}
if err := yaml.Unmarshal(data, &document); err != nil {
t.Fatalf("decode OpenAPI bundle: %v", err)
}
if len(ownerCompanyOperations) != 14 {
t.Fatalf("owner operation inventory has %d entries, want 14", len(ownerCompanyOperations))
}
candidateExceptions := map[string]string{
"HideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}",
"UnhideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}",
"RevokeMyOrganizationContactConsent": "/api/v1/me/consents/c4/organizations/{org_id}",
}
seen := make(map[string]string, len(ownerCompanyOperations))
seenExceptions := make(map[string]bool, len(candidateExceptions))
for path, methods := range document.Paths {
for _, operation := range methods {
if operation.OperationID == "" {
continue
}
_, ownerScoped := ownerCompanyOperations[operation.OperationID]
if ownerScoped {
if !strings.HasPrefix(path, "/api/v1/organizations/") || !strings.Contains(path, "{org_id}") {
t.Errorf("owner operation %s is at unexpected path %s", operation.OperationID, path)
}
if previous, exists := seen[operation.OperationID]; exists {
t.Errorf("owner operation %s appears at both %s and %s", operation.OperationID, previous, path)
}
seen[operation.OperationID] = path
continue
}
if !strings.Contains(path, "{org_id}") {
continue
}
expectedPath, candidateOperation := candidateExceptions[operation.OperationID]
if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") {
seenExceptions[operation.OperationID] = true
continue
}
t.Errorf("unclassified organization-scoped operation %s at %s", operation.OperationID, path)
}
}
for operation := range ownerCompanyOperations {
if _, ok := seen[operation]; !ok {
t.Errorf("owner operation %s is absent from the organization-scoped API contract", operation)
}
}
for operation := range candidateExceptions {
if !seenExceptions[operation] {
t.Errorf("candidate exception %s is absent or moved without updating the explicit exception", operation)
}
}
}
type companyContextAuthenticator struct {
session identity.AuthenticatedSession
}
func (authenticator companyContextAuthenticator) Authenticate(context.Context, string) (identity.AuthenticatedSession, error) {
return authenticator.session, nil
}
func ownerCompanyMiddlewareRequest(t *testing.T, actorID uuid.UUID, operation apiadapter.OperationName, organizationID uuid.UUID) ogenmiddleware.Request {
t.Helper()
token, err := domain.NewSecretToken()
if err != nil {
t.Fatalf("NewSecretToken() error = %v", err)
}
verifiedAt := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
request := httptest.NewRequest(http.MethodGet, "https://api.example.test/api/v1/organizations/"+organizationID.String(), nil)
request.AddCookie(&http.Cookie{Name: httpmiddleware.SessionCookieName, Value: token.Reveal()})
metadata := &requestContextRecorder{}
httpmiddleware.SessionRequestMetadata()(metadata).ServeHTTP(httptest.NewRecorder(), request)
metadataContext := metadata.context
security := v1.NewSessionSecurity(companyContextAuthenticator{session: identity.AuthenticatedSession{
User: domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt},
SessionID: uuid.New(), CSRFToken: "company-context-test-csrf",
}}, "https://api.example.test")
ctx, err := security.HandleSessionCookie(metadataContext, operation, apiadapter.SessionCookie{APIKey: token.Reveal()})
if err != nil {
t.Fatalf("HandleSessionCookie() error = %v", err)
}
return ogenmiddleware.Request{
Context: ctx, OperationName: operation,
Params: ogenmiddleware.Parameters{{Name: "org_id", In: openapi.LocationPath}: organizationID},
}
}
@@ -39,6 +39,7 @@ func NewRouter(
collector httpmiddleware.RequestMetrics,
logger *slog.Logger,
trustedProxies []netip.Prefix,
operationMiddleware ...apiadapter.Middleware,
) (http.Handler, error) {
apiServer, err := apiadapter.NewServer(
apiHandler,
@@ -46,6 +47,7 @@ func NewRouter(
apiadapter.WithErrorHandler(problems.HandleServerError),
apiadapter.WithNotFound(problems.NotFound),
apiadapter.WithMethodNotAllowed(problems.MethodNotAllowed),
apiadapter.WithMiddleware(operationMiddleware...),
)
if err != nil {
return nil, fmt.Errorf("httpadapter.NewRouter - create API server: %w", err)
@@ -20,6 +20,7 @@ type Handler struct {
health *HealthHandler
identity *IdentityHandler
consent *ConsentHandler
profile *ProfileHandler
organization *OrganizationHandler
problems *problem.Responder
}
@@ -39,6 +40,11 @@ func WithConsent(consent *ConsentHandler) HandlerOption {
return func(handler *Handler) { handler.consent = consent }
}
// WithProfile serves the candidate's private profile.
func WithProfile(profile *ProfileHandler) HandlerOption {
return func(handler *Handler) { handler.profile = profile }
}
// WithOrganization serves company profiles and owner operations.
func WithOrganization(organization *OrganizationHandler) HandlerOption {
return func(handler *Handler) { handler.organization = organization }
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
@@ -19,6 +20,8 @@ import (
type OrganizationOperations interface {
Create(ctx context.Context, command organization.CreateCommand) (organization.CreateResult, error)
Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error)
AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (organization.CompanyAccess, error)
ListMyOrganizations(ctx context.Context, command organization.OrganizationListCommand) (outbound.OrganizationPage, error)
Update(ctx context.Context, command organization.UpdateCommand) (domain.Organization, error)
}
@@ -45,6 +48,18 @@ func (handler *Handler) GetOrganization(
return handler.organization.GetOrganization(ctx, params)
}
// ListMyOrganizations delegates the session-scoped company directory to its
// business-area handler.
func (handler *Handler) ListMyOrganizations(
ctx context.Context,
params api.ListMyOrganizationsParams,
) (api.ListMyOrganizationsRes, error) {
if handler.organization == nil {
return handler.UnimplementedHandler.ListMyOrganizations(ctx, params)
}
return handler.organization.ListMyOrganizations(ctx, params)
}
// UpdateOrganization delegates company edits to their business-area handler.
func (handler *Handler) UpdateOrganization(
ctx context.Context,
@@ -68,6 +83,17 @@ func NewOrganizationHandler(operations OrganizationOperations, publicOrigin stri
return &OrganizationHandler{operations: operations, publicOrigin: publicOrigin}
}
// AuthorizeCompany delegates current owner membership checks to the use case.
func (handler *OrganizationHandler) AuthorizeCompany(
ctx context.Context,
actorID, organizationID uuid.UUID,
) (organization.CompanyAccess, error) {
if handler == nil || handler.operations == nil {
return organization.CompanyAccess{}, errors.New("OrganizationHandler.AuthorizeCompany - organization operations are not configured")
}
return handler.operations.AuthorizeCompany(ctx, actorID, organizationID)
}
func (handler *OrganizationHandler) CreateOrganization(
ctx context.Context,
request *api.OrganizationCreate,
@@ -146,6 +172,53 @@ func (handler *OrganizationHandler) UpdateOrganization(
}, nil
}
func (handler *OrganizationHandler) ListMyOrganizations(
ctx context.Context,
params api.ListMyOrganizationsParams,
) (api.ListMyOrganizationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyOrganizationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, paramErr := organizationListCommand(principal.UserID, params)
if paramErr != nil {
return organizationListInvalid(ctx, paramErr.pointer), nil
}
page, err := handler.operations.ListMyOrganizations(ctx, command)
if err != nil {
switch {
case errors.Is(err, organization.ErrForbidden):
return (*api.ListMyOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.ListMyOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, domain.ErrInvalidMembership):
return organizationListInvalid(ctx, "cursor"), nil
default:
return nil, err
}
}
items := make([]api.MyOrganization, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, myOrganizationFromDomain(item))
}
var nextCursor api.NilString
nextCursor.SetToNull()
if page.HasMore && len(page.Items) > 0 {
cursor, err := encodeOrganizationCursor(principal.UserID, outbound.OrganizationPositionOf(page.Items[len(page.Items)-1]))
if err != nil {
return nil, fmt.Errorf("OrganizationHandler.ListMyOrganizations - encode cursor: %w", err)
}
nextCursor.SetTo(cursor)
}
return &api.MyOrganizationListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.MyOrganizationList{
Items: items,
Page: api.PageInfo{HasMore: page.HasMore, NextCursor: nextCursor},
},
}, nil
}
func createProfileInput(request *api.OrganizationCreate) domain.OrganizationProfileInput {
contacts := request.Contacts.Or(api.OrganizationContactChannels{})
description, _ := request.Description.Get()
@@ -321,7 +394,7 @@ func createOrganizationFailure(ctx context.Context, err error) (api.CreateOrgani
func getOrganizationFailure(ctx context.Context, err error) (api.GetOrganizationRes, error) {
switch {
case errors.Is(err, organization.ErrForbidden):
case errors.Is(err, organization.ErrForbidden), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
@@ -0,0 +1,105 @@
package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/organization"
)
const (
organizationCursorVersion = 1
organizationCursorBytes = 45
defaultOrganizationLimit = 20
maxOrganizationCursorTime = uint64(1<<63 - 1)
)
type organizationListParamError struct {
pointer string
}
func organizationListCommand(actorID uuid.UUID, params api.ListMyOrganizationsParams) (organization.OrganizationListCommand, *organizationListParamError) {
limit, ok := params.Limit.Get()
if !ok {
limit = defaultOrganizationLimit
}
if limit < 1 || limit > outbound.MaxOrganizationPageSize {
return organization.OrganizationListCommand{}, &organizationListParamError{pointer: "limit"}
}
command := organization.OrganizationListCommand{ActorID: actorID, Limit: limit}
if cursor, ok := params.Cursor.Get(); ok {
position, err := decodeOrganizationCursor(cursor, actorID)
if err != nil {
return organization.OrganizationListCommand{}, &organizationListParamError{pointer: "cursor"}
}
command.After = &position
}
return command, nil
}
func encodeOrganizationCursor(actorID uuid.UUID, position outbound.OrganizationListPosition) (string, error) {
seconds := position.JoinedAt.Unix()
nanos := position.JoinedAt.Nanosecond()
if actorID == uuid.Nil || position.OrganizationID == uuid.Nil || position.JoinedAt.IsZero() || seconds < 0 || nanos < 0 || nanos >= 1_000_000_000 {
return "", errors.New("organization cursor requires an actor and a valid page position")
}
var value [organizationCursorBytes]byte
value[0] = organizationCursorVersion
copy(value[1:17], actorID[:])
binary.BigEndian.PutUint64(value[17:25], uint64(seconds))
binary.BigEndian.PutUint32(value[25:29], uint32(nanos))
copy(value[29:45], position.OrganizationID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodeOrganizationCursor(cursor string, actorID uuid.UUID) (outbound.OrganizationListPosition, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != organizationCursorBytes || actorID == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != organizationCursorVersion ||
uuid.UUID(value[1:17]) != actorID {
return outbound.OrganizationListPosition{}, errors.New("organization cursor is invalid")
}
nanos := binary.BigEndian.Uint32(value[25:29])
organizationID := uuid.UUID(value[29:45])
if nanos >= 1_000_000_000 || organizationID == uuid.Nil {
return outbound.OrganizationListPosition{}, errors.New("organization cursor position is invalid")
}
seconds := binary.BigEndian.Uint64(value[17:25])
if seconds > maxOrganizationCursorTime {
return outbound.OrganizationListPosition{}, errors.New("organization cursor timestamp is invalid")
}
joinedAt := time.Unix(int64(seconds), int64(nanos)).UTC()
if joinedAt.IsZero() {
return outbound.OrganizationListPosition{}, errors.New("organization cursor timestamp is invalid")
}
return outbound.OrganizationListPosition{JoinedAt: joinedAt, OrganizationID: organizationID}, nil
}
func organizationListInvalid(ctx context.Context, pointer string) *api.ListMyOrganizationsBadRequest {
return (*api.ListMyOrganizationsBadRequest)(
&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response,
)
}
func myOrganizationFromDomain(item outbound.MemberOrganization) api.MyOrganization {
organization := item.Organization
membership := item.Membership
return api.MyOrganization{
Organization: api.OrganizationSummary{
ID: organization.ID(), Name: api.OrganizationName(organization.Name()),
VerificationLevel: api.OrganizationVerificationLevel(organization.VerificationLevel()),
},
Membership: api.OrganizationMembership{
OrganizationID: membership.OrganizationID(), Role: api.OrganizationRole(membership.Role()),
State: api.MembershipState(membership.State()), JoinedAt: api.Timestamp(membership.CreatedAt()),
},
}
}
@@ -0,0 +1,76 @@
package v1
import (
"encoding/base64"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/port/outbound"
)
func TestOrganizationCursorRoundTripAndPrincipalBinding(t *testing.T) {
actorID := uuid.New()
position := outbound.OrganizationListPosition{
JoinedAt: time.Date(2026, 8, 15, 10, 30, 0, 123456000, time.UTC), OrganizationID: uuid.New(),
}
cursor, err := encodeOrganizationCursor(actorID, position)
if err != nil {
t.Fatalf("encodeOrganizationCursor() error = %v", err)
}
decoded, err := decodeOrganizationCursor(cursor, actorID)
if err != nil || decoded != position {
t.Fatalf("decodeOrganizationCursor() = %+v, %v; want %+v", decoded, err, position)
}
if _, err := decodeOrganizationCursor(cursor, uuid.New()); err == nil {
t.Fatal("decodeOrganizationCursor accepted a cursor from another principal")
}
if _, err := decodeOrganizationCursor(cursor+"A", actorID); err == nil {
t.Fatal("decodeOrganizationCursor accepted a non-canonical cursor")
}
encoded, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
t.Fatalf("decode cursor bytes: %v", err)
}
encoded[17] = 0x80
if _, err := decodeOrganizationCursor(base64.RawURLEncoding.EncodeToString(encoded), actorID); err == nil {
t.Fatal("decodeOrganizationCursor accepted a timestamp outside the int64 range")
}
if _, err := encodeOrganizationCursor(actorID, outbound.OrganizationListPosition{
JoinedAt: time.Unix(-1, 0), OrganizationID: position.OrganizationID,
}); err == nil {
t.Fatal("encodeOrganizationCursor accepted a negative timestamp")
}
}
func TestOrganizationListCommandValidatesPagination(t *testing.T) {
actorID := uuid.New()
for _, test := range []struct {
name string
params api.ListMyOrganizationsParams
pointer string
}{
{name: "default limit", params: api.ListMyOrganizationsParams{}},
{name: "smallest limit", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(1)}},
{name: "largest limit", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(100)}},
{name: "zero limit", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(0)}, pointer: "limit"},
{name: "oversized limit", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(101)}, pointer: "limit"},
{name: "malformed cursor", params: api.ListMyOrganizationsParams{Limit: api.NewOptInt32(20), Cursor: api.NewOptString(strings.Repeat("x", 512))}, pointer: "cursor"},
} {
t.Run(test.name, func(t *testing.T) {
command, paramErr := organizationListCommand(actorID, test.params)
if test.pointer != "" {
if paramErr == nil || paramErr.pointer != test.pointer {
t.Fatalf("organizationListCommand() error = %+v, want pointer %q", paramErr, test.pointer)
}
return
}
if paramErr != nil || command.ActorID != actorID || command.Limit < 1 || command.Limit > 100 {
t.Fatalf("organizationListCommand() = %+v, %+v; want bounded actor-scoped command", command, paramErr)
}
})
}
}
@@ -0,0 +1,415 @@
package v1
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/profile"
)
// ProfileOperations reads and version-saves the authenticated candidate's
// private manual profile.
type ProfileOperations interface {
GetMyProfile(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error)
SaveMyProfile(ctx context.Context, userID uuid.UUID, expectedVersion int64, input domain.CandidateProfileInput) (domain.CandidateProfile, error)
}
// ProfileHandler serves the candidate's own profile operations.
type ProfileHandler struct {
operations ProfileOperations
}
func NewProfileHandler(operations ProfileOperations) *ProfileHandler {
if operations == nil {
panic("v1.NewProfileHandler - profile operations must not be nil")
}
return &ProfileHandler{operations: operations}
}
func (handler *Handler) GetMyProfile(ctx context.Context) (api.GetMyProfileRes, error) {
if handler.profile == nil {
return handler.UnimplementedHandler.GetMyProfile(ctx)
}
return handler.profile.GetMyProfile(ctx)
}
func (handler *Handler) SaveMyProfile(ctx context.Context, request *api.CandidateProfileUpdate) (api.SaveMyProfileRes, error) {
if handler.profile == nil {
return handler.UnimplementedHandler.SaveMyProfile(ctx, request)
}
return handler.profile.SaveMyProfile(ctx, request)
}
func (handler *ProfileHandler) GetMyProfile(ctx context.Context) (api.GetMyProfileRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyProfileUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
profile, err := handler.operations.GetMyProfile(ctx, principal.UserID)
if err != nil {
return profileReadFailure(ctx, err)
}
return &api.CandidateProfileHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: candidateProfileResponse(profile),
}, nil
}
func (handler *ProfileHandler) SaveMyProfile(ctx context.Context, request *api.CandidateProfileUpdate) (api.SaveMyProfileRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SaveMyProfileUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.SaveMyProfileBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
profile, err := handler.operations.SaveMyProfile(ctx, principal.UserID, int64(request.ExpectedVersion), candidateProfileInput(request))
if err != nil {
return profileSaveFailure(ctx, err)
}
return &api.CandidateProfileHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: candidateProfileResponse(profile),
}, nil
}
func profileReadFailure(ctx context.Context, err error) (api.GetMyProfileRes, error) {
if errors.Is(err, profile.ErrForbidden) {
return (*api.GetMyProfileForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
if errors.Is(err, profile.ErrEmailNotVerified) {
return (*api.GetMyProfileForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
if errors.Is(err, outbound.ErrUserNotFound) {
return (*api.GetMyProfileUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
return nil, err
}
func profileSaveFailure(ctx context.Context, err error) (api.SaveMyProfileRes, error) {
switch {
case errors.Is(err, domain.ErrCandidateProfileVersionConflict), errors.Is(err, outbound.ErrCandidateProfileVersionConflict):
return (*api.SaveMyProfilePreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, profile.ErrForbidden), errors.Is(err, profile.ErrEmailNotVerified):
return (*api.SaveMyProfileForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrUserNotFound):
return (*api.SaveMyProfileUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
case errors.Is(err, domain.ErrInvalidCandidateProfile):
field, ok := errors.AsType[*domain.CandidateProfileFieldError](err)
if !ok {
return (*api.SaveMyProfileBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
return (*api.SaveMyProfileBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer).Response), nil
default:
return nil, err
}
}
func candidateProfileInput(request *api.CandidateProfileUpdate) domain.CandidateProfileInput {
input := domain.CandidateProfileInput{
Stack: make([]domain.ProfileClaimInput[string], 0, len(request.Stack)),
Roles: make([]domain.ProfileClaimInput[domain.ProfileRole], 0, len(request.Roles)),
Experience: make([]domain.ProfileClaimInput[domain.ProfileExperience], 0, len(request.Experience)),
ParallelPeriodAcknowledgements: make([]domain.ProfileParallelPeriodAcknowledgement, 0, len(request.ConfirmedParallelPeriods)),
SoftSkills: make([]domain.ProfileClaimInput[string], 0, len(request.SoftSkills)),
}
if value, ok := request.FullName.Get(); ok {
input.FullName = profileStringInput(string(value.Value), value.Status)
}
if value, ok := request.Contacts.Email.Get(); ok {
input.Email = profileStringInput(string(value.Value), value.Status)
}
if value, ok := request.Contacts.Phone.Get(); ok {
input.Phone = profileStringInput(string(value.Value), value.Status)
}
if value, ok := request.Contacts.Telegram.Get(); ok {
input.Telegram = profileStringInput(string(value.Value), value.Status)
}
for _, item := range request.Stack {
input.Stack = append(input.Stack, domain.ProfileClaimInput[string]{Value: string(item.Tag), Status: domain.ProfileClaimStatus(item.Status)})
}
for _, item := range request.Roles {
grade, _ := item.SelfAssessedGrade.Get()
input.Roles = append(input.Roles, domain.ProfileClaimInput[domain.ProfileRole]{
Value: domain.ProfileRole{Specialization: domain.SpecializationCode(item.Specialization), SelfAssessedGrade: domain.GradeCode(grade)},
Status: domain.ProfileClaimStatus(item.Status),
})
}
for _, item := range request.Experience {
employer, _ := item.EmployerName.Get()
endedOn := profileYearMonth(item.EndedOn)
summary, _ := item.Summary.Get()
input.Experience = append(input.Experience, domain.ProfileClaimInput[domain.ProfileExperience]{
Value: domain.ProfileExperience{
EmployerName: string(employer), Specialization: domain.SpecializationCode(item.Specialization),
StartedOn: string(item.StartedOn), EndedOn: endedOn, Summary: string(summary),
},
Status: domain.ProfileClaimStatus(item.Status),
})
}
for _, item := range request.ConfirmedParallelPeriods {
input.ParallelPeriodAcknowledgements = append(input.ParallelPeriodAcknowledgements, domain.ProfileParallelPeriodAcknowledgement{
FirstIndex: item.FirstIndex, SecondIndex: item.SecondIndex,
FirstPeriod: domain.ProfileExperiencePeriod{
StartedOn: string(item.FirstPeriod.StartedOn), EndedOn: profileYearMonth(item.FirstPeriod.EndedOn),
},
SecondPeriod: domain.ProfileExperiencePeriod{
StartedOn: string(item.SecondPeriod.StartedOn), EndedOn: profileYearMonth(item.SecondPeriod.EndedOn),
},
})
}
for _, item := range request.SoftSkills {
input.SoftSkills = append(input.SoftSkills, domain.ProfileClaimInput[string]{Value: string(item.Skill), Status: domain.ProfileClaimStatus(item.Status)})
}
if value, ok := request.Terms.Location.Get(); ok {
input.Location = profileStringInput(string(value.Value), value.Status)
}
if value, ok := request.Terms.Relocation.Get(); ok {
input.Relocation = &domain.ProfileClaimInput[bool]{Value: value.Value, Status: domain.ProfileClaimStatus(value.Status)}
}
if value, ok := request.Terms.SalaryMinimum.Get(); ok {
input.SalaryMinimum = &domain.ProfileClaimInput[domain.ProfileSalaryMinimum]{
Value: domain.ProfileSalaryMinimum{Amount: int64(value.Value.Amount), TaxBasis: domain.ProfileTaxBasis(value.Value.TaxBasis)},
Status: domain.ProfileClaimStatus(value.Status),
}
}
return input
}
func profileStringInput(value string, status api.ProfileItemStatus) *domain.ProfileClaimInput[string] {
return &domain.ProfileClaimInput[string]{Value: value, Status: domain.ProfileClaimStatus(status)}
}
func profileYearMonth(value api.NilProfileYearMonth) string {
month, ok := value.Get()
if !ok {
return ""
}
return string(month)
}
func candidateProfileResponse(profile domain.CandidateProfile) api.CandidateProfile {
content := profile.Content()
response := api.CandidateProfile{
Version: api.ProfileVersion(profile.Version()),
ExperienceOverlaps: make([]api.ProfileExperienceOverlap, 0),
Stack: make([]api.ProfileStackItem, 0),
Roles: make([]api.ProfileRoleItem, 0),
Experience: make([]api.ProfileExperienceItem, 0),
SoftSkills: make([]api.ProfileSoftSkillItem, 0),
ConfirmedCategories: make([]api.ProfileConfirmedCategory, 0),
}
if name, ok := content.FullName(); ok {
response.FullName = profileFullNameClaim(name)
} else {
response.FullName = profileFullNameClaim(domain.ProfileClaim[string]{}, false)
}
contacts := api.ProfileContacts{}
if email, ok := content.Email(); ok {
contacts.Email = profileEmailClaim(email)
} else {
contacts.Email = profileEmailClaim(domain.ProfileClaim[string]{}, false)
}
if phone, ok := content.Phone(); ok {
contacts.Phone = profilePhoneClaim(phone)
} else {
contacts.Phone = profilePhoneClaim(domain.ProfileClaim[string]{}, false)
}
if telegram, ok := content.Telegram(); ok {
contacts.Telegram = profileTelegramClaim(telegram)
} else {
contacts.Telegram = profileTelegramClaim(domain.ProfileClaim[string]{}, false)
}
response.Contacts = contacts
for _, item := range content.Stack() {
response.Stack = append(response.Stack, api.ProfileStackItem{Tag: api.StackTag(item.Value()), Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source())})
}
for _, item := range content.Roles() {
grade := api.NilGradeCode{}
if item.Value().SelfAssessedGrade == "" {
grade.SetToNull()
} else {
grade.SetTo(api.GradeCode(item.Value().SelfAssessedGrade))
}
response.Roles = append(response.Roles, api.ProfileRoleItem{
Specialization: api.SpecializationCode(item.Value().Specialization), SelfAssessedGrade: grade,
Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
})
}
for _, item := range content.Experience() {
value := item.Value()
employer := api.NilProfileEmployerName{}
if value.EmployerName == "" {
employer.SetToNull()
} else {
employer.SetTo(api.ProfileEmployerName(value.EmployerName))
}
endedOn := api.NilProfileYearMonth{}
if value.EndedOn == "" {
endedOn.SetToNull()
} else {
endedOn.SetTo(api.ProfileYearMonth(value.EndedOn))
}
summary := api.NilProfileExperienceSummary{}
if value.Summary == "" {
summary.SetToNull()
} else {
summary.SetTo(api.ProfileExperienceSummary(value.Summary))
}
response.Experience = append(response.Experience, api.ProfileExperienceItem{
EmployerName: employer, Specialization: api.SpecializationCode(value.Specialization), StartedOn: api.ProfileYearMonth(value.StartedOn),
EndedOn: endedOn, Summary: summary, Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
})
}
for _, item := range content.ExperienceOverlaps() {
response.ExperienceOverlaps = append(response.ExperienceOverlaps, api.ProfileExperienceOverlap{
FirstIndex: item.FirstIndex, SecondIndex: item.SecondIndex, Status: api.ProfileExperienceOverlapStatus(item.Status),
})
}
for _, item := range content.SoftSkills() {
response.SoftSkills = append(response.SoftSkills, api.ProfileSoftSkillItem{
Skill: api.ProfileSoftSkill(item.Value()), Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
})
}
response.Terms = candidateProfileTerms(content)
updatedAt := api.NilTimestamp{}
if profile.UpdatedAt().IsZero() {
updatedAt.SetToNull()
} else {
updatedAt.SetTo(api.Timestamp(profile.UpdatedAt()))
}
response.UpdatedAt = updatedAt
return response
}
func candidateProfileTerms(content domain.CandidateProfileContent) api.ProfileTerms {
terms := api.ProfileTerms{}
if location, ok := content.Location(); ok {
terms.Location = api.ProfileLocationClaim{
Status: api.ProfileClaimStatus(location.Status()), Value: api.NewNilProfileLocationName(api.ProfileLocationName(location.Value())),
Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(location.Source())),
}
} else {
terms.Location = unknownProfileLocationClaim()
}
if relocation, ok := content.Relocation(); ok {
terms.Relocation = api.ProfileRelocationClaim{
Status: api.ProfileClaimStatus(relocation.Status()), Value: api.NewNilBool(relocation.Value()),
Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(relocation.Source())),
}
} else {
terms.Relocation = unknownProfileRelocationClaim()
}
if salary, ok := content.SalaryMinimum(); ok {
terms.SalaryMinimum = api.ProfileSalaryMinimumClaim{
Status: api.ProfileClaimStatus(salary.Status()),
Value: api.NewNilProfileSalaryMinimum(api.ProfileSalaryMinimum{
Amount: api.RubAmount(salary.Value().Amount), Currency: api.CurrencyCodeRUB, Period: api.SalaryPeriodMonth,
TaxBasis: api.SalaryTaxBasis(salary.Value().TaxBasis),
}),
Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(salary.Source())),
}
} else {
terms.SalaryMinimum = unknownProfileSalaryClaim()
}
return terms
}
func profileFullNameClaim(claim domain.ProfileClaim[string], exists ...bool) api.ProfileFullNameClaim {
if len(exists) > 0 && !exists[0] {
value := api.NilContactFullName{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileFullNameClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
return api.ProfileFullNameClaim{Status: api.ProfileClaimStatus(claim.Status()), Value: api.NewNilContactFullName(api.ContactFullName(claim.Value())), Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(claim.Source()))}
}
func profileEmailClaim(claim domain.ProfileClaim[string], exists ...bool) api.ProfileEmailClaim {
if len(exists) > 0 && !exists[0] {
value := api.NilEmailAddress{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileEmailClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
return api.ProfileEmailClaim{Status: api.ProfileClaimStatus(claim.Status()), Value: api.NewNilEmailAddress(api.EmailAddress(claim.Value())), Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(claim.Source()))}
}
func profilePhoneClaim(claim domain.ProfileClaim[string], exists ...bool) api.ProfilePhoneClaim {
if len(exists) > 0 && !exists[0] {
value := api.NilContactPhoneNumber{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfilePhoneClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
return api.ProfilePhoneClaim{Status: api.ProfileClaimStatus(claim.Status()), Value: api.NewNilContactPhoneNumber(api.ContactPhoneNumber(claim.Value())), Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(claim.Source()))}
}
func profileTelegramClaim(claim domain.ProfileClaim[string], exists ...bool) api.ProfileTelegramClaim {
if len(exists) > 0 && !exists[0] {
value := api.NilContactTelegramUsername{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileTelegramClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
return api.ProfileTelegramClaim{Status: api.ProfileClaimStatus(claim.Status()), Value: api.NewNilContactTelegramUsername(api.ContactTelegramUsername(claim.Value())), Source: api.NewNilProfileClaimSource(profileClaimSourceResponse(claim.Source()))}
}
func unknownProfileLocationClaim() api.ProfileLocationClaim {
value := api.NilProfileLocationName{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileLocationClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
func unknownProfileRelocationClaim() api.ProfileRelocationClaim {
value := api.NilBool{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileRelocationClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
func unknownProfileSalaryClaim() api.ProfileSalaryMinimumClaim {
value := api.NilProfileSalaryMinimum{}
value.SetToNull()
source := api.NilProfileClaimSource{}
source.SetToNull()
return api.ProfileSalaryMinimumClaim{Status: api.ProfileClaimStatusUnknown, Value: value, Source: source}
}
func profileClaimSourceResponse(source domain.ProfileClaimSource) api.ProfileClaimSource {
quote := api.NilProfileClaimQuote{}
if source.Quote() == "" {
quote.SetToNull()
} else {
quote.SetTo(api.ProfileClaimQuote(source.Quote()))
}
extractionVersion := api.NilNeedVersionLabel{}
if source.ExtractionVersion() == "" {
extractionVersion.SetToNull()
} else {
extractionVersion.SetTo(api.NeedVersionLabel(source.ExtractionVersion()))
}
confirmedAt := api.NilTimestamp{}
if source.ConfirmedAt().IsZero() {
confirmedAt.SetToNull()
} else {
confirmedAt.SetTo(api.Timestamp(source.ConfirmedAt()))
}
return api.ProfileClaimSource{
Origin: api.ProfileClaimOrigin(source.Origin()), TrustLevel: api.ProfileClaimTrustLevel(domain.ProfileClaimTrustLevel),
Quote: quote, ExtractionVersion: extractionVersion, ConfirmedAt: confirmedAt,
}
}
@@ -0,0 +1,301 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"slices"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const maxCandidateProfileHistorySnapshotBytes = 262144
var _ outbound.CandidateProfileRepositories = (*UnitOfWork)(nil)
func (unit *UnitOfWork) CandidateProfiles() outbound.CandidateProfileRepository {
return candidateProfileRepository{queries: unit.queries}
}
type candidateProfileRepository struct {
queries *sqlc.Queries
}
type candidateProfileHistoryClaim struct {
Kind string `json:"kind"`
Ordinal int `json:"ordinal"`
Value json.RawMessage `json:"value"`
Status string `json:"status"`
Origin string `json:"origin"`
TrustLevel int `json:"trust_level"`
Quote *string `json:"quote,omitempty"`
ExtractionVersion *string `json:"extraction_version,omitempty"`
ConfirmedAt *time.Time `json:"confirmed_at,omitempty"`
}
type candidateProfileHistorySnapshot struct {
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Claims []candidateProfileHistoryClaim `json:"claims"`
ParallelPeriodAcknowledgements []domain.ProfileParallelPeriodAcknowledgement `json:"parallel_period_acknowledgements"`
}
func (repository candidateProfileRepository) Get(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error) {
const location = "candidateProfileRepository.Get"
if userID == uuid.Nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
rows, err := repository.queries.ReadCandidateProfile(ctx, pgUUID(userID))
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - select profile: %w", location, mapCandidateProfileError(err))
}
if len(rows) == 0 {
profile, err := domain.EmptyCandidateProfile(userID)
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - create empty profile: %w", location, err)
}
return profile, nil
}
stored := domain.StoredCandidateProfile{
UserID: userID, Version: rows[0].Version,
CreatedAt: rows[0].CreatedAt.Time, UpdatedAt: rows[0].UpdatedAt.Time,
}
if err := json.Unmarshal([]byte(rows[0].ParallelPeriodAcknowledgements), &stored.ParallelPeriodAcknowledgements); err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - decode stored period confirmations: %w", location, domain.ErrInvalidCandidateProfile)
}
for _, row := range rows {
if !row.Kind.Valid {
continue
}
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 {
return domain.CandidateProfile{}, fmt.Errorf("%s - restore profile: %w", location, err)
}
return profile, nil
}
func (repository candidateProfileRepository) Save(
ctx context.Context,
expectedVersion int64,
profile domain.CandidateProfile,
) (domain.CandidateProfile, error) {
const location = "candidateProfileRepository.Save"
if profile.IsZero() || expectedVersion < 0 || profile.Version() != expectedVersion || profile.UpdatedAt().IsZero() {
return domain.CandidateProfile{}, fmt.Errorf("%s - profile and expected version are inconsistent: %w", location, domain.ErrInvalidCandidateProfile)
}
claims, err := profile.Content().StoredClaims()
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - encode profile claims: %w", location, err)
}
snapshot, err := candidateProfileSnapshot(profile, claims)
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - encode profile history: %w", location, err)
}
if len(snapshot) > maxCandidateProfileHistorySnapshotBytes {
return domain.CandidateProfile{}, fmt.Errorf("%s - history snapshot exceeds its storage bound: %w", location, outbound.ErrCandidateProfileHistoryTooLarge)
}
userID := pgUUID(profile.UserID())
stored, err := repository.advanceProfileVersion(ctx, userID, expectedVersion, profile.UpdatedAt())
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - advance profile version: %w", location, mapCandidateProfileError(err))
}
if err := repository.replaceProfileClaims(ctx, userID, claims); err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - replace claims: %w", location, err)
}
if err := repository.replaceProfilePeriodConfirmations(ctx, userID, profile.Content().ParallelPeriodAcknowledgements()); err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - replace period confirmations: %w", location, err)
}
if err := repository.queries.AppendCandidateProfileHistory(ctx, sqlc.AppendCandidateProfileHistoryParams{
UserID: userID, Version: stored.Version, ChangedAt: stored.UpdatedAt, Snapshot: snapshot,
}); err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - append profile history: %w", location, mapCandidateProfileError(err))
}
return domain.RestoreCandidateProfile(domain.StoredCandidateProfile{
UserID: profile.UserID(), Version: stored.Version, CreatedAt: stored.CreatedAt.Time, UpdatedAt: stored.UpdatedAt.Time,
Claims: claims, ParallelPeriodAcknowledgements: profile.Content().ParallelPeriodAcknowledgements(),
})
}
func (repository candidateProfileRepository) advanceProfileVersion(
ctx context.Context,
userID pgtype.UUID,
expectedVersion int64,
at time.Time,
) (sqlc.CandidateProfile, error) {
var stored sqlc.CandidateProfile
var err error
if expectedVersion == 0 {
stored, err = repository.queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{
UserID: userID, At: pgTime(at),
})
} else {
stored, err = repository.queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{
UserID: userID, ExpectedVersion: expectedVersion, At: pgTime(at),
})
}
if errors.Is(err, pgx.ErrNoRows) {
return sqlc.CandidateProfile{}, outbound.ErrCandidateProfileVersionConflict
}
if err != nil {
return sqlc.CandidateProfile{}, mapCandidateProfileError(err)
}
return stored, nil
}
func (repository candidateProfileRepository) replaceProfileClaims(
ctx context.Context,
userID pgtype.UUID,
claims []domain.StoredProfileClaim,
) error {
if err := repository.queries.DeleteCandidateProfileClaims(ctx, userID); err != nil {
return mapCandidateProfileError(err)
}
for _, claim := range claims {
ordinal, err := candidateProfileOrdinal(claim.Ordinal)
if err != nil {
return err
}
var confirmedAt *time.Time
if !claim.ConfirmedAt.IsZero() {
confirmedAt = &claim.ConfirmedAt
}
if err := repository.queries.InsertCandidateProfileClaim(ctx, sqlc.InsertCandidateProfileClaimParams{
UserID: userID, Kind: claim.Kind, Ordinal: ordinal, Value: claim.Value,
Status: claim.Status, Origin: claim.Origin, Quote: pgOptionalText(claim.Quote),
ExtractionVersion: pgOptionalText(claim.ExtractionVersion), ConfirmedAt: pgOptionalTime(confirmedAt),
}); err != nil {
return mapCandidateProfileError(err)
}
}
return nil
}
func (repository candidateProfileRepository) replaceProfilePeriodConfirmations(
ctx context.Context,
userID pgtype.UUID,
confirmations []domain.ProfileParallelPeriodAcknowledgement,
) error {
if err := repository.queries.DeleteCandidateProfileOverlapConfirmations(ctx, userID); err != nil {
return mapCandidateProfileError(err)
}
for _, confirmation := range confirmations {
if confirmation.FirstIndex >= confirmation.SecondIndex {
return fmt.Errorf("postgres.replaceProfilePeriodConfirmations - pair indices are invalid: %w", domain.ErrInvalidCandidateProfile)
}
firstIndex, err := candidateProfilePeriodIndex(confirmation.FirstIndex)
if err != nil {
return err
}
secondIndex, err := candidateProfilePeriodIndex(confirmation.SecondIndex)
if err != nil {
return err
}
if err := repository.queries.InsertCandidateProfileOverlapConfirmation(ctx, sqlc.InsertCandidateProfileOverlapConfirmationParams{
UserID: userID, FirstIndex: firstIndex, SecondIndex: secondIndex,
FirstStartedOn: confirmation.FirstPeriod.StartedOn, FirstEndedOn: pgOptionalText(confirmation.FirstPeriod.EndedOn),
SecondStartedOn: confirmation.SecondPeriod.StartedOn, SecondEndedOn: pgOptionalText(confirmation.SecondPeriod.EndedOn),
}); err != nil {
return mapCandidateProfileError(err)
}
}
return nil
}
func candidateProfileOrdinal(value int) (int16, error) {
if value < 0 || value > math.MaxInt16 {
return 0, fmt.Errorf("postgres.candidateProfileOrdinal - ordinal is outside the storage range: %w", domain.ErrInvalidCandidateProfile)
}
return int16(value), nil
}
func candidateProfilePeriodIndex(value int) (int16, error) {
if value < 0 || value > 19 || value > math.MaxInt16 {
return 0, fmt.Errorf("postgres.candidateProfilePeriodIndex - index is outside the storage range: %w", domain.ErrInvalidCandidateProfile)
}
return int16(value), nil
}
func candidateProfileSnapshot(profile domain.CandidateProfile, claims []domain.StoredProfileClaim) ([]byte, error) {
encodedClaims := make([]candidateProfileHistoryClaim, 0, len(claims))
for _, claim := range claims {
item := candidateProfileHistoryClaim{
Kind: claim.Kind, Ordinal: claim.Ordinal, Value: json.RawMessage(claim.Value),
Status: claim.Status, Origin: claim.Origin, TrustLevel: claim.TrustLevel,
}
if claim.Quote != "" {
item.Quote = &claim.Quote
}
if claim.ExtractionVersion != "" {
item.ExtractionVersion = &claim.ExtractionVersion
}
if !claim.ConfirmedAt.IsZero() {
confirmedAt := claim.ConfirmedAt
item.ConfirmedAt = &confirmedAt
}
encodedClaims = append(encodedClaims, item)
}
return json.Marshal(candidateProfileHistorySnapshot{
Version: profile.Version() + 1, CreatedAt: profile.CreatedAt().UTC().Truncate(time.Microsecond),
UpdatedAt: profile.UpdatedAt().UTC().Truncate(time.Microsecond),
Claims: encodedClaims, ParallelPeriodAcknowledgements: profile.Content().ParallelPeriodAcknowledgements(),
})
}
func (repository candidateProfileRepository) AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error {
const location = "candidateProfileRepository.AdvanceOnboarding"
if userID == uuid.Nil || at.IsZero() {
return fmt.Errorf("%s - user ID and time must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
if err := repository.queries.AdvanceCandidateOnboardingAfterProfile(ctx, sqlc.AdvanceCandidateOnboardingAfterProfileParams{
UserID: pgUUID(userID), At: pgTime(at),
}); err != nil {
return fmt.Errorf("%s - advance candidate step: %w", location, mapCandidateProfileError(err))
}
return nil
}
func mapCandidateProfileError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
switch {
case pgError.Code == foreignKeyViolationCode && slices.Contains([]string{
"candidate_profiles_user_id_fkey", "candidate_profile_claims_user_id_fkey",
"candidate_profile_overlap_confirmations_profile_fkey", "candidate_profile_history_profile_fkey",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapCandidateProfileError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrUserNotFound)
case pgError.Code == checkViolationCode && pgError.ConstraintName == "candidate_profile_history_snapshot_bounded":
return outbound.ErrCandidateProfileHistoryTooLarge
case pgError.Code == checkViolationCode && slices.Contains([]string{
"candidate_profiles_version_positive", "candidate_profile_claims_kind_ordinal",
"candidate_profile_claims_status_known", "candidate_profile_claims_origin_known",
"candidate_profile_claims_trust_level_zero", "candidate_profile_claims_confirmation",
"candidate_profile_claims_origin_provenance", "candidate_profile_claims_quote_format",
"candidate_profile_claims_extraction_version_format", "candidate_profile_overlap_confirmations_indices",
"candidate_profile_overlap_confirmations_months",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapCandidateProfileError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidCandidateProfile)
default:
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
}
@@ -11,6 +11,31 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const advanceCandidateOnboardingAfterProfile = `-- name: AdvanceCandidateOnboardingAfterProfile :exec
UPDATE users
SET
onboarding_step = 'candidate_questionnaire',
version = users.version + 1,
updated_at = GREATEST(users.updated_at, $1::timestamptz)
WHERE
users.id = $2
AND users.scenario = 'candidate'
AND users.email_verified_at IS NOT NULL
AND users.onboarding_step = 'candidate_profile'
`
type AdvanceCandidateOnboardingAfterProfileParams struct {
At pgtype.Timestamptz
UserID pgtype.UUID
}
// Saving a profile advances onboarding only from that exact step. A retry or
// a save after a later step is already stored never regresses onboarding.
func (q *Queries) AdvanceCandidateOnboardingAfterProfile(ctx context.Context, arg AdvanceCandidateOnboardingAfterProfileParams) error {
_, err := q.db.Exec(ctx, advanceCandidateOnboardingAfterProfile, arg.At, arg.UserID)
return err
}
const advanceCandidateProfileVersion = `-- name: AdvanceCandidateProfileVersion :one
UPDATE candidate_profiles
SET
@@ -47,6 +72,39 @@ func (q *Queries) AdvanceCandidateProfileVersion(ctx context.Context, arg Advanc
return i, err
}
const appendCandidateProfileHistory = `-- name: AppendCandidateProfileHistory :exec
INSERT INTO candidate_profile_history (
user_id,
version,
changed_at,
snapshot
) VALUES (
$1,
$2,
$3,
$4::jsonb
)
`
type AppendCandidateProfileHistoryParams struct {
UserID pgtype.UUID
Version int64
ChangedAt pgtype.Timestamptz
Snapshot []byte
}
// Every changed version appends exactly one private snapshot. The unique
// key prevents a second snapshot for the same profile version.
func (q *Queries) AppendCandidateProfileHistory(ctx context.Context, arg AppendCandidateProfileHistoryParams) error {
_, err := q.db.Exec(ctx, appendCandidateProfileHistory,
arg.UserID,
arg.Version,
arg.ChangedAt,
arg.Snapshot,
)
return err
}
const deleteCandidateProfileClaims = `-- name: DeleteCandidateProfileClaims :exec
DELETE FROM candidate_profile_claims
WHERE user_id = $1
@@ -59,6 +117,18 @@ func (q *Queries) DeleteCandidateProfileClaims(ctx context.Context, userID pgtyp
return err
}
const deleteCandidateProfileOverlapConfirmations = `-- name: DeleteCandidateProfileOverlapConfirmations :exec
DELETE FROM candidate_profile_overlap_confirmations
WHERE user_id = $1
`
// Replaces the current explicit decisions with those in the new profile.
// The versioned profile row is advanced first in this same transaction.
func (q *Queries) DeleteCandidateProfileOverlapConfirmations(ctx context.Context, userID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteCandidateProfileOverlapConfirmations, userID)
return err
}
const insertCandidateProfile = `-- name: InsertCandidateProfile :one
INSERT INTO candidate_profiles (
@@ -157,6 +227,49 @@ func (q *Queries) InsertCandidateProfileClaim(ctx context.Context, arg InsertCan
return err
}
const insertCandidateProfileOverlapConfirmation = `-- name: InsertCandidateProfileOverlapConfirmation :exec
INSERT INTO candidate_profile_overlap_confirmations (
user_id,
first_index,
second_index,
first_started_on,
first_ended_on,
second_started_on,
second_ended_on
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertCandidateProfileOverlapConfirmationParams struct {
UserID pgtype.UUID
FirstIndex int16
SecondIndex int16
FirstStartedOn string
FirstEndedOn pgtype.Text
SecondStartedOn string
SecondEndedOn pgtype.Text
}
func (q *Queries) InsertCandidateProfileOverlapConfirmation(ctx context.Context, arg InsertCandidateProfileOverlapConfirmationParams) error {
_, err := q.db.Exec(ctx, insertCandidateProfileOverlapConfirmation,
arg.UserID,
arg.FirstIndex,
arg.SecondIndex,
arg.FirstStartedOn,
arg.FirstEndedOn,
arg.SecondStartedOn,
arg.SecondEndedOn,
)
return err
}
const readCandidateProfile = `-- name: ReadCandidateProfile :many
SELECT
candidate_profiles.user_id,
@@ -171,7 +284,28 @@ SELECT
candidate_profile_claims.trust_level,
candidate_profile_claims.quote,
candidate_profile_claims.extraction_version,
candidate_profile_claims.confirmed_at
candidate_profile_claims.confirmed_at,
COALESCE(
(
SELECT jsonb_agg(
jsonb_build_object(
'first_index', confirmations.first_index,
'second_index', confirmations.second_index,
'first_period', jsonb_build_object(
'started_on', confirmations.first_started_on,
'ended_on', confirmations.first_ended_on
),
'second_period', jsonb_build_object(
'started_on', confirmations.second_started_on,
'ended_on', confirmations.second_ended_on
)
) ORDER BY confirmations.first_index, confirmations.second_index
)::text
FROM candidate_profile_overlap_confirmations AS confirmations
WHERE confirmations.user_id = candidate_profiles.user_id
),
'[]'::text
)::text AS parallel_period_acknowledgements
FROM candidate_profiles
LEFT JOIN candidate_profile_claims
ON candidate_profile_claims.user_id = candidate_profiles.user_id
@@ -180,19 +314,20 @@ 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
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
ParallelPeriodAcknowledgements string
}
// Reads the profile row of an account together with every claim in one
@@ -225,6 +360,7 @@ func (q *Queries) ReadCandidateProfile(ctx context.Context, userID pgtype.UUID)
&i.Quote,
&i.ExtractionVersion,
&i.ConfirmedAt,
&i.ParallelPeriodAcknowledgements,
); err != nil {
return nil, err
}
@@ -94,6 +94,23 @@ type CandidateProfileClaim struct {
ConfirmedAt pgtype.Timestamptz
}
type CandidateProfileHistory struct {
UserID pgtype.UUID
Version int64
ChangedAt pgtype.Timestamptz
Snapshot []byte
}
type CandidateProfileOverlapConfirmation struct {
UserID pgtype.UUID
FirstIndex int16
SecondIndex int16
FirstStartedOn string
FirstEndedOn pgtype.Text
SecondStartedOn string
SecondEndedOn pgtype.Text
}
type CandidatePublication struct {
UserID pgtype.UUID
State string
@@ -14,6 +14,9 @@ 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)
// Saving a profile advances onboarding only from that exact step. A retry or
// a save after a later step is already stored never regresses onboarding.
AdvanceCandidateOnboardingAfterProfile(ctx context.Context, arg AdvanceCandidateOnboardingAfterProfileParams) 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
@@ -28,6 +31,9 @@ type Querier interface {
// ends every earlier token, and deletes the registration C1 of the earlier
// registrant like UpdateUserRegistration does.
AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error)
// Every changed version appends exactly one private snapshot. The unique
// key prevents a second snapshot for the same profile version.
AppendCandidateProfileHistory(ctx context.Context, arg AppendCandidateProfileHistoryParams) error
// Authorizes one retry of a terminal unknown delivery. The update and append-
// only decision share one statement and lock the current row, so a second or
// concurrent operator decision cannot schedule another send for the same
@@ -118,6 +124,9 @@ type Querier interface {
// 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
// Replaces the current explicit decisions with those in the new profile.
// The versioned profile row is advanced first in this same transaction.
DeleteCandidateProfileOverlapConfirmations(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,
@@ -286,6 +295,7 @@ type Querier interface {
// statement never takes a trust level from the caller, because every claim
// has level 0.
InsertCandidateProfileClaim(ctx context.Context, arg InsertCandidateProfileClaimParams) error
InsertCandidateProfileOverlapConfirmation(ctx context.Context, arg InsertCandidateProfileOverlapConfirmationParams) error
// Stores the first publication at version 1. No row returns when the account
// already has a row, so a first publication that lost a race with another
// one is answered as a version conflict. The foreign key refuses a record
+2
View File
@@ -36,11 +36,13 @@ func newAPIHandler(
problems *problem.Responder,
identityHandler *v1.IdentityHandler,
consentHandler *v1.ConsentHandler,
profileHandler *v1.ProfileHandler,
organizationHandler *v1.OrganizationHandler,
) *v1.Handler {
return v1.NewHandler(health, problems,
v1.WithIdentity(identityHandler),
v1.WithConsent(consentHandler),
v1.WithProfile(profileHandler),
v1.WithOrganization(organizationHandler),
)
}
+27
View File
@@ -0,0 +1,27 @@
package bootstrap
import (
"context"
"log/slog"
"time"
"lincodex/backend/config"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
profileusecase "lincodex/backend/internal/usecase/profile"
)
const profilePoolMaxConns = 8
func newProfileHandler(ctx context.Context, settings config.Config, logger *slog.Logger) (*v1.ProfileHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("candidate profile operations are not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, profilePoolMaxConns)
if err != nil {
return nil, nil, err
}
service := profileusecase.NewService(postgres.NewTransactor(pool), time.Now)
return v1.NewProfileHandler(service), pool.Close, nil
}
+32
View File
@@ -0,0 +1,32 @@
package bootstrap
import (
"log/slog"
"net/http"
"net/netip"
httpadapter "lincodex/backend/internal/adapter/primary/http"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
)
// newRouter installs company authorization even when its database is unavailable.
func newRouter(
health *v1.HealthHandler,
apiHandler apiadapter.Handler,
security apiadapter.SecurityHandler,
problems *problem.Responder,
collector httpmiddleware.RequestMetrics,
logger *slog.Logger,
trustedProxies []netip.Prefix,
organizationHandler *v1.OrganizationHandler,
) (http.Handler, error) {
var authorizer httpadapter.CompanyAuthorizer
if organizationHandler != nil {
authorizer = organizationHandler
}
return httpadapter.NewRouter(health, apiHandler, security, problems,
collector, logger, trustedProxies, httpadapter.NewCompanyContextMiddleware(authorizer))
}
+2 -2
View File
@@ -9,7 +9,6 @@ import (
"github.com/goforj/wire"
"lincodex/backend/config"
httpadapter "lincodex/backend/internal/adapter/primary/http"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
@@ -49,9 +48,10 @@ func initialize(
newIdentityHandler,
newIdentityKeyring,
newConsentHandler,
newProfileHandler,
newOrganizationHandler,
newSessionSecurity,
httpadapter.NewRouter,
newRouter,
newOutboxRelay,
newEventConsumers,
newJobWorker,
+43 -27
View File
@@ -9,7 +9,6 @@ package bootstrap
import (
"context"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/primary/http"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/postgres"
@@ -68,7 +67,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
organizationHandler, cleanup6, err := newOrganizationHandler(ctx, config2, logger, keyring)
profileHandler, cleanup6, err := newProfileHandler(ctx, config2, logger)
if err != nil {
cleanup5()
cleanup4()
@@ -77,30 +76,20 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, organizationHandler)
organizationHandler, cleanup7, err := newOrganizationHandler(ctx, config2, logger, keyring)
if err != nil {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, organizationHandler)
sessionSecurity := newSessionSecurity(identityHandler)
v := newTrustedProxies(config2)
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v)
if err != nil {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
relay, cleanup7, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup8, err := newEventConsumers(ctx, config2, logger, metrics)
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
if err != nil {
cleanup7()
cleanup6()
@@ -111,7 +100,18 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
worker, cleanup9, err := newJobWorker(ctx, config2, logger, metrics)
relay, cleanup8, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup9, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup8()
cleanup7()
@@ -123,7 +123,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup10, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
worker, cleanup10, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup9()
cleanup8()
@@ -136,7 +136,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup11, err := newDeliveryMetrics(ctx, config2, logger, metrics)
mailsenderWorker, cleanup11, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup10()
cleanup9()
@@ -150,8 +150,24 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup12, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
return application, func() {
cleanup12()
cleanup11()
cleanup10()
cleanup9()
+383 -64
View File
@@ -343,6 +343,56 @@ func (ProfileExperience) LogValue() slog.Value {
}
func (ProfileExperience) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
// ProfileExperiencePeriod is the exact month range used to acknowledge
// overlapping work. Its dates are personal data, so formatting redacts them.
type ProfileExperiencePeriod struct {
StartedOn string `json:"started_on"`
EndedOn string `json:"ended_on"`
}
func (ProfileExperiencePeriod) String() string { return redactedProfile }
func (ProfileExperiencePeriod) GoString() string { return redactedProfile }
func (ProfileExperiencePeriod) LogValue() slog.Value {
return slog.StringValue(redactedProfile)
}
func (ProfileExperiencePeriod) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
// ProfileParallelPeriodAcknowledgement records that the candidate reviewed
// the exact dates of two overlapping experience entries at their indices.
// Employer names and summaries are not part of the decision.
type ProfileParallelPeriodAcknowledgement struct {
FirstIndex int `json:"first_index"`
SecondIndex int `json:"second_index"`
FirstPeriod ProfileExperiencePeriod `json:"first_period"`
SecondPeriod ProfileExperiencePeriod `json:"second_period"`
}
func (ProfileParallelPeriodAcknowledgement) String() string { return redactedProfile }
func (ProfileParallelPeriodAcknowledgement) GoString() string { return redactedProfile }
func (ProfileParallelPeriodAcknowledgement) LogValue() slog.Value {
return slog.StringValue(redactedProfile)
}
func (ProfileParallelPeriodAcknowledgement) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedProfile)
}
// ProfileExperienceOverlapStatus reports whether the candidate acknowledged
// an overlapping pair of periods in the current profile version.
type ProfileExperienceOverlapStatus string
const (
ProfileExperienceOverlapNeedsConfirmation ProfileExperienceOverlapStatus = "needs_confirmation"
ProfileExperienceOverlapConfirmed ProfileExperienceOverlapStatus = "confirmed"
)
// ProfileExperienceOverlap identifies two entries whose inclusive month
// ranges overlap. Indices refer to one profile version's experience list.
type ProfileExperienceOverlap struct {
FirstIndex int
SecondIndex int
Status ProfileExperienceOverlapStatus
}
// ProfileTaxBasis is the tax basis of a salary amount.
type ProfileTaxBasis string
@@ -379,17 +429,20 @@ type ProfileClaimInput[V comparable] struct {
// 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]
FullName *ProfileClaimInput[string]
Email *ProfileClaimInput[string]
Phone *ProfileClaimInput[string]
Telegram *ProfileClaimInput[string]
Stack []ProfileClaimInput[string]
Roles []ProfileClaimInput[ProfileRole]
Experience []ProfileClaimInput[ProfileExperience]
// ParallelPeriodAcknowledgements contains explicit acknowledgements for
// the exact periods and indices in Experience.
ParallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
SoftSkills []ProfileClaimInput[string]
Location *ProfileClaimInput[string]
Relocation *ProfileClaimInput[bool]
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
}
// CandidateProfileContent is the validated content of a profile: every claim
@@ -398,17 +451,18 @@ type CandidateProfileInput struct {
// 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]
fullName *ProfileClaim[string]
email *ProfileClaim[string]
phone *ProfileClaim[string]
telegram *ProfileClaim[string]
stack []ProfileClaim[string]
roles []ProfileClaim[ProfileRole]
experience []ProfileClaim[ProfileExperience]
parallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
softSkills []ProfileClaim[string]
location *ProfileClaim[string]
relocation *ProfileClaim[bool]
salaryMinimum *ProfileClaim[ProfileSalaryMinimum]
}
func optionalClaim[V comparable](claim *ProfileClaim[V]) (ProfileClaim[V], bool) {
@@ -469,6 +523,35 @@ func (content CandidateProfileContent) Experience() []ProfileClaim[ProfileExperi
return slices.Clone(content.experience)
}
// ParallelPeriodAcknowledgements returns a copy of the stored date-pair
// decisions for this profile version.
func (content CandidateProfileContent) ParallelPeriodAcknowledgements() []ProfileParallelPeriodAcknowledgement {
return slices.Clone(content.parallelPeriodAcknowledgements)
}
// ExperienceOverlaps returns every overlapping pair in index order. A pair's
// status is derived from an acknowledgement that still matches both periods.
func (content CandidateProfileContent) ExperienceOverlaps() []ProfileExperienceOverlap {
var overlaps []ProfileExperienceOverlap
acknowledged := make(map[experiencePair]struct{}, len(content.parallelPeriodAcknowledgements))
for _, acknowledgement := range content.parallelPeriodAcknowledgements {
acknowledged[experiencePair{first: acknowledgement.FirstIndex, second: acknowledgement.SecondIndex}] = struct{}{}
}
for first := range content.experience {
for second := first + 1; second < len(content.experience); second++ {
if !experiencePeriodsOverlap(content.experience[first].value, content.experience[second].value) {
continue
}
status := ProfileExperienceOverlapNeedsConfirmation
if _, ok := acknowledged[experiencePair{first: first, second: second}]; ok {
status = ProfileExperienceOverlapConfirmed
}
overlaps = append(overlaps, ProfileExperienceOverlap{FirstIndex: first, SecondIndex: second, Status: status})
}
}
return overlaps
}
// SoftSkills returns a copy of the soft skills in the order the candidate
// gave them.
func (content CandidateProfileContent) SoftSkills() []ProfileClaim[string] {
@@ -488,6 +571,7 @@ func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool
slices.EqualFunc(content.stack, other.stack, claimsEqual) &&
slices.EqualFunc(content.roles, other.roles, claimsEqual) &&
slices.EqualFunc(content.experience, other.experience, claimsEqual) &&
slices.Equal(content.parallelPeriodAcknowledgements, other.parallelPeriodAcknowledgements) &&
slices.EqualFunc(content.softSkills, other.softSkills, claimsEqual)
}
@@ -730,6 +814,166 @@ func newProfileRules(now time.Time) profileRules {
}
}
type experiencePair struct {
first int
second int
}
func experiencePeriod(value ProfileExperience) ProfileExperiencePeriod {
return ProfileExperiencePeriod{StartedOn: value.StartedOn, EndedOn: value.EndedOn}
}
func experiencePeriodsOverlap(first, second ProfileExperience) bool {
return (first.EndedOn == "" || second.StartedOn <= first.EndedOn) &&
(second.EndedOn == "" || first.StartedOn <= second.EndedOn)
}
func invalidParallelPeriodField(location string, index int, pointer, reason string) error {
return invalidProfileField(location, fmt.Sprintf("/confirmed_parallel_periods/%d/%s", index, pointer), reason)
}
func resolveParallelPeriodAcknowledgements(
stored CandidateProfileContent,
experiences []ProfileClaim[ProfileExperience],
requested []ProfileParallelPeriodAcknowledgement,
location string,
) ([]ProfileParallelPeriodAcknowledgement, error) {
const maxPairs = maxProfileExperienceItems * (maxProfileExperienceItems - 1) / 2
if len(requested) > maxPairs {
return nil, invalidProfileField(location, "/confirmed_parallel_periods", "must not contain more pairs than the experience list allows")
}
acknowledgements := make(map[experiencePair]ProfileParallelPeriodAcknowledgement, len(requested)+len(stored.parallelPeriodAcknowledgements))
requestedPairs := make(map[experiencePair]struct{}, len(requested))
for index, acknowledgement := range requested {
if err := addRequestedParallelPeriodAcknowledgement(
acknowledgement, experiences, index, location, requestedPairs, acknowledgements,
); err != nil {
return nil, err
}
}
previousOverlaps := overlappingExperiencePairs(stored.experience)
carryMatchingParallelPeriodAcknowledgements(stored.parallelPeriodAcknowledgements, experiences, acknowledgements)
return resolveCurrentExperienceOverlaps(experiences, previousOverlaps, acknowledgements, location)
}
func addRequestedParallelPeriodAcknowledgement(
acknowledgement ProfileParallelPeriodAcknowledgement,
experiences []ProfileClaim[ProfileExperience],
index int,
location string,
requestedPairs map[experiencePair]struct{},
acknowledgements map[experiencePair]ProfileParallelPeriodAcknowledgement,
) error {
pair := experiencePair{first: acknowledgement.FirstIndex, second: acknowledgement.SecondIndex}
if pair.first < 0 || pair.first >= len(experiences) {
return invalidParallelPeriodField(location, index, "first_index", "must refer to an experience entry")
}
if pair.second <= pair.first || pair.second >= len(experiences) {
return invalidParallelPeriodField(location, index, "second_index", "must refer to a later experience entry")
}
if _, duplicate := requestedPairs[pair]; duplicate {
return invalidParallelPeriodField(location, index, "second_index", "must not repeat a pair")
}
requestedPairs[pair] = struct{}{}
first := experiences[pair.first].value
second := experiences[pair.second].value
firstPeriod := experiencePeriod(first)
secondPeriod := experiencePeriod(second)
if acknowledgement.FirstPeriod.StartedOn != firstPeriod.StartedOn {
return invalidParallelPeriodField(location, index, "first_period/started_on", "must match the indexed experience period")
}
if acknowledgement.FirstPeriod.EndedOn != firstPeriod.EndedOn {
return invalidParallelPeriodField(location, index, "first_period/ended_on", "must match the indexed experience period")
}
if acknowledgement.SecondPeriod.StartedOn != secondPeriod.StartedOn {
return invalidParallelPeriodField(location, index, "second_period/started_on", "must match the indexed experience period")
}
if acknowledgement.SecondPeriod.EndedOn != secondPeriod.EndedOn {
return invalidParallelPeriodField(location, index, "second_period/ended_on", "must match the indexed experience period")
}
if !experiencePeriodsOverlap(first, second) {
return invalidParallelPeriodField(location, index, "second_index", "must identify an overlapping period")
}
acknowledgements[pair] = ProfileParallelPeriodAcknowledgement{
FirstIndex: pair.first, SecondIndex: pair.second, FirstPeriod: firstPeriod, SecondPeriod: secondPeriod,
}
return nil
}
func overlappingExperiencePairs(experiences []ProfileClaim[ProfileExperience]) map[experiencePair]ProfileParallelPeriodAcknowledgement {
previous := make(map[experiencePair]ProfileParallelPeriodAcknowledgement)
for first := range experiences {
for second := first + 1; second < len(experiences); second++ {
firstValue := experiences[first].value
secondValue := experiences[second].value
if !experiencePeriodsOverlap(firstValue, secondValue) {
continue
}
previous[experiencePair{first: first, second: second}] = ProfileParallelPeriodAcknowledgement{
FirstIndex: first, SecondIndex: second,
FirstPeriod: experiencePeriod(firstValue), SecondPeriod: experiencePeriod(secondValue),
}
}
}
return previous
}
func carryMatchingParallelPeriodAcknowledgements(
stored []ProfileParallelPeriodAcknowledgement,
experiences []ProfileClaim[ProfileExperience],
acknowledgements map[experiencePair]ProfileParallelPeriodAcknowledgement,
) {
for _, previous := range stored {
pair := experiencePair{first: previous.FirstIndex, second: previous.SecondIndex}
if pair.first < 0 || pair.second < 0 || pair.first >= len(experiences) || pair.second >= len(experiences) {
continue
}
first := experiences[pair.first].value
second := experiences[pair.second].value
if experiencePeriod(first) != previous.FirstPeriod || experiencePeriod(second) != previous.SecondPeriod ||
!experiencePeriodsOverlap(first, second) {
continue
}
if _, explicitlyAcknowledged := acknowledgements[pair]; !explicitlyAcknowledged {
acknowledgements[pair] = previous
}
}
}
func resolveCurrentExperienceOverlaps(
experiences []ProfileClaim[ProfileExperience],
previousOverlaps map[experiencePair]ProfileParallelPeriodAcknowledgement,
acknowledgements map[experiencePair]ProfileParallelPeriodAcknowledgement,
location string,
) ([]ProfileParallelPeriodAcknowledgement, error) {
resolved := make([]ProfileParallelPeriodAcknowledgement, 0, len(acknowledgements))
for first := range experiences {
for second := first + 1; second < len(experiences); second++ {
firstValue := experiences[first].value
secondValue := experiences[second].value
if !experiencePeriodsOverlap(firstValue, secondValue) {
continue
}
pair := experiencePair{first: first, second: second}
if acknowledgement, ok := acknowledgements[pair]; ok {
resolved = append(resolved, acknowledgement)
continue
}
previous, existed := previousOverlaps[pair]
if existed && previous.FirstPeriod == experiencePeriod(firstValue) && previous.SecondPeriod == experiencePeriod(secondValue) {
continue
}
return nil, invalidStateDependentProfileField(location,
fmt.Sprintf("/experience/%d/started_on", second),
"overlaps another period and needs an explicit confirmation",
)
}
}
return resolved, nil
}
// 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
@@ -798,6 +1042,12 @@ func ResolveCandidateProfileContent(stored CandidateProfileContent, input Candid
return CandidateProfileContent{}, err
}
}
content.parallelPeriodAcknowledgements, err = resolveParallelPeriodAcknowledgements(
stored, content.experience, input.ParallelPeriodAcknowledgements, location,
)
if err != nil {
return CandidateProfileContent{}, fmt.Errorf("%s - resolve parallel period acknowledgements: %w", location, err)
}
return content, nil
}
@@ -873,6 +1123,12 @@ func (profile CandidateProfile) Replace(input CandidateProfileInput, expectedVer
if content.Equal(profile.content) {
return profile, false, nil
}
if err := requireConfirmedExperienceOverlaps(content, location); err != nil {
if expectedVersion != profile.version {
return CandidateProfile{}, false, conflict
}
return CandidateProfile{}, false, err
}
if expectedVersion != profile.version {
return CandidateProfile{}, false, conflict
}
@@ -888,6 +1144,18 @@ func (profile CandidateProfile) Replace(input CandidateProfileInput, expectedVer
return updated, true, nil
}
func requireConfirmedExperienceOverlaps(content CandidateProfileContent, location string) error {
for _, overlap := range content.ExperienceOverlaps() {
if overlap.Status == ProfileExperienceOverlapNeedsConfirmation {
return invalidStateDependentProfileField(location,
fmt.Sprintf("/experience/%d/started_on", overlap.SecondIndex),
"overlaps another period and needs an explicit confirmation",
)
}
}
return nil
}
func (CandidateProfile) String() string { return redactedProfile }
func (CandidateProfile) GoString() string { return redactedProfile }
func (CandidateProfile) Format(state fmt.State, _ rune) {
@@ -924,15 +1192,15 @@ const (
// 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
Kind string `json:"kind"`
Ordinal int `json:"ordinal"`
Value []byte `json:"value"`
Status string `json:"status"`
Origin string `json:"origin"`
TrustLevel int `json:"trust_level"`
Quote string `json:"quote"`
ExtractionVersion string `json:"extraction_version"`
ConfirmedAt time.Time `json:"confirmed_at"`
}
// The JSON shapes of structured values. Their keys are the ones that the
@@ -1053,6 +1321,16 @@ func (content CandidateProfileContent) StoredClaims() ([]StoredProfileClaim, err
// 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) {
return RestoreCandidateProfileContentWithParallelPeriods(rows, nil)
}
// RestoreCandidateProfileContentWithParallelPeriods also restores the
// explicit date-pair decisions stored for this profile. Existing profiles may
// contain unresolved overlaps, which are returned for the owner to resolve.
func RestoreCandidateProfileContentWithParallelPeriods(
rows []StoredProfileClaim,
acknowledgements []ProfileParallelPeriodAcknowledgement,
) (CandidateProfileContent, error) {
const location = "domain.RestoreCandidateProfileContent"
rules := newProfileRules(time.Time{})
fail := func(row StoredProfileClaim, reason string) error {
@@ -1070,39 +1348,78 @@ func RestoreCandidateProfileContent(rows []StoredProfileClaim) (CandidateProfile
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")
}
err = restoreCandidateProfileClaim(&content, rules, row, status, source)
if err != nil {
return CandidateProfileContent{}, fail(row, err.Error())
}
}
content.parallelPeriodAcknowledgements = slices.Clone(acknowledgements)
if err := validateStoredParallelPeriodAcknowledgements(content.experience, content.parallelPeriodAcknowledgements); err != nil {
return CandidateProfileContent{}, fmt.Errorf("%s - validate parallel period acknowledgements: %w", location, err)
}
return content, nil
}
func restoreCandidateProfileClaim(
content *CandidateProfileContent,
rules profileRules,
row StoredProfileClaim,
status ProfileClaimStatus,
source ProfileClaimSource,
) error {
switch row.Kind {
case profileKindFullName:
return restoreSingle(&content.fullName, rules.fullName, row, status, source)
case profileKindEmail:
return restoreSingle(&content.email, rules.email, row, status, source)
case profileKindPhone:
return restoreSingle(&content.phone, rules.phone, row, status, source)
case profileKindTelegram:
return restoreSingle(&content.telegram, rules.telegram, row, status, source)
case profileKindLocation:
return restoreSingle(&content.location, rules.location, row, status, source)
case profileKindRelocation:
return restoreSingle(&content.relocation, rules.relocation, row, status, source)
case profileKindSalaryMinimum:
return restoreSingle(&content.salaryMinimum, rules.salaryMinimum, row, status, source)
case profileKindStack:
return restoreItem(&content.stack, rules.stack, row, status, source)
case profileKindSoftSkill:
return restoreItem(&content.softSkills, rules.softSkills, row, status, source)
case profileKindRole:
return restoreItem(&content.roles, rules.roles, row, status, source)
case profileKindExperience:
return restoreItem(&content.experience, rules.experience, row, status, source)
default:
return errors.New("kind is unknown")
}
}
func validateStoredParallelPeriodAcknowledgements(
experiences []ProfileClaim[ProfileExperience],
acknowledgements []ProfileParallelPeriodAcknowledgement,
) error {
const location = "domain.validateStoredParallelPeriodAcknowledgements"
seen := make(map[experiencePair]struct{}, len(acknowledgements))
for _, acknowledgement := range acknowledgements {
pair := experiencePair{first: acknowledgement.FirstIndex, second: acknowledgement.SecondIndex}
if pair.first < 0 || pair.second <= pair.first || pair.second >= len(experiences) {
return fmt.Errorf("%s - pair indices are invalid: %w", location, ErrInvalidCandidateProfile)
}
if _, duplicate := seen[pair]; duplicate {
return fmt.Errorf("%s - pair is duplicated: %w", location, ErrInvalidCandidateProfile)
}
seen[pair] = struct{}{}
first := experiences[pair.first].value
second := experiences[pair.second].value
if experiencePeriod(first) != acknowledgement.FirstPeriod ||
experiencePeriod(second) != acknowledgement.SecondPeriod || !experiencePeriodsOverlap(first, second) {
return fmt.Errorf("%s - pair does not match the stored experience periods: %w", location, ErrInvalidCandidateProfile)
}
}
return nil
}
// decodeStoredValue decodes the canonical JSON of a stored value into V.
func decodeStoredValue[V comparable](row StoredProfileClaim) (V, error) {
var value V
@@ -1202,13 +1519,15 @@ func restoreItem[V comparable](
return nil
}
// StoredCandidateProfile carries the profile row and its claims.
// StoredCandidateProfile carries the profile row, claims, and acknowledged
// overlapping date pairs.
type StoredCandidateProfile struct {
UserID uuid.UUID
Version int64
CreatedAt time.Time
UpdatedAt time.Time
Claims []StoredProfileClaim
UserID uuid.UUID
Version int64
CreatedAt time.Time
UpdatedAt time.Time
Claims []StoredProfileClaim
ParallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
}
// RestoreCandidateProfile validates a stored profile with the rules of the
@@ -1224,7 +1543,7 @@ func RestoreCandidateProfile(stored StoredCandidateProfile) (CandidateProfile, e
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)
content, err := RestoreCandidateProfileContentWithParallelPeriods(stored.Claims, stored.ParallelPeriodAcknowledgements)
if err != nil {
return CandidateProfile{}, fmt.Errorf("%s - restore content: %w", location, err)
}
+195
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"log/slog"
"reflect"
"slices"
"strings"
"testing"
"time"
@@ -283,6 +284,200 @@ func TestResolveCandidateProfileContentNormalizesValues(t *testing.T) {
}
}
func TestResolveCandidateProfileContentRequiresExplicitParallelPeriodAcknowledgements(t *testing.T) {
input := CandidateProfileInput{Experience: confirmedItems(
ProfileExperience{EmployerName: "First employer", Specialization: SpecializationBackend, StartedOn: "2020-01", EndedOn: "2021-06"},
ProfileExperience{EmployerName: "Second employer", Specialization: SpecializationQA, StartedOn: "2021-06", EndedOn: "2022-01"},
)}
assertProfileFieldError(t, resolveErr(CandidateProfileContent{}, input, candidateTestTime), "/experience/1/started_on")
input.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{{
FirstIndex: 0, SecondIndex: 1,
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2020-01", EndedOn: "2021-06"},
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2021-06", EndedOn: "2022-01"},
}}
content := mustCandidateContent(t, CandidateProfileContent{}, input, candidateTestTime)
overlaps := content.ExperienceOverlaps()
if len(overlaps) != 1 || overlaps[0].FirstIndex != 0 || overlaps[0].SecondIndex != 1 || overlaps[0].Status != ProfileExperienceOverlapConfirmed {
t.Fatalf("overlaps = %+v, want the acknowledged pair at indices 0 and 1", overlaps)
}
}
func TestResolveCandidateProfileContentRejectsInvalidParallelPeriodAcknowledgements(t *testing.T) {
base := CandidateProfileInput{Experience: confirmedItems(
ProfileExperience{EmployerName: "First employer", Specialization: SpecializationBackend, StartedOn: "2020-01", EndedOn: "2020-05"},
ProfileExperience{EmployerName: "Second employer", Specialization: SpecializationQA, StartedOn: "2020-06", EndedOn: "2021-01"},
)}
period := func(startedOn, endedOn string) ProfileExperiencePeriod {
return ProfileExperiencePeriod{StartedOn: startedOn, EndedOn: endedOn}
}
tests := []struct {
name string
confirm ProfileParallelPeriodAcknowledgement
pointer string
}{
{
name: "first period does not match the submitted entry",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 1, FirstPeriod: period("2020-02", "2020-05"), SecondPeriod: period("2020-06", "2021-01"),
},
pointer: "/confirmed_parallel_periods/0/first_period/started_on",
},
{
name: "second period does not match the submitted entry",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 1, FirstPeriod: period("2020-01", "2020-05"), SecondPeriod: period("2020-05", "2021-01"),
},
pointer: "/confirmed_parallel_periods/0/second_period/started_on",
},
{
name: "self pair",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 0, FirstPeriod: period("2020-01", "2020-05"), SecondPeriod: period("2020-01", "2020-05"),
},
pointer: "/confirmed_parallel_periods/0/second_index",
},
{
name: "reversed indices",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 1, SecondIndex: 0, FirstPeriod: period("2020-06", "2021-01"), SecondPeriod: period("2020-01", "2020-05"),
},
pointer: "/confirmed_parallel_periods/0/second_index",
},
{
name: "out-of-range index",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 2, FirstPeriod: period("2020-01", "2020-05"), SecondPeriod: period("2020-06", "2021-01"),
},
pointer: "/confirmed_parallel_periods/0/second_index",
},
{
name: "periods do not overlap",
confirm: ProfileParallelPeriodAcknowledgement{
FirstIndex: 0, SecondIndex: 1, FirstPeriod: period("2020-01", "2020-05"), SecondPeriod: period("2020-06", "2021-01"),
},
pointer: "/confirmed_parallel_periods/0/second_index",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := base
input.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{test.confirm}
assertProfileFieldError(t, resolveErr(CandidateProfileContent{}, input, candidateTestTime), test.pointer)
})
}
}
func TestCandidateProfileReplaceCarriesParallelPeriodAcknowledgementsOnlyForTheSameIndexedDates(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
profile, err := EmptyCandidateProfile(userID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
input := CandidateProfileInput{Experience: confirmedItems(
ProfileExperience{EmployerName: "First employer", Specialization: SpecializationBackend, StartedOn: "2020-01", EndedOn: "2021-06", Summary: "First"},
ProfileExperience{EmployerName: "Second employer", Specialization: SpecializationQA, StartedOn: "2021-06", EndedOn: "2022-01", Summary: "Second"},
)}
input.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{{
FirstIndex: 0, SecondIndex: 1,
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2020-01", EndedOn: "2021-06"},
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2021-06", EndedOn: "2022-01"},
}}
profile, changed, err := profile.Replace(input, 0, candidateTestTime)
if err != nil || !changed {
t.Fatalf("Replace(first save) = changed %v, %v, want a confirmed change", changed, err)
}
t.Run("unrelated experience fields preserve acknowledgement", func(t *testing.T) {
edited := input
edited.ParallelPeriodAcknowledgements = nil
edited.Experience = slices.Clone(input.Experience)
edited.Experience[0].Value.Summary = "Updated work"
updated, changed, err := profile.Replace(edited, 0, candidateTestTime.Add(time.Hour))
if err != nil || !changed || updated.Content().ExperienceOverlaps()[0].Status != ProfileExperienceOverlapConfirmed {
t.Fatalf("Replace(summary edit) = changed %v, overlaps %+v, error %v", changed, updated.Content().ExperienceOverlaps(), err)
}
})
t.Run("changed period requires a fresh acknowledgement", func(t *testing.T) {
edited := input
edited.ParallelPeriodAcknowledgements = nil
edited.Experience = slices.Clone(input.Experience)
edited.Experience[0].Value.EndedOn = "2021-07"
assertProfileFieldError(t, errOnly(profile.Replace(edited, 0, candidateTestTime.Add(time.Hour))), "/experience/1/started_on")
})
t.Run("reordered periods require a fresh acknowledgement", func(t *testing.T) {
edited := input
edited.ParallelPeriodAcknowledgements = nil
edited.Experience = []ProfileClaimInput[ProfileExperience]{input.Experience[1], input.Experience[0]}
assertProfileFieldError(t, errOnly(profile.Replace(edited, 0, candidateTestTime.Add(time.Hour))), "/experience/1/started_on")
})
t.Run("changed period can be explicitly acknowledged", func(t *testing.T) {
edited := input
edited.Experience = slices.Clone(input.Experience)
edited.Experience[0].Value.EndedOn = "2021-07"
edited.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{{
FirstIndex: 0, SecondIndex: 1,
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2020-01", EndedOn: "2021-07"},
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2021-06", EndedOn: "2022-01"},
}}
updated, changed, err := profile.Replace(edited, 0, candidateTestTime.Add(time.Hour))
if err != nil || !changed || updated.Content().ExperienceOverlaps()[0].Status != ProfileExperienceOverlapConfirmed {
t.Fatalf("Replace(confirmed period edit) = changed %v, overlaps %+v, error %v", changed, updated.Content().ExperienceOverlaps(), err)
}
})
}
func TestCandidateProfileWithStoredUnconfirmedOverlapOnlyAllowsNoOpOrExplicitConfirmation(t *testing.T) {
profile, err := RestoreCandidateProfile(StoredCandidateProfile{
UserID: uuid.Must(uuid.NewV7()), Version: 1,
CreatedAt: candidateTestTime, UpdatedAt: candidateTestTime,
Claims: []StoredProfileClaim{
{
Kind: profileKindExperience, Ordinal: 0,
Value: []byte(`{"employer_name":"First","specialization":"backend","started_on":"2020-01","ended_on":"2021-06","summary":null}`),
Status: string(ProfileClaimConfirmed), Origin: string(ProfileOriginManual), TrustLevel: 0, ConfirmedAt: candidateTestTime,
},
{
Kind: profileKindExperience, Ordinal: 1,
Value: []byte(`{"employer_name":"Second","specialization":"qa","started_on":"2021-06","ended_on":"2022-01","summary":null}`),
Status: string(ProfileClaimConfirmed), Origin: string(ProfileOriginManual), TrustLevel: 0, ConfirmedAt: candidateTestTime,
},
},
})
if err != nil {
t.Fatalf("RestoreCandidateProfile() error = %v", err)
}
input := CandidateProfileInput{Experience: confirmedItems(
ProfileExperience{EmployerName: "First", Specialization: SpecializationBackend, StartedOn: "2020-01", EndedOn: "2021-06"},
ProfileExperience{EmployerName: "Second", Specialization: SpecializationQA, StartedOn: "2021-06", EndedOn: "2022-01"},
)}
if unchanged, changed, err := profile.Replace(input, 0, candidateTestTime.Add(time.Hour)); err != nil || changed || unchanged.Version() != profile.Version() {
t.Fatalf("Replace(no-op retry) = version %d, changed %v, error %v", unchanged.Version(), changed, err)
}
changedName := input
changedName.FullName = confirmed("Anna Sokolova")
assertProfileFieldError(t, errOnly(profile.Replace(changedName, 1, candidateTestTime.Add(time.Hour))), "/experience/1/started_on")
if _, _, err := profile.Replace(changedName, 0, candidateTestTime.Add(time.Hour)); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("Replace(stale changed profile) error = %v, want version conflict", err)
}
input.ParallelPeriodAcknowledgements = []ProfileParallelPeriodAcknowledgement{{
FirstIndex: 0, SecondIndex: 1,
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2020-01", EndedOn: "2021-06"},
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2021-06", EndedOn: "2022-01"},
}}
confirmedProfile, changed, err := profile.Replace(input, 1, candidateTestTime.Add(time.Hour))
if err != nil || !changed || confirmedProfile.Content().ExperienceOverlaps()[0].Status != ProfileExperienceOverlapConfirmed {
t.Fatalf("Replace(explicit confirmation) = changed %v, error %v", changed, err)
}
}
func TestCandidateProfileReplaceTellsAChangeFromANoOp(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
empty, err := EmptyCandidateProfile(userID)
@@ -0,0 +1,42 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrCandidateProfileVersionConflict reports a stale expected version.
ErrCandidateProfileVersionConflict = errors.New("candidate profile changed concurrently")
// ErrCandidateProfileHistoryTooLarge reports a snapshot that exceeds the
// private history table's fixed storage bound.
ErrCandidateProfileHistoryTooLarge = errors.New("candidate profile history snapshot exceeds its bound")
)
// CandidateProfileRepositories exposes the candidate profile repository.
// UnitOfWork binds it to the transaction that also records profile history
// and advances onboarding.
type CandidateProfileRepositories interface {
CandidateProfiles() CandidateProfileRepository
}
// CandidateProfileRepository reads and replaces only the profile identified
// by userID. A missing profile row is the version-0 empty profile.
type CandidateProfileRepository interface {
Get(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error)
// Save writes a changed profile only when its stored version equals
// expectedVersion. It replaces claims and period acknowledgements and
// appends the bounded immutable snapshot in the same transaction.
Save(ctx context.Context, expectedVersion int64, profile domain.CandidateProfile) (domain.CandidateProfile, error)
// AdvanceOnboarding advances a verified candidate only from
// candidate_profile to candidate_questionnaire. A later step is left alone.
AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error
}
@@ -50,6 +50,7 @@ type Transactor interface {
type UnitOfWork interface {
IdentityRepositories
ConsentRepositories
CandidateProfileRepositories
AccountDeletionRequests() AccountDeletionRequests
ConsentRevocationEffects() ConsentRevocationEffects
OrganizationRepositories
@@ -0,0 +1,44 @@
package organization
import (
"context"
"github.com/google/uuid"
)
// CompanyAccess is a request-scoped capability issued after the current
// account has been checked as an active owner. Business operations still
// repeat authorization inside their transaction before reading or writing.
type CompanyAccess struct {
actorID uuid.UUID
organizationID uuid.UUID
membershipID uuid.UUID
}
// Matches reports whether this capability was issued for actorID and
// organizationID.
func (access CompanyAccess) Matches(actorID, organizationID uuid.UUID) bool {
return access.actorID != uuid.Nil && access.organizationID != uuid.Nil && access.membershipID != uuid.Nil &&
access.actorID == actorID && access.organizationID == organizationID
}
type companyAccessContextKey struct{}
// WithCompanyAccess attaches a validated company capability to a request
// context. An empty capability is ignored.
func WithCompanyAccess(ctx context.Context, access CompanyAccess) context.Context {
if !access.Matches(access.actorID, access.organizationID) {
return ctx
}
return context.WithValue(ctx, companyAccessContextKey{}, access)
}
// CompanyAccessFromContext returns the capability attached by the HTTP
// boundary, if one is present and valid.
func CompanyAccessFromContext(ctx context.Context) (CompanyAccess, bool) {
access, ok := ctx.Value(companyAccessContextKey{}).(CompanyAccess)
if !ok || !access.Matches(access.actorID, access.organizationID) {
return CompanyAccess{}, false
}
return access, true
}
@@ -252,6 +252,9 @@ func (service *Service) Update(ctx context.Context, command UpdateCommand) (doma
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
if err := matchCompanyContext(ctx, command.ActorID, command.OrganizationID, location); err != nil {
return domain.Organization{}, err
}
if command.ExpectedVersion < 1 {
return domain.Organization{}, fmt.Errorf("%s - expected version must be positive: %w", location, domain.ErrInvalidOrganization)
}
@@ -299,13 +302,16 @@ func (service *Service) Update(ctx context.Context, command UpdateCommand) (doma
return result, nil
}
// Get reads an organization only for an active member of the employer
// account. The membership is checked in the same transaction as the account.
// Get reads an organization only for its active owner. The membership is
// checked in the same transaction as the account.
func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error) {
const location = "organization.Service.Get"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
if err := matchCompanyContext(ctx, actorID, organizationID, location); err != nil {
return domain.Organization{}, err
}
var result domain.Organization
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
@@ -318,6 +324,9 @@ func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UU
if !membership.GrantsAccess() {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
if membership.Role() != domain.OrganizationRoleOwner {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
result = organization
return nil
})
@@ -327,6 +336,82 @@ func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UU
return result, nil
}
// AuthorizeCompany verifies the current verified employer account, active
// membership, and owner role before issuing a request-scoped capability.
func (service *Service) AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (CompanyAccess, error) {
const location = "organization.Service.AuthorizeCompany"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return CompanyAccess{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
var access CompanyAccess
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
return fmt.Errorf("%s - authorize company actor: %w", location, err)
}
_, membership, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
if err != nil {
return fmt.Errorf("%s - read active company membership: %w", location, err)
}
if !membership.GrantsAccess() {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
if membership.Role() != domain.OrganizationRoleOwner {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
access = CompanyAccess{actorID: actorID, organizationID: organizationID, membershipID: membership.ID()}
return nil
})
if err != nil {
return CompanyAccess{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return access, nil
}
// ListMyOrganizations returns active organization memberships for one
// verified employer. The actor always comes from the authenticated session.
func (service *Service) ListMyOrganizations(ctx context.Context, command OrganizationListCommand) (outbound.OrganizationPage, error) {
const location = "organization.Service.ListMyOrganizations"
if command.ActorID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden)
}
if command.Limit < 1 || command.Limit > outbound.MaxOrganizationPageSize {
return outbound.OrganizationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxOrganizationPageSize, domain.ErrInvalidMembership)
}
var result outbound.OrganizationPage
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, command.ActorID, location); err != nil {
return fmt.Errorf("%s - authorize list actor: %w", location, err)
}
page, err := unit.Organizations().ListForUser(ctx, outbound.OrganizationListQuery{
UserID: command.ActorID, After: command.After, Limit: command.Limit,
})
if err != nil {
return fmt.Errorf("%s - list active memberships: %w", location, err)
}
result = page
return nil
})
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// OrganizationListCommand selects a page of the actor's own memberships.
type OrganizationListCommand struct {
ActorID uuid.UUID
After *outbound.OrganizationListPosition
Limit int32
}
func matchCompanyContext(ctx context.Context, actorID, organizationID uuid.UUID, location string) error {
access, ok := CompanyAccessFromContext(ctx)
if ok && !access.Matches(actorID, organizationID) {
return fmt.Errorf("%s - company context does not match the operation: %w", location, ErrForbidden)
}
return nil
}
func applyPatch(current domain.OrganizationProfile, patch ProfilePatch) (domain.OrganizationProfile, error) {
contacts := current.Contacts()
input := domain.OrganizationProfileInput{
@@ -22,6 +22,7 @@ type organizationTestState struct {
memberships map[organizationTestMembershipKey]domain.Membership
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
results map[[outbound.IdempotencyDigestSize]byte]outbound.OrganizationCreationResult
lastListQuery *outbound.OrganizationListQuery
}
type organizationTestMembershipKey struct {
@@ -56,6 +57,14 @@ func (state organizationTestState) clone() organizationTestState {
for scope, result := range state.results {
cloned.results[scope] = result
}
if state.lastListQuery != nil {
query := *state.lastListQuery
if query.After != nil {
position := *query.After
query.After = &position
}
cloned.lastListQuery = &query
}
return cloned
}
@@ -227,9 +236,10 @@ func (repository organizationTestOrganizations) GetForMember(
}
func (repository organizationTestOrganizations) ListForUser(
context.Context,
outbound.OrganizationListQuery,
_ context.Context,
query outbound.OrganizationListQuery,
) (outbound.OrganizationPage, error) {
repository.state.lastListQuery = &query
return outbound.OrganizationPage{}, nil
}
@@ -550,6 +560,93 @@ func TestUpdateRequiresOwnerAndPreservesVerification(t *testing.T) {
}
}
func TestAuthorizeCompanyIssuesContextCapabilityOnlyToActiveOwner(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
tx := newOrganizationTestTransactor()
ownerID, recruiterID, candidateID, unverifiedID, foreignID := uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New()
tx.state.users[ownerID] = verifiedEmployer(ownerID, now)
tx.state.users[recruiterID] = verifiedEmployer(recruiterID, now)
tx.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
tx.state.users[unverifiedID] = domain.User{ID: unverifiedID, Scenario: domain.ScenarioEmployer}
tx.state.users[foreignID] = verifiedEmployer(foreignID, now)
service := newOrganizationTestService(t, tx, func() time.Time { return now })
profile := organizationProfile("ООО Пример", "Данные")
created, err := service.Create(ctx, CreateCommand{
ActorID: ownerID, IdempotencyKey: "company-access-01", CanonicalBody: canonicalBodyForTest(t, profile), Profile: profile,
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
organizationID := created.Organization.ID()
for _, input := range []domain.MembershipInput{
{OrganizationID: organizationID, UserID: recruiterID, Role: domain.OrganizationRoleRecruiter, At: now.Add(time.Second)},
{OrganizationID: organizationID, UserID: candidateID, Role: domain.OrganizationRoleOwner, At: now.Add(time.Second)},
{OrganizationID: organizationID, UserID: unverifiedID, Role: domain.OrganizationRoleOwner, At: now.Add(time.Second)},
} {
membership, err := domain.NewMembership(input)
if err != nil {
t.Fatalf("NewMembership() error = %v", err)
}
tx.state.memberships[organizationTestMembershipKey{organizationID, input.UserID}] = membership
}
access, err := service.AuthorizeCompany(ctx, ownerID, organizationID)
if err != nil || !access.Matches(ownerID, organizationID) {
t.Fatalf("AuthorizeCompany(owner) = %+v, %v; want matching capability", access, err)
}
if access.Matches(foreignID, organizationID) || access.Matches(ownerID, uuid.New()) {
t.Fatal("CompanyAccess matched a different actor or organization")
}
for _, test := range []struct {
name string
user uuid.UUID
want error
}{
{name: "recruiter role", user: recruiterID, want: outbound.ErrOrganizationManagerRequired},
{name: "candidate even with owner membership", user: candidateID, want: ErrForbidden},
{name: "unverified employer", user: unverifiedID, want: ErrEmailNotVerified},
{name: "no membership", user: foreignID, want: outbound.ErrOrganizationNotFound},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := service.AuthorizeCompany(ctx, test.user, organizationID); !errors.Is(err, test.want) {
t.Fatalf("AuthorizeCompany() error = %v, want %v", err, test.want)
}
})
}
if _, err := service.Get(ctx, recruiterID, organizationID); !errors.Is(err, outbound.ErrOrganizationManagerRequired) {
t.Fatalf("Get(recruiter) error = %v, want ErrOrganizationManagerRequired", err)
}
if _, err := service.Get(WithCompanyAccess(ctx, access), ownerID, uuid.New()); !errors.Is(err, ErrForbidden) {
t.Fatalf("Get(mismatched company context) error = %v, want ErrForbidden", err)
}
}
func TestListMyOrganizationsUsesOnlyVerifiedEmployerActorAndBoundedPage(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
tx := newOrganizationTestTransactor()
employerID, candidateID := uuid.New(), uuid.New()
tx.state.users[employerID] = verifiedEmployer(employerID, now)
tx.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
service := newOrganizationTestService(t, tx, func() time.Time { return now })
position := outbound.OrganizationListPosition{JoinedAt: now.Add(-time.Minute), OrganizationID: uuid.New()}
page, err := service.ListMyOrganizations(ctx, OrganizationListCommand{ActorID: employerID, After: &position, Limit: 8})
if err != nil || len(page.Items) != 0 || page.HasMore {
t.Fatalf("ListMyOrganizations() = %+v, %v; want empty page", page, err)
}
query := tx.snapshot().lastListQuery
if query == nil || query.UserID != employerID || query.Limit != 8 || query.After == nil || *query.After != position {
t.Fatalf("ListForUser query = %+v, want principal-scoped cursor and limit", query)
}
if _, err := service.ListMyOrganizations(ctx, OrganizationListCommand{ActorID: candidateID, Limit: 8}); !errors.Is(err, ErrForbidden) {
t.Fatalf("ListMyOrganizations(candidate) error = %v, want ErrForbidden", err)
}
if _, err := service.ListMyOrganizations(ctx, OrganizationListCommand{ActorID: employerID, Limit: outbound.MaxOrganizationPageSize + 1}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("ListMyOrganizations(oversized limit) error = %v, want ErrInvalidMembership", err)
}
}
func TestConcurrentCreateWithSameKeyReturnsOneCompany(t *testing.T) {
ctx := t.Context()
now := time.Date(2026, 8, 15, 10, 30, 0, 0, time.UTC)
+135
View File
@@ -0,0 +1,135 @@
// Package profile reads and version-saves a candidate's private manual profile.
package profile
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
// ErrForbidden reports an account that cannot use the candidate profile.
ErrForbidden = errors.New("candidate profile operation forbidden")
// ErrEmailNotVerified reports an account whose current email is not confirmed.
ErrEmailNotVerified = errors.New("candidate profile requires a confirmed email")
)
// Service is stateless between calls. Profile data, its history, and onboarding
// movement are written through one transaction.
type Service struct {
transactor outbound.Transactor
clock func() time.Time
}
// NewService takes the transaction boundary and application clock. A nil
// dependency is a wiring error and panics at construction.
func NewService(transactor outbound.Transactor, clock func() time.Time) *Service {
if transactor == nil {
panic("profile.NewService - transactor must not be nil")
}
if clock == nil {
panic("profile.NewService - clock must not be nil")
}
return &Service{transactor: transactor, clock: clock}
}
// GetMyProfile reads only the profile owned by userID. Version zero means the
// candidate has not saved a profile yet.
func (service *Service) GetMyProfile(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error) {
const location = "Service.GetMyProfile"
if userID == uuid.Nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
var result domain.CandidateProfile
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, userID, location); err != nil {
return err
}
var err error
result, err = unit.CandidateProfiles().Get(ctx, userID)
if err != nil {
return fmt.Errorf("%s - read profile: %w", location, err)
}
return nil
})
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
// SaveMyProfile replaces the candidate's manual profile when expectedVersion
// is current. Identical retries remain no-ops, while every successful request
// advances onboarding only from candidate_profile.
func (service *Service) SaveMyProfile(
ctx context.Context,
userID uuid.UUID,
expectedVersion int64,
input domain.CandidateProfileInput,
) (domain.CandidateProfile, error) {
const location = "Service.SaveMyProfile"
if userID == uuid.Nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
at := service.clock().UTC()
if at.IsZero() {
return domain.CandidateProfile{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateProfile)
}
var result domain.CandidateProfile
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, userID, location); err != nil {
return err
}
repository := unit.CandidateProfiles()
current, err := repository.Get(ctx, userID)
if err != nil {
return fmt.Errorf("%s - read profile: %w", location, err)
}
updated, changed, err := current.Replace(input, expectedVersion, at)
if err != nil {
return fmt.Errorf("%s - apply profile: %w", location, err)
}
if changed {
updated, err = repository.Save(ctx, expectedVersion, updated)
if err != nil {
return fmt.Errorf("%s - save profile: %w", location, err)
}
}
if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil {
return fmt.Errorf("%s - advance onboarding: %w", location, err)
}
result = updated
return nil
})
if err != nil {
if errors.Is(err, outbound.ErrCandidateProfileVersionConflict) || errors.Is(err, domain.ErrCandidateProfileVersionConflict) {
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateProfileVersionConflict)
}
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error {
user, err := unit.Users().GetByID(ctx, userID)
if err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
return ErrForbidden
}
return fmt.Errorf("%s - read account: %w", location, err)
}
if !user.EmailVerified() {
return ErrEmailNotVerified
}
if user.Scenario != domain.ScenarioCandidate {
return ErrForbidden
}
return nil
}
@@ -0,0 +1,184 @@
package profile
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type profileTestTransactor struct {
unit outbound.UnitOfWork
}
func (transactor profileTestTransactor) WithinTransaction(
ctx context.Context,
fn func(context.Context, outbound.UnitOfWork) error,
) error {
return fn(ctx, transactor.unit)
}
type profileTestUnit struct {
outbound.UnitOfWork
users outbound.UserRepository
profiles outbound.CandidateProfileRepository
}
func (unit profileTestUnit) Users() outbound.UserRepository { return unit.users }
func (unit profileTestUnit) CandidateProfiles() outbound.CandidateProfileRepository {
return unit.profiles
}
type profileTestUsers struct {
outbound.UserRepository
user domain.User
err error
getCalls int
}
func (users *profileTestUsers) GetByID(_ context.Context, userID uuid.UUID) (domain.User, error) {
users.getCalls++
if users.err != nil {
return domain.User{}, users.err
}
if userID != users.user.ID {
return domain.User{}, outbound.ErrUserNotFound
}
return users.user, nil
}
type profileTestRepository struct {
profile domain.CandidateProfile
getCalls int
saveCalls int
advanceCalls int
saveErr error
advanceErr error
}
func (repository *profileTestRepository) Get(_ context.Context, _ uuid.UUID) (domain.CandidateProfile, error) {
repository.getCalls++
return repository.profile, nil
}
func (repository *profileTestRepository) Save(
_ context.Context,
expectedVersion int64,
profile domain.CandidateProfile,
) (domain.CandidateProfile, error) {
repository.saveCalls++
if repository.saveErr != nil {
return domain.CandidateProfile{}, repository.saveErr
}
claims, err := profile.Content().StoredClaims()
if err != nil {
return domain.CandidateProfile{}, err
}
repository.profile, err = domain.RestoreCandidateProfile(domain.StoredCandidateProfile{
UserID: profile.UserID(), Version: expectedVersion + 1,
CreatedAt: profile.CreatedAt(), UpdatedAt: profile.UpdatedAt(), Claims: claims,
ParallelPeriodAcknowledgements: profile.Content().ParallelPeriodAcknowledgements(),
})
return repository.profile, err
}
func (repository *profileTestRepository) AdvanceOnboarding(_ context.Context, _ uuid.UUID, _ time.Time) error {
repository.advanceCalls++
return repository.advanceErr
}
func TestServiceRequiresVerifiedCandidateBeforeReadingOrWritingProfile(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
tests := []struct {
name string
scenario domain.Scenario
verified bool
wantErr error
}{
{name: "verified candidate", scenario: domain.ScenarioCandidate, verified: true},
{name: "unverified candidate", scenario: domain.ScenarioCandidate, wantErr: ErrEmailNotVerified},
{name: "verified employer", scenario: domain.ScenarioEmployer, verified: true, wantErr: ErrForbidden},
{name: "unverified employer", scenario: domain.ScenarioEmployer, wantErr: ErrEmailNotVerified},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: test.scenario}
if test.verified {
user.EmailVerifiedAt = &now
}
users := &profileTestUsers{user: user}
profiles := &profileTestRepository{}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
_, readErr := service.GetMyProfile(context.Background(), id)
if !errors.Is(readErr, test.wantErr) {
t.Fatalf("GetMyProfile() error = %v, want %v", readErr, test.wantErr)
}
_, saveErr := service.SaveMyProfile(context.Background(), id, 0, domain.CandidateProfileInput{})
if !errors.Is(saveErr, test.wantErr) {
t.Fatalf("SaveMyProfile() error = %v, want %v", saveErr, test.wantErr)
}
wantProfileReads := 0
wantAdvances := 0
if test.wantErr == nil {
wantProfileReads = 2
wantAdvances = 1
}
if profiles.getCalls != wantProfileReads || profiles.saveCalls != 0 || profiles.advanceCalls != wantAdvances {
t.Fatalf("profile calls = get %d, save %d, advance %d; want %d, 0, %d", profiles.getCalls, profiles.saveCalls, profiles.advanceCalls, wantProfileReads, wantAdvances)
}
})
}
}
func TestSaveMyProfileWritesOnlyChangedVersionsAndAdvancesOnNoOp(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
users := &profileTestUsers{user: user}
profiles := &profileTestRepository{}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
input := domain.CandidateProfileInput{FullName: &domain.ProfileClaimInput[string]{Value: "Anna Sokolova", Status: domain.ProfileClaimConfirmed}}
if _, err := service.SaveMyProfile(context.Background(), id, 0, input); err != nil {
t.Fatalf("SaveMyProfile(first save) error = %v", err)
}
if profiles.saveCalls != 1 || profiles.advanceCalls != 1 || profiles.profile.Version() != 1 {
t.Fatalf("first save calls = save %d, advance %d, version %d", profiles.saveCalls, profiles.advanceCalls, profiles.profile.Version())
}
if _, err := service.SaveMyProfile(context.Background(), id, 1, input); err != nil {
t.Fatalf("SaveMyProfile(no-op retry) error = %v", err)
}
if profiles.saveCalls != 1 || profiles.advanceCalls != 2 {
t.Fatalf("no-op calls = save %d, advance %d, want one saved version and two onboarding checks", profiles.saveCalls, profiles.advanceCalls)
}
}
func TestSaveMyProfileDoesNotAdvanceAfterProfileWriteFailure(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
users := &profileTestUsers{user: user}
profiles := &profileTestRepository{saveErr: outbound.ErrTransactionConflict}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
input := domain.CandidateProfileInput{FullName: &domain.ProfileClaimInput[string]{Value: "Anna Sokolova", Status: domain.ProfileClaimConfirmed}}
if _, err := service.SaveMyProfile(context.Background(), id, 0, input); !errors.Is(err, outbound.ErrTransactionConflict) {
t.Fatalf("SaveMyProfile() error = %v, want transaction conflict", err)
}
if profiles.advanceCalls != 0 {
t.Fatalf("onboarding advances %d times after a failed write, want 0", profiles.advanceCalls)
}
}
+8 -2
View File
@@ -773,7 +773,9 @@ Known limits. A resend for an unknown or verified address skips the token and me
### Organizations and memberships
Organization creation, reads, and owner edits are implemented in `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go`, and `backend/internal/bootstrap/organization.go`. Storage and membership ports remain in `backend/internal/port/outbound/organizations.go` and the PostgreSQL adapter. Migration `00019_create_organization_creation_results.sql` preserves the original create result. General tenant context and the organization directory are planned separately. See [backend documentation](../../backend/README.en.md#organizations) for behavior and validation.
Organization creation, reads, and owner edits are implemented in `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go`, and `backend/internal/bootstrap/organization.go`. Storage and membership ports remain in `backend/internal/port/outbound/organizations.go` and the PostgreSQL adapter. Migration `00019_create_organization_creation_results.sql` preserves the original create result. General tenant context and the paginated directory of the current account's organizations are also implemented. See [backend documentation](../../backend/README.en.md#organizations) for behavior and validation.
The middleware in `backend/internal/adapter/primary/http/company_context.go` checks the verified employer account and active `owner` membership after session, CSRF, and parameter decoding, before the business handler or its 501 fallback. All 14 organization, need, and invitation operations are classified explicitly; a contract test requires new paths with `org_id` to be classified. Candidate-owned company hiding and C4 revocation retain their separate authorization. Request context is not cached and never replaces authorization repeated inside a business transaction. Other roles receive 403; foreign or ended memberships receive 404. `ListMyOrganizations` returns only the current employer's active memberships; a company appearing in that directory does not itself grant owner authority.
Tables:
@@ -799,7 +801,11 @@ What the ports guarantee (`outbound.OrganizationRepositories`, available on `Uni
### Candidate profile
Implemented as storage, domain, and the source contract: 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.
Own `GetMyProfile` and `SaveMyProfile` operations are implemented through `backend/internal/usecase/profile/`, the transactional `CandidateProfileRepository` port, `backend/internal/adapter/secondary/postgres/candidate.go`, and `backend/internal/adapter/primary/http/v1/profile.go`. The use case rechecks the verified candidate account inside the transaction; the owner identifier comes only from the server session. Without DATABASE_URL, the operations retain their 501 fallback. Schemas and full-replacement rules live in `api/core/components/schemas/candidate_schemas.yml` and `api/core/routes/candidate_profile.yml`. No ML service, resume file, or FSP account is required.
Migration `00020_create_candidate_profile_history.sql` adds overlapping-period confirmations and version history. `experience_overlaps` lists intersections of inclusive calendar months. An explicit confirmation binds two indices to their exact dates in the current request and its `expected_version`; an earlier confirmation carries forward only for the same indices and dates. Editing an employer or description alone does not invalidate the confirmed periods. A stored unconfirmed overlap permits only an exact no-op; a changed profile requires confirmation or corrected dates.
The changed version, complete claim set, period confirmations, and private history snapshot commit in one transaction. Each snapshot is bounded to 256 KiB; a trigger refuses history UPDATE, and deleting the profile cascades to its history. There is no automatic retention expiry. A no-op creates no history. A successful save, including a no-op, advances only `candidate_profile` to `candidate_questionnaire`, leaving later steps unchanged. Confirmed categories currently remain empty until assessment-result reading is implemented and are never written by the profile form.
Tables:
+8 -2
View File
@@ -773,7 +773,9 @@ Cookie называется `__Host-lincodex_session` и имеет `Path=/`, `S
### Организации и членства
Создание, чтение и редактирование организации владельцем реализованы в `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go` и `backend/internal/bootstrap/organization.go`. Порты хранения и членства находятся в `backend/internal/port/outbound/organizations.go` и адаптере PostgreSQL. Миграция `00019_create_organization_creation_results.sql` сохраняет исходный результат создания. Общий tenant-контекст и список организаций запланированы отдельно. Поведение и проверки описаны в [документации backend](../../backend/README.md#организации).
Создание, чтение и редактирование организации владельцем реализованы в `backend/internal/usecase/organization/`, `backend/internal/adapter/primary/http/v1/organization.go` и `backend/internal/bootstrap/organization.go`. Порты хранения и членства находятся в `backend/internal/port/outbound/organizations.go` и адаптере PostgreSQL. Миграция `00019_create_organization_creation_results.sql` сохраняет исходный результат создания. Общий tenant-контекст и постраничный список своих организаций также реализованы. Поведение и проверки описаны в [документации backend](../../backend/README.md#организации).
Middleware `backend/internal/adapter/primary/http/company_context.go` проверяет подтвержденный аккаунт работодателя и активное членство `owner` после сессии, CSRF и разбора параметров, до бизнес-обработчика или ответа 501. Все 14 операций организации, потребностей и приглашений перечислены явно; контрактный тест требует классифицировать новые пути с `org_id`. Кандидатские операции скрытия компании и отзыва C4 проверяют собственные права отдельно. Контекст запроса не кешируется и не заменяет повторную проверку внутри бизнес-транзакции. Другие роли получают 403, чужое или прекращенное членство - 404. `ListMyOrganizations` возвращает только активные членства текущего работодателя; наличие компании в этом справочнике само по себе не дает полномочий владельца.
Таблицы:
@@ -799,7 +801,11 @@ Cookie называется `__Host-lincodex_session` и имеет `Path=/`, `S
### Профиль кандидата
Реализовано как хранение, домен и исходный контракт: миграция `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`) уже готовы и проверены интеграционным тестом.
Собственные `GetMyProfile` и `SaveMyProfile` реализованы через `backend/internal/usecase/profile/`, транзакционный порт `CandidateProfileRepository`, адаптер `backend/internal/adapter/secondary/postgres/candidate.go` и обработчик `backend/internal/adapter/primary/http/v1/profile.go`. Usecase повторно проверяет подтвержденный кандидатский аккаунт внутри транзакции; идентификатор владельца приходит только из серверной сессии. Без DATABASE_URL остается ответ 501. Схемы и правила полного обновления находятся в `api/core/components/schemas/candidate_schemas.yml` и `api/core/routes/candidate_profile.yml`. ML, файл резюме и ФСП не нужны.
Миграция `00020_create_candidate_profile_history.sql` добавляет подтверждения пересекающихся периодов и историю версий. `experience_overlaps` перечисляет пересечения включительных календарных месяцев. Явное подтверждение связывает два индекса с точными датами в текущем запросе и его `expected_version`; прежнее подтверждение переносится только при тех же индексах и датах. Изменение работодателя или описания само по себе не меняет подтвержденные периоды. Сохраненный неподтвержденный overlap допускает только точный no-op; перед изменением профиля его надо подтвердить или исправить даты.
Измененная версия, полный набор заявлений, подтверждения периодов и закрытый снимок истории записываются одной транзакцией. Каждый снимок ограничен 256 KiB; UPDATE истории запрещен триггером, удаление профиля каскадно удаляет историю. Автоматического срока очистки нет. No-op не создает историю. Успешное сохранение, включая no-op, переводит только шаг `candidate_profile` в `candidate_questionnaire`; поздний шаг не меняется. Подтвержденные категории пока возвращаются пустыми до реализации чтения результатов оценки и никогда не записываются формой профиля.
Таблицы:
@@ -46,13 +46,13 @@ export const getGetMyProfileResponseProfileClaimSourceMock = (overrideResponse:
export const getGetMyProfileResponseProfileSalaryMinimumMock = (overrideResponse: Partial<ProfileSalaryMinimum> = {}): ProfileSalaryMinimum => ({...{amount: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse});
export const getGetMyProfileResponseMock = (overrideResponse: Partial<Extract<CandidateProfile, object>> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {location: {stLine truncated
export const getGetMyProfileResponseMock = (overrideResponse: Partial<Extract<CandidateProfile, object>> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getGetMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience_overlaps: Array.from({ length: faker.number.int({min: 1, max: 190}) }, (_, i) => i + 1).map(() => ({first_index: faker.number.int({min: 0, max: 19}), second_index: faker.number.int({min: 1, max: 19}), status: faker.helpers.arrayElement(['needs_confirmation','confirmed'] as const)})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.aLine truncated
export const getSaveMyProfileResponseProfileClaimSourceMock = (overrideResponse: Partial<ProfileClaimSource> = {}): ProfileClaimSource => ({...{origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}, ...overrideResponse});
export const getSaveMyProfileResponseProfileSalaryMinimumMock = (overrideResponse: Partial<ProfileSalaryMinimum> = {}): ProfileSalaryMinimum => ({...{amount: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, ...overrideResponse});
export const getSaveMyProfileResponseMock = (overrideResponse: Partial<Extract<CandidateProfile, object>> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), terms: {locationLine truncated
export const getSaveMyProfileResponseMock = (overrideResponse: Partial<Extract<CandidateProfile, object>> = {}): CandidateProfile => ({version: faker.number.int({min: 0}), full_name: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, contacts: {email: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([faker.internet.email(),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, phone: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}, telegram: {status: faker.helpers.arrayElement(['confirmed','extracted','unknown'] as const), value: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), source: faker.helpers.arrayElement([{...getSaveMyProfileResponseProfileClaimSourceMock()},null,])}}, stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => ({tag: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), roles: Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), self_assessed_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => ({employer_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), started_on: fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}), ended_on: faker.helpers.arrayElement([fakeFromPattern("^[0-9]{4}-(0[1-9]|1[0-2])$", {minLength: 7, maxLength: 7}),null,]), summary: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 1000}}),null,]), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 300}}),null,]), extraction_version: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}),null,]), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,])}})), experience_overlaps: Array.from({ length: faker.number.int({min: 1, max: 190}) }, (_, i) => i + 1).map(() => ({first_index: faker.number.int({min: 0, max: 19}), second_index: faker.number.int({min: 1, max: 19}), status: faker.helpers.arrayElement(['needs_confirmation','confirmed'] as const)})), soft_skills: Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => ({skill: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}), status: faker.helpers.arrayElement(['confirmed','extracted'] as const), source: {origin: faker.helpers.arrayElement(['manual','extracted_from_resume','imported'] as const), trust_level: faker.number.int({min: 0, max: 0}), quote: faker.helpers.arrayElement([faker.strLine truncated
export const getGetMyQuestionnaireMockHandler = (overrideResponse?: CandidateQuestionnaire | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<CandidateQuestionnaire> | CandidateQuestionnaire), options?: RequestHandlerOptions) => {
@@ -270,6 +270,8 @@ export const useSaveMyQuestionnaire = <TError = ErrorType<Problem>,
*
* 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.
*
* `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices refer to this response's `experience` array and are scoped to the same `version`; each pair is either `needs_confirmation` or `confirmed`.
*
* 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.
*/
@@ -373,7 +375,7 @@ export const getSaveMyProfileUrl = () => {
/**
* 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.
* 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. A successful save advances an account whose current onboarding step is candidate_profile to candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update is atomic with the profile and its history.
*
* 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.
*
@@ -383,7 +385,9 @@ export const getSaveMyProfileUrl = () => {
*
* 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.
* Experience periods use inclusive calendar months. An overlap is allowed only when `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel work. Each acknowledgement names two distinct experience indices and repeats their exact normalized `started_on` and `ended_on` values; both indices and periods must match the submitted array and `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries an earlier acknowledgement only when the same two indices still contain the same dates; reordering or changing either date requires a new acknowledgement. Editing other experience fields does not invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping acknowledgements are invalid.
*
* 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, a changed overlap without explicit confirmation, and a decision `extracted` for a value that is not a stored suggestion, with 400 validation_failed and pointers to the items, for example `/roles/1/specialization` or `/stack/1/status`. Error bodies never repeat a submitted value.
* @summary Replace the private profile of the current candidate.
*/
export const saveMyProfile = async (candidateProfileUpdate: CandidateProfileUpdate, options?: Parameters<typeof apiRequest>[1]): Promise<CandidateProfile> => {
@@ -274,14 +274,12 @@ export const useCreateOrganization = <TError = ErrorType<Problem>,
}
/**
* Requires the session cookie of an employer account with an active membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing.
* Requires the session cookie of a verified employer account with an active owner membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing.
*
* Returns the profile with its current `version`, the verification level (`verification`), and the card as a candidate sees it (`candidate_card`). The verification level is always the one the server holds: it never rises because the profile is complete, because the organization has members, or because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations returns it with the membership.
*
* In the MVP the profile is readable by any active member; every member is an owner, because the operations that add members are planned. The roles of PRD FR07 that read a company card without managing it change no field of this contract.
*
* Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed with the path pointer.
* @summary Read an organization of which the caller is a member.
* Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer.
* @summary Read an organization managed by the caller.
*/
export const getOrganization = async (orgId: string, options?: Parameters<typeof apiRequest>[1]): Promise<Organization> => {
@@ -352,7 +350,7 @@ export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganiza
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Read an organization of which the caller is a member.
* @summary Read an organization managed by the caller.
*/
export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(
@@ -64,6 +64,7 @@ const validUpdate = {
status: "confirmed",
},
],
confirmed_parallel_periods: [],
soft_skills: [{ skill: "Mentoring", status: "confirmed" }],
terms: {
location: { value: "Kazan", status: "confirmed" },
@@ -82,6 +83,7 @@ const emptyUpdate = {
stack: [],
roles: [],
experience: [],
confirmed_parallel_periods: [],
soft_skills: [],
terms: { location: null, relocation: null, salary_minimum: null },
};
@@ -104,6 +106,7 @@ const profile = {
},
],
experience: [],
experience_overlaps: [],
soft_skills: [],
terms: { location: unknownClaim, relocation: unknownClaim, salary_minimum: unknownClaim },
confirmed_categories: [
@@ -306,6 +309,7 @@ describe("generated CandidateProfile", () => {
stack: [],
roles: [],
experience: [],
experience_overlaps: [],
soft_skills: [],
terms: { location: unknownClaim, relocation: unknownClaim, salary_minimum: unknownClaim },
confirmed_categories: [],
@@ -329,6 +333,7 @@ it("exposes the profile DTOs without a confirmed grade or a category in requests
expectTypeOf<CandidateProfileUpdate>().not.toHaveProperty("confirmed_categories");
expectTypeOf<CandidateProfileUpdate>().not.toHaveProperty("version");
expectTypeOf<CandidateProfileUpdate>().toHaveProperty("confirmed_parallel_periods");
expectTypeOf<UpdateRole>().not.toHaveProperty("confirmed_grade");
expectTypeOf<UpdateRole>().not.toHaveProperty("category");
expectTypeOf<UpdateRole>().not.toHaveProperty("source");
@@ -336,6 +341,7 @@ it("exposes the profile DTOs without a confirmed grade or a category in requests
expectTypeOf<ProfileRoleItem>().not.toHaveProperty("confirmed_grade");
expectTypeOf<ProfileRoleItem>().not.toHaveProperty("category");
expectTypeOf<CandidateProfile>().toHaveProperty("confirmed_categories");
expectTypeOf<CandidateProfile>().toHaveProperty("experience_overlaps");
expectTypeOf(saveMyProfile).parameter(0).toEqualTypeOf<CandidateProfileUpdate>();
});
@@ -114,6 +114,13 @@ export const candidateProfileExperienceItemSourceExtractionVersionOneMax = 64;
export const candidateProfileExperienceItemSourceExtractionVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateProfileExperienceMax = 20;
export const candidateProfileExperienceOverlapsItemFirstIndexMin = 0;
export const candidateProfileExperienceOverlapsItemFirstIndexMax = 19;
export const candidateProfileExperienceOverlapsItemSecondIndexMax = 19;
export const candidateProfileExperienceOverlapsMax = 190;
export const candidateProfileSoftSkillsItemSkillMax = 50;
@@ -253,6 +260,11 @@ export const CandidateProfile = zod.object({
"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.'),
"experience_overlaps": zod.array(zod.object({
"first_index": zod.int().min(candidateProfileExperienceOverlapsItemFirstIndexMin).max(candidateProfileExperienceOverlapsItemFirstIndexMax),
"second_index": zod.int().min(1).max(candidateProfileExperienceOverlapsItemSecondIndexMax),
"status": zod.enum(['needs_confirmation', 'confirmed']).describe('Whether the candidate confirmed that two overlapping periods are genuine parallel work.')
}).describe('One pair of work history entries whose inclusive month ranges overlap. The indices refer to the experience array in this profile version. `confirmed` records an explicit acknowledgement for this pair of dates; otherwise the pair needs confirmation before a changed profile can be saved.')).max(candidateProfileExperienceOverlapsMax).describe('Every pair of overlapping experience periods, with its confirmation status. The indices refer to this version\'s experience array.'),
"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.'),
@@ -51,6 +51,33 @@ export const candidateProfileUpdateExperienceItemSummaryOneMax = 1000;
export const candidateProfileUpdateExperienceMax = 20;
export const candidateProfileUpdateConfirmedParallelPeriodsItemFirstIndexMin = 0;
export const candidateProfileUpdateConfirmedParallelPeriodsItemFirstIndexMax = 19;
export const candidateProfileUpdateConfirmedParallelPeriodsItemSecondIndexMax = 19;
export const candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodStartedOnMin = 7;
export const candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodStartedOnMax = 7;
export const candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodEndedOnOneMin = 7;
export const candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodEndedOnOneMax = 7;
export const candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodStartedOnMin = 7;
export const candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodStartedOnMax = 7;
export const candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodEndedOnOneMin = 7;
export const candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodEndedOnOneMax = 7;
export const candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const candidateProfileUpdateConfirmedParallelPeriodsMax = 190;
export const candidateProfileUpdateSoftSkillsItemSkillMax = 50;
@@ -103,6 +130,18 @@ export const CandidateProfileUpdate = zod.object({
"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.'),
"confirmed_parallel_periods": zod.array(zod.object({
"first_index": zod.int().min(candidateProfileUpdateConfirmedParallelPeriodsItemFirstIndexMin).max(candidateProfileUpdateConfirmedParallelPeriodsItemFirstIndexMax),
"second_index": zod.int().min(1).max(candidateProfileUpdateConfirmedParallelPeriodsItemSecondIndexMax),
"first_period": zod.object({
"started_on": zod.string().min(candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodStartedOnMin).max(candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodStartedOnMax).regex(candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodStartedOnRegExp).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(candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodEndedOnOneMin).max(candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodEndedOnOneMax).regex(candidateProfileUpdateConfirmedParallelPeriodsItemFirstPeriodEndedOnOneRegExp).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 work, or null when the period is open-ended.')
}).describe('The exact month range of an experience entry, copied into a confirmation.'),
"second_period": zod.object({
"started_on": zod.string().min(candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodStartedOnMin).max(candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodStartedOnMax).regex(candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodStartedOnRegExp).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(candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodEndedOnOneMin).max(candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodEndedOnOneMax).regex(candidateProfileUpdateConfirmedParallelPeriodsItemSecondPeriodEndedOnOneRegExp).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 work, or null when the period is open-ended.')
}).describe('The exact month range of an experience entry, copied into a confirmation.')
}).describe('Explicit acknowledgement that the two indexed experience periods are genuine parallel work. The indices and exact ranges must match the submitted experience array; expected_version binds the acknowledgement to the profile version the candidate read.')).max(candidateProfileUpdateConfirmedParallelPeriodsMax).exactOptional().describe('Explicit acknowledgements for overlapping periods. Each pair must use distinct in-range indices and repeat the exact normalized started_on and ended_on values of those entries in this body. A changed or reordered period needs a new acknowledgement. The server retains a previous acknowledgement only for the same indices and dates. Duplicate pairs and pairs that do not overlap are rejected.'),
"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.')
@@ -23,6 +23,9 @@ export * from './profileEmailInput.zod';
export * from './profileEmployerName.zod';
export * from './profileExperienceItem.zod';
export * from './profileExperienceItemInput.zod';
export * from './profileExperienceOverlap.zod';
export * from './profileExperienceOverlapStatus.zod';
export * from './profileExperiencePeriod.zod';
export * from './profileExperienceSummary.zod';
export * from './profileFullNameClaim.zod';
export * from './profileFullNameInput.zod';
@@ -30,6 +33,7 @@ export * from './profileItemStatus.zod';
export * from './profileLocationClaim.zod';
export * from './profileLocationInput.zod';
export * from './profileLocationName.zod';
export * from './profileParallelPeriodConfirmation.zod';
export * from './profilePhoneClaim.zod';
export * from './profilePhoneInput.zod';
export * from './profileRelocationClaim.zod';
@@ -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 profileExperienceOverlapFirstIndexMin = 0;
export const profileExperienceOverlapFirstIndexMax = 19;
export const profileExperienceOverlapSecondIndexMax = 19;
export const ProfileExperienceOverlap = zod.object({
"first_index": zod.int().min(profileExperienceOverlapFirstIndexMin).max(profileExperienceOverlapFirstIndexMax),
"second_index": zod.int().min(1).max(profileExperienceOverlapSecondIndexMax),
"status": zod.enum(['needs_confirmation', 'confirmed']).describe('Whether the candidate confirmed that two overlapping periods are genuine parallel work.')
}).describe('One pair of work history entries whose inclusive month ranges overlap. The indices refer to the experience array in this profile version. `confirmed` records an explicit acknowledgement for this pair of dates; otherwise the pair needs confirmation before a changed profile can be saved.')
export type ProfileExperienceOverlap = zod.input<typeof ProfileExperienceOverlap>;
export type ProfileExperienceOverlapOutput = zod.output<typeof ProfileExperienceOverlap>;
@@ -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 ProfileExperienceOverlapStatus = zod.enum(['needs_confirmation', 'confirmed']).describe('Whether the candidate confirmed that two overlapping periods are genuine parallel work.')
export type ProfileExperienceOverlapStatus = zod.input<typeof ProfileExperienceOverlapStatus>;
export type ProfileExperienceOverlapStatusOutput = zod.output<typeof ProfileExperienceOverlapStatus>;
@@ -0,0 +1,26 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileExperiencePeriodStartedOnMin = 7;
export const profileExperiencePeriodStartedOnMax = 7;
export const profileExperiencePeriodStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const profileExperiencePeriodEndedOnOneMin = 7;
export const profileExperiencePeriodEndedOnOneMax = 7;
export const profileExperiencePeriodEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const ProfileExperiencePeriod = zod.object({
"started_on": zod.string().min(profileExperiencePeriodStartedOnMin).max(profileExperiencePeriodStartedOnMax).regex(profileExperiencePeriodStartedOnRegExp).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(profileExperiencePeriodEndedOnOneMin).max(profileExperiencePeriodEndedOnOneMax).regex(profileExperiencePeriodEndedOnOneRegExp).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 work, or null when the period is open-ended.')
}).describe('The exact month range of an experience entry, copied into a confirmation.')
export type ProfileExperiencePeriod = zod.input<typeof ProfileExperiencePeriod>;
export type ProfileExperiencePeriodOutput = zod.output<typeof ProfileExperiencePeriod>;
@@ -0,0 +1,49 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const profileParallelPeriodConfirmationFirstIndexMin = 0;
export const profileParallelPeriodConfirmationFirstIndexMax = 19;
export const profileParallelPeriodConfirmationSecondIndexMax = 19;
export const profileParallelPeriodConfirmationFirstPeriodStartedOnMin = 7;
export const profileParallelPeriodConfirmationFirstPeriodStartedOnMax = 7;
export const profileParallelPeriodConfirmationFirstPeriodStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const profileParallelPeriodConfirmationFirstPeriodEndedOnOneMin = 7;
export const profileParallelPeriodConfirmationFirstPeriodEndedOnOneMax = 7;
export const profileParallelPeriodConfirmationFirstPeriodEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const profileParallelPeriodConfirmationSecondPeriodStartedOnMin = 7;
export const profileParallelPeriodConfirmationSecondPeriodStartedOnMax = 7;
export const profileParallelPeriodConfirmationSecondPeriodStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const profileParallelPeriodConfirmationSecondPeriodEndedOnOneMin = 7;
export const profileParallelPeriodConfirmationSecondPeriodEndedOnOneMax = 7;
export const profileParallelPeriodConfirmationSecondPeriodEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const ProfileParallelPeriodConfirmation = zod.object({
"first_index": zod.int().min(profileParallelPeriodConfirmationFirstIndexMin).max(profileParallelPeriodConfirmationFirstIndexMax),
"second_index": zod.int().min(1).max(profileParallelPeriodConfirmationSecondIndexMax),
"first_period": zod.object({
"started_on": zod.string().min(profileParallelPeriodConfirmationFirstPeriodStartedOnMin).max(profileParallelPeriodConfirmationFirstPeriodStartedOnMax).regex(profileParallelPeriodConfirmationFirstPeriodStartedOnRegExp).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(profileParallelPeriodConfirmationFirstPeriodEndedOnOneMin).max(profileParallelPeriodConfirmationFirstPeriodEndedOnOneMax).regex(profileParallelPeriodConfirmationFirstPeriodEndedOnOneRegExp).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 work, or null when the period is open-ended.')
}).describe('The exact month range of an experience entry, copied into a confirmation.'),
"second_period": zod.object({
"started_on": zod.string().min(profileParallelPeriodConfirmationSecondPeriodStartedOnMin).max(profileParallelPeriodConfirmationSecondPeriodStartedOnMax).regex(profileParallelPeriodConfirmationSecondPeriodStartedOnRegExp).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(profileParallelPeriodConfirmationSecondPeriodEndedOnOneMin).max(profileParallelPeriodConfirmationSecondPeriodEndedOnOneMax).regex(profileParallelPeriodConfirmationSecondPeriodEndedOnOneRegExp).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 work, or null when the period is open-ended.')
}).describe('The exact month range of an experience entry, copied into a confirmation.')
}).describe('Explicit acknowledgement that the two indexed experience periods are genuine parallel work. The indices and exact ranges must match the submitted experience array; expected_version binds the acknowledgement to the profile version the candidate read.')
export type ProfileParallelPeriodConfirmation = zod.input<typeof ProfileParallelPeriodConfirmation>;
export type ProfileParallelPeriodConfirmationOutput = zod.output<typeof ProfileParallelPeriodConfirmation>;
@@ -51,6 +51,33 @@ export const saveMyProfileBodyExperienceItemSummaryOneMax = 1000;
export const saveMyProfileBodyExperienceMax = 20;
export const saveMyProfileBodyConfirmedParallelPeriodsItemFirstIndexMin = 0;
export const saveMyProfileBodyConfirmedParallelPeriodsItemFirstIndexMax = 19;
export const saveMyProfileBodyConfirmedParallelPeriodsItemSecondIndexMax = 19;
export const saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodStartedOnMin = 7;
export const saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodStartedOnMax = 7;
export const saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodEndedOnOneMin = 7;
export const saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodEndedOnOneMax = 7;
export const saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodStartedOnMin = 7;
export const saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodStartedOnMax = 7;
export const saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodStartedOnRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodEndedOnOneMin = 7;
export const saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodEndedOnOneMax = 7;
export const saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodEndedOnOneRegExp = new RegExp('^[0-9]{4}-(0[1-9]|1[0-2])$');
export const saveMyProfileBodyConfirmedParallelPeriodsMax = 190;
export const saveMyProfileBodySoftSkillsItemSkillMax = 50;
@@ -103,6 +130,18 @@ export const SaveMyProfileBody = zod.object({
"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.'),
"confirmed_parallel_periods": zod.array(zod.object({
"first_index": zod.int().min(saveMyProfileBodyConfirmedParallelPeriodsItemFirstIndexMin).max(saveMyProfileBodyConfirmedParallelPeriodsItemFirstIndexMax),
"second_index": zod.int().min(1).max(saveMyProfileBodyConfirmedParallelPeriodsItemSecondIndexMax),
"first_period": zod.object({
"started_on": zod.string().min(saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodStartedOnMin).max(saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodStartedOnMax).regex(saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodStartedOnRegExp).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(saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodEndedOnOneMin).max(saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodEndedOnOneMax).regex(saveMyProfileBodyConfirmedParallelPeriodsItemFirstPeriodEndedOnOneRegExp).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 work, or null when the period is open-ended.')
}).describe('The exact month range of an experience entry, copied into a confirmation.'),
"second_period": zod.object({
"started_on": zod.string().min(saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodStartedOnMin).max(saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodStartedOnMax).regex(saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodStartedOnRegExp).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(saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodEndedOnOneMin).max(saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodEndedOnOneMax).regex(saveMyProfileBodyConfirmedParallelPeriodsItemSecondPeriodEndedOnOneRegExp).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 work, or null when the period is open-ended.')
}).describe('The exact month range of an experience entry, copied into a confirmation.')
}).describe('Explicit acknowledgement that the two indexed experience periods are genuine parallel work. The indices and exact ranges must match the submitted experience array; expected_version binds the acknowledgement to the profile version the candidate read.')).max(saveMyProfileBodyConfirmedParallelPeriodsMax).exactOptional().describe('Explicit acknowledgements for overlapping periods. Each pair must use distinct in-range indices and repeat the exact normalized started_on and ended_on values of those entries in this body. A changed or reordered period needs a new acknowledgement. The server retains a previous acknowledgement only for the same indices and dates. Duplicate pairs and pairs that do not overlap are rejected.'),
"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.')