diff --git a/api/README.en.md b/api/README.en.md index 0c21712..adb9ff6 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -718,6 +718,47 @@ Each operation also declares the problem response `default`. No new problem code Open questions: whether the C2 consent text needs a new version now that publishing `categories` also sends one supporting assessment fact (skill, grade, trust level, year) to an organization - a decision for the owner and the lawyer, and the consent texts are not changed here; whether the evidence needs its own card field instead of the `categories` field; whether the year is the right precision for an employer; an operation for the candidate to hide or show a fact (the stored visibility exists, no operation changes it); and when claims of the profile and facts from other sources join the list. +### Match search + +The tag `organization` has one search operation for the organization-visible candidate bank (PRD FR09). It is implemented as a deterministic search without ML; the model, the groups, and the data it reads are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations). + +| Method and path | operationId | Protection | Success | Specific errors | +| --- | --- | --- | --- | --- | +| `POST /api/v1/organizations/{org_id}/matches` | `SearchOrganizationMatches` | session, CSRF, `Origin`, active owner | 200 `MatchSearchResponse`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found` | + +The operation changes nothing and needs no Idempotency-Key; `POST` carries the body. The 200 response also declares no 429. + +- Access. The organization comes from the path and the active owner membership of the session account. A missing session answers 401, a candidate account, a member who is not the owner, a missing CSRF token, and a foreign `Origin` answer 403, and an unknown organization, an organization without an active membership, a need of another organization, an unknown need, or a `requirements_version` that no change of the confirmed requirements created answer 404. Hidden profiles, a revoked or missing C2 publication, the organization's own hiding, and the minimum cohort of the card are applied before any entry exists: a handle in the result is a handle that `GetOrganizationCandidateCard` opens at that moment. +- Basis. `MatchSearchByNeed` searches the immutable `requirements_version` snapshot (not the general `version`), and its optional `filters` narrow it; `MatchSearchByBank` searches all organization-visible entries with explicit filters. The response `source` repeats the basis: the need reference, or the bank filters with every key present and null for a filter that was not sent (the stack is sorted). +- Entries. Every entry is one candidate specialization under the organization-scoped `candidate_handle`. `main` and `near` hold confirmed categories (`near` when a required skill of the request earns less than 0.25), `unconfirmed` holds the declared specializations, sorted by Fit, then Coverage, then an internal identifier that is never returned. An unconfirmed entry has `category: null`, `strength: null`, and only `fit` and `coverage`. The groups are not one scale, and one handle can be confirmed in one specialization and unconfirmed in another. +- Neutral and unknown values. The semantics component is 0.5 for every entry with `ml_unavailable`; `percentile` is null with `cohort_below_30` and T is 0.5 (no comparable real cohort exists, and demonstration results never form one); domain, freshness, and responsiveness are 0.5 with their flags; competition is 0 and is neither a penalty nor an unknown; a card value that is not published is `null` in `public_context` with `not_in_public_card`. +- A search is charged like card reads, because an entry carries card content. The whole visible bank is ranked, and each group returns at most `max_results_per_group` entries of the policy version (demo 10, so at most 30 reveals for one search, below the 50 views per day of tier E0); no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate counts as one distinct card view of the organization (the same reservation as `GetOrganizationCandidateCard`, so a candidate already viewed inside the window costs nothing again, and repeating the search or opening the card afterwards does not charge twice) and gets one `card_viewed` entry in the access history per search with the fields actually returned. When the allowance ends, the entries already paid for are returned with `truncated: true`, nothing is written for the rest, and no error and no new problem code is returned. `truncated` is also true when a group exceeded its limit and never carries a count. The response `truncated` is required. +- No contact, candidate location, salary amount or minimum, raw answer, failed attempt, or reason for withheld data is in any entry; the explanation uses the bounded `MatchEvidenceCode` and `MatchEvidenceState` values only. A deployment whose effective policy has no `matching` section answers an internal error and never ranks with defaults. + +Accepted residual risks: `truncated` is one bit about the size of the visible bank, and the response time grows with it; both are bounded by the group limit and carry no count. When the real comparable cohort of a category reaches the policy minimum, the percentile is still null with the reason `percentile_not_computed` and the search does not fail. A change of the visible cohort during a search repeats it up to three times; two simultaneous searches of one organization are serialized by its quota lock. + +Open questions: the demo value 10 of `max_results_per_group` and whether the output needs paging beyond it; whether a search should charge a candidate for a summary entry at the price of a full card view; whether the grade of a need should be an implicit filter or only an explanation; whether the PRD values should keep an online Backend result (trust 0.6 times the broad relation 0.4 gives 0.24) below the near threshold 0.25 while a stated tag (0.25) reaches it, so that a candidate whose only evidence for a required technology is an assessment of the specialization is always in `near` for it; whether the `stack` filter should require every tag (as implemented) or any; and whether the demonstration relation between specializations and technologies (Backend over Go, PostgreSQL, Kafka, and Docker; DevOps over Docker) is the taxonomy the owner wants. + +### Notifications + +The tag `notification` describes the in-platform inbox of the current account, in the candidate cabinet and in the cabinet of one organization. It has four operations; the logic behind them is implemented, and no product module produces a real notification yet (see [architecture](../docs/en/ARCHITECTURE.md#internal-notifications)). + +| Method and path | operationId | Protection | Success | Specific errors | +| --- | --- | --- | --- | --- | +| `GET /api/v1/me/notifications` | `ListMyNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (an employer account) | +| `POST /api/v1/me/notifications/{notification_id}/read` | `MarkMyNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | +| `GET /api/v1/organizations/{org_id}/notifications` | `ListOrganizationNotifications` | session | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (a candidate account) or `email_not_verified`, 404 `not_found` | +| `POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read` | `MarkOrganizationNotificationRead` | session and CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | + +Each operation also declares the problem response `default`. No new problem code is added. + +- The inbox is the delivery state inside the platform. An item exists once the event reached the platform, whether or not an email was sent, and a failed or missing email never blocks it. A repeated delivery of the same event is the same item (`id` is the event identifier). +- The inbox stores references, not text. `content` is resolved from the current source for the recipient on every read and is `null` when the source is gone or the recipient may not see it now (for example the candidate hid the organization); the item stays in the list, can be marked, and a client shows a generic line, never an earlier copy. `content.link_path` is a same-origin absolute path (`^/[A-Za-z0-9/_-]{0,255}$`) or `null`. +- The recipient is the session account. The organization route also needs an active membership of any role in `org_id` and lists only the caller's items of that organization. A candidate on the organization route and an employer on the candidate route get 403 `forbidden`, and an employer with an unconfirmed email gets 403 `email_not_verified` on the organization route. A missing membership, an unknown organization, an item of another account or of another organization, and an unknown identifier get the same 404 `not_found`, so identifiers cannot be enumerated. +- Pagination follows the shared `limit` (1-100, default 20) and `cursor`, newest delivery first with the identifier as the tie-breaker. The cursor is bound to the account and the cabinet; a cursor of another account or cabinet gets 400. +- A mark is idempotent by its effect and needs no Idempotency-Key: the first read time is stored and every repeat returns it. It reads no source and returns no content. `kind` is `invitation_delivered` (no module produces it yet) or `synthetic` (a notice with no product meaning that exercises the path). +- Closed schemas and checks. Every notification object has `additionalProperties: false` and all properties required. `TestNotificationOperationsFollowTheConventions` and `TestNotificationSchemasAreClosedAndKeepTextInTheContent` (Go) check the tag, the security of reads and marks, the statuses, no-store, the parameters, and that an item carries no text, name, or contact outside `content`. + ### Generator checks `testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core. diff --git a/api/README.md b/api/README.md index cfb71c2..e943f3b 100644 --- a/api/README.md +++ b/api/README.md @@ -718,6 +718,47 @@ ML-сервис отвечает на ошибки той же схемой `Pro Открытые вопросы: нужна ли новая версия текста согласия C2, раз публикация `categories` теперь отправляет организации еще один подтверждающий факт оценки (навык, грейд, уровень доверия, год) - решение владельца продукта и юриста, тексты согласий здесь не меняются; нужно ли доказательствам собственное поле карточки вместо поля `categories`; подходит ли работодателю точность в один год; операция скрыть или показать факт для кандидата (сохраненная видимость есть, операции для ее изменения нет); когда в список добавятся заявления профиля и факты из других источников. +### Подбор + +В теге `organization` одна операция поиска по банку кандидатов, видимому организации (PRD FR09). Она реализована как детерминированный поиск без ML; модель, группы и читаемые данные описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение). + +| Метод и путь | operationId | Защита | Успех | Специфичные ошибки | +| --- | --- | --- | --- | --- | +| `POST /api/v1/organizations/{org_id}/matches` | `SearchOrganizationMatches` | сессия, CSRF, `Origin`, действующий владелец | 200 `MatchSearchResponse`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found` | + +Операция ничего не меняет и не требует Idempotency-Key; `POST` нужен для тела. Ответ 200 также не объявляет 429. + +- Доступ. Организация берется из пути и действующего членства владельца аккаунта сессии. Отсутствие сессии дает 401; аккаунт кандидата, участник не владелец, отсутствие CSRF-токена и чужой `Origin` дают 403; неизвестная организация, организация без действующего членства, потребность другой организации, неизвестная потребность и `requirements_version`, которую не создавало изменение подтвержденных требований, дают 404. Скрытые профили, отозванная или отсутствующая публикация C2, скрытие именно этой организации и минимальная когорта карточки применяются до появления любой записи: handle в результате - это handle, который `GetOrganizationCandidateCard` открывает в тот же момент. +- Основание. `MatchSearchByNeed` ищет по неизменяемому снимку `requirements_version` (не по общей `version`), необязательные `filters` сужают его; `MatchSearchByBank` ищет по всем записям, видимым организации, с явными фильтрами. `source` в ответе повторяет основание: ссылку на потребность либо фильтры банка, где присутствует каждый ключ, а неотправленный фильтр равен null (стек отсортирован). +- Записи. Каждая запись - одна специализация кандидата под организационным `candidate_handle`. В `main` и `near` лежат подтвержденные категории (`near`, если обязательный навык запроса дает меньше 0.25), в `unconfirmed` - заявленные специализации, отсортированные по Fit, затем Coverage, затем по внутреннему идентификатору, который не возвращается. У неподтвержденной записи `category: null`, `strength: null` и только `fit` и `coverage`. Группы - не одна шкала, и один handle может быть подтвержден по одной специализации и не подтвержден по другой. +- Нейтральные и неизвестные значения. Семантика равна 0.5 для каждой записи с `ml_unavailable`; `percentile` равен null с `cohort_below_30`, а T равен 0.5 (сопоставимой реальной когорты нет, демонстрационные результаты ее не образуют); домен, свежесть и своевременность равны 0.5 со своими признаками; соревновательный вклад равен 0 и не является ни штрафом, ни неизвестностью; неопубликованное значение карточки - `null` в `public_context` с `not_in_public_card`. +- Поиск оплачивается как чтение карточек, потому что запись несет содержимое карточки. Ранжируется весь видимый банк, а каждая группа возвращает не более `max_results_per_group` записей версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 просмотров в сутки для уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат считается одним уникальным просмотром карточки организации (то же резервирование, что у `GetOrganizationCandidateCard`: кандидат, уже просмотренный в окне, второй раз ничего не стоит, и повтор поиска или последующее открытие карточки не списывает дважды) и получает по одной записи `card_viewed` в истории доступа за поиск с фактически возвращенными полями. Когда лимит заканчивается, возвращаются уже оплаченные записи с `truncated: true`, для остальных ничего не пишется, ошибка и новый код проблемы не возвращаются. `truncated` также истинно, когда группа превысила предел, и никогда не несет число. В ответе `truncated` обязателен. +- Ни в одной записи нет контакта, локации кандидата, суммы или минимума зарплаты, сырого ответа, проваленной попытки и причины скрытых данных; объяснение использует только ограниченные значения `MatchEvidenceCode` и `MatchEvidenceState`. Развертывание, действующая политика которого не содержит раздела `matching`, отвечает внутренней ошибкой и не ранжирует по умолчаниям. + +Принятые остаточные риски: `truncated` - один бит о размере видимого банка, и время ответа растет вместе с ним; оба ограничены пределом группы и не несут числа. Когда реальная сопоставимая когорта категории достигает минимума политики, перцентиль все равно null с причиной `percentile_not_computed`, и поиск не падает. Изменение видимой когорты во время поиска повторяет его до трех раз; два одновременных поиска одной организации сериализуются ее блокировкой квоты. + +Открытые вопросы: демонстрационное значение 10 для `max_results_per_group` и нужна ли постраничная выдача сверх него; должен ли поиск списывать кандидата за краткую запись по цене полного просмотра карточки; должен ли грейд потребности быть неявным фильтром или только объяснением; должны ли значения PRD оставлять онлайн-результат Backend (доверие 0.6 на широкую связь 0.4 дает 0.24) ниже порога близости 0.25, тогда как заявленный тег (0.25) его достигает, так что кандидат, у которого единственное доказательство нужной технологии - оценка специализации, всегда попадает для нее в `near`; должен ли фильтр `stack` требовать каждый тег (как реализовано) или любой; и является ли демонстрационная связь специализаций с технологиями (Backend над Go, PostgreSQL, Kafka и Docker; DevOps над Docker) таксономией, которую хочет владелец продукта. + +### Уведомления + +Тег `notification` описывает внутренний inbox текущего аккаунта в кабинете кандидата и в кабинете одной организации. В нем четыре операции; логика за ними реализована, но настоящие уведомления пока не создает ни один продуктовый модуль (см. [архитектуру](../docs/ru/ARCHITECTURE.md#внутренние-уведомления)). + +| Метод и путь | operationId | Защита | Успех | Специфичные ошибки | +| --- | --- | --- | --- | --- | +| `GET /api/v1/me/notifications` | `ListMyNotifications` | сессия | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (аккаунт работодателя) | +| `POST /api/v1/me/notifications/{notification_id}/read` | `MarkMyNotificationRead` | сессия и CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | +| `GET /api/v1/organizations/{org_id}/notifications` | `ListOrganizationNotifications` | сессия | 200 `NotificationList`, `Cache-Control: no-store` | 400, 401, 403 `forbidden` (аккаунт кандидата) или `email_not_verified`, 404 `not_found` | +| `POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read` | `MarkOrganizationNotificationRead` | сессия и CSRF | 200 `NotificationReadReceipt`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 429 | + +Каждая операция также объявляет проблемный ответ `default`. Новый код problem не добавляется. + +- Inbox - состояние доставки внутри платформы. Элемент существует, как только событие дошло до платформы, независимо от того, отправлено ли письмо, и неудачное или отсутствующее письмо его не блокирует. Повторная доставка того же события - тот же элемент (`id` - идентификатор события). +- Inbox хранит ссылки, а не текст. `content` вычисляется из текущего источника для получателя при каждом чтении и равен `null`, когда источника нет или получатель сейчас не вправе его видеть (например, кандидат скрыл организацию); элемент остается в списке, его можно отметить, а клиент показывает общую строку и никогда не показывает прежнюю копию. `content.link_path` - абсолютный путь того же origin (`^/[A-Za-z0-9/_-]{0,255}$`) или `null`. +- Получатель - аккаунт сессии. Маршрут организации дополнительно требует активное членство любой роли в `org_id` и показывает только элементы вызывающего в этой организации. Кандидат на маршруте организации и работодатель на маршруте кандидата получают 403 `forbidden`, а работодатель с неподтвержденной почтой на маршруте организации - 403 `email_not_verified`. Нет членства, неизвестная организация, элемент другого аккаунта или другой организации и неизвестный идентификатор дают один и тот же 404 `not_found`, поэтому идентификаторы нельзя перебирать. +- Пагинация использует общие `limit` (1-100, по умолчанию 20) и `cursor`, новые доставки первыми, идентификатор разрешает равенство. Курсор привязан к аккаунту и кабинету; курсор другого аккаунта или кабинета дает 400. +- Отметка идемпотентна по эффекту и не требует Idempotency-Key: первое время прочтения сохраняется, и каждый повтор возвращает его. Она не читает источник и не возвращает содержимое. `kind` равен `invitation_delivered` (пока его не создает ни один модуль) или `synthetic` (уведомление без продуктового смысла, которое проверяет путь). +- Закрытые схемы и проверки. У каждого объекта уведомлений `additionalProperties: false`, и все свойства обязательны. `TestNotificationOperationsFollowTheConventions` и `TestNotificationSchemasAreClosedAndKeepTextInTheContent` (Go) проверяют тег, защиту чтений и отметок, статусы, no-store, параметры и то, что у элемента нет текста, названия и контакта вне `content`. + ### Проверки генераторов `testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core. diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index be73cd3..a720590 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -4536,3 +4536,30 @@ HiddenOrganizationLimitReached: pointer: /org_id code: limit_reached message: The candidate already hides the maximum number of organizations. +NotificationListPage: + summary: An unread notice and a read one whose source is no longer visible + value: + items: + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + kind: synthetic + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + delivered_at: "2026-10-09T08:30:00Z" + read_at: null + content: + title: Тестовое уведомление + summary: Организация «Север» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий. + link_path: null + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f6f + kind: synthetic + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + delivered_at: "2026-10-08T17:05:00Z" + read_at: "2026-10-08T17:10:00Z" + content: null + page: + has_more: false + next_cursor: null +NotificationReadReceipt: + summary: The first read time of an item + value: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + read_at: "2026-10-09T08:45:00Z" diff --git a/api/core/components/examples/matches.yml b/api/core/components/examples/matches.yml index 35a7691..cfffb6d 100644 --- a/api/core/components/examples/matches.yml +++ b/api/core/components/examples/matches.yml @@ -139,6 +139,7 @@ ThreeGroups: unknown_flags: - component: assessment reason: no_confirmation_for_specialization + truncated: false Empty: summary: A valid search with no eligible visible candidates. @@ -157,6 +158,7 @@ Empty: main: [] near: [] unconfirmed: [] + truncated: false MLUnavailable: summary: Semantic similarity uses the documented neutral value while ML is unavailable. @@ -207,6 +209,7 @@ MLUnavailable: reason: ml_unavailable near: [] unconfirmed: [] + truncated: false CohortBelow30: summary: A small comparison cohort has no published percentile. @@ -257,3 +260,57 @@ CohortBelow30: reason: cohort_below_30 near: [] unconfirmed: [] + truncated: false + +Truncated: + summary: The group limit or the card-view allowance cut the output. + description: >- + Synthetic example. The entries returned are in rank order and already + counted as card views; the flag carries no total. + value: + source: + kind: bank + filters: + specialization: backend + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE + specialization: backend + confirmation_status: confirmed + declared_grade: null + category: + specialization: backend + grade: junior + strength: standard + public_context: + stack: null + experience_band: null + work_formats: null + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + components: + fit: 0.5 + coverage: 0.5 + domain: 0.5 + semantics: 0.5 + percentile: null + competition: 0.0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.45125 + unknown_flags: + - component: semantics + reason: ml_unavailable + - component: percentile + reason: cohort_below_30 + near: [] + unconfirmed: [] + truncated: true diff --git a/api/core/components/parameters.yml b/api/core/components/parameters.yml index 52ea5bb..d19f14e 100644 --- a/api/core/components/parameters.yml +++ b/api/core/components/parameters.yml @@ -158,3 +158,16 @@ HiddenOrganizationId: type: string format: uuid example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 +NotificationId: + name: notification_id + in: path + required: true + description: >- + Identifier of an item of the inbox of the current account in the cabinet + that the path names. An item of another account, an item of another + organization context, and an unknown identifier all answer 404 not_found, + so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 3c95d63..f9ee518 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -4847,7 +4847,7 @@ MatchUnknownComponent: - domain MatchUnknownReason: type: string - description: Bounded explanation for an unknown component, not a hiding reason. + description: Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5. enum: - ml_unavailable - cohort_below_30 @@ -4856,6 +4856,7 @@ MatchUnknownReason: - need_field_unconfirmed - no_freshness_history - no_response_history + - percentile_not_computed MatchUnknownFlag: type: object description: A safe, bounded explanation for one unavailable component. @@ -5110,11 +5111,15 @@ MatchSearchResponse: required: - source - groups + - truncated properties: source: $ref: '#/MatchSearchSource' groups: $ref: '#/MatchSearchGroups' + truncated: + type: boolean + description: 'True when the groups are not the whole ranked result: a group exceeded the versioned per-group limit, or the organization''s card-view allowance ended while the entries were being revealed. The entries returned are in rank order and already counted as card views. It carries no total, so it does not reveal how many candidates match.' NeedVersion: type: integer format: int64 @@ -6027,6 +6032,112 @@ NeedUpdate: oneOf: - $ref: '#/NeedSalaryInput' - type: 'null' +NotificationKind: + type: string + description: 'Which event put the notification into the inbox. The inbox stores a reference to the event, never its text. + + + - invitation_delivered: an invitation reached the candidate''s inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet. + + - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action. + + + Adding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.' + enum: + - invitation_delivered + - synthetic +NotificationContent: + type: object + description: The text of a notification as the current source shows it to the recipient now. It is computed on every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it from the next read. It holds no contact, no score, and no result of an assessment. + additionalProperties: false + required: + - title + - summary + - link_path + properties: + title: + type: string + minLength: 1 + maxLength: 120 + description: Short heading in Russian. + summary: + type: string + minLength: 1 + maxLength: 500 + description: One or two sentences in Russian. Plain text, never markup. + link_path: + type: + - string + - 'null' + maxLength: 256 + pattern: ^/[A-Za-z0-9/_-]{0,255}$ + description: Same-origin absolute path of the screen that the notification opens, or null when there is none. It has no origin, query, fragment, or escape; a client opens it only as a path of its own router. + examples: + - /candidate/invitations +Notification: + type: object + description: One item of the inbox of the current account. Its identity, kind, organization, delivery time, and read state are stored; its content is resolved from the current source on every read. + additionalProperties: false + required: + - id + - kind + - organization_id + - delivered_at + - read_at + - content + properties: + id: + type: string + format: uuid + description: Identifier of the item. It equals the identifier of the event that produced it, so a repeated delivery of the same event is the same item. + kind: + $ref: '#/NotificationKind' + organization_id: + type: string + format: uuid + description: 'The organization context of the item: the organization that sent it to a candidate, or the organization whose cabinet holds it for an employer. The identifier is not a right to read the organization.' + delivered_at: + $ref: '#/Timestamp' + read_at: + description: When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + content: + description: The current content, or null when the source is gone or the recipient may not see it now. A client then shows a generic line such as "The content is no longer available" and never an old copy. The item stays in the list and can be marked read. + oneOf: + - $ref: '#/NotificationContent' + - type: 'null' +NotificationList: + type: object + description: One page of the inbox, newest delivery first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Items of the page. + items: + $ref: '#/Notification' + page: + $ref: '#/PageInfo' +NotificationReadReceipt: + type: object + description: The read state of one item after a mark. It carries no content, so marking never reads the source. + additionalProperties: false + required: + - id + - read_at + properties: + id: + type: string + format: uuid + description: Identifier of the marked item. + read_at: + $ref: '#/Timestamp' OrganizationVersion: type: integer format: int64 diff --git a/api/core/components/schemas/match_schemas.yml b/api/core/components/schemas/match_schemas.yml index 47da798..7a83a4e 100644 --- a/api/core/components/schemas/match_schemas.yml +++ b/api/core/components/schemas/match_schemas.yml @@ -278,7 +278,12 @@ schemas: - domain MatchUnknownReason: type: string - description: Bounded explanation for an unknown component, not a hiding reason. + description: >- + Bounded explanation for an unknown component, not a hiding reason. + `cohort_below_30` is reported only while the comparable real cohort of + the category is smaller than the versioned minimum; once the cohort + reaches the minimum but the percentile is still not computed, the reason + is `percentile_not_computed`. In both cases T is the neutral 0.5. enum: - ml_unavailable - cohort_below_30 @@ -287,6 +292,7 @@ schemas: - need_field_unconfirmed - no_freshness_history - no_response_history + - percentile_not_computed MatchUnknownFlag: type: object description: A safe, bounded explanation for one unavailable component. @@ -567,8 +573,17 @@ schemas: required: - source - groups + - truncated properties: source: $ref: "#/schemas/MatchSearchSource" groups: $ref: "#/schemas/MatchSearchGroups" + truncated: + type: boolean + description: >- + True when the groups are not the whole ranked result: a group exceeded + the versioned per-group limit, or the organization's card-view + allowance ended while the entries were being revealed. The entries + returned are in rank order and already counted as card views. It + carries no total, so it does not reveal how many candidates match. diff --git a/api/core/components/schemas/notification_schemas.yml b/api/core/components/schemas/notification_schemas.yml new file mode 100644 index 0000000..8dc4739 --- /dev/null +++ b/api/core/components/schemas/notification_schemas.yml @@ -0,0 +1,131 @@ +schemas: + NotificationKind: + type: string + description: |- + Which event put the notification into the inbox. The inbox stores a reference to the event, never its text. + + - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet. + - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action. + + Adding a value is a contract change; a client shows an unknown kind with the generic text of an item without content. + enum: + - invitation_delivered + - synthetic + NotificationContent: + type: object + description: >- + The text of a notification as the current source shows it to the + recipient now. It is computed on every read and never stored, so a + hiding, a revoked membership, or a withdrawn source removes it from the + next read. It holds no contact, no score, and no result of an + assessment. + additionalProperties: false + required: + - title + - summary + - link_path + properties: + title: + type: string + minLength: 1 + maxLength: 120 + description: Short heading in Russian. + summary: + type: string + minLength: 1 + maxLength: 500 + description: One or two sentences in Russian. Plain text, never markup. + link_path: + type: + - string + - "null" + maxLength: 256 + pattern: "^/[A-Za-z0-9/_-]{0,255}$" + description: >- + Same-origin absolute path of the screen that the notification + opens, or null when there is none. It has no origin, query, + fragment, or escape; a client opens it only as a path of its own + router. + examples: + - /candidate/invitations + Notification: + type: object + description: >- + One item of the inbox of the current account. Its identity, kind, + organization, delivery time, and read state are stored; its content is + resolved from the current source on every read. + additionalProperties: false + required: + - id + - kind + - organization_id + - delivered_at + - read_at + - content + properties: + id: + type: string + format: uuid + description: >- + Identifier of the item. It equals the identifier of the event that + produced it, so a repeated delivery of the same event is the same + item. + kind: + $ref: "#/schemas/NotificationKind" + organization_id: + type: string + format: uuid + description: >- + The organization context of the item: the organization that sent it + to a candidate, or the organization whose cabinet holds it for an + employer. The identifier is not a right to read the organization. + delivered_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + read_at: + description: >- + When the recipient first marked the item read, or null while it is + unread. A repeated mark keeps the first time. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + content: + description: >- + The current content, or null when the source is gone or the + recipient may not see it now. A client then shows a generic line + such as "The content is no longer available" and never an old + copy. The item stays in the list and can be marked read. + oneOf: + - $ref: "#/schemas/NotificationContent" + - type: "null" + NotificationList: + type: object + description: One page of the inbox, newest delivery first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Items of the page. + items: + $ref: "#/schemas/Notification" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + NotificationReadReceipt: + type: object + description: >- + The read state of one item after a mark. It carries no content, so + marking never reads the source. + additionalProperties: false + required: + - id + - read_at + properties: + id: + type: string + format: uuid + description: Identifier of the marked item. + read_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 6666e3c..ae40eef 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -27,6 +27,8 @@ tags: description: 'Visibility of the current candidate: the publication of the anonymous card (a setting that refers to the C2 consent of the ledger and never replaces it), the search status that is not a consent, the organizations that the candidate hides the profile from, the preview of the card, and the history of the settings and of the accesses. Everything is closed by default, and no change makes a candidate more visible than they chose. No schema here reaches a contact, a name, or the lowest salary.' - name: evidence description: 'Skill evidence derived from confirmed assessment results: one fact per source event with its skills, trust level, attribution, date, and visibility. The candidate reads their own facts; an organization reads only the permitted projection of a currently visible card. Raw answers, failures, and anti-cheat data are never part of it.' + - name: notification + description: 'The in-platform inbox of the current account: references to delivered events with a read state, in the candidate cabinet and in the cabinet of one organization. The inbox is the source of the delivery state inside the platform and never depends on email. It stores no text: the content of every item is resolved from the current source for the recipient on each read, and an item whose source is gone or no longer visible stays in the list without content.' - name: consent description: 'The consent ledger of the current account: the independent consents C1-C5 with their text versions, sources, states, and revocations. The ledger is append-only and returns only the caller''s own records.' - name: support @@ -1647,9 +1649,11 @@ paths: The body selects either a Need's `requirements_version` snapshot or the current organization-visible bank with explicit filters. A need reference uses `Need.requirements_version`, not the general `Need.version`; title or suggestion-only edits do not change the confirmed-requirements snapshot. An empty bank filter searches all otherwise eligible specializations, returning each specialization separately. + A search reveals card content, so it is charged like card reads. The whole visible bank is ranked, but each group returns at most the versioned per-group limit and no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of the organization (a candidate it already viewed inside the window costs nothing again, so repeating the search or opening the card afterwards does not charge twice) and appears in the candidate's access history with the fields actually returned. When the allowance ends, the entries already counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit, and it carries no count. No new error is returned for an exhausted allowance. + Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed entries belong to `main` (FR09). Entries in `unconfirmed` are ordered by Fit, then coverage, then a stable internal tie-breaker that is never returned. Their category and strength remain null, and they have no theta, T, P, or test percentile. The search result uses the organization-scoped opaque `candidate_handle` as its display pseudonym and invitation reference, never a candidate account or profile identifier. - The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. + The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not fail. A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without active membership answers 404 not_found. The response is `Cache-Control: no-store`. security: @@ -1689,6 +1693,8 @@ paths: $ref: '#/components/examples/MLUnavailable' cohort_below_30: $ref: '#/components/examples/CohortBelow30' + truncated: + $ref: '#/components/examples/Truncated' '400': $ref: '#/components/responses/ValidationFailed' '401': @@ -2556,6 +2562,174 @@ paths: $ref: '#/components/responses/TooManyRequests' default: $ref: '#/components/responses/Problem' + /api/v1/me/notifications: + get: + operationId: ListMyNotifications + summary: List the inbox of the current candidate. + description: |- + Requires the session cookie of a candidate account with a confirmed email. The recipient comes from the session, never from a request parameter, so the response holds only the caller's own items. Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The inbox is the in-platform delivery state of a notification. An item exists as soon as the event reached the platform, whether or not any email was sent, and an email that failed or was never sent does not block it. The inbox stores a reference to the event, not its text: the `content` of every item is resolved from the current source for this recipient on this read. When the source is gone or the recipient may not see it now (for example the candidate hid the organization), the item stays in the list with `content` null, and no earlier text is shown. An event that is delivered twice is one item. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - notification + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the inbox of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + examples: + page: + $ref: '#/components/examples/NotificationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/notifications/{notification_id}/read: + post: + operationId: MarkMyNotificationRead + summary: Mark an item of the inbox of the current candidate as read. + description: |- + Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request has no body. + + The command is idempotent by its effect: the first mark stores the read time and every repeat returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no content, so marking an item whose content is no longer available still works. It changes no other item. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - notification + parameters: + - $ref: '#/components/parameters/NotificationId' + responses: + '200': + description: The read state of the item, newly set or repeated. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationReadReceipt' + examples: + read: + $ref: '#/components/examples/NotificationReadReceipt' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/notifications: + get: + operationId: ListOrganizationNotifications + summary: List the inbox of the current employer in one organization. + description: |- + Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role. The recipient comes from the session and the organization from the path and the membership that the server holds, never from the request. Returns only the items addressed to the caller in this organization, newest delivery first with the identifier as the tie-breaker, with cursor pagination. An item of the same account in another organization, and an item of another member, are never listed. The response is `Cache-Control: no-store`. + + Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email never blocks an item, and the `content` of every item is resolved from the current source for this recipient on this read. An employer sees content only while the membership is active. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization and an unknown organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`, `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - notification + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the inbox of the current employer in the organization. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + examples: + page: + $ref: '#/components/examples/NotificationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/notifications/{notification_id}/read: + post: + operationId: MarkOrganizationNotificationRead + summary: Mark an item of the inbox of the current employer in one organization as read. + description: |- + Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session and the organization from the path and the server-side membership. The request has no body. + + The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The item must belong to the caller in this organization. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization, an unknown organization, an item of another account, an item of another organization, and an unknown identifier all answer 404 not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - notification + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/NotificationId' + responses: + '200': + description: The read state of the item, newly set or repeated. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationReadReceipt' + examples: + read: + $ref: '#/components/examples/NotificationReadReceipt' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' /api/v1/me/consents: get: operationId: ListMyConsents @@ -9719,6 +9893,110 @@ components: description: Permitted facts, one for each supported category. items: $ref: '#/components/schemas/OrganizationEvidenceFact' + NotificationKind: + type: string + description: |- + Which event put the notification into the inbox. The inbox stores a reference to the event, never its text. + + - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet. + - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action. + + Adding a value is a contract change; a client shows an unknown kind with the generic text of an item without content. + enum: + - invitation_delivered + - synthetic + NotificationContent: + type: object + description: The text of a notification as the current source shows it to the recipient now. It is computed on every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it from the next read. It holds no contact, no score, and no result of an assessment. + additionalProperties: false + required: + - title + - summary + - link_path + properties: + title: + type: string + minLength: 1 + maxLength: 120 + description: Short heading in Russian. + summary: + type: string + minLength: 1 + maxLength: 500 + description: One or two sentences in Russian. Plain text, never markup. + link_path: + type: + - string + - 'null' + maxLength: 256 + pattern: ^/[A-Za-z0-9/_-]{0,255}$ + description: Same-origin absolute path of the screen that the notification opens, or null when there is none. It has no origin, query, fragment, or escape; a client opens it only as a path of its own router. + examples: + - /candidate/invitations + Notification: + type: object + description: One item of the inbox of the current account. Its identity, kind, organization, delivery time, and read state are stored; its content is resolved from the current source on every read. + additionalProperties: false + required: + - id + - kind + - organization_id + - delivered_at + - read_at + - content + properties: + id: + type: string + format: uuid + description: Identifier of the item. It equals the identifier of the event that produced it, so a repeated delivery of the same event is the same item. + kind: + $ref: '#/components/schemas/NotificationKind' + organization_id: + type: string + format: uuid + description: 'The organization context of the item: the organization that sent it to a candidate, or the organization whose cabinet holds it for an employer. The identifier is not a right to read the organization.' + delivered_at: + $ref: '#/components/schemas/Timestamp' + read_at: + description: When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + content: + description: The current content, or null when the source is gone or the recipient may not see it now. A client then shows a generic line such as "The content is no longer available" and never an old copy. The item stays in the list and can be marked read. + oneOf: + - $ref: '#/components/schemas/NotificationContent' + - type: 'null' + NotificationList: + type: object + description: One page of the inbox, newest delivery first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Items of the page. + items: + $ref: '#/components/schemas/Notification' + page: + $ref: '#/components/schemas/PageInfo' + NotificationReadReceipt: + type: object + description: The read state of one item after a mark. It carries no content, so marking never reads the source. + additionalProperties: false + required: + - id + - read_at + properties: + id: + type: string + format: uuid + description: Identifier of the marked item. + read_at: + $ref: '#/components/schemas/Timestamp' HealthResponse: type: object additionalProperties: false @@ -10717,7 +10995,7 @@ components: - domain MatchUnknownReason: type: string - description: Bounded explanation for an unknown component, not a hiding reason. + description: Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5. enum: - ml_unavailable - cohort_below_30 @@ -10726,6 +11004,7 @@ components: - need_field_unconfirmed - no_freshness_history - no_response_history + - percentile_not_computed MatchUnknownFlag: type: object description: A safe, bounded explanation for one unavailable component. @@ -10875,11 +11154,15 @@ components: required: - source - groups + - truncated properties: source: $ref: '#/components/schemas/MatchSearchSource' groups: $ref: '#/components/schemas/MatchSearchGroups' + truncated: + type: boolean + description: 'True when the groups are not the whole ranked result: a group exceeded the versioned per-group limit, or the organization''s card-view allowance ended while the entries were being revealed. The entries returned are in rank order and already counted as card views. It carries no total, so it does not reveal how many candidates match.' CardSelfAssessment: type: object description: Candidate-declared specialization and optional grade. This is never an assessment result. @@ -11022,6 +11305,15 @@ components: type: string format: uuid example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + NotificationId: + name: notification_id + in: path + required: true + description: Identifier of an item of the inbox of the current account in the cabinet that the path names. An item of another account, an item of another organization context, and an unknown identifier all answer 404 not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 CandidateHandle: name: candidate_handle in: path @@ -14347,6 +14639,7 @@ components: unknown_flags: - component: assessment reason: no_confirmation_for_specialization + truncated: false Empty: summary: A valid search with no eligible visible candidates. value: @@ -14364,6 +14657,7 @@ components: main: [] near: [] unconfirmed: [] + truncated: false MLUnavailable: summary: Semantic similarity uses the documented neutral value while ML is unavailable. description: Synthetic example; 0.5 is the FR09 neutral value, not an inference. @@ -14413,6 +14707,7 @@ components: reason: ml_unavailable near: [] unconfirmed: [] + truncated: false CohortBelow30: summary: A small comparison cohort has no published percentile. description: Synthetic example; the exact cohort size is not disclosed. @@ -14462,6 +14757,57 @@ components: reason: cohort_below_30 near: [] unconfirmed: [] + truncated: false + Truncated: + summary: The group limit or the card-view allowance cut the output. + description: Synthetic example. The entries returned are in rank order and already counted as card views; the flag carries no total. + value: + source: + kind: bank + filters: + specialization: backend + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE + specialization: backend + confirmation_status: confirmed + declared_grade: null + category: + specialization: backend + grade: junior + strength: standard + public_context: + stack: null + experience_band: null + work_formats: null + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + components: + fit: 0.5 + coverage: 0.5 + domain: 0.5 + semantics: 0.5 + percentile: null + competition: 0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.45125 + unknown_flags: + - component: semantics + reason: ml_unavailable + - component: percentile + reason: cohort_below_30 + near: [] + unconfirmed: [] + truncated: true OrganizationAnonymousCandidateCard: summary: An anonymous card currently visible to one organization description: The alias is scoped to the reading organization; no contact values are included. @@ -15719,6 +16065,33 @@ components: granted_at: '2026-10-06T15:00:00Z' revoked_at: '2026-10-07T10:00:00Z' revocation_reason: participation_cancelled + NotificationListPage: + summary: An unread notice and a read one whose source is no longer visible + value: + items: + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + kind: synthetic + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + delivered_at: '2026-10-09T08:30:00Z' + read_at: null + content: + title: Тестовое уведомление + summary: Организация «Север» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий. + link_path: null + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f6f + kind: synthetic + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + delivered_at: '2026-10-08T17:05:00Z' + read_at: '2026-10-08T17:10:00Z' + content: null + page: + has_more: false + next_cursor: null + NotificationReadReceipt: + summary: The first read time of an item + value: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + read_at: '2026-10-09T08:45:00Z' ConsentRecordListPage: summary: The whole consent history of a candidate on one page description: C1 was accepted at registration and again for a newer text version, so the first record is superseded; the version c1-2026-10-05 is an illustration, since the migration publishes only c1-2026-10-01 so far. C2 was granted and revoked. C4 was given in the acceptance of one invitation with the email only; the organization name is the one the consent text showed. diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 37d2a0a..bf83f88 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -67,6 +67,15 @@ tags: visibility. The candidate reads their own facts; an organization reads only the permitted projection of a currently visible card. Raw answers, failures, and anti-cheat data are never part of it. + - name: notification + description: >- + The in-platform inbox of the current account: references to delivered + events with a read state, in the candidate cabinet and in the cabinet of + one organization. The inbox is the source of the delivery state inside + the platform and never depends on email. It stores no text: the content + of every item is resolved from the current source for the recipient on + each read, and an item whose source is gone or no longer visible stays + in the list without content. - name: consent description: >- The consent ledger of the current account: the independent consents @@ -168,6 +177,14 @@ paths: $ref: ./routes/candidate_invitation_decline.yml /api/v1/me/invitations/{invitation_id}/cancel: $ref: ./routes/candidate_invitation_cancel.yml + /api/v1/me/notifications: + $ref: ./routes/candidate_notifications.yml + /api/v1/me/notifications/{notification_id}/read: + $ref: ./routes/candidate_notification_read.yml + /api/v1/organizations/{org_id}/notifications: + $ref: ./routes/organization_notifications.yml + /api/v1/organizations/{org_id}/notifications/{notification_id}/read: + $ref: ./routes/organization_notification_read.yml /api/v1/me/consents: $ref: ./routes/consents.yml /api/v1/me/consents/{purpose}: @@ -910,6 +927,16 @@ components: $ref: ./components/schemas.yml#/OrganizationEvidenceFact OrganizationEvidence: $ref: ./components/schemas.yml#/OrganizationEvidence + NotificationKind: + $ref: ./components/schemas.yml#/NotificationKind + NotificationContent: + $ref: ./components/schemas.yml#/NotificationContent + Notification: + $ref: ./components/schemas.yml#/Notification + NotificationList: + $ref: ./components/schemas.yml#/NotificationList + NotificationReadReceipt: + $ref: ./components/schemas.yml#/NotificationReadReceipt parameters: IdempotencyKey: $ref: ./components/parameters.yml#/IdempotencyKey @@ -933,6 +960,8 @@ components: $ref: ./components/parameters.yml#/MyInvitationId HiddenOrganizationId: $ref: ./components/parameters.yml#/HiddenOrganizationId + NotificationId: + $ref: ./components/parameters.yml#/NotificationId headers: ETag: $ref: ./components/headers.yml#/ETag diff --git a/api/core/routes/candidate_notification_read.yml b/api/core/routes/candidate_notification_read.yml new file mode 100644 index 0000000..d9d19a6 --- /dev/null +++ b/api/core/routes/candidate_notification_read.yml @@ -0,0 +1,43 @@ +post: + operationId: MarkMyNotificationRead + summary: Mark an item of the inbox of the current candidate as read. + description: |- + Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request has no body. + + The command is idempotent by its effect: the first mark stores the read time and every repeat returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no content, so marking an item whose content is no longer available still works. It changes no other item. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - notification + parameters: + - $ref: ../components/parameters.yml#/NotificationId + responses: + "200": + description: The read state of the item, newly set or repeated. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NotificationReadReceipt + examples: + read: + $ref: ../components/examples.yml#/NotificationReadReceipt + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_notifications.yml b/api/core/routes/candidate_notifications.yml new file mode 100644 index 0000000..b494b94 --- /dev/null +++ b/api/core/routes/candidate_notifications.yml @@ -0,0 +1,37 @@ +get: + operationId: ListMyNotifications + summary: List the inbox of the current candidate. + description: |- + Requires the session cookie of a candidate account with a confirmed email. The recipient comes from the session, never from a request parameter, so the response holds only the caller's own items. Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The inbox is the in-platform delivery state of a notification. An item exists as soon as the event reached the platform, whether or not any email was sent, and an email that failed or was never sent does not block it. The inbox stores a reference to the event, not its text: the `content` of every item is resolved from the current source for this recipient on this read. When the source is gone or the recipient may not see it now (for example the candidate hid the organization), the item stays in the list with `content` null, and no earlier text is shown. An event that is delivered twice is one item. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - notification + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the inbox of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NotificationList + examples: + page: + $ref: ../components/examples.yml#/NotificationListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/matches.yml b/api/core/routes/matches.yml index d58eeb2..613739a 100644 --- a/api/core/routes/matches.yml +++ b/api/core/routes/matches.yml @@ -6,9 +6,11 @@ post: The body selects either a Need's `requirements_version` snapshot or the current organization-visible bank with explicit filters. A need reference uses `Need.requirements_version`, not the general `Need.version`; title or suggestion-only edits do not change the confirmed-requirements snapshot. An empty bank filter searches all otherwise eligible specializations, returning each specialization separately. + A search reveals card content, so it is charged like card reads. The whole visible bank is ranked, but each group returns at most the versioned per-group limit and no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of the organization (a candidate it already viewed inside the window costs nothing again, so repeating the search or opening the card afterwards does not charge twice) and appears in the candidate's access history with the fields actually returned. When the allowance ends, the entries already counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit, and it carries no count. No new error is returned for an exhausted allowance. + Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed entries belong to `main` (FR09). Entries in `unconfirmed` are ordered by Fit, then coverage, then a stable internal tie-breaker that is never returned. Their category and strength remain null, and they have no theta, T, P, or test percentile. The search result uses the organization-scoped opaque `candidate_handle` as its display pseudonym and invitation reference, never a candidate account or profile identifier. - The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. + The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not fail. A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without active membership answers 404 not_found. The response is `Cache-Control: no-store`. security: @@ -48,6 +50,8 @@ post: $ref: ../components/examples/matches.yml#/MLUnavailable cohort_below_30: $ref: ../components/examples/matches.yml#/CohortBelow30 + truncated: + $ref: ../components/examples/matches.yml#/Truncated "400": $ref: ../components/responses.yml#/ValidationFailed "401": diff --git a/api/core/routes/organization_notification_read.yml b/api/core/routes/organization_notification_read.yml new file mode 100644 index 0000000..843a4d1 --- /dev/null +++ b/api/core/routes/organization_notification_read.yml @@ -0,0 +1,44 @@ +post: + operationId: MarkOrganizationNotificationRead + summary: Mark an item of the inbox of the current employer in one organization as read. + description: |- + Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session and the organization from the path and the server-side membership. The request has no body. + + The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The item must belong to the caller in this organization. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization, an unknown organization, an item of another account, an item of another organization, and an unknown identifier all answer 404 not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - notification + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/NotificationId + responses: + "200": + description: The read state of the item, newly set or repeated. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NotificationReadReceipt + examples: + read: + $ref: ../components/examples.yml#/NotificationReadReceipt + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_notifications.yml b/api/core/routes/organization_notifications.yml new file mode 100644 index 0000000..5a8809b --- /dev/null +++ b/api/core/routes/organization_notifications.yml @@ -0,0 +1,40 @@ +get: + operationId: ListOrganizationNotifications + summary: List the inbox of the current employer in one organization. + description: |- + Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role. The recipient comes from the session and the organization from the path and the membership that the server holds, never from the request. Returns only the items addressed to the caller in this organization, newest delivery first with the identifier as the tie-breaker, with cursor pagination. An item of the same account in another organization, and an item of another member, are never listed. The response is `Cache-Control: no-store`. + + Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email never blocks an item, and the `content` of every item is resolved from the current source for this recipient on this read. An employer sees content only while the membership is active. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization and an unknown organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`, `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - notification + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the inbox of the current employer in the organization. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NotificationList + examples: + page: + $ref: ../components/examples.yml#/NotificationListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/Makefile b/backend/Makefile index 35c8c98..70d2f51 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -57,6 +57,14 @@ assessment-category-attest-build: ## Build the local category attestation operat @mkdir -p bin $(GO) build -buildvcs=false -trimpath -o bin/assessment-category-attest ./cmd/assessment-category-attest +.PHONY: policy-publish policy-publish-build +policy-publish: ## Add the demo matching section to the product policy (set ARGS) + $(GO) run ./cmd/policy-publish $(ARGS) + +policy-publish-build: ## Build the local policy publication operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/policy-publish ./cmd/policy-publish + .PHONY: deps install install-tools deps: ## Download pinned Go module dependencies $(GO) mod download diff --git a/backend/README.en.md b/backend/README.en.md index e19f143..465ad2a 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -118,4 +118,21 @@ A confirmed real assessment result leaves one fact of skill evidence per attempt The candidate reads the facts at `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, query `ListCandidateEvidenceFacts`); an employer reads the permitted projection at `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, which runs the checks of the card read (`candidateview.Service.AuthorizeCategoriesSection`: membership, effective C2 publication, hiding, minimum cohort, quota, access audit) and then the statement `ListOrganizationVisibleEvidence` (effective publication view, `NOT EXISTS` over the hidden organizations, the `categories` field, visible measurements, one fact for each category of the card that supports its confirmed grade, an allowlist of six columns: skill, grade, trust, basis, calibration, year). The preview of the candidate (`GetMyCardPreview`) shows the same section through `ListCandidatePreviewEvidence`. The reads touch only the two evidence tables; `backend/db/evidence_queries_test.go` fails when an evidence query names a result, attempt, answer, signal, or review table. The facts, the tags, and the rules are described in [architecture](../docs/en/ARCHITECTURE.md#skill-evidence). The integration test `TestSkillEvidenceOverHTTP` runs against a real PostgreSQL and covers the fact tied to its result with trust 1, two more tags on one event, an express run and a failed attempt, paging, the organization projection with C2 granted and revoked, a hidden organization, a hidden fact, a card without categories, tags that can join a fact only in its creating transaction, the erasure of an account with facts through both cascade paths, the refusal to roll the migration back while a fact is hidden, and the rebuild after the migration is rolled back and applied again. + +## Match search + +`POST /api/v1/organizations/{org_id}/matches` ranks the organization-visible candidate bank without ML (`usecase/matching/`). It runs in one transaction: `candidateview.Service.ListVisibleCards` applies the checks of a card read (verified employer, locked active membership, `ListVisibleCandidateViewSources` over `candidate_effective_publications` with `NOT EXISTS` over the hidden organizations, the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five), the need snapshot is read by `requirements_version`, and the permitted evidence comes only from `ListOrganizationFacts`. The usecase repeats the owner role check; the HTTP boundary lists the operation in `ownerCompanyOperations`. A search is charged like card reads: each group is cut to the policy limit, and each candidate returned is reserved through the company quota port and recorded in the access history with the returned fields (`candidateview.SearchViews`); when the allowance ends the response is cut and flagged `truncated`. The operator publishes the matching section with `make policy-publish ARGS='matching --actor operator:'` (`cmd/policy-publish`), see [DEPLOY](../docs/en/DEPLOY.md#match-search-policy-on-a-stand). + +Each entry is one candidate specialization. Scores use the `matching` section of the effective product policy (`domain.MatchingPolicy`, demo version `DemoProductPolicyV4`); a policy without the section makes the search fail closed. The arithmetic is integer (micro units for components, basis points for shares), so the order is reproducible: confirmed groups sort by S, then coverage, then the internal candidate identifier; the unconfirmed group by Fit, then coverage, then the identifier, and it never computes theta, T, P, a percentile, or S. The explanation and the unknown flags are built from the same computed contributions. The model, the neutral values, and what is not implemented are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations). + +The integration test `TestMatchSearchOverHTTP` runs against a real PostgreSQL through the real router, the profile, consent, publication, need, organization, and assessment operations: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, one handle confirmed in Backend and unconfirmed in Networks, a profile published without a grade and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the access denials, and the policy without the section. The browser fixture `questionnaire-fixture` publishes `DemoProductPolicyV4`, so a local stand has the matching section. + See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md). + +## Internal notifications + +The inbox stores a reference to a delivered event for one recipient (`notification_inbox_events`, migrations 32 and 36), never its text. The consumer `notification_inbox` (`usecase/notification/inbox_handler.go`) writes the row in the transaction of its dedup marker; the key `(recipient_user_id, event_id)` keeps one row per recipient and event, and an event ID that returns with other metadata is rejected. The row exists whether or not an email was sent, and nothing in the handler reads mail state. + +The text is resolved when the list is read (`usecase/notification/inbox.go`, `inbox_content.go`): `InboxService` authorizes the cabinet in the read transaction (a verified candidate for `GET /api/v1/me/notifications`; a verified employer with an active membership for `GET /api/v1/organizations/{org_id}/notifications`), then asks the resolver of each item's source type for the content that the recipient may see now. A source that is gone or hidden leaves the item in the list without content. The mark (`POST .../{notification_id}/read`) keeps the first read time and reads no source. A foreign, cross-organization, or unknown item answers 404. + +A producer appends an `invitation.delivered` event with the payload `recipient_user_id` and `organization_id` and registers a resolver for its source; the synthetic `notification.synthetic_delivered` event exercises the path and has no product meaning. The contract is in [docs/en/ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#internal-notifications) and [api/README.en.md](../api/README.en.md#notifications); no invitation produces an event yet. diff --git a/backend/README.md b/backend/README.md index 7c1eae6..da76e06 100644 --- a/backend/README.md +++ b/backend/README.md @@ -118,4 +118,20 @@ Кандидат читает факты через `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, запрос `ListCandidateEvidenceFacts`); работодатель читает разрешенную проекцию через `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, которая выполняет проверки чтения карточки (`candidateview.Service.AuthorizeCategoriesSection`: членство, действующая публикация с C2, скрытие, минимальная когорта, квота, аудит доступа), а затем запрос `ListOrganizationVisibleEvidence` (представление действующих публикаций, `NOT EXISTS` по скрытым организациям, поле `categories`, видимые измерения, по одному факту на каждую категорию карточки, подтверждающему ее грейд, белый список из шести колонок: навык, грейд, доверие, основание, калибровка, год). Предпросмотр кандидата (`GetMyCardPreview`) показывает тот же раздел через `ListCandidatePreviewEvidence`. Чтения трогают только две таблицы доказательств; `backend/db/evidence_queries_test.go` падает, если запрос доказательств называет таблицу результатов, попыток, ответов, сигналов или проверок. Факты, теги и правила описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#доказательства-навыков). Интеграционный тест `TestSkillEvidenceOverHTTP` выполняется на настоящем PostgreSQL и проверяет: факт, связанный с результатом, с доверием 1, два дополнительных тега одного события, экспресс-прогон и проваленная попытка, постраничное чтение, проекция организации при выданном и отозванном C2, скрытая организация, скрытый факт, карточка без категорий теги, которые могут присоединиться к факту только в создавшей его транзакции, удаление аккаунта с фактами по обоим каскадным путям, отказ откатывать миграцию, пока есть скрытый факт, и перестроение после отката и повторного применения миграции. +## Подбор + +`POST /api/v1/organizations/{org_id}/matches` ранжирует банк кандидатов, видимый организации, без ML (`usecase/matching/`). Он выполняется в одной транзакции: `candidateview.Service.ListVisibleCards` применяет проверки чтения карточки (подтвержденный работодатель, заблокированное действующее членство, `ListVisibleCandidateViewSources` по `candidate_effective_publications` с `NOT EXISTS` по скрытым организациям, блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти), снимок потребности читается по `requirements_version`, а разрешенные доказательства приходят только из `ListOrganizationFacts`. Usecase повторяет проверку роли владельца; HTTP-граница перечисляет операцию в `ownerCompanyOperations`. Поиск оплачивается как чтение карточек: каждая группа обрезается до предела политики, а каждый возвращенный кандидат резервируется через порт квоты компании и записывается в историю доступа с возвращенными полями (`candidateview.SearchViews`); когда лимит заканчивается, ответ обрезается и получает флаг `truncated`. Раздел подбора оператор публикует командой `make policy-publish ARGS='matching --actor operator:'` (`cmd/policy-publish`), см. [DEPLOY](../docs/ru/DEPLOY.md#политика-подбора-на-стенде). + +Каждая запись - одна специализация кандидата. Баллы используют раздел `matching` действующей политики `product` (`domain.MatchingPolicy`, демонстрационная версия `DemoProductPolicyV4`); политика без раздела приводит к закрытому отказу. Арифметика целочисленная (микроединицы для компонентов, базисные пункты для долей), поэтому порядок воспроизводим: подтвержденные группы сортируются по S, затем по покрытию, затем по внутреннему идентификатору кандидата; неподтвержденная - по Fit, затем по покрытию, затем по идентификатору, и она никогда не вычисляет theta, T, P, перцентиль или S. Объяснение и признаки неизвестности строятся из тех же рассчитанных вкладов. Модель, нейтральные значения и нереализованное описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение). + +Интеграционный тест `TestMatchSearchOverHTTP` работает на настоящем PostgreSQL через настоящий маршрутизатор и операции профиля, согласий, публикации, потребностей, организаций и оценки: скрытые кандидаты и две организации, потребность и ее измененные требования, повторные одинаковые ответы, один handle подтвержден по Backend и не подтвержден по сетям, профиль без грейда, опубликованный и убранный отзывом C2, кандидат один в своей когорте, отсутствие контактов и идентификаторов в теле, оплата и история доступа за поиск, организация с лимитом меньше ее банка, предел группы, отказы доступа и политика без раздела. Браузерный стенд `questionnaire-fixture` публикует `DemoProductPolicyV4`, поэтому локальный стенд имеет раздел подбора. + Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md). + +## Внутренние уведомления + +Inbox хранит ссылку на доставленное событие для одного получателя (`notification_inbox_events`, миграции 32 и 36), но не его текст. Обработчик `notification_inbox` (`usecase/notification/inbox_handler.go`) пишет строку в транзакции своего dedup-маркера; ключ `(recipient_user_id, event_id)` держит одну строку на получателя и событие, а ID события, пришедший снова с другими метаданными, отклоняется. Строка существует независимо от того, отправлено ли письмо, и обработчик не читает состояние почты. + +Текст вычисляется при чтении списка (`usecase/notification/inbox.go`, `inbox_content.go`): `InboxService` проверяет кабинет в транзакции чтения (подтвержденный кандидат для `GET /api/v1/me/notifications`; подтвержденный работодатель с активным членством для `GET /api/v1/organizations/{org_id}/notifications`), затем просит преобразователь типа источника каждого элемента дать содержимое, которое получатель вправе видеть сейчас. Исчезнувший или скрытый источник оставляет элемент в списке без содержимого. Отметка (`POST .../{notification_id}/read`) сохраняет первое время прочтения и не читает источник. Чужой элемент, элемент другой организации и неизвестный элемент дают 404. + +Источник добавляет событие `invitation.delivered` с payload `recipient_user_id` и `organization_id` и регистрирует преобразователь для своего источника; синтетическое событие `notification.synthetic_delivered` проверяет путь и продуктового смысла не имеет. Контракт описан в [docs/ru/ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#внутренние-уведомления) и [api/README.md](../api/README.md#уведомления); пока ни одно приглашение не создает событие. diff --git a/backend/cmd/company-fixture/main.go b/backend/cmd/company-fixture/main.go index 76aceda..c0f25fd 100644 --- a/backend/cmd/company-fixture/main.go +++ b/backend/cmd/company-fixture/main.go @@ -12,6 +12,7 @@ import ( "errors" "io" "log" + "log/slog" "mime" "net/http" "os" @@ -45,6 +46,7 @@ type membershipRevoker func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) er type fixtureHandler struct { token string revoke membershipRevoker + notices *noticeFixture requests atomic.Uint32 } @@ -98,6 +100,20 @@ func serve() error { revoke: func(ctx context.Context, organizationID, userID, successorUserID uuid.UUID) error { return postgres.RevokeCompanyFixtureMembership(ctx, pool, organizationID, userID, successorUserID) }, + notices: newNoticeFixture( + postgres.NewTransactor(pool), + postgres.NewEventConsumerStore(pool, requestTimeout), + func(ctx context.Context, recipientID, organizationID uuid.UUID) error { + return postgres.CheckNotificationFixtureScope(ctx, pool, recipientID, organizationID) + }, + func(ctx context.Context, eventID uuid.UUID) (outbound.ConsumedEvent, error) { + return postgres.NotificationFixtureEvent(ctx, pool, eventID) + }, + func(ctx context.Context, recipientID, organizationID uuid.UUID) error { + return postgres.HideNotificationFixtureOrganization(ctx, pool, recipientID, organizationID) + }, + slog.New(slog.DiscardHandler), + ), }, ReadHeaderTimeout: readHeaderTimeout, ReadTimeout: readTimeout, @@ -142,6 +158,8 @@ func (handler *fixtureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) handler.serveHealthcheck(w, r) case fixtureEndpoint: handler.serveMembershipRevocation(w, r) + case noticeEndpoint, noticeReplayEndpoint, noticeHideEndpoint: + handler.serveNotice(w, r) default: w.WriteHeader(http.StatusNotFound) } diff --git a/backend/cmd/company-fixture/notifications.go b/backend/cmd/company-fixture/notifications.go new file mode 100644 index 0000000..126d89c --- /dev/null +++ b/backend/cmd/company-fixture/notifications.go @@ -0,0 +1,232 @@ +//go:build e2e + +package main + +import ( + "context" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" +) + +// The notification endpoints share the process, the bearer token, and the +// isolated database of the membership fixture. They let the browser suite +// put a synthetic event into the real outbox, so the relay, the event bus, +// and the inbox consumer deliver it, and then replay it the way an +// at-least-once bus does. +const ( + noticeEndpoint = "/notifications/synthetic" + noticeReplayEndpoint = "/notifications/synthetic/replay" + noticeHideEndpoint = "/notifications/synthetic/hide-organization" + renamedInboxConsumer = "notification_inbox_replayed" + noticeConsumerTimeout = requestTimeout +) + +// noticeFixture is the data access of the notification endpoints. +type noticeFixture struct { + // publish appends one synthetic event to the outbox and returns its ID. + publish func(ctx context.Context, recipientID, organizationID uuid.UUID) (uuid.UUID, error) + // replay delivers the event again to the inbox consumer and to a consumer + // of another name. It reports whether each delivery stored a new row + // claim, which is false for a duplicate. + replay func(ctx context.Context, eventID uuid.UUID) (noticeReplayResult, error) + // hide records that the recipient hides the organization. + hide func(ctx context.Context, recipientID, organizationID uuid.UUID) error +} + +type noticeReplayResult struct { + // PrimaryApplied is true when the inbox consumer had not processed the + // event yet. The browser suite waits for the real consumer first, so it + // expects false. + PrimaryApplied bool `json:"primary_applied"` + // RenamedApplied is true for a consumer without a marker for the event; + // the inbox key must still keep one row. + RenamedApplied bool `json:"renamed_applied"` +} + +type noticeRequest struct { + RecipientUserID string `json:"recipient_user_id"` + OrganizationID string `json:"organization_id"` + EventID string `json:"event_id"` +} + +func newNoticeFixture( + transactor outbound.Transactor, + store outbound.EventConsumerStore, + check func(ctx context.Context, recipientID, organizationID uuid.UUID) error, + readEvent func(ctx context.Context, eventID uuid.UUID) (outbound.ConsumedEvent, error), + hide func(ctx context.Context, recipientID, organizationID uuid.UUID) error, + logger *slog.Logger, +) *noticeFixture { + inbox := notification.NewInboxHandler(logger, true) + return ¬iceFixture{ + publish: func(ctx context.Context, recipientID, organizationID uuid.UUID) (uuid.UUID, error) { + if err := check(ctx, recipientID, organizationID); err != nil { + return uuid.Nil, err + } + payload, err := notification.SyntheticNoticeEventPayload(recipientID, organizationID) + if err != nil { + return uuid.Nil, err + } + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: string(domain.NotificationInboxSyntheticDelivered), SchemaVersion: 1, + AggregateType: notification.SyntheticNoticeAggregateType, AggregateID: uuid.New(), + AggregateVersion: notification.SyntheticNoticeAggregateVersion, Payload: payload, + }) + if err != nil { + return uuid.Nil, err + } + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Outbox().Append(ctx, event) + }) + return event.EventID(), err + }, + replay: func(ctx context.Context, eventID uuid.UUID) (noticeReplayResult, error) { + event, err := readEvent(ctx, eventID) + if err != nil { + return noticeReplayResult{}, err + } + apply := func(ctx context.Context, unit outbound.UnitOfWork) error { + return inbox.Handle(ctx, unit, event) + } + var result noticeReplayResult + if result.PrimaryApplied, err = store.ApplyOnce(ctx, notification.InboxConsumerName, event.EventID, apply); err != nil { + return noticeReplayResult{}, err + } + if result.RenamedApplied, err = store.ApplyOnce(ctx, renamedInboxConsumer, event.EventID, apply); err != nil { + return noticeReplayResult{}, err + } + return result, nil + }, + hide: hide, + } +} + +func (handler *fixtureHandler) serveNotice(w http.ResponseWriter, r *http.Request) { + if handler.notices == nil { + w.WriteHeader(http.StatusNotFound) + return + } + if !handler.admit(w, r) { + return + } + request, status := decodeNoticeRequest(w, r) + if status != 0 { + w.WriteHeader(status) + return + } + ctx, cancel := context.WithTimeout(r.Context(), noticeConsumerTimeout) + defer cancel() + switch r.URL.Path { + case noticeEndpoint: + recipientID, organizationID, ok := noticeIdentities(request) + if !ok { + w.WriteHeader(http.StatusBadRequest) + return + } + eventID, err := handler.notices.publish(ctx, recipientID, organizationID) + if err != nil { + w.WriteHeader(statusForNoticeError(err)) + return + } + writeNoticeJSON(w, http.StatusCreated, map[string]string{"event_id": eventID.String()}) + case noticeReplayEndpoint: + eventID, err := uuid.Parse(request.EventID) + if err != nil || eventID == uuid.Nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := handler.notices.replay(ctx, eventID) + if err != nil { + w.WriteHeader(statusForNoticeError(err)) + return + } + writeNoticeJSON(w, http.StatusOK, result) + case noticeHideEndpoint: + recipientID, organizationID, ok := noticeIdentities(request) + if !ok { + w.WriteHeader(http.StatusBadRequest) + return + } + if err := handler.notices.hide(ctx, recipientID, organizationID); err != nil { + w.WriteHeader(statusForNoticeError(err)) + return + } + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +// admit applies the checks that every mutating fixture request passes: the +// method, the request budget, the bearer token, and the JSON media type. +func (handler *fixtureHandler) admit(w http.ResponseWriter, r *http.Request) bool { + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + w.WriteHeader(http.StatusMethodNotAllowed) + return false + } + if handler.requests.Add(1) > maxFixtureRequests { + w.WriteHeader(http.StatusTooManyRequests) + return false + } + if !hasFixtureBearerToken(r.Header.Get("Authorization"), handler.token) { + w.WriteHeader(http.StatusUnauthorized) + return false + } + if !isJSONRequest(r) { + w.WriteHeader(http.StatusUnsupportedMediaType) + return false + } + return true +} + +func decodeNoticeRequest(w http.ResponseWriter, r *http.Request) (noticeRequest, int) { + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBody)) + decoder.DisallowUnknownFields() + var request noticeRequest + if err := decoder.Decode(&request); err != nil { + return noticeRequest{}, statusForDecodeError(err) + } + var trailing any + if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) { + return noticeRequest{}, statusForDecodeError(err) + } + return request, 0 +} + +func noticeIdentities(request noticeRequest) (recipientID, organizationID uuid.UUID, ok bool) { + recipientID, recipientErr := uuid.Parse(request.RecipientUserID) + organizationID, organizationErr := uuid.Parse(request.OrganizationID) + return recipientID, organizationID, recipientErr == nil && organizationErr == nil && + recipientID != uuid.Nil && organizationID != uuid.Nil +} + +func statusForNoticeError(err error) int { + switch { + case errors.Is(err, postgres.ErrCompanyFixtureScope), + errors.Is(err, outbound.ErrUserNotFound), + errors.Is(err, outbound.ErrOrganizationNotFound), + errors.Is(err, outbound.ErrNotificationInboxEntryNotFound): + return http.StatusNotFound + case errors.Is(err, outbound.ErrTransactionConflict): + return http.StatusConflict + default: + return http.StatusInternalServerError + } +} + +func writeNoticeJSON(w http.ResponseWriter, status int, body any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(body) +} diff --git a/backend/cmd/company-fixture/notifications_test.go b/backend/cmd/company-fixture/notifications_test.go new file mode 100644 index 0000000..7011c39 --- /dev/null +++ b/backend/cmd/company-fixture/notifications_test.go @@ -0,0 +1,86 @@ +//go:build e2e + +package main + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/port/outbound" +) + +func TestNoticeEndpointsNeedTheBearerAndDecodeStrictly(t *testing.T) { + recipientID, organizationID, eventID := uuid.New(), uuid.New(), uuid.New() + var published, hidden int + handler := &fixtureHandler{ + token: strings.Repeat("ab", 32), + notices: ¬iceFixture{ + publish: func(_ context.Context, gotRecipient, gotOrganization uuid.UUID) (uuid.UUID, error) { + published++ + if gotRecipient != recipientID || gotOrganization != organizationID { + t.Fatalf("publish IDs = %s/%s, want %s/%s", gotRecipient, gotOrganization, recipientID, organizationID) + } + return eventID, nil + }, + replay: func(_ context.Context, got uuid.UUID) (noticeReplayResult, error) { + if got != eventID { + t.Fatalf("replay event = %s, want %s", got, eventID) + } + return noticeReplayResult{RenamedApplied: true}, nil + }, + hide: func(context.Context, uuid.UUID, uuid.UUID) error { + hidden++ + return postgres.ErrCompanyFixtureScope + }, + }, + } + bearer := "Bearer " + handler.token + body := `{"recipient_user_id":"` + recipientID.String() + `","organization_id":"` + organizationID.String() + `"}` + + if response := fixtureRequest(handler, http.MethodPost, noticeEndpoint, body, "Bearer "+strings.Repeat("cd", 32), "application/json"); response.Code != http.StatusUnauthorized || published != 0 { + t.Fatalf("unauthorized publish = %d, published %d", response.Code, published) + } + response := fixtureRequest(handler, http.MethodPost, noticeEndpoint, body, bearer, "application/json") + var created struct { + EventID uuid.UUID `json:"event_id"` + } + if response.Code != http.StatusCreated || json.Unmarshal(response.Body.Bytes(), &created) != nil || created.EventID != eventID { + t.Fatalf("publish = %d %s, want 201 with the event ID", response.Code, response.Body.String()) + } + replay := fixtureRequest(handler, http.MethodPost, noticeReplayEndpoint, `{"event_id":"`+eventID.String()+`"}`, bearer, "application/json") + var result noticeReplayResult + if replay.Code != http.StatusOK || json.Unmarshal(replay.Body.Bytes(), &result) != nil || result.PrimaryApplied || !result.RenamedApplied { + t.Fatalf("replay = %d %s, want 200 with a duplicate for the primary consumer", replay.Code, replay.Body.String()) + } + if hide := fixtureRequest(handler, http.MethodPost, noticeHideEndpoint, body, bearer, "application/json"); hide.Code != http.StatusNotFound || hidden != 1 { + t.Fatalf("hide outside the fixture scope = %d, want 404", hide.Code) + } + for name, test := range map[string]struct { + path, body string + want int + }{ + "unknown field": {noticeEndpoint, `{"recipient_user_id":"` + recipientID.String() + `","organization_id":"` + organizationID.String() + `","email":"x"}`, http.StatusBadRequest}, + "bad recipient": {noticeEndpoint, `{"recipient_user_id":"x","organization_id":"` + organizationID.String() + `"}`, http.StatusBadRequest}, + "nil event": {noticeReplayEndpoint, `{"event_id":"` + uuid.Nil.String() + `"}`, http.StatusBadRequest}, + "trailing content": {noticeEndpoint, body + " {}", http.StatusBadRequest}, + } { + if got := fixtureRequest(handler, http.MethodPost, test.path, test.body, bearer, "application/json"); got.Code != test.want { + t.Errorf("%s = %d, want %d", name, got.Code, test.want) + } + } + if got := fixtureRequest(handler, http.MethodGet, noticeEndpoint, "", bearer, ""); got.Code != http.StatusMethodNotAllowed { + t.Errorf("GET = %d, want 405", got.Code) + } + if statusForNoticeError(outbound.ErrOrganizationNotFound) != http.StatusNotFound { + t.Error("an unknown organization must answer 404") + } + if got := fixtureRequest(&fixtureHandler{token: handler.token}, http.MethodPost, noticeEndpoint, body, bearer, "application/json"); got.Code != http.StatusNotFound { + t.Errorf("a handler without notices = %d, want 404", got.Code) + } +} diff --git a/backend/cmd/policy-publish/main.go b/backend/cmd/policy-publish/main.go new file mode 100644 index 0000000..d0c436c --- /dev/null +++ b/backend/cmd/policy-publish/main.go @@ -0,0 +1,29 @@ +// Command policy-publish adds the demo matching section to the product +// policy of a stand. It publishes a new immutable version and changes nothing +// else. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/backend/internal/adapter/primary/cli/policypublish" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := policypublish.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout, time.Now); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "policy-publish: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/cmd/questionnaire-fixture/main.go b/backend/cmd/questionnaire-fixture/main.go index d81af80..1e3000a 100644 --- a/backend/cmd/questionnaire-fixture/main.go +++ b/backend/cmd/questionnaire-fixture/main.go @@ -315,8 +315,9 @@ func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) ( } // The isolated browser fixture opts into the extended demo policy explicitly, -// including the manual-review band thresholds. Normal startup still seeds V1, -// and an operator's policy must never be replaced. +// including the manual-review band thresholds and the matching coefficients. +// Normal startup still seeds V1, and an operator's policy must never be +// replaced. func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) { initial, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, @@ -345,7 +346,7 @@ func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) ( } version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return databaseTime }).Publish(ctx, policy.PublishInput{ Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, - Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV3(), + Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV4(), }) return err }) diff --git a/backend/config/config.go b/backend/config/config.go index 350abd2..a985d2e 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -63,6 +63,10 @@ type Config struct { // ConsumerEnabled runs the registered event consumers next to the HTTP // servers. ConsumerEnabled bool + // NotificationSyntheticEnabled lets the inbox consume and render the + // synthetic notification event. Off by default; a development or browser + // test stand turns it on. + NotificationSyntheticEnabled bool // ConsumerGroupPrefix and a consumer name form the consumer group ID. ConsumerGroupPrefix string ConsumerMaxAttempts int @@ -191,6 +195,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { if err := config.loadConsumer(lookup); err != nil { return Config{}, err } + if err := config.loadNotification(lookup); err != nil { + return Config{}, err + } if err := config.loadJobs(lookup); err != nil { return Config{}, err } diff --git a/backend/config/notification.go b/backend/config/notification.go new file mode 100644 index 0000000..f68fe9a --- /dev/null +++ b/backend/config/notification.go @@ -0,0 +1,12 @@ +package config + +// defaultNotificationSyntheticEnabled keeps the synthetic inbox event off: +// a production deployment neither consumes nor renders it. A development or +// browser-test stand turns it on. +const defaultNotificationSyntheticEnabled = false + +func (config *Config) loadNotification(lookup LookupEnv) error { + var err error + config.NotificationSyntheticEnabled, err = boolOrDefault(lookup, "NOTIFICATION_SYNTHETIC_ENABLED", defaultNotificationSyntheticEnabled) + return err +} diff --git a/backend/config/notification_test.go b/backend/config/notification_test.go new file mode 100644 index 0000000..434213c --- /dev/null +++ b/backend/config/notification_test.go @@ -0,0 +1,17 @@ +package config + +import "testing" + +func TestLoadFromEnvReadsTheSyntheticNotificationSwitch(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil || settings.NotificationSyntheticEnabled { + t.Fatalf("default = %t, %v, want off", settings.NotificationSyntheticEnabled, err) + } + settings, err = LoadFromEnv(testEnvironment(map[string]string{"NOTIFICATION_SYNTHETIC_ENABLED": " True "})) + if err != nil || !settings.NotificationSyntheticEnabled { + t.Fatalf("enabled = %t, %v, want on", settings.NotificationSyntheticEnabled, err) + } + if _, err := LoadFromEnv(testEnvironment(map[string]string{"NOTIFICATION_SYNTHETIC_ENABLED": "yes"})); err == nil { + t.Fatal("LoadFromEnv() accepted a value that is not true or false") + } +} diff --git a/backend/db/evidence_queries_test.go b/backend/db/evidence_queries_test.go index 1782e4e..3a0c5ea 100644 --- a/backend/db/evidence_queries_test.go +++ b/backend/db/evidence_queries_test.go @@ -12,7 +12,9 @@ import ( var ( evidenceTableName = regexp.MustCompile(`(?i)\bskill_evidence_(facts|skills)\b`) // evidenceReaders are the only queries that may name the evidence tables. - evidenceReaders = []string{"ListCandidateEvidenceFacts", "ListCandidatePreviewEvidence", "ListOrganizationVisibleEvidence"} + evidenceReaders = []string{ + "ListCandidateEvidenceFacts", "ListCandidatePreviewEvidence", "ListOrganizationVisibleEvidence", "ListOrganizationVisibleEvidenceBatch", + } // evidenceForbiddenSources are tables whose content must never reach the // evidence reads: raw answers and items, results with their scores, // attempts, signals, and the anti-cheat review band. @@ -123,3 +125,41 @@ func TestOrganizationEvidenceReadUsesTheVisibilityBarrier(t *testing.T) { t.Errorf("organization evidence query reads the publication table directly: %s", statement) } } + +// The batch read repeats every barrier of the single organization read, and +// the match-search queries name no evidence table. +func TestOrganizationEvidenceBatchReadRepeatsTheVisibilityBarrier(t *testing.T) { + statements := evidenceStatements(t) + statement := statements["ListOrganizationVisibleEvidenceBatch"] + if statement == "" { + t.Fatal("the batch organization evidence query is missing") + } + for _, required := range []string{ + "inner join candidate_effective_publications as effective", + "from candidate_hidden_organizations as hidden", + "not exists", + "hidden.organization_id = sqlc.arg(organization_id)", + "'categories' = any(effective.fields)", + "fact.visibility = 'visible'", + "fact.kind = 'measurement'", + "(skill.skill_code || '/' || fact.grade) = wanted.category", + } { + if !strings.Contains(statement, required) { + t.Errorf("batch organization evidence query lacks %q: %s", required, statement) + } + } + if strings.Contains(statement, "candidate_publications") && !strings.Contains(statement, "candidate_effective_publications") { + t.Errorf("batch organization evidence query reads the publication table directly: %s", statement) + } + for _, private := range []string{"fact.id,", "event_id", "result_id", "fact.visibility,", "occurred_at,"} { + selected := statement[len("select"):strings.Index(statement, " from (")] + if strings.Contains(selected, private) { + t.Errorf("batch organization evidence query selects %q: %s", private, selected) + } + } + for name, search := range statements { + if strings.HasPrefix(name, "CountReal") && evidenceTableName.MatchString(search) { + t.Errorf("%s names an evidence table: %s", name, search) + } + } +} diff --git a/backend/db/migrations/00036_allow_synthetic_notification_event.sql b/backend/db/migrations/00036_allow_synthetic_notification_event.sql new file mode 100644 index 0000000..a87a8d1 --- /dev/null +++ b/backend/db/migrations/00036_allow_synthetic_notification_event.sql @@ -0,0 +1,48 @@ +-- The inbox allowlist gains a synthetic event type. It carries no product +-- meaning: it lets the consumer, the read-time visibility check, the list, +-- and the read state run end to end before real producers exist. Each event +-- type is bound to the one source type its content is resolved from. +-- +goose Up +ALTER TABLE notification_inbox_events +DROP CONSTRAINT notification_inbox_events_type_known; + +ALTER TABLE notification_inbox_events +ADD CONSTRAINT notification_inbox_events_type_known CHECK ( + schema_version = 1 + AND ( + (event_type = 'invitation.delivered' AND source_type = 'invitation') + OR ( + event_type = 'notification.synthetic_delivered' + AND source_type = 'organization' + ) + ) +); + +-- A rollback must not silently lose or orphan recipient-visible history. +-- +goose Down +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM notification_inbox_events + WHERE event_type <> 'invitation.delivered' + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'notification_inbox_events_type_known', + TABLE = 'notification_inbox_events', + MESSAGE = 'synthetic notification inbox records must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE notification_inbox_events +DROP CONSTRAINT notification_inbox_events_type_known; + +ALTER TABLE notification_inbox_events +ADD CONSTRAINT notification_inbox_events_type_known CHECK ( + event_type = 'invitation.delivered' + AND schema_version = 1 + AND source_type = 'invitation' +); diff --git a/backend/db/queries/candidate_search.sql b/backend/db/queries/candidate_search.sql new file mode 100644 index 0000000..50a33cb --- /dev/null +++ b/backend/db/queries/candidate_search.sql @@ -0,0 +1,18 @@ +-- Reads that only the match search needs. The visibility of the candidates and +-- their permitted evidence come from the card and evidence queries, which are +-- the single copy of those barriers; this file adds no candidate-facing read. + +-- The number of candidates who hold each given category from a source that is +-- not a synthetic demonstration, which is the size of the comparable real +-- cohort that a percentile needs. It returns counts only, for the pairs the +-- caller passes as "specialization/grade", and no row for a pair nobody holds. +-- name: CountRealComparableCategories :many +SELECT + category.specialization, + category.grade, + count(*)::bigint AS candidates +FROM candidate_assessment_categories AS category +WHERE + category.source <> 'synthetic_demo' + AND (category.specialization || '/' || category.grade) = any(sqlc.arg(categories)::text []) +GROUP BY category.specialization, category.grade; diff --git a/backend/db/queries/company_quota.sql b/backend/db/queries/company_quota.sql index 345be7d..3b45536 100644 --- a/backend/db/queries/company_quota.sql +++ b/backend/db/queries/company_quota.sql @@ -2,6 +2,20 @@ -- finally usage rows. The organization lock serializes quota decisions for -- the tenant and makes the subsequent count and insert atomic. +-- Takes the organization lock ahead of every share lock of a reader that will +-- reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR +-- SHARE, so readers of one organization queue up instead of deadlocking on a +-- share lock that each then tries to raise, but it does not conflict with the +-- FOR KEY SHARE that a foreign key takes, such as the hidden-organization +-- insert of a candidate, which holds the candidate's row and then needs this +-- one. The reservation itself still takes FOR UPDATE inside the same +-- transaction. +-- name: LockCompanyQuotaOrganizationFirst :one +SELECT id +FROM organizations +WHERE id = sqlc.arg(organization_id) +FOR NO KEY UPDATE; + -- name: LockCompanyQuotaOrganization :one SELECT id, diff --git a/backend/db/queries/evidence.sql b/backend/db/queries/evidence.sql index 1b35b71..f12a3a4 100644 --- a/backend/db/queries/evidence.sql +++ b/backend/db/queries/evidence.sql @@ -103,3 +103,48 @@ WHERE AND fact.kind = 'measurement' AND fact.visibility = 'visible' ORDER BY skill.skill_code, fact.occurred_at, fact.id; + +-- The same organization read for a whole candidate set, so a search reads the +-- evidence of every listed candidate in one statement. The pairs come from the +-- caller as two parallel arrays, one row per candidate and category of the card +-- that was just projected. The statement repeats every barrier of the single +-- read: the effective publication view, NOT EXISTS over the candidates that +-- hide the organization, the categories field, and only visible measurements. +-- The candidate identifier is returned for the caller to group by and never +-- leaves the server; the other columns are the same allowlist. +-- name: ListOrganizationVisibleEvidenceBatch :many +SELECT DISTINCT ON (wanted.candidate_id, skill.skill_code) + wanted.candidate_id::uuid AS candidate_id, + skill.skill_code AS skill, + fact.grade, + fact.trust, + fact.basis, + fact.calibration_status, + extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year +FROM ( + SELECT + candidate_ids.candidate_id, + wanted_categories.category + FROM unnest(sqlc.arg(candidate_ids)::uuid []) WITH ORDINALITY AS candidate_ids (candidate_id, position) + INNER JOIN unnest(sqlc.arg(categories)::text []) WITH ORDINALITY AS wanted_categories (category, position) + ON candidate_ids.position = wanted_categories.position +) AS wanted +INNER JOIN candidate_effective_publications AS effective + ON wanted.candidate_id = effective.user_id +INNER JOIN skill_evidence_facts AS fact + ON effective.user_id = fact.candidate_id +INNER JOIN skill_evidence_skills AS skill + ON fact.id = skill.fact_id +WHERE + 'categories' = any(effective.fields) + AND (skill.skill_code || '/' || fact.grade) = wanted.category + AND fact.kind = 'measurement' + AND fact.visibility = 'visible' + AND NOT EXISTS ( + SELECT 1 + FROM candidate_hidden_organizations AS hidden + WHERE + hidden.user_id = effective.user_id + AND hidden.organization_id = sqlc.arg(organization_id) + ) +ORDER BY wanted.candidate_id, skill.skill_code, fact.occurred_at, fact.id; diff --git a/backend/db/queries/notification_inbox.sql b/backend/db/queries/notification_inbox.sql index 669f2e4..b66d095 100644 --- a/backend/db/queries/notification_inbox.sql +++ b/backend/db/queries/notification_inbox.sql @@ -69,13 +69,19 @@ WHERE recipient_user_id = sqlc.arg(recipient_user_id) ORDER BY occurred_at DESC, event_id DESC LIMIT sqlc.arg(page_limit); --- Persist the first read time under exact recipient and organization scope. --- Repeated calls preserve the original read timestamp. +-- Persist the first read time for the recipient, optionally under one exact +-- organization context. A missing organization is the candidate cabinet, +-- which spans the organizations that sent to it; the employer cabinet always +-- names its organization. Repeated calls preserve the original read +-- timestamp. -- name: MarkNotificationInboxEventRead :one UPDATE notification_inbox_events SET read_at = COALESCE(read_at, sqlc.arg(read_at)::timestamptz) WHERE recipient_user_id = sqlc.arg(recipient_user_id) - AND organization_id = sqlc.arg(organization_id) + AND ( + sqlc.narg(organization_id)::uuid IS NULL + OR organization_id = sqlc.narg(organization_id)::uuid + ) AND event_id = sqlc.arg(event_id) RETURNING recipient_user_id, @@ -87,3 +93,33 @@ RETURNING source_id, occurred_at, read_at; + +-- Resolve the sender organization of a synthetic notice under the recipient's +-- current standing, so the notice never outlives that standing. A candidate +-- sees the name only while the organization is not hidden from them; an +-- employer sees it only while they are an active member. No row means the +-- content is no longer visible to this recipient. +-- name: GetNotificationOrganizationNameForRecipient :one +SELECT organizations.name +FROM organizations +INNER JOIN users ON users.id = sqlc.arg(recipient_user_id) +WHERE organizations.id = sqlc.arg(organization_id) + AND ( + ( + users.scenario = 'candidate' + AND NOT EXISTS ( + SELECT 1 FROM candidate_hidden_organizations + WHERE candidate_hidden_organizations.user_id = users.id + AND candidate_hidden_organizations.organization_id = organizations.id + ) + ) + OR ( + users.scenario = 'employer' + AND EXISTS ( + SELECT 1 FROM memberships + WHERE memberships.user_id = users.id + AND memberships.organization_id = organizations.id + AND memberships.state = 'active' + ) + ) + ); diff --git a/backend/integration_test/assessment_attempt_http_test.go b/backend/integration_test/assessment_attempt_http_test.go index 07b84e2..6fa21ed 100644 --- a/backend/integration_test/assessment_attempt_http_test.go +++ b/backend/integration_test/assessment_attempt_http_test.go @@ -23,6 +23,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" httpadapter "lincodex/backend/internal/adapter/primary/http" + 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/adapter/secondary/argon2id" @@ -524,6 +525,21 @@ func newAssessmentAttemptHTTPHarnessWithOptions( env *testEnvironment, categories assessment.AssessmentCategoryDecisionSettings, extra func(assessmentHarnessParts) []v1.HandlerOption, +) *assessmentAttemptHTTPHarness { + t.Helper() + return newAssessmentAttemptHTTPHarnessWithMiddleware(ctx, t, env, categories, extra, nil) +} + +// newAssessmentAttemptHTTPHarnessWithMiddleware also mounts the operation +// middleware that middleware returns, after extra has built its handlers, so a +// scenario can add the owner company context to the same router. +func newAssessmentAttemptHTTPHarnessWithMiddleware( + ctx context.Context, + t *testing.T, + env *testEnvironment, + categories assessment.AssessmentCategoryDecisionSettings, + extra func(assessmentHarnessParts) []v1.HandlerOption, + middleware func() []apiadapter.Middleware, ) *assessmentAttemptHTTPHarness { t.Helper() pool := env.newPool(ctx, t) @@ -585,7 +601,11 @@ func newAssessmentAttemptHTTPHarnessWithOptions( options = append(options, extra(assessmentHarnessParts{pool: pool, transactor: transactor, keyring: keyring, clock: clock})...) } handler := v1.NewHandler(healthHandler, responder, options...) - router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil) + var operationMiddleware []apiadapter.Middleware + if middleware != nil { + operationMiddleware = middleware() + } + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil, operationMiddleware...) if err != nil { t.Fatalf("NewRouter() error = %v", err) } diff --git a/backend/integration_test/match_search_http_test.go b/backend/integration_test/match_search_http_test.go new file mode 100644 index 0000000..2ffbeb5 --- /dev/null +++ b/backend/integration_test/match_search_http_test.go @@ -0,0 +1,1347 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "math" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + apiadapter "lincodex/backend/internal/adapter/primary/http/api" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/candidateprivacy" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/evidence" + "lincodex/backend/internal/usecase/matching" + needusecase "lincodex/backend/internal/usecase/need" + "lincodex/backend/internal/usecase/organization" + "lincodex/backend/internal/usecase/policy" + profileusecase "lincodex/backend/internal/usecase/profile" +) + +const matchSearchHTTPTimeout = 15 * time.Minute + +// matchScoreTolerance covers the six-decimal rounding of the response. +const matchScoreTolerance = 1.5e-6 + +type matchSearchHarness struct { + *assessmentAttemptHTTPHarness + key domain.CandidateViewPseudonymKey +} + +func newMatchSearchHarness(ctx context.Context, t *testing.T, env *testEnvironment) *matchSearchHarness { + t.Helper() + var key domain.CandidateViewPseudonymKey + var organizationHandler *v1.OrganizationHandler + harness := newAssessmentAttemptHTTPHarnessWithMiddleware(ctx, t, env, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}, + func(parts assessmentHarnessParts) []v1.HandlerOption { + var err error + if key, err = parts.keyring.CandidateViewPseudonymKey(); err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(parts.pool), key, parts.clock.Now) + quota := companyquota.NewService(parts.clock.Now) + views, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: parts.transactor, Projector: projector, PseudonymKey: key, Clock: parts.clock.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + settings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now}) + if err != nil { + t.Fatalf("candidateprivacy.NewService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{ + Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now, + }) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + needService, err := needusecase.NewService(needusecase.Dependencies{ + Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now, + }) + if err != nil { + t.Fatalf("need.NewService() error = %v", err) + } + search, err := matching.NewService(matching.Dependencies{ + Transactor: parts.transactor, Cards: views.ListVisibleCards, Clock: parts.clock.Now, + Views: func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (matching.ViewSession, error) { + session, err := views.BeginSearchViews(ctx, unit, actorID, organizationID) + if err != nil { + return nil, err + } + return session, nil + }, + }) + if err != nil { + t.Fatalf("matching.NewService() error = %v", err) + } + evidenceService, err := evidence.NewService(evidence.Dependencies{ + Transactor: parts.transactor, AuthorizeCategories: views.AuthorizeCategoriesSection, + }) + if err != nil { + t.Fatalf("evidence.NewService() error = %v", err) + } + organizationHandler = v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + return []v1.HandlerOption{ + v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)), + v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)), + v1.WithProfile(v1.NewProfileHandler(profileusecase.NewService(parts.transactor, parts.clock.Now))), + v1.WithOrganization(organizationHandler), + v1.WithNeed(v1.NewNeedHandler(needService)), + v1.WithMatches(v1.NewMatchHandler(search)), + } + }, + func() []apiadapter.Middleware { + return []apiadapter.Middleware{httpadapter.NewCompanyContextMiddleware(organizationHandler)} + }) + return &matchSearchHarness{assessmentAttemptHTTPHarness: harness, key: key} +} + +type matchEntryBody struct { + CandidateHandle string `json:"candidate_handle"` + Specialization string `json:"specialization"` + ConfirmationStatus string `json:"confirmation_status"` + DeclaredGrade *string `json:"declared_grade"` + Category *struct { + Specialization string `json:"specialization"` + Grade string `json:"grade"` + } `json:"category"` + Strength *string `json:"strength"` + PublicContext struct { + Stack []string `json:"stack"` + ExperienceBand *string `json:"experience_band"` + WorkFormats []string `json:"work_formats"` + SalaryCompatibility *string `json:"salary_compatibility"` + } `json:"public_context"` + EvidenceSummary []struct { + Code string `json:"code"` + State string `json:"state"` + } `json:"evidence_summary"` + Components map[string]*float64 `json:"components"` + UnknownFlags []struct { + Component string `json:"component"` + Reason string `json:"reason"` + } `json:"unknown_flags"` +} + +func (entry matchEntryBody) component(name string) float64 { + if value := entry.Components[name]; value != nil { + return *value + } + return math.NaN() +} + +func (entry matchEntryBody) summary() []string { + items := make([]string, 0, len(entry.EvidenceSummary)) + for _, item := range entry.EvidenceSummary { + items = append(items, item.Code+":"+item.State) + } + return items +} + +func (entry matchEntryBody) flags() []string { + flags := make([]string, 0, len(entry.UnknownFlags)) + for _, flag := range entry.UnknownFlags { + flags = append(flags, flag.Component+":"+flag.Reason) + } + return flags +} + +type matchSearchBody struct { + Source map[string]any `json:"source"` + Groups struct { + Main []matchEntryBody `json:"main"` + Near []matchEntryBody `json:"near"` + Unconfirmed []matchEntryBody `json:"unconfirmed"` + } `json:"groups"` + Truncated bool `json:"truncated"` +} + +func (body matchSearchBody) handles() map[string]string { + handles := make(map[string]string) + for group, entries := range map[string][]matchEntryBody{"main": body.Groups.Main, "near": body.Groups.Near, "unconfirmed": body.Groups.Unconfirmed} { + for _, entry := range entries { + handles[entry.CandidateHandle+"/"+entry.Specialization] = group + } + } + return handles +} + +func TestMatchSearchOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), matchSearchHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newMatchSearchHarness(ctx, t, &isolatedEnv) + // The scenarios below read banks of 11 and 16 entries, so the group limit is + // widened here; the demo value is checked by its own subtest. + wideLimit := func(product *domain.ProductPolicy) { product.Matching.MaxResultsPerGroup = 100 } + widePolicy := domain.DemoProductPolicyV4() + wideLimit(&widePolicy) + bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, widePolicy, true) + threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark)) + client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx} + transactor := postgresadapter.NewTransactor(harness.pool) + + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identity, transactor: transactor, now: now} + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, + organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + + const profileMarkers = "Private Marker" + allFields := []string{"categories", "stack", "experience", "self_assessment", "work_formats"} + unconfirmedFields := []string{"stack", "self_assessment", "work_formats"} + profileBody := func(stack []string, roles map[string]string) string { + stackItems := make([]map[string]any, 0, len(stack)) + for _, tag := range stack { + stackItems = append(stackItems, map[string]any{"tag": tag, "status": "confirmed"}) + } + roleItems := make([]map[string]any, 0, len(roles)) + for _, specialization := range []string{"backend", "network_engineer"} { + if grade, ok := roles[specialization]; ok { + roleItems = append(roleItems, map[string]any{"specialization": specialization, "self_assessed_grade": grade, "status": "confirmed"}) + } + } + body, err := json.Marshal(map[string]any{ + "expected_version": 0, + "full_name": map[string]any{"value": profileMarkers + " Name", "status": "confirmed"}, + "contacts": map[string]any{ + "email": map[string]any{"value": "private-marker-contact@example.test", "status": "confirmed"}, "phone": nil, "telegram": nil, + }, + "stack": stackItems, "roles": roleItems, + "experience": []any{map[string]any{ + "employer_name": profileMarkers + " Employer", "specialization": "backend", "started_on": "2020-01", + "ended_on": "2023-12", "summary": profileMarkers + " Summary", "status": "confirmed", + }}, + "confirmed_parallel_periods": []any{}, "soft_skills": []any{}, + "terms": map[string]any{ + "location": map[string]any{"value": profileMarkers + " Location", "status": "confirmed"}, "relocation": nil, + "salary_minimum": map[string]any{"value": map[string]any{ + "amount": 731000, "currency": "RUB", "period": "month", "tax_basis": "net", + }, "status": "confirmed"}, + }, + }) + if err != nil { + t.Fatalf("marshal profile: %v", err) + } + return string(body) + } + call := func(who categoryHTTPCandidate, method, path, body string) (int, []byte) { + t.Helper() + return client.call(t, who, method, path, body, "") + } + mustCall := func(who categoryHTTPCandidate, method, path, body string, want int) []byte { + t.Helper() + status, response := call(who, method, path, body) + if status != want { + t.Fatalf("%s %s for %s = %d %s, want %d", method, path, who.email, status, response, want) + } + return response + } + // publish saves a profile and publishes the given card fields through the + // real candidate operations: the profile, the C2 consent, and the + // publication setting. + publish := func(who categoryHTTPCandidate, stack []string, roles map[string]string, fields []string) { + t.Helper() + mustCall(who, http.MethodPut, "/api/v1/me/profile", profileBody(stack, roles), http.StatusOK) + mustCall(who, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK) + encoded, err := json.Marshal(fields) + if err != nil { + t.Fatalf("marshal fields: %v", err) + } + mustCall(who, http.MethodPut, "/api/v1/me/privacy/publication", + fmt.Sprintf(`{"expected_version":0,"state":"published","fields":%s}`, encoded), http.StatusOK) + } + passing := func(who categoryHTTPCandidate) attemptRun { + t.Helper() + run := client.run(t, who, "backend", "intern", func(int) int { return threshold }) + if run.result["outcome"] != "confirmed" || decisionOf(t, run.result)["status"] != "assigned" { + t.Fatalf("passing run of %s = %v, want a confirmed assigned category", who.email, run.result) + } + return run + } + + bothRoles := map[string]string{"backend": "junior", "network_engineer": "middle"} + backendRole := map[string]string{"backend": "junior"} + + // G1: confirmed Backend with the Go tag; seven candidates so that each + // organization still sees six after one is hidden from it. + withGo := make([]categoryHTTPCandidate, 0, 7) + for index := range 7 { + member := client.candidate(t, fmt.Sprintf("match-go-%d@example.test", index)) + passing(member) + publish(member, []string{"go"}, bothRoles, allFields) + withGo = append(withGo, member) + } + // G2: the same confirmed category without any stack tag. + withoutStack := make([]categoryHTTPCandidate, 0, 5) + var promotionSource attemptRun + for index := range 5 { + member := client.candidate(t, fmt.Sprintf("match-plain-%d@example.test", index)) + run := passing(member) + if index == 4 { + promotionSource = run + } + publish(member, nil, bothRoles, allFields) + withoutStack = append(withoutStack, member) + } + // U: a declared Backend without a confirmed grade. One of them failed the + // attempt, which must change nothing in the result. + declaredOnly := make([]categoryHTTPCandidate, 0, 5) + for index := range 5 { + member := client.candidate(t, fmt.Sprintf("match-declared-%d@example.test", index)) + if index == 0 { + failed := client.run(t, member, "backend", "intern", func(int) int { return threshold - 1 }) + if failed.result["outcome"] != "not_confirmed" { + t.Fatalf("failing run = %v, want not_confirmed", failed.result["outcome"]) + } + } + publish(member, []string{"go"}, backendRole, unconfirmedFields) + declaredOnly = append(declaredOnly, member) + } + + employer := client.employer(t, "match-employer@example.test") + foreign := client.employer(t, "match-foreign@example.test") + recruiter := client.employer(t, "match-recruiter@example.test") + candidateOnly := client.candidate(t, "match-candidate-only@example.test") + orgA := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization A"), now) + orgB := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization B"), now) + foreignOrg := organizations.create(t, domain.User{ID: foreign.id}, organizations.completeProfile(t, "Match foreign organization"), now) + insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA.ID(), recruiter.id, "recruiter", "active", now) + hiddenFromA, hiddenFromB := withGo[0], withGo[1] + privacy.hide(t, hiddenFromA.id, orgA.ID(), now) + privacy.hide(t, hiddenFromB.id, orgB.ID(), now) + // The policy and the organizations take effect when they are stored, which + // is after the clock of the harness was read. + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond)) + + candidateIDs := make(map[uuid.UUID]string) + for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} { + for _, member := range group { + candidateIDs[member.id] = member.email + } + } + aliasIn := func(organizationID, candidateID uuid.UUID) string { + t.Helper() + alias, err := harness.key.ForOrganization(organizationID, candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return alias + } + candidateOfHandle := func(organizationID uuid.UUID) map[string]uuid.UUID { + handles := make(map[string]uuid.UUID, len(candidateIDs)) + for id := range candidateIDs { + handles[aliasIn(organizationID, id)] = id + } + return handles + } + searchPath := func(organizationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/matches", organizationID) + } + search := func(who categoryHTTPCandidate, organizationID uuid.UUID, body string) (matchSearchBody, *httptest.ResponseRecorder) { + t.Helper() + response := harness.request(t, http.MethodPost, searchPath(organizationID), body, sessionHTTPTestOrigin, who.cookie, who.csrf, client.remote()) + var decoded matchSearchBody + if response.Code == http.StatusOK { + if err := json.Unmarshal(response.Body.Bytes(), &decoded); err != nil { + t.Fatalf("decode search result: %v\n%s", err, response.Body.String()) + } + } + return decoded, response + } + mustSearch := func(organizationID uuid.UUID, body string) matchSearchBody { + t.Helper() + result, response := search(employer, organizationID, body) + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("search = %d Cache-Control=%q %s, want a no-store 200", response.Code, response.Header().Get("Cache-Control"), response.Body.String()) + } + return result + } + handlesOf := func(entries []matchEntryBody) []string { + handles := make([]string, 0, len(entries)) + for _, entry := range entries { + handles = append(handles, entry.CandidateHandle) + } + return handles + } + handlesFor := func(organizationID uuid.UUID, groups ...[]categoryHTTPCandidate) []string { + var handles []string + for _, group := range groups { + for _, member := range group { + handles = append(handles, aliasIn(organizationID, member.id)) + } + } + slices.Sort(handles) + return handles + } + sortedHandles := func(entries []matchEntryBody) []string { + handles := handlesOf(entries) + slices.Sort(handles) + return handles + } + almost := func(got, want float64) bool { return math.Abs(got-want) <= matchScoreTolerance } + assertScores := func(t *testing.T, label string, entries []matchEntryBody, want map[string]float64) { + t.Helper() + for _, entry := range entries { + for name, value := range want { + if got := entry.component(name); !almost(got, value) { + t.Errorf("%s entry %s %s = %v, want %v", label, entry.Specialization, name, got, value) + } + } + } + } + // assertOrder checks the documented order of a group from the internal + // identifiers that the test knows and the response never shows. + assertOrder := func(t *testing.T, organizationID uuid.UUID, entries []matchEntryBody, confirmed bool) { + t.Helper() + candidates := candidateOfHandle(organizationID) + for index := 1; index < len(entries); index++ { + previous, current := entries[index-1], entries[index] + var previousKeys, currentKeys []float64 + if confirmed { + previousKeys = []float64{previous.component("rank_score"), previous.component("coverage")} + currentKeys = []float64{current.component("rank_score"), current.component("coverage")} + } else { + previousKeys = []float64{previous.component("fit"), previous.component("coverage")} + currentKeys = []float64{current.component("fit"), current.component("coverage")} + } + for key := range previousKeys { + if previousKeys[key] > currentKeys[key] { + break + } + if previousKeys[key] < currentKeys[key] { + t.Fatalf("entry %d precedes %d although its scores are lower: %v then %v", index-1, index, previousKeys, currentKeys) + } + if key == len(previousKeys)-1 { + previousID, currentID := candidates[previous.CandidateHandle].String(), candidates[current.CandidateHandle].String() + if previousID > currentID || (previousID == currentID && previous.Specialization > current.Specialization) { + t.Fatalf("equal scores are not ordered by the internal identifier: %s before %s", previousID, currentID) + } + } + } + } + } + countRows := func(query string, args ...any) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { + t.Fatalf("count rows: %v", err) + } + return count + } + revealedBy := func(organizationID uuid.UUID) int { + t.Helper() + return countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1`, organizationID) + } + historyOf := func(candidateID, organizationID uuid.UUID) [][]string { + t.Helper() + rows, err := harness.pool.Query(ctx, `SELECT field_codes FROM candidate_card_access_events + WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' ORDER BY occurred_at, id`, candidateID, organizationID) + if err != nil { + t.Fatalf("read access history: %v", err) + } + defer rows.Close() + var history [][]string + for rows.Next() { + var fields []string + if err := rows.Scan(&fields); err != nil { + t.Fatalf("scan access history: %v", err) + } + history = append(history, fields) + } + return history + } + clockOffset := time.Minute + publishPolicy := func(change func(*domain.ProductPolicy)) { + t.Helper() + product := domain.DemoProductPolicyV4() + wideLimit(&product) + if change != nil { + change(&product) + } + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now) + if _, err := publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: policyTestAuthor, Policy: product, + }); err != nil { + t.Fatalf("Publish(policy) error = %v", err) + } + clockOffset += time.Minute + harness.clock.Set(time.Now().UTC().Add(clockOffset).Truncate(time.Microsecond)) + } + createNeed := func(organizationID uuid.UUID, body, key string) (uuid.UUID, int64) { + t.Helper() + status, response := client.call(t, employer, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/needs", organizationID), body, key) + var need struct { + ID uuid.UUID `json:"id"` + Version int64 `json:"version"` + RequirementsVersion int64 `json:"requirements_version"` + } + if status != http.StatusCreated || json.Unmarshal(response, &need) != nil || need.ID == uuid.Nil { + t.Fatalf("create need = %d %s, want 201", status, response) + } + return need.ID, need.RequirementsVersion + } + patchNeed := func(organizationID, needID uuid.UUID, body string) (version, requirementsVersion int64) { + t.Helper() + status, response := client.call(t, employer, http.MethodPatch, fmt.Sprintf("/api/v1/organizations/%s/needs/%s", organizationID, needID), body, "") + var need struct { + Version int64 `json:"version"` + RequirementsVersion int64 `json:"requirements_version"` + } + if status != http.StatusOK || json.Unmarshal(response, &need) != nil { + t.Fatalf("patch need = %d %s, want 200", status, response) + } + return need.Version, need.RequirementsVersion + } + needRequest := func(needID uuid.UUID, version int64, filters string) string { + body := fmt.Sprintf(`{"need_id":%q,"requirements_version":%d`, needID, version) + if filters != "" { + body += `,"filters":` + filters + } + return body + "}" + } + + // The standing cohort sizes: each organization sees six of the seven + // candidates with the Go tag and all five of the others. + t.Run("the bank search applies visibility and hiding before any group and keeps an unconfirmed category visible", func(t *testing.T) { + bankA := mustSearch(orgA.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`) + if bankA.Truncated { + t.Fatal("a result under the group limit and the allowance is flagged as truncated") + } + wantA := handlesFor(orgA.ID(), withGo[1:], withoutStack) + if got := sortedHandles(bankA.Groups.Main); !slices.Equal(got, wantA) || len(bankA.Groups.Near) != 0 || len(bankA.Groups.Unconfirmed) != 0 { + t.Fatalf("organization A confirmed bank = %d main, %d near, %d unconfirmed; want exactly the eleven visible confirmed candidates", + len(bankA.Groups.Main), len(bankA.Groups.Near), len(bankA.Groups.Unconfirmed)) + } + if slices.Contains(handlesOf(bankA.Groups.Main), aliasIn(orgA.ID(), hiddenFromA.id)) { + t.Fatal("organization A received a candidate that hides it") + } + bankB := mustSearch(orgB.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`) + wantB := handlesFor(orgB.ID(), append([]categoryHTTPCandidate{withGo[0]}, withGo[2:]...), withoutStack) + if got := sortedHandles(bankB.Groups.Main); !slices.Equal(got, wantB) { + t.Fatalf("organization B main handles = %v, want %v", got, wantB) + } + if slices.Contains(handlesOf(bankB.Groups.Main), aliasIn(orgB.ID(), hiddenFromB.id)) { + t.Fatal("organization B received a candidate that hides it") + } + // The same candidate has a different handle in each organization. + if aliasIn(orgA.ID(), withGo[2].id) == aliasIn(orgB.ID(), withGo[2].id) { + t.Fatal("organizations share a candidate handle") + } + + for _, entry := range append(bankA.Groups.Main, bankB.Groups.Main...) { + if entry.ConfirmationStatus != "confirmed" || entry.Category == nil || entry.Category.Specialization != "backend" || + entry.Category.Grade != "intern" || entry.Strength == nil || *entry.Strength != "standard" { + t.Fatalf("confirmed entry = %+v, want the confirmed Backend intern category", entry) + } + if entry.Components["percentile"] != nil || entry.component("competition") != 0 || !almost(entry.component("semantics"), 0.5) || + !slices.Contains(entry.flags(), "semantics:ml_unavailable") || !slices.Contains(entry.flags(), "percentile:cohort_below_30") { + t.Fatalf("confirmed entry components = %v flags %v, want neutral Sem, no percentile, and V = 0", entry.Components, entry.flags()) + } + } + + // Without a filter the same bank also lists the specializations that + // are only declared; a missing confirmation never hides a profile. + general := mustSearch(orgA.ID(), `{"filters":{}}`) + if len(general.Groups.Main) != 11 || len(general.Groups.Near) != 0 { + t.Fatalf("general search = %d main, %d near, want eleven main and no near without a request for skills", len(general.Groups.Main), len(general.Groups.Near)) + } + var networks, backendDeclared []string + for _, entry := range general.Groups.Unconfirmed { + switch entry.Specialization { + case "network_engineer": + networks = append(networks, entry.CandidateHandle) + case "backend": + backendDeclared = append(backendDeclared, entry.CandidateHandle) + } + if entry.ConfirmationStatus != "unconfirmed" || entry.Category != nil || entry.Strength != nil { + t.Fatalf("unconfirmed entry = %+v, want no category and no strength", entry) + } + } + slices.Sort(networks) + slices.Sort(backendDeclared) + if !slices.Equal(networks, handlesFor(orgA.ID(), withGo[1:], withoutStack)) || + !slices.Equal(backendDeclared, handlesFor(orgA.ID(), declaredOnly)) || len(general.Groups.Unconfirmed) != 11+5 { + t.Fatalf("unconfirmed group = %d entries (networks %d, declared Backend %d), want 16", len(general.Groups.Unconfirmed), len(networks), len(backendDeclared)) + } + assertScores(t, "general unconfirmed", general.Groups.Unconfirmed, map[string]float64{"fit": 0.5, "coverage": 0.5}) + assertScores(t, "general confirmed", general.Groups.Main, map[string]float64{"fit": 0.5, "coverage": 0.5, "rank_score": 0.45125}) + if source, _ := general.Source["kind"].(string); source != "bank" { + t.Fatalf("source = %v, want the bank basis", general.Source) + } + }) + + var needID uuid.UUID + var needRequirementsV1 int64 + var firstNeedSearch, secondNeedSearch matchSearchBody + var secondRequirementsVersion int64 + t.Run("a need search scores the confirmed requirements and the explanation follows the same components", func(t *testing.T) { + needID, needRequirementsV1 = createNeed(orgA.ID(), + `{"title":"Payments backend","specialization":{"value":"backend","status":"confirmed"},"required_skills":[{"name":"Go","status":"confirmed"}]}`, + "match-need-1") + firstNeedSearch = mustSearch(orgA.ID(), needRequest(needID, needRequirementsV1, "")) + if source := firstNeedSearch.Source; source["kind"] != "need" || source["need_id"] != needID.String() || source["requirements_version"] != float64(needRequirementsV1) { + t.Fatalf("source = %v, want the need snapshot", source) + } + // A Go tag is a stated claim worth 0.25 and meets the near threshold; a + // backend measurement is broader than the requested skill, worth + // 0.6 * 1.0 * 0.4 = 0.24, and falls below it. + if got, want := sortedHandles(firstNeedSearch.Groups.Main), handlesFor(orgA.ID(), withGo[1:]); !slices.Equal(got, want) { + t.Fatalf("main = %v, want the six candidates with the Go tag", got) + } + if got, want := sortedHandles(firstNeedSearch.Groups.Near), handlesFor(orgA.ID(), withoutStack); !slices.Equal(got, want) { + t.Fatalf("near = %v, want the five candidates without the tag", got) + } + if got, want := sortedHandles(firstNeedSearch.Groups.Unconfirmed), handlesFor(orgA.ID(), declaredOnly); !slices.Equal(got, want) { + t.Fatalf("unconfirmed = %v, want the five declared Backend profiles, and no other specialization of a Backend need", got) + } + assertScores(t, "main", firstNeedSearch.Groups.Main, map[string]float64{"coverage": 0.25, "fit": 0.3125, "rank_score": 0.366641}) + assertScores(t, "near", firstNeedSearch.Groups.Near, map[string]float64{"coverage": 0.24, "fit": 0.305, "rank_score": 0.363256}) + assertScores(t, "unconfirmed", firstNeedSearch.Groups.Unconfirmed, map[string]float64{"coverage": 0.25, "fit": 0.3125}) + wantMain := []string{"confirmed_category:supports", "declared_grade:declared_only", "required_skill_evidence:declared_only"} + wantNear := []string{"confirmed_category:supports", "declared_grade:declared_only", "required_skill_evidence:partial"} + wantUnconfirmed := []string{"declared_grade:declared_only", "required_skill_evidence:declared_only"} + for _, check := range []struct { + entries []matchEntryBody + want []string + }{{firstNeedSearch.Groups.Main, wantMain}, {firstNeedSearch.Groups.Near, wantNear}, {firstNeedSearch.Groups.Unconfirmed, wantUnconfirmed}} { + for _, entry := range check.entries { + if got := entry.summary(); !slices.Equal(got, check.want) { + t.Fatalf("explanation of %s = %v, want %v", entry.Specialization, got, check.want) + } + } + } + + // Changing the required skills moves the numbers, the groups, and the + // explanation together. + version, requirementsVersion := patchNeed(orgA.ID(), needID, + `{"expected_version":1,"required_skills":[{"name":"Go","status":"confirmed"},{"name":"Kafka","status":"confirmed"}]}`) + secondRequirementsVersion = requirementsVersion + if requirementsVersion != version || requirementsVersion == needRequirementsV1 { + t.Fatalf("requirements version after the change = %d (version %d), want a new snapshot", requirementsVersion, version) + } + secondNeedSearch = mustSearch(orgA.ID(), needRequest(needID, requirementsVersion, "")) + if len(secondNeedSearch.Groups.Main) != 0 || len(secondNeedSearch.Groups.Near) != 11 || len(secondNeedSearch.Groups.Unconfirmed) != 5 { + t.Fatalf("second search = %d main, %d near, %d unconfirmed, want every confirmed profile in near", len(secondNeedSearch.Groups.Main), len(secondNeedSearch.Groups.Near), len(secondNeedSearch.Groups.Unconfirmed)) + } + for _, entry := range secondNeedSearch.Groups.Near { + if entry.PublicContext.Stack == nil { + assertScores(t, "near without a tag", []matchEntryBody{entry}, map[string]float64{"coverage": 0.24, "fit": 0.305, "rank_score": 0.363256}) + continue + } + // (2 * 0.25 + 2 * 0.24) / 4 = 0.245 + assertScores(t, "near with the Go tag", []matchEntryBody{entry}, map[string]float64{"coverage": 0.245, "fit": 0.30875, "rank_score": 0.364948}) + if got := entry.summary(); !slices.Equal(got, []string{"confirmed_category:supports", "declared_grade:declared_only", "required_skill_evidence:partial"}) { + t.Fatalf("explanation with the Kafka requirement = %v", got) + } + } + // (2 * 0.25 + 2 * 0) / 4 = 0.125: Kafka has no evidence, and that is a gap, not a ban. + assertScores(t, "unconfirmed", secondNeedSearch.Groups.Unconfirmed, map[string]float64{"coverage": 0.125, "fit": 0.21875}) + for _, entry := range secondNeedSearch.Groups.Unconfirmed { + if got := entry.summary(); !slices.Equal(got, []string{"declared_grade:declared_only", "required_skill_evidence:partial"}) { + t.Fatalf("explanation of an unconfirmed entry with the Kafka requirement = %v", got) + } + } + + // The first snapshot is immutable: it answers as it did. + again := mustSearch(orgA.ID(), needRequest(needID, needRequirementsV1, "")) + if !jsonEqual(t, again, firstNeedSearch) { + t.Fatal("the search of the first requirements version changed after the need was edited") + } + // A title edit makes a need version but no requirements version. + titleVersion, titleRequirements := patchNeed(orgA.ID(), needID, `{"expected_version":2,"title":"Payments backend team"}`) + if titleVersion != 3 || titleRequirements != secondRequirementsVersion { + t.Fatalf("title edit = version %d, requirements %d, want 3 and %d", titleVersion, titleRequirements, secondRequirementsVersion) + } + if _, response := search(employer, orgA.ID(), needRequest(needID, titleVersion, "")); response.Code != http.StatusNotFound { + t.Fatalf("search by a need version that is not a requirements version = %d, want 404", response.Code) + } + if _, response := search(employer, orgA.ID(), needRequest(needID, secondRequirementsVersion+5, "")); response.Code != http.StatusNotFound { + t.Fatalf("search by an unknown requirements version = %d, want 404", response.Code) + } + // Another organization cannot search a need it does not own. + if _, response := search(employer, orgB.ID(), needRequest(needID, needRequirementsV1, "")); response.Code != http.StatusNotFound { + t.Fatalf("search of a need of another organization = %d, want 404", response.Code) + } + if _, response := search(employer, orgA.ID(), needRequest(uuid.New(), 1, "")); response.Code != http.StatusNotFound { + t.Fatalf("search of an unknown need = %d, want 404", response.Code) + } + // A need without a confirmed specialization searches every + // specialization, and the unconfirmed group then mixes them: Fit + // decides, then coverage, then the internal identifier. + anyID, anyVersion := createNeed(orgA.ID(), + `{"title":"Any specialization","required_skills":[{"name":"Go","status":"confirmed"},{"name":"Kafka","status":"confirmed"}]}`, + "match-need-any") + anySearch := mustSearch(orgA.ID(), needRequest(anyID, anyVersion, "")) + if len(anySearch.Groups.Main) != 0 || len(anySearch.Groups.Near) != 11 || len(anySearch.Groups.Unconfirmed) != 16 { + t.Fatalf("search without a need specialization = %d main, %d near, %d unconfirmed, want 0, 11, 16", + len(anySearch.Groups.Main), len(anySearch.Groups.Near), len(anySearch.Groups.Unconfirmed)) + } + // The five Networks entries of candidates without the Go tag have no + // evidence for either skill and come last, as a gap and not as a ban. + lastFive := anySearch.Groups.Unconfirmed[11:] + for _, entry := range lastFive { + if entry.Specialization != "network_engineer" || entry.component("coverage") != 0 || !almost(entry.component("fit"), 0.125) { + t.Fatalf("last unconfirmed entry = %+v %v, want a Networks entry without evidence", entry.Specialization, entry.Components) + } + if got := entry.summary(); !slices.Equal(got, []string{"declared_grade:declared_only", "required_skill_evidence:gap"}) { + t.Fatalf("explanation of an entry without evidence = %v", got) + } + } + assertScores(t, "unconfirmed with evidence", anySearch.Groups.Unconfirmed[:11], map[string]float64{"coverage": 0.125, "fit": 0.21875}) + assertOrder(t, orgA.ID(), anySearch.Groups.Unconfirmed, false) + assertOrder(t, orgA.ID(), anySearch.Groups.Near, true) + // A different specialization filter than the need leaves nothing. + empty := mustSearch(orgA.ID(), needRequest(needID, needRequirementsV1, `{"specialization":"frontend"}`)) + if len(empty.Groups.Main)+len(empty.Groups.Near)+len(empty.Groups.Unconfirmed) != 0 { + t.Fatalf("search with a specialization filter that contradicts the need returned entries: %+v", empty.Groups) + } + }) + + t.Run("the same data and policy give the same order and scores, and each organization its own handles", func(t *testing.T) { + request := needRequest(needID, needRequirementsV1, "") + var first []byte + for range 3 { + _, response := search(employer, orgA.ID(), request) + if response.Code != http.StatusOK { + t.Fatalf("repeat search = %d %s", response.Code, response.Body.String()) + } + if first == nil { + first = bytes.Clone(response.Body.Bytes()) + } else if !bytes.Equal(first, response.Body.Bytes()) { + t.Fatalf("repeat search changed:\n%s\n%s", first, response.Body.Bytes()) + } + } + assertOrder(t, orgA.ID(), firstNeedSearch.Groups.Main, true) + assertOrder(t, orgA.ID(), firstNeedSearch.Groups.Near, true) + assertOrder(t, orgA.ID(), firstNeedSearch.Groups.Unconfirmed, false) + assertOrder(t, orgA.ID(), secondNeedSearch.Groups.Near, true) + // Organization B sees the bank through its own handles and its own + // hiding, with the same scores. + bank := `{"filters":{"specialization":"backend"}}` + forA, forB := mustSearch(orgA.ID(), bank), mustSearch(orgB.ID(), bank) + for _, handle := range handlesOf(forB.Groups.Main) { + if slices.Contains(handlesOf(forA.Groups.Main), handle) { + t.Fatalf("handle %s is shared by two organizations", handle) + } + } + if slices.Contains(handlesOf(forB.Groups.Main), aliasIn(orgB.ID(), hiddenFromB.id)) || !slices.Contains(handlesOf(forB.Groups.Main), aliasIn(orgB.ID(), hiddenFromA.id)) { + t.Fatal("organization B does not get exactly the cards that are not hidden from B") + } + }) + + t.Run("a candidate keeps a separate state for each specialization", func(t *testing.T) { + general := mustSearch(orgA.ID(), `{"filters":{}}`) + member := withGo[3] + handle := aliasIn(orgA.ID(), member.id) + var confirmedEntry, networkEntry *matchEntryBody + for index := range general.Groups.Main { + if general.Groups.Main[index].CandidateHandle == handle { + confirmedEntry = &general.Groups.Main[index] + } + } + for index := range general.Groups.Unconfirmed { + if general.Groups.Unconfirmed[index].CandidateHandle == handle { + networkEntry = &general.Groups.Unconfirmed[index] + } + } + if confirmedEntry == nil || networkEntry == nil || confirmedEntry.Specialization != "backend" || networkEntry.Specialization != "network_engineer" { + t.Fatalf("entries of one handle = %+v and %+v, want confirmed Backend and unconfirmed Networks", confirmedEntry, networkEntry) + } + if confirmedEntry.DeclaredGrade == nil || *confirmedEntry.DeclaredGrade != "junior" || + networkEntry.DeclaredGrade == nil || *networkEntry.DeclaredGrade != "middle" { + t.Fatalf("declared grades = %v and %v, want junior for Backend and middle for Networks", confirmedEntry.DeclaredGrade, networkEntry.DeclaredGrade) + } + if got := networkEntry.flags(); !slices.Equal(got, []string{ + "semantics:ml_unavailable", "assessment:no_confirmation_for_specialization", "salary_compatibility:not_in_public_card", "domain:need_field_unconfirmed", + }) { + t.Fatalf("unknown flags of the unconfirmed entry = %v", got) + } + // The unconfirmed object holds a fit and a coverage and nothing else: + // no theta, T, P, percentile, or rank score. + if len(networkEntry.Components) != 2 || networkEntry.Components["fit"] == nil || networkEntry.Components["coverage"] == nil { + t.Fatalf("unconfirmed components = %v, want only fit and coverage", networkEntry.Components) + } + // A search for Networks shows Backend's confirmation nowhere. + networks := mustSearch(orgA.ID(), `{"filters":{"specialization":"network_engineer"}}`) + if len(networks.Groups.Main)+len(networks.Groups.Near) != 0 || len(networks.Groups.Unconfirmed) != 11 { + t.Fatalf("Networks search = %d confirmed, %d unconfirmed, want 11 unconfirmed and no transferred confirmation", + len(networks.Groups.Main)+len(networks.Groups.Near), len(networks.Groups.Unconfirmed)) + } + // An explicit filter on a confirmed grade or category excludes every + // unconfirmed profile; a declared grade is a separate claim. + for _, filters := range []string{ + `{"confirmed_grade":"intern"}`, `{"confirmed_category":{"specialization":"backend","grade":"intern"}}`, `{"confirmation_status":"confirmed"}`, + } { + filtered := mustSearch(orgA.ID(), fmt.Sprintf(`{"filters":%s}`, filters)) + if len(filtered.Groups.Unconfirmed) != 0 || len(filtered.Groups.Main) != 11 { + t.Fatalf("filters %s = %d main, %d unconfirmed, want only the confirmed profiles", filters, len(filtered.Groups.Main), len(filtered.Groups.Unconfirmed)) + } + } + if filtered := mustSearch(orgA.ID(), `{"filters":{"confirmed_grade":"senior"}}`); len(filtered.Groups.Main)+len(filtered.Groups.Unconfirmed) != 0 { + t.Fatalf("a confirmed senior filter matched %d entries, want none", len(filtered.Groups.Main)+len(filtered.Groups.Unconfirmed)) + } + onlyUnconfirmed := mustSearch(orgA.ID(), `{"filters":{"confirmation_status":"unconfirmed"}}`) + if len(onlyUnconfirmed.Groups.Main)+len(onlyUnconfirmed.Groups.Near) != 0 || len(onlyUnconfirmed.Groups.Unconfirmed) != 16 { + t.Fatalf("unconfirmed-only search = %d entries, want the 16 unconfirmed", len(onlyUnconfirmed.Groups.Unconfirmed)) + } + declared := mustSearch(orgA.ID(), `{"filters":{"declared_grade":"middle"}}`) + if len(declared.Groups.Main)+len(declared.Groups.Near) != 0 || len(declared.Groups.Unconfirmed) != 11 { + t.Fatalf("declared middle search = %d entries, want the 11 Networks declarations and no confirmed entry", len(declared.Groups.Unconfirmed)) + } + // Safe card conditions and stack filters narrow the visible set. + stack := mustSearch(orgA.ID(), `{"filters":{"stack":["go"]}}`) + if len(stack.Groups.Main) != 6 || len(stack.Groups.Unconfirmed) != 6+5 { + t.Fatalf("stack filter = %d main, %d unconfirmed, want the six candidates with the tag and their entries", len(stack.Groups.Main), len(stack.Groups.Unconfirmed)) + } + conditions := mustSearch(orgA.ID(), `{"filters":{"conditions":{"work_formats":["office"]}}}`) + if len(conditions.Groups.Main)+len(conditions.Groups.Near)+len(conditions.Groups.Unconfirmed) != 0 { + t.Fatal("a work format that no card offers matched a candidate") + } + remote := mustSearch(orgA.ID(), `{"filters":{"conditions":{"work_formats":["remote","office"],"salary_compatibility":"compatible"}}}`) + if len(remote.Groups.Main)+len(remote.Groups.Near)+len(remote.Groups.Unconfirmed) != 0 { + t.Fatal("an unknown salary compatibility satisfied a compatibility filter") + } + if remoteOnly := mustSearch(orgA.ID(), `{"filters":{"conditions":{"work_formats":["remote"]}}}`); len(remoteOnly.Groups.Main) != 11 { + t.Fatalf("remote filter = %d main, want 11", len(remoteOnly.Groups.Main)) + } + }) + + t.Run("a failed promotion keeps the confirmed category and leaves no trace in the result", func(t *testing.T) { + member := withoutStack[4] + before := mustSearch(orgA.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`) + // The promotion interval counts on database time, so the finished + // intern attempt is moved past it instead of waiting for days. + moveFinishedAttemptBack(t, ctx, harness.pool, promotionSource.id, categoryHTTPPromotionGap) + failed := client.run(t, member, "backend", "junior", func(int) int { return threshold - 1 }) + if failed.result["outcome"] != "not_confirmed" || failed.result["previous_confirmed_grade"] != "intern" { + t.Fatalf("failed promotion = %v, want not_confirmed with the intern grade in force", failed.result) + } + after := mustSearch(orgA.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`) + if !jsonEqual(t, before, after) { + t.Fatal("a failed promotion changed the search result: the confirmed grade must stay and the failure must not count") + } + }) + + t.Run("the response holds no contact, minimum, identifier, failure, or percentile", func(t *testing.T) { + _, response := search(employer, orgA.ID(), `{"filters":{}}`) + text := response.Body.String() + for _, forbidden := range []string{ + profileMarkers, "private-marker-contact", "731000", "email", "phone", "telegram", "salary_minimum", "full_name", "location", + "theta", "not_confirmed", "failed", "attempt", "answer", "score_id", "fsp", "FSP", "policy", orgA.ID().String(), orgB.ID().String(), + } { + if strings.Contains(text, forbidden) { + t.Fatalf("search result contains %q: %s", forbidden, text) + } + } + for id, email := range candidateIDs { + if strings.Contains(text, id.String()) || strings.Contains(text, email) { + t.Fatalf("search result contains an account identifier or email of %s", email) + } + } + // The candidate whose attempt failed is scored exactly like the others + // who declared the same profile: no failure and no missing FSP is a penalty. + var reference *matchEntryBody + for index, entry := range mustSearch(orgA.ID(), `{"filters":{"specialization":"backend","confirmation_status":"unconfirmed"}}`).Groups.Unconfirmed { + if index == 0 { + reference = &entry + continue + } + if entry.component("fit") != reference.component("fit") || entry.component("coverage") != reference.component("coverage") { + t.Fatalf("an unconfirmed entry is scored differently from its twin: %v vs %v", entry.Components, reference.Components) + } + } + }) + + t.Run("a search is charged like card reads and the candidate sees it in the access history", func(t *testing.T) { + // Each organization has paid once for each candidate it was shown: the + // sixteen visible ones, never the candidate who hides it, and the + // organizations are counted independently. + if got := revealedBy(orgA.ID()); got != 16 { + t.Fatalf("organization A paid for %d candidates, want 16", got) + } + if got := revealedBy(orgB.ID()); got != 16 { + t.Fatalf("organization B paid for %d candidates, want 16", got) + } + if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgA.ID(), hiddenFromA.id) != 0 || + countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgB.ID(), hiddenFromB.id) != 0 { + t.Fatal("an organization paid for a candidate who hides it") + } + if countRows(`SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2`, hiddenFromA.id, orgA.ID()) != 0 { + t.Fatal("a candidate who hides the organization has a card view from it") + } + // The history names the fields actually returned: a candidate with a + // confirmed category shows all five published fields in a full search and + // a declared profile never shows the ones it did not publish. + confirmedHistory := historyOf(withGo[3].id, orgA.ID()) + fullFields := []string{"categories", "experience", "self_assessment", "stack", "work_formats"} + full := false + for _, fields := range confirmedHistory { + full = full || slices.Equal(fields, fullFields) + for _, field := range fields { + if !slices.Contains(fullFields, field) { + t.Fatalf("history of a confirmed candidate names %q, which no entry shows", field) + } + } + } + if len(confirmedHistory) == 0 || !full { + t.Fatalf("history of a confirmed candidate = %v, want card views including the five fields", confirmedHistory) + } + declaredHistory := historyOf(declaredOnly[1].id, orgA.ID()) + if len(declaredHistory) == 0 { + t.Fatal("a declared candidate has no card view in the history") + } + for _, fields := range declaredHistory { + if !slices.Equal(fields, []string{"self_assessment", "stack", "work_formats"}) { + t.Fatalf("history of a declared candidate = %v, want only the published declared fields", fields) + } + } + // Repeating the search charges nothing new, and a card read afterwards + // does not charge a second time. + before := revealedBy(orgA.ID()) + mustSearch(orgA.ID(), `{"filters":{}}`) + if revealedBy(orgA.ID()) != before { + t.Fatal("a repeated search charged the organization again") + } + // A search that is refused writes nothing. + eventsBefore := countRows(`SELECT count(*) FROM candidate_card_access_events`) + if _, response := search(recruiter, orgA.ID(), `{"filters":{}}`); response.Code != http.StatusForbidden { + t.Fatalf("recruiter search = %d, want 403", response.Code) + } + if countRows(`SELECT count(*) FROM candidate_card_access_events`) != eventsBefore || revealedBy(orgA.ID()) != before { + t.Fatal("a refused search charged or recorded") + } + }) + + t.Run("a profile published without a grade appears last, a confirmed filter excludes it, and a revoked C2 removes it", func(t *testing.T) { + extra := client.candidate(t, "match-declared-extra@example.test") + handle := aliasIn(orgA.ID(), extra.id) + candidateIDs[extra.id] = extra.email + listed := func() string { + result := mustSearch(orgA.ID(), `{"filters":{}}`) + return result.handles()[handle+"/backend"] + } + if listed() != "" { + t.Fatal("an unpublished profile is listed") + } + publish(extra, []string{"go"}, backendRole, unconfirmedFields) + if group := listed(); group != "unconfirmed" { + t.Fatalf("a profile published without a grade is in group %q, want unconfirmed", group) + } + for _, filters := range []string{`{"confirmed_grade":"intern"}`, `{"confirmation_status":"confirmed"}`, `{"confirmed_category":{"specialization":"backend","grade":"junior"}}`} { + if _, listed := mustSearch(orgA.ID(), fmt.Sprintf(`{"filters":%s}`, filters)).handles()[handle+"/backend"]; listed { + t.Fatalf("filters %s kept an unconfirmed profile", filters) + } + } + mustCall(extra, http.MethodDelete, "/api/v1/me/consents/c2", "", http.StatusNoContent) + if group := listed(); group != "" { + t.Fatalf("a profile whose C2 was revoked is still in group %q", group) + } + }) + + t.Run("a card that the cohort rules suppress is not searched, and a listed handle opens as a card", func(t *testing.T) { + single := client.candidate(t, "match-unique@example.test") + candidateIDs[single.id] = single.email + publish(single, []string{"kafka"}, map[string]string{"backend": "senior"}, unconfirmedFields) + handle := aliasIn(orgA.ID(), single.id) + general := mustSearch(orgA.ID(), `{"filters":{}}`) + if _, listed := general.handles()[handle+"/backend"]; listed { + t.Fatal("a profile alone in its cohort is listed although its card would not open") + } + if got := harness.request(t, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgA.ID(), handle), "", + "", employer.cookie, "", client.remote()); got.Code != http.StatusNotFound { + t.Fatalf("card of the suppressed profile = %d, want 404", got.Code) + } + if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgA.ID(), single.id) != 0 || + len(historyOf(single.id, orgA.ID())) != 0 { + t.Fatal("a suppressed profile was charged or recorded") + } + opened := general.Groups.Main[0].CandidateHandle + openedID := candidateOfHandle(orgA.ID())[opened] + paid, seen := revealedBy(orgA.ID()), len(historyOf(openedID, orgA.ID())) + if got := harness.request(t, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgA.ID(), opened), "", + "", employer.cookie, "", client.remote()); got.Code != http.StatusOK { + t.Fatalf("card of a listed handle = %d %s, want 200", got.Code, got.Body.String()) + } + // The candidate was already paid for by the search, so opening the card + // charges nothing again, and the card read is one more history entry. + if revealedBy(orgA.ID()) != paid || len(historyOf(openedID, orgA.ID())) != seen+1 { + t.Fatalf("after the card read: paid %d (was %d), history %d (was %d), want no new charge and one new entry", + revealedBy(orgA.ID()), paid, len(historyOf(openedID, orgA.ID())), seen) + } + }) + + t.Run("only the active owner of the organization may search, and the body is closed", func(t *testing.T) { + body := `{"filters":{}}` + path := searchPath(orgA.ID()) + unauthenticated := harness.request(t, http.MethodPost, path, body, sessionHTTPTestOrigin, "", "", client.remote()) + requireSessionProblem(t, unauthenticated, http.StatusUnauthorized, "unauthenticated") + if _, response := search(candidateOnly, orgA.ID(), body); response.Code != http.StatusForbidden { + t.Fatalf("candidate account search = %d, want 403", response.Code) + } + if _, response := search(foreign, orgA.ID(), body); response.Code != http.StatusNotFound { + t.Fatalf("search of an organization without membership = %d, want 404", response.Code) + } + if _, response := search(employer, uuid.New(), body); response.Code != http.StatusNotFound { + t.Fatalf("search of an unknown organization = %d, want 404", response.Code) + } + // A recruiter has an active membership, which grants nothing without + // the owner role in the minimal milestone. + if _, response := search(recruiter, orgA.ID(), body); response.Code != http.StatusForbidden { + t.Fatalf("recruiter search = %d, want 403", response.Code) + } + noCSRF := harness.request(t, http.MethodPost, path, body, sessionHTTPTestOrigin, employer.cookie, "", client.remote()) + requireSessionProblem(t, noCSRF, http.StatusForbidden, "csrf_check_failed") + foreignOrigin := harness.request(t, http.MethodPost, path, body, "https://attacker.example", employer.cookie, employer.csrf, client.remote()) + requireSessionProblem(t, foreignOrigin, http.StatusForbidden, "csrf_check_failed") + for _, invalid := range []string{ + `{"filters":{"unknown":1}}`, `{"filters":{"stack":["go","go"]}}`, `{"filters":{"confirmed_grade":"principal"}}`, + `{"filters":{"conditions":{"salary_compatibility":"maybe"}}}`, `{"filters":{},"need_id":"` + uuid.NewString() + `"}`, `{}`, + } { + if _, response := search(employer, orgA.ID(), invalid); response.Code != http.StatusBadRequest { + t.Fatalf("search with body %s = %d %s, want 400", invalid, response.Code, response.Body.String()) + } + } + _ = foreignOrg + }) + + t.Run("the batch evidence read equals the single read and honors hiding", func(t *testing.T) { + categories := []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard}} + members := []categoryHTTPCandidate{withGo[0], withGo[2], withoutStack[0], declaredOnly[0]} + requests := make([]outbound.EvidenceCandidateCategories, 0, len(members)) + for _, member := range members { + requests = append(requests, outbound.EvidenceCandidateCategories{CandidateID: member.id, Categories: categories}) + } + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + batch, err := unit.Evidence().ListOrganizationFactsBatch(ctx, orgA.ID(), requests) + if err != nil { + return err + } + for _, member := range members { + single, err := unit.Evidence().ListOrganizationFacts(ctx, orgA.ID(), member.id, categories) + if err != nil { + return err + } + if len(batch[member.id]) != len(single) || len(single) > 0 && !reflect.DeepEqual(batch[member.id], single) { + t.Errorf("batch facts of %s = %v, single = %v", member.email, batch[member.id], single) + } + } + // The candidate who hides organization A and the candidate without a + // published category have no fact in the batch. + if len(batch[hiddenFromA.id]) != 0 || len(batch[declaredOnly[0].id]) != 0 || len(batch[withGo[2].id]) != 1 { + t.Errorf("batch = %v, want one fact for a visible confirmed candidate and none for hidden or declared ones", batch) + } + counts, err := unit.Evidence().CountComparableRealCategories(ctx, []outbound.CategoryKey{{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern}}) + if err != nil { + return err + } + if len(counts) != 0 { + t.Errorf("real cohort counts = %v, want none: every stored category is a synthetic demonstration", counts) + } + return nil + }) + if err != nil { + t.Fatalf("read evidence in a batch: %v", err) + } + }) + + t.Run("the allowance of an organization ends the output and the group limit cuts it, without a total", func(t *testing.T) { + orgC := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization C"), now) + bounded := func(product *domain.ProductPolicy) { + product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8 + } + publishPolicy(bounded) + searchC := func() (matchSearchBody, string) { + result, response := search(employer, orgC.ID(), `{"filters":{}}`) + if response.Code != http.StatusOK { + t.Fatalf("search of organization C = %d %s", response.Code, response.Body.String()) + } + return result, response.Body.String() + } + first, firstBody := searchC() + returned := len(first.Groups.Main) + len(first.Groups.Near) + len(first.Groups.Unconfirmed) + if !first.Truncated || len(first.Groups.Main) != 8 || returned != 8 || revealedBy(orgC.ID()) != 8 { + t.Fatalf("first search = %d main, %d near, %d unconfirmed, truncated %v, paid %d; want eight confirmed entries, the flag, and eight paid", + len(first.Groups.Main), len(first.Groups.Near), len(first.Groups.Unconfirmed), first.Truncated, revealedBy(orgC.ID())) + } + for _, forbidden := range []string{"total", "count", "remaining", "quota"} { + if strings.Contains(firstBody, forbidden) { + t.Fatalf("a truncated result exposes %q: %s", forbidden, firstBody) + } + } + assertOrder(t, orgC.ID(), first.Groups.Main, true) + // The same search again returns the same entries and charges nothing. + if _, secondBody := searchC(); secondBody != firstBody || revealedBy(orgC.ID()) != 8 { + t.Fatal("a repeated search of an exhausted organization changed or charged") + } + // Each returned candidate has the card view in the history, and opening + // the card of a returned handle is free, while the ninth candidate's card + // is refused by the same allowance. + candidates := candidateOfHandle(orgC.ID()) + for _, entry := range first.Groups.Main { + if len(historyOf(candidates[entry.CandidateHandle], orgC.ID())) < 2 { + t.Fatalf("a returned candidate has %d card views from organization C, want one for each search", + len(historyOf(candidates[entry.CandidateHandle], orgC.ID()))) + } + } + cardPath := func(handle string) string { + return fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgC.ID(), handle) + } + if got := harness.request(t, http.MethodGet, cardPath(first.Groups.Main[0].CandidateHandle), "", "", employer.cookie, "", client.remote()); got.Code != http.StatusOK || + revealedBy(orgC.ID()) != 8 { + t.Fatalf("card of a paid candidate = %d, paid %d, want 200 and no new charge", got.Code, revealedBy(orgC.ID())) + } + unpaid := "" + for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} { + for _, member := range group { + if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgC.ID(), member.id) == 0 { + unpaid = aliasIn(orgC.ID(), member.id) + } + } + } + if got := harness.request(t, http.MethodGet, cardPath(unpaid), "", "", employer.cookie, "", client.remote()); got.Code != http.StatusTooManyRequests { + t.Fatalf("card of an unpaid candidate = %d, want 429 from the same allowance", got.Code) + } + // The organizations pay independently of each other. + if revealedBy(orgA.ID()) < 16 || revealedBy(orgB.ID()) != 16 { + t.Fatalf("paid by A and B = %d and %d, want the counts of earlier searches untouched", revealedBy(orgA.ID()), revealedBy(orgB.ID())) + } + + // The group limit cuts the output of an organization that still has + // allowance, ranks the whole bank first, and also raises the flag. + publishPolicy(func(product *domain.ProductPolicy) { product.Matching.MaxResultsPerGroup = 4 }) + paidBefore := revealedBy(orgA.ID()) + cut := mustSearch(orgA.ID(), `{"filters":{}}`) + if len(cut.Groups.Main) != 4 || len(cut.Groups.Unconfirmed) != 4 || !cut.Truncated { + t.Fatalf("limited search = %d main, %d unconfirmed, truncated %v, want both groups cut at four and the flag", + len(cut.Groups.Main), len(cut.Groups.Unconfirmed), cut.Truncated) + } + if revealedBy(orgA.ID()) != paidBefore { + t.Fatal("a limited search charged candidates that were already paid for") + } + // The head of the cut group is the head of the full ranking. + publishPolicy(nil) + full := mustSearch(orgA.ID(), `{"filters":{}}`) + if full.Truncated || !slices.Equal(handlesOf(cut.Groups.Main), handlesOf(full.Groups.Main[:4])) || + !slices.Equal(handlesOf(cut.Groups.Unconfirmed), handlesOf(full.Groups.Unconfirmed[:4])) { + t.Fatal("the limited result is not the head of the full ranking") + } + }) + + t.Run("the demo group limit is 10, at most 30 reveals for a search, below the daily allowance", func(t *testing.T) { + demo := domain.DemoMatchingPolicy().MaxResultsPerGroup + if demo != 10 || 3*demo >= domain.DemoProductPolicyV4().OrganizationQuotas.TierE0.DistinctCardViewsPerWindow { + t.Fatalf("demo group limit = %d, want 10 and three groups under the E0 allowance", demo) + } + publishPolicy(func(product *domain.ProductPolicy) { product.Matching.MaxResultsPerGroup = demo }) + paid := revealedBy(orgA.ID()) + cut := mustSearch(orgA.ID(), `{"filters":{}}`) + if len(cut.Groups.Main) != 10 || len(cut.Groups.Unconfirmed) != 10 || !cut.Truncated || revealedBy(orgA.ID()) != paid { + t.Fatalf("demo-limited search = %d main, %d unconfirmed, truncated %v, paid %d (was %d); want both groups at 10 and the flag", + len(cut.Groups.Main), len(cut.Groups.Unconfirmed), cut.Truncated, revealedBy(orgA.ID()), paid) + } + publishPolicy(nil) + }) + + t.Run("two concurrent searches of one organization never charge beyond the allowance", func(t *testing.T) { + orgD := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization D"), now) + publishPolicy(func(product *domain.ProductPolicy) { product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8 }) + type outcome struct { + status int + body string + } + const parallel = 4 + outcomes := make(chan outcome, parallel) + remotes := make([]string, parallel) + for index := range remotes { + remotes[index] = client.remote() + } + var group sync.WaitGroup + for _, remote := range remotes { + group.Add(1) + go func() { + defer group.Done() + response := harness.request(t, http.MethodPost, searchPath(orgD.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, employer.cookie, employer.csrf, remote) + outcomes <- outcome{status: response.Code, body: response.Body.String()} + }() + } + group.Wait() + close(outcomes) + var bodies []string + for result := range outcomes { + if result.status != http.StatusOK { + t.Fatalf("concurrent search = %d %s, want 200; log: %s", result.status, result.body, harness.logs.String()) + } + bodies = append(bodies, result.body) + } + if got := revealedBy(orgD.ID()); got != 8 { + t.Fatalf("organization D paid for %d candidates under concurrent searches, want exactly 8", got) + } + paid := make(map[string]bool) + for id := range candidateIDs { + if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgD.ID(), id) == 1 { + paid[aliasIn(orgD.ID(), id)] = true + } + } + for _, body := range bodies { + var decoded matchSearchBody + if err := json.Unmarshal([]byte(body), &decoded); err != nil { + t.Fatalf("decode concurrent result: %v", err) + } + if !decoded.Truncated || len(decoded.Groups.Main) != 8 || len(decoded.Groups.Near)+len(decoded.Groups.Unconfirmed) != 0 { + t.Fatalf("concurrent result = %d main, truncated %v, want eight paid entries and the flag", len(decoded.Groups.Main), decoded.Truncated) + } + for _, handle := range handlesOf(decoded.Groups.Main) { + if !paid[handle] { + t.Fatalf("a response holds %s, a candidate the organization did not pay for", handle) + } + } + } + for _, body := range bodies[1:] { + if body != bodies[0] { + t.Fatal("two concurrent searches of one organization answered differently") + } + } + publishPolicy(nil) + }) + + t.Run("concurrent card reads, evidence reads, and searches of one organization neither deadlock nor overcharge", func(t *testing.T) { + orgF := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization F"), now) + visible := make([]categoryHTTPCandidate, 0, 17) + for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} { + visible = append(visible, group...) + } + type outcome struct { + what string + status int + } + run := func(jobs []func() outcome) []outcome { + results := make(chan outcome, len(jobs)) + var group sync.WaitGroup + for _, job := range jobs { + group.Add(1) + go func() { + defer group.Done() + results <- job() + }() + } + group.Wait() + close(results) + var all []outcome + for result := range results { + all = append(all, result) + } + return all + } + card := func(member categoryHTTPCandidate, suffix string) func() outcome { + remote := client.remote() + path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s%s", orgF.ID(), aliasIn(orgF.ID(), member.id), suffix) + return func() outcome { + response := harness.request(t, http.MethodGet, path, "", "", employer.cookie, "", remote) + return outcome{what: "card" + suffix, status: response.Code} + } + } + searchJob := func() func() outcome { + remote := client.remote() + return func() outcome { + response := harness.request(t, http.MethodPost, searchPath(orgF.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, employer.cookie, employer.csrf, remote) + return outcome{what: "search", status: response.Code} + } + } + check := func(results []outcome) { + t.Helper() + for _, result := range results { + if result.status != http.StatusOK { + t.Fatalf("concurrent %s = %d, want 200; log: %s", result.what, result.status, harness.logs.String()) + } + } + if strings.Contains(harness.logs.String(), "40P01") { + t.Fatal("a concurrent read of one organization hit a deadlock") + } + } + + // Several card reads of one organization at once. + var jobs []func() outcome + for _, member := range visible[:6] { + jobs = append(jobs, card(member, "")) + } + check(run(jobs)) + if got := revealedBy(orgF.ID()); got != 6 { + t.Fatalf("six concurrent card reads charged %d candidates, want 6", got) + } + + // A mixed round: searches, card reads, and evidence reads together. + jobs = []func() outcome{searchJob(), searchJob()} + for _, member := range visible[3:9] { + jobs = append(jobs, card(member, ""), card(member, "/evidence")) + } + check(run(jobs)) + if got := revealedBy(orgF.ID()); got != len(visible) { + t.Fatalf("the mixed round charged %d candidates, want %d: one row for each visible candidate and no more", got, len(visible)) + } + if countRows(`SELECT count(*) FROM (SELECT candidate_id FROM company_card_view_quota_usage WHERE organization_id = $1 + GROUP BY candidate_id HAVING count(*) > 1) AS repeated`, orgF.ID()) != 0 { + t.Fatal("a candidate was charged twice") + } + }) + + t.Run("the skill taxonomy is part of the policy version", func(t *testing.T) { + request := needRequest(needID, needRequirementsV1, "") + withTaxonomy := mustSearch(orgA.ID(), request) + publishPolicy(func(product *domain.ProductPolicy) { product.Matching.SkillTaxonomy = nil }) + without := mustSearch(orgA.ID(), request) + if len(withTaxonomy.Groups.Near) != 5 || len(without.Groups.Near) != 5 { + t.Fatalf("near = %d and %d, want the five candidates without the tag in both", len(withTaxonomy.Groups.Near), len(without.Groups.Near)) + } + assertScores(t, "near with the taxonomy", withTaxonomy.Groups.Near, map[string]float64{"coverage": 0.24}) + assertScores(t, "near without the taxonomy", without.Groups.Near, map[string]float64{"coverage": 0}) + assertScores(t, "main without the taxonomy", without.Groups.Main, map[string]float64{"coverage": 0.25}) + publishPolicy(nil) + }) + + t.Run("a policy without the matching section fails closed", func(t *testing.T) { + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now) + if _, err := publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: policyTestAuthor, Policy: domain.DemoProductPolicyV3(), + }); err != nil { + t.Fatalf("Publish(policy without matching) error = %v", err) + } + clockOffset += time.Minute + harness.clock.Set(time.Now().UTC().Add(clockOffset).Truncate(time.Microsecond)) + if _, response := search(employer, orgA.ID(), `{"filters":{}}`); response.Code != http.StatusInternalServerError { + t.Fatalf("search under a policy without matching = %d %s, want 500 and no ranking from defaults", response.Code, response.Body.String()) + } + }) +} diff --git a/backend/integration_test/notification_inbox_migration_test.go b/backend/integration_test/notification_inbox_migration_test.go new file mode 100644 index 0000000..f89d527 --- /dev/null +++ b/backend/integration_test/notification_inbox_migration_test.go @@ -0,0 +1,135 @@ +//go:build integration + +package integration_test + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" +) + +const ( + // syntheticNotificationMigrationVersion adds the synthetic event type to + // the inbox allowlist. + syntheticNotificationMigrationVersion = 36 + checkViolation = "23514" + notificationTypeConstraint = "notification_inbox_events_type_known" +) + +func TestSyntheticNotificationMigrationAllowlistAndGuardedRollback(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion) + + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + candidate := identity.createUser(t, "inbox-migration@example.com", domain.ScenarioCandidate, now.Add(-time.Hour)) + organizations := organizationFixture{ + ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now, + } + owner := organizations.employer(t, "inbox-migration-owner@example.com") + organization := organizations.create(t, owner, organizations.completeProfile(t, "Example Company"), now) + + insert := func(eventType, sourceType string, schemaVersion int) error { + _, err := pool.Exec(ctx, `INSERT INTO notification_inbox_events ( + recipient_user_id, event_id, organization_id, event_type, schema_version, source_type, source_id, occurred_at + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, + candidate.ID, uuid.New(), organization.ID(), eventType, schemaVersion, sourceType, organization.ID(), now) + return err + } + if err := insert("invitation.delivered", "invitation", 1); err != nil { + t.Fatalf("insert invitation event: %v", err) + } + if err := insert("notification.synthetic_delivered", "organization", 1); err != nil { + t.Fatalf("insert synthetic event: %v", err) + } + for name, args := range map[string][3]any{ + "synthetic event with the invitation source": {"notification.synthetic_delivered", "invitation", 1}, + "invitation event with the organization": {"invitation.delivered", "organization", 1}, + "unknown event type": {"notification.mail_requested", "organization", 1}, + "unsupported schema version": {"notification.synthetic_delivered", "organization", 2}, + } { + err := insert(args[0].(string), args[1].(string), args[2].(int)) + assertPgError(t, name, err, checkViolation, notificationTypeConstraint) + } + + // A rollback refuses to orphan a synthetic row and leaves the migration + // applied. + _, err := migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a synthetic inbox event", err, privacyIntegrityViolation, notificationTypeConstraint) + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() error = %v", err) + } + for _, status := range statuses { + if status.Version == syntheticNotificationMigrationVersion && !status.Applied { + t.Fatal("the migration was rolled back despite a synthetic inbox event") + } + } +} + +func TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion) + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != syntheticNotificationMigrationVersion { + t.Fatalf("DownOne() = %+v, %v, want version %d rolled back", result, err, syntheticNotificationMigrationVersion) + } + var constraint string + if err := pool.QueryRow(ctx, `SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conname = $1`, notificationTypeConstraint).Scan(&constraint); err != nil { + t.Fatalf("read the restored constraint: %v", err) + } + if constraint != "CHECK (((event_type = 'invitation.delivered'::text) AND (schema_version = 1) AND (source_type = 'invitation'::text)))" { + t.Fatalf("restored constraint = %s, want the invitation-only allowlist", constraint) + } + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } +} + +// rollBackAboveVersion rolls back every migration newer than version, so a +// test of one migration keeps working when later migrations exist. +func rollBackAboveVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator, version int64) { + t.Helper() + for { + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() while preparing migration %d: %v", version, err) + } + latest := int64(0) + for _, status := range statuses { + if status.Applied && status.Version > latest { + latest = status.Version + } + } + if latest < version { + t.Fatalf("migration %d is not applied", version) + } + if latest == version { + return + } + if _, err := migrator.DownOne(ctx); err != nil { + t.Fatalf("DownOne() while preparing migration %d: %v", version, err) + } + } +} diff --git a/backend/integration_test/notification_inbox_test.go b/backend/integration_test/notification_inbox_test.go new file mode 100644 index 0000000..8dce141 --- /dev/null +++ b/backend/integration_test/notification_inbox_test.go @@ -0,0 +1,431 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + 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/port/outbound" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/organization" +) + +const ( + notificationHTTPTimeout = 5 * time.Minute + notificationConsumerTTL = 10 * time.Second + // inboxRenamedConsumer stands for a consumer renamed after a deployment: + // its markers are empty, so only the inbox key can absorb the replay. + inboxRenamedConsumer = "notification_inbox_renamed" +) + +type notificationBody struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + OrganizationID uuid.UUID `json:"organization_id"` + DeliveredAt time.Time `json:"delivered_at"` + ReadAt *time.Time `json:"read_at"` + Content *struct { + Title string `json:"title"` + Summary string `json:"summary"` + LinkPath *string `json:"link_path"` + } `json:"content"` +} + +type notificationPageBody struct { + Items []notificationBody `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +func newNotificationHTTPHarness(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)} + transactor := postgresadapter.NewTransactor(pool) + sessionService, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, 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) + } + organizationService, err := organization.NewService(organization.Dependencies{ + Transactor: transactor, Keyring: keyring, Clock: clock.Now, + }) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + inbox, err := notification.NewInboxService(transactor, + notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(true)), clock.Now) + if err != nil { + t.Fatalf("notification.NewInboxService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.DiscardHandler) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(sessionService), + v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), + v1.WithNotifications(v1.NewNotificationHandler(inbox)), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +// appendSyntheticNotice records a synthetic inbox event through the real +// outbox writer, as a producer does in its own transaction, and returns the +// envelope a consumer would receive for it. +func appendSyntheticNotice( + ctx context.Context, + t *testing.T, + transactor outbound.Transactor, + recipientID, organizationID uuid.UUID, + occurredAt time.Time, +) outbound.ConsumedEvent { + t.Helper() + payload, err := notification.SyntheticNoticeEventPayload(recipientID, organizationID) + if err != nil { + t.Fatalf("SyntheticNoticeEventPayload() error = %v", err) + } + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: string(domain.NotificationInboxSyntheticDelivered), SchemaVersion: 1, + AggregateType: notification.SyntheticNoticeAggregateType, AggregateID: uuid.New(), + AggregateVersion: notification.SyntheticNoticeAggregateVersion, Payload: payload, + }) + if err != nil { + t.Fatalf("NewDomainEvent() error = %v", err) + } + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Outbox().Append(ctx, event) + }) + if err != nil { + t.Fatalf("Append(synthetic notice) error = %v", err) + } + return outbound.ConsumedEvent{ + EventID: event.EventID(), EventType: event.EventType(), SchemaVersion: event.SchemaVersion(), + AggregateType: event.AggregateType(), AggregateID: event.AggregateID(), AggregateVersion: event.AggregateVersion(), + OccurredAt: occurredAt, Payload: event.Payload(), + } +} + +func deliverToInbox( + ctx context.Context, + t *testing.T, + store *postgresadapter.EventConsumerStore, + consumer string, + event outbound.ConsumedEvent, +) bool { + t.Helper() + handler := notification.NewInboxHandler(slog.New(slog.DiscardHandler), true) + applied, err := store.ApplyOnce(ctx, consumer, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + return handler.Handle(ctx, unit, event) + }) + if err != nil { + t.Fatalf("ApplyOnce(%s, %s) error = %v", consumer, event.EventID, err) + } + return applied +} + +func notificationRequest( + t *testing.T, + harness *sessionHTTPHarness, + method, path, origin string, + session organizationHTTPSession, +) *httptest.ResponseRecorder { + t.Helper() + return organizationHTTPRequest(t, harness, method, path, "", origin, session, "") +} + +func decodeNotificationPage(t *testing.T, response *httptest.ResponseRecorder) notificationPageBody { + t.Helper() + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("notification list = %d %q %s, want a no-store 200", response.Code, response.Header().Get("Cache-Control"), response.Body.String()) + } + var page notificationPageBody + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode notification page: %v", err) + } + return page +} + +func requireNotificationProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code string) { + t.Helper() + requireSessionProblem(t, response, status, code) +} + +func TestNotificationInboxOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), notificationHTTPTimeout) + defer cancel() + harness := newNotificationHTTPHarness(ctx, t, env) + resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"}) + truncateTables(ctx, t, harness.pool, resetTables...) + transactor := postgresadapter.NewTransactor(harness.pool) + consumerStore := postgresadapter.NewEventConsumerStore(harness.pool, notificationConsumerTTL) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + candidate := createOrganizationHTTPUser(ctx, t, harness, "inbox-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + otherCandidate := createOrganizationHTTPUser(ctx, t, harness, "inbox-other-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + owner := createOrganizationHTTPUser(ctx, t, harness, "inbox-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + foreign := createOrganizationHTTPUser(ctx, t, harness, "inbox-foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now) + recruiter := createOrganizationHTTPUser(ctx, t, harness, "inbox-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now) + candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address()) + otherCandidateSession := loginOrganizationHTTP(t, harness, otherCandidate.Email.Address()) + ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) + foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address()) + recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address()) + origin := env.Config.AppPublicURL + organizationID := createCompanyForContextTest(t, harness, origin, ownerSession, "inbox-company") + foreignOrganizationID := createCompanyForContextTest(t, harness, origin, foreignSession, "inbox-foreign-company") + var organizationName string + if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, organizationID).Scan(&organizationName); err != nil { + t.Fatalf("read organization name: %v", err) + } + + // One synthetic event delivered twice, and once more by a renamed + // consumer, stores exactly one row. + deliveredAt := now.Add(-time.Hour) + event := appendSyntheticNotice(ctx, t, transactor, candidate.ID, organizationID, deliveredAt) + if !deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, event) { + t.Fatal("the first delivery was reported as a duplicate") + } + if deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, event) { + t.Fatal("the second delivery of the same event ID was applied again") + } + deliverToInbox(ctx, t, consumerStore, inboxRenamedConsumer, event) + var rows int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM notification_inbox_events WHERE event_id = $1`, event.EventID).Scan(&rows); err != nil || rows != 1 { + t.Fatalf("inbox rows for the repeated event = %d, %v, want 1", rows, err) + } + + list := func(session organizationHTTPSession) notificationPageBody { + t.Helper() + return decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", session)) + } + page := list(candidateSession) + if len(page.Items) != 1 || page.Page.HasMore || page.Page.NextCursor != nil { + t.Fatalf("candidate inbox = %+v, want one item on the last page", page) + } + item := page.Items[0] + if item.ID != event.EventID || item.Kind != "synthetic" || item.OrganizationID != organizationID || + item.ReadAt != nil || !item.DeliveredAt.Equal(deliveredAt.Truncate(time.Second)) { + t.Fatalf("candidate item = %+v, want the unread synthetic event", item) + } + if item.Content == nil || item.Content.Title != "Тестовое уведомление" || !strings.Contains(item.Content.Summary, organizationName) || + item.Content.LinkPath != nil { + t.Fatalf("candidate item content = %+v, want the current organization name", item.Content) + } + if got := list(otherCandidateSession); len(got.Items) != 0 { + t.Fatalf("another candidate's inbox = %+v, want empty", got) + } + + // Account and cabinet boundaries. + markPath := "/api/v1/me/notifications/" + event.EventID.String() + "/read" + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", organizationHTTPSession{}), http.StatusUnauthorized, "unauthenticated") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", ownerSession), http.StatusForbidden, "forbidden") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, origin, ownerSession), http.StatusForbidden, "forbidden") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, origin, otherCandidateSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, "/api/v1/me/notifications/"+uuid.NewString()+"/read", origin, candidateSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, "/api/v1/me/notifications/not-a-uuid/read", origin, candidateSession), http.StatusBadRequest, "validation_failed") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, "https://evil.example", candidateSession), http.StatusForbidden, "csrf_check_failed") + noCSRFSession := candidateSession + noCSRFSession.csrf = "" + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, origin, noCSRFSession), http.StatusForbidden, "csrf_check_failed") + if got := list(candidateSession); got.Items[0].ReadAt != nil { + t.Fatal("a refused request marked the item read") + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, + "/api/v1/organizations/"+organizationID.String()+"/notifications", "", candidateSession), http.StatusForbidden, "forbidden") + + // Mark read twice: the first time stays, and the list persists it. + first := notificationRequest(t, harness, http.MethodPost, markPath, origin, candidateSession) + var receipt struct { + ID uuid.UUID `json:"id"` + ReadAt time.Time `json:"read_at"` + } + if first.Code != http.StatusOK || first.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("mark read = %d %s, want a no-store 200", first.Code, first.Body.String()) + } + if err := json.Unmarshal(first.Body.Bytes(), &receipt); err != nil || receipt.ID != event.EventID || receipt.ReadAt.IsZero() { + t.Fatalf("mark read receipt = %s, %v", first.Body.String(), err) + } + harness.clock.Advance(time.Hour) + again := notificationRequest(t, harness, http.MethodPost, markPath, origin, candidateSession) + var repeated struct { + ReadAt time.Time `json:"read_at"` + } + if err := json.Unmarshal(again.Body.Bytes(), &repeated); err != nil || !repeated.ReadAt.Equal(receipt.ReadAt) { + t.Fatalf("repeated mark = %s, %v, want the first read time %s", again.Body.String(), err, receipt.ReadAt) + } + if got := list(candidateSession); got.Items[0].ReadAt == nil || !got.Items[0].ReadAt.Equal(receipt.ReadAt) { + t.Fatalf("list after mark = %+v, want the persisted read time", got.Items) + } + + // Hiding the organization removes the content from the next read; the + // item and its read state stay. + if _, err := harness.pool.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, + candidate.ID, organizationID, now); err != nil { + t.Fatalf("hide organization: %v", err) + } + hidden := list(candidateSession) + if len(hidden.Items) != 1 || hidden.Items[0].Content != nil || hidden.Items[0].ReadAt == nil { + t.Fatalf("list after hiding = %+v, want the item without content and still read", hidden.Items) + } + if strings.Contains(notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", candidateSession).Body.String(), organizationName) { + t.Fatal("the organization name still reaches a candidate who hid the organization") + } + + // Pagination: newest first, a cursor bound to the account. + for offset := 1; offset <= 3; offset++ { + extra := appendSyntheticNotice(ctx, t, transactor, candidate.ID, organizationID, now.Add(-time.Duration(offset)*time.Minute)) + deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, extra) + } + firstPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?limit=2", "", candidateSession)) + if len(firstPage.Items) != 2 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || + !firstPage.Items[0].DeliveredAt.After(firstPage.Items[1].DeliveredAt) { + t.Fatalf("first page = %+v, want two newest-first items and a cursor", firstPage) + } + cursor := url.QueryEscape(*firstPage.Page.NextCursor) + secondPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?limit=2&cursor="+cursor, "", candidateSession)) + if len(secondPage.Items) != 2 || secondPage.Page.HasMore || secondPage.Items[0].ID == firstPage.Items[1].ID || + !secondPage.Items[0].DeliveredAt.Before(firstPage.Items[1].DeliveredAt) { + t.Fatalf("second page = %+v, want the remaining two items after the first page", secondPage) + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?cursor="+cursor, "", otherCandidateSession), http.StatusBadRequest, "validation_failed") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?limit=101", "", candidateSession), http.StatusBadRequest, "validation_failed") + + // The employer cabinet: only the caller's items of this organization, and + // no access after the membership ends. + employerEvent := appendSyntheticNotice(ctx, t, transactor, owner.ID, organizationID, now.Add(-time.Minute)) + deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, employerEvent) + foreignOrganizationEvent := appendSyntheticNotice(ctx, t, transactor, owner.ID, foreignOrganizationID, now.Add(-time.Minute)) + // An owner of another organization is not a member of it: the row exists + // but stays out of the cabinet of the first organization. + deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, foreignOrganizationEvent) + organizationPath := "/api/v1/organizations/" + organizationID.String() + "/notifications" + organizationPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", ownerSession)) + if len(organizationPage.Items) != 1 || organizationPage.Items[0].ID != employerEvent.EventID || organizationPage.Items[0].Content == nil { + t.Fatalf("employer inbox = %+v, want only the item of this organization with content", organizationPage.Items) + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", foreignSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+uuid.NewString()+"/notifications", "", ownerSession), http.StatusNotFound, "not_found") + employerMark := organizationPath + "/" + employerEvent.EventID.String() + "/read" + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, employerMark, origin, foreignSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, + organizationPath+"/"+foreignOrganizationEvent.EventID.String()+"/read", origin, ownerSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, + organizationPath+"/"+event.EventID.String()+"/read", origin, ownerSession), http.StatusNotFound, "not_found") + if marked := notificationRequest(t, harness, http.MethodPost, employerMark, origin, ownerSession); marked.Code != http.StatusOK { + t.Fatalf("employer mark read = %d %s, want 200", marked.Code, marked.Body.String()) + } + // A member of another role reads and marks its own items only, although the + // owner-only operations refuse it. + insertOrganizationHTTPMembership(ctx, t, harness, organizationID, recruiter.ID, "recruiter", "active", now) + recruiterEvent := appendSyntheticNotice(ctx, t, transactor, recruiter.ID, organizationID, now.Add(-time.Minute)) + deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, recruiterEvent) + recruiterPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", recruiterSession)) + if len(recruiterPage.Items) != 1 || recruiterPage.Items[0].ID != recruiterEvent.EventID || recruiterPage.Items[0].Content == nil { + t.Fatalf("recruiter inbox = %+v, want only its own item with content", recruiterPage.Items) + } + if marked := notificationRequest(t, harness, http.MethodPost, organizationPath+"/"+recruiterEvent.EventID.String()+"/read", origin, recruiterSession); marked.Code != http.StatusOK { + t.Fatalf("recruiter mark read = %d %s, want 200", marked.Code, marked.Body.String()) + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, employerMark, origin, recruiterSession), http.StatusNotFound, "not_found") + if _, err := harness.pool.Exec(ctx, `UPDATE memberships SET state = 'removed' WHERE organization_id = $1 AND user_id = $2`, organizationID, owner.ID); err != nil { + t.Fatalf("revoke membership: %v", err) + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", ownerSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, employerMark, origin, ownerSession), http.StatusNotFound, "not_found") +} + +// A recipient or an organization that does not exist is told apart, so a +// handler can retry and skip a deleted account but reject a broken reference. +func TestNotificationInboxStoreNamesTheMissingReference(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), notificationHTTPTimeout) + defer cancel() + harness := newNotificationHTTPHarness(ctx, t, env) + truncateTables(ctx, t, harness.pool, append([]pgx.Identifier{}, usersDependentTables...)...) + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + candidate := createOrganizationHTTPUser(ctx, t, harness, "inbox-ref-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + owner := createOrganizationHTTPUser(ctx, t, harness, "inbox-ref-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) + organizationID := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "inbox-ref-company") + + repository := postgresadapter.NewNotificationInboxRepository(harness.pool) + entry := func(recipientID, orgID uuid.UUID) domain.NotificationInboxEntry { + built, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: orgID, + EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1, + SourceType: domain.NotificationInboxSourceOrganization, SourceID: orgID, OccurredAt: now, + }) + if err != nil { + t.Fatalf("NewNotificationInboxEntry() error = %v", err) + } + return built + } + if _, err := repository.Store(ctx, entry(uuid.New(), organizationID)); !errors.Is(err, outbound.ErrNotificationInboxRecipientMissing) { + t.Fatalf("Store(unknown recipient) error = %v, want ErrNotificationInboxRecipientMissing", err) + } + if _, err := repository.Store(ctx, entry(candidate.ID, uuid.New())); !errors.Is(err, outbound.ErrNotificationInboxReferenceMissing) { + t.Fatalf("Store(unknown organization) error = %v, want ErrNotificationInboxReferenceMissing", err) + } + if created, err := repository.Store(ctx, entry(candidate.ID, organizationID)); err != nil || !created { + t.Fatalf("Store(valid) = %t, %v, want true, nil", created, err) + } +} diff --git a/backend/integration_test/skill_evidence_http_test.go b/backend/integration_test/skill_evidence_http_test.go index 739f402..0e7ceac 100644 --- a/backend/integration_test/skill_evidence_http_test.go +++ b/backend/integration_test/skill_evidence_http_test.go @@ -807,6 +807,8 @@ func TestSkillEvidenceOverHTTP(t *testing.T) { if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE event_id = $1`, targetRun.id); err != nil { t.Fatalf("hide the fact: %v", err) } + // Later migrations may exist; the rollback under test is the evidence one. + rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion) _, err = migrator.DownOne(ctx) assertPgError(t, "rollback with a hidden fact", err, "23000", "skill_evidence_retained") assertTablesExist(ctx, t, harness.pool, true, "skill_evidence_facts", "skill_evidence_skills") diff --git a/backend/internal/adapter/primary/cli/policypublish/command.go b/backend/internal/adapter/primary/cli/policypublish/command.go new file mode 100644 index 0000000..95b8584 --- /dev/null +++ b/backend/internal/adapter/primary/cli/policypublish/command.go @@ -0,0 +1,113 @@ +// Package policypublish implements the local operator command that adds the +// demo matching section to the product policy. Until an administrative policy +// editor exists, this is how a stand gets the coefficients that the match +// search needs: startup seeds only the first demo version. +package policypublish + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "strings" + "time" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" +) + +const usage = "usage: policy-publish matching --actor operator:" + +// Command is a parsed, validated request. +type Command struct { + Author domain.PolicyAuthor +} + +// Extender publishes the demo matching section. +type Extender interface { + EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) +} + +// Parse validates every argument before Run reads configuration or connects. +func Parse(args []string) (Command, error) { + if len(args) == 0 || args[0] != "matching" { + return Command{}, errors.New(usage) + } + flags := flag.NewFlagSet("policy-publish matching", flag.ContinueOnError) + flags.SetOutput(io.Discard) + actor := flags.String("actor", "", "operator handle") + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 { + return Command{}, errors.New(usage) + } + value := strings.TrimSpace(*actor) + author, err := domain.ParsePolicyAuthor(value) + if err != nil || !strings.HasPrefix(value, "operator:") { + return Command{}, errors.New("actor must be operator:") + } + return Command{Author: author}, nil +} + +// Run parses the command, loads only DATABASE_URL from the supplied +// environment, and publishes. It does not load dotenv files. +func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error { + command, err := Parse(args) + if err != nil { + return err + } + if lookup == nil || output == nil || clock == nil { + return errors.New("policy publication command dependencies are required") + } + databaseURL := config.DatabaseURLFromEnv(lookup) + if databaseURL == "" { + return errors.New("DATABASE_URL is not set") + } + pool, err := postgres.NewPool(ctx, databaseURL) + if err != nil { + return errors.New("database configuration is invalid") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("database is unavailable") + } + return Execute(ctx, command, policy.NewPublisher(postgres.NewPolicyStore(pool).Policies(), clock), output) +} + +// Execute publishes the section and prints the version number only. +func Execute(ctx context.Context, command Command, extender Extender, output io.Writer) error { + if extender == nil || output == nil { + return errors.New("policy publication command dependencies are required") + } + result, err := extender.EnsureDemoMatchingSection(ctx, command.Author) + if err != nil { + return safeOperationError(err) + } + status := "already present" + if result.Created { + status = "published" + } + if _, err := fmt.Fprintf(output, + "%s: product policy version %d carries the demo matching section\n"+ + "note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n", + status, result.Version.Version(), + ); err != nil { + return errors.New("could not write the result") + } + return nil +} + +func safeOperationError(err error) error { + switch { + case errors.Is(err, policy.ErrNotDemoPolicy): + return errors.New("the latest product policy is not a demonstration version; publish the matching section with the calibrated policy instead") + case errors.Is(err, policy.ErrPolicyChanged): + return errors.New("the product policy changed while publishing; run the command again") + case errors.Is(err, outbound.ErrPolicyVersionNotFound): + return errors.New("the product policy has no version yet; start the service once so that it seeds the demo policy") + default: + return errors.New("policy publication failed") + } +} diff --git a/backend/internal/adapter/primary/cli/policypublish/command_test.go b/backend/internal/adapter/primary/cli/policypublish/command_test.go new file mode 100644 index 0000000..e9976f3 --- /dev/null +++ b/backend/internal/adapter/primary/cli/policypublish/command_test.go @@ -0,0 +1,64 @@ +package policypublish + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" +) + +type extenderFake struct { + result policy.MatchingResult + err error + author domain.PolicyAuthor +} + +func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) { + extender.author = author + return extender.result, extender.err +} + +func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) { + command, err := Parse([]string{"matching", "--actor", "operator:night"}) + if err != nil || command.Author != "operator:night" { + t.Fatalf("Parse(valid) = %+v, %v", command, err) + } + for _, args := range [][]string{ + nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"}, + {"matching", "--actor", "operator:night", "extra"}, + } { + if _, err := Parse(args); err == nil { + t.Errorf("Parse(%v) accepted invalid arguments", args) + } + } +} + +func TestExecutePrintsOnlyTheVersionAndMapsFailuresToSafeMessages(t *testing.T) { + var output bytes.Buffer + extender := &extenderFake{} + if err := Execute(context.Background(), Command{Author: "operator:night"}, extender, &output); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if !strings.HasPrefix(output.String(), "already present: product policy version 0") || extender.author != "operator:night" { + t.Fatalf("output = %q, author %q", output.String(), extender.author) + } + for _, test := range []struct { + err error + want string + }{ + {policy.ErrNotDemoPolicy, "not a demonstration version"}, + {outbound.ErrPolicyVersionNotFound, "no version yet"}, + {policy.ErrPolicyChanged, "run the command again"}, + {errors.New("pq: password authentication failed for user x"), "policy publication failed"}, + } { + err := Execute(context.Background(), Command{Author: "operator:night"}, &extenderFake{err: test.err}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "password") { + t.Errorf("Execute(%v) error = %v, want a safe message containing %q", test.err, err, test.want) + } + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index 564e1a1..e0637f7 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -19,6 +19,7 @@ import ( var regexMap = map[string]ogenregex.Regexp{ "\\S": ogenregex.MustCompile("\\S"), "^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"), + "^/[A-Za-z0-9/_-]{0,255}$": ogenregex.MustCompile("^/[A-Za-z0-9/_-]{0,255}$"), "^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"), "^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"), "^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"), diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index f857cda..fba7927 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -9263,6 +9263,225 @@ func (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool } } +// handleListMyNotificationsRequest handles ListMyNotifications operation. +// +// Requires the session cookie of a candidate account with a confirmed email. The recipient comes from +// the session, never from a request parameter, so the response holds only the caller's own items. +// Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor +// pagination. The response is `Cache-Control: no-store`. +// +// The inbox is the in-platform delivery state of a notification. An item exists as soon as the event +// reached the platform, whether or not any email was sent, and an email that failed or was never sent +// does not block it. The inbox stores a reference to the event, not its text: the `content` of every +// item is resolved from the current source for this recipient on this read. When the source is gone or +// the recipient may not see it now (for example the candidate hid the organization), the item stays in +// the list with `content` null, and no earlier text is shown. An event that is delivered twice is one +// item. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer +// account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account, +// answers 400 validation_failed. +// +// GET /api/v1/me/notifications +func (s *Server) handleListMyNotificationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListMyNotifications"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/notifications"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyNotificationsOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: ListMyNotificationsOperation, + ID: "ListMyNotifications", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListMyNotificationsOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeListMyNotificationsParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response ListMyNotificationsRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListMyNotificationsOperation, + OperationSummary: "List the inbox of the current candidate.", + OperationID: "ListMyNotifications", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "limit", + In: "query", + }: params.Limit, + { + Name: "cursor", + In: "query", + }: params.Cursor, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = ListMyNotificationsParams + Response = ListMyNotificationsRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListMyNotificationsParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListMyNotifications(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListMyNotifications(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeListMyNotificationsResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleListMyOrganizationsRequest handles ListMyOrganizations operation. // // Requires the session cookie of an employer account. The account comes from the session, never from a @@ -10366,6 +10585,229 @@ func (s *Server) handleListOrganizationNeedsRequest(args [1]string, argsEscaped } } +// handleListOrganizationNotificationsRequest handles ListOrganizationNotifications operation. +// +// Requires the session cookie of an employer account with a confirmed email and an active membership +// in `org_id`, whatever its role. The recipient comes from the session and the organization from the +// path and the membership that the server holds, never from the request. Returns only the items +// addressed to the caller in this organization, newest delivery first with the identifier as the +// tie-breaker, with cursor pagination. An item of the same account in another organization, and an +// item of another member, are never listed. The response is `Cache-Control: no-store`. +// +// Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email +// never blocks an item, and the `content` of every item is resolved from the current source for this +// recipient on this read. An employer sees content only while the membership is active. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate +// account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 +// email_not_verified; an account without an active membership in the organization and an unknown +// organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`, +// `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed. +// +// GET /api/v1/organizations/{org_id}/notifications +func (s *Server) handleListOrganizationNotificationsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListOrganizationNotifications"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/notifications"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListOrganizationNotificationsOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: ListOrganizationNotificationsOperation, + ID: "ListOrganizationNotifications", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListOrganizationNotificationsOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeListOrganizationNotificationsParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response ListOrganizationNotificationsRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListOrganizationNotificationsOperation, + OperationSummary: "List the inbox of the current employer in one organization.", + OperationID: "ListOrganizationNotifications", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "limit", + In: "query", + }: params.Limit, + { + Name: "cursor", + In: "query", + }: params.Cursor, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = ListOrganizationNotificationsParams + Response = ListOrganizationNotificationsRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListOrganizationNotificationsParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListOrganizationNotifications(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListOrganizationNotifications(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeListOrganizationNotificationsResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleLoginRequest handles Login operation. // // Public operation that starts a server session. The server verifies the password with Argon2id; for @@ -10745,6 +11187,477 @@ func (s *Server) handleLogoutRequest(args [0]string, argsEscaped bool, w http.Re } } +// handleMarkMyNotificationReadRequest handles MarkMyNotificationRead operation. +// +// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that +// session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request +// has no body. +// +// The command is idempotent by its effect: the first mark stores the read time and every repeat +// returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no +// content, so marking an item whose content is no longer available still works. It changes no other +// item. +// +// The general rate limit can answer 429 with Retry-After before any check. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or +// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers +// 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so +// identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400 +// validation_failed with the path pointer. +// +// POST /api/v1/me/notifications/{notification_id}/read +func (s *Server) handleMarkMyNotificationReadRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("MarkMyNotificationRead"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/notifications/{notification_id}/read"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), MarkMyNotificationReadOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: MarkMyNotificationReadOperation, + ID: "MarkMyNotificationRead", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, MarkMyNotificationReadOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, MarkMyNotificationReadOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeMarkMyNotificationReadParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response MarkMyNotificationReadRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: MarkMyNotificationReadOperation, + OperationSummary: "Mark an item of the inbox of the current candidate as read.", + OperationID: "MarkMyNotificationRead", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "notification_id", + In: "path", + }: params.NotificationID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = MarkMyNotificationReadParams + Response = MarkMyNotificationReadRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackMarkMyNotificationReadParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.MarkMyNotificationRead(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.MarkMyNotificationRead(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeMarkMyNotificationReadResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleMarkOrganizationNotificationReadRequest handles MarkOrganizationNotificationRead operation. +// +// Requires the session cookie of an employer account with a confirmed email and an active membership +// in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed +// Origin. The recipient comes from the session and the organization from the path and the server-side +// membership. The request has no body. +// +// The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The +// item must belong to the caller in this organization. +// +// The general rate limit can answer 429 with Retry-After before any check. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or +// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers +// 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an +// account without an active membership in the organization, an unknown organization, an item of +// another account, an item of another organization, and an unknown identifier all answer 404 +// not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path +// pointer. +// +// POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read +func (s *Server) handleMarkOrganizationNotificationReadRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("MarkOrganizationNotificationRead"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/notifications/{notification_id}/read"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), MarkOrganizationNotificationReadOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: MarkOrganizationNotificationReadOperation, + ID: "MarkOrganizationNotificationRead", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, MarkOrganizationNotificationReadOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, MarkOrganizationNotificationReadOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeMarkOrganizationNotificationReadParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response MarkOrganizationNotificationReadRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: MarkOrganizationNotificationReadOperation, + OperationSummary: "Mark an item of the inbox of the current employer in one organization as read.", + OperationID: "MarkOrganizationNotificationRead", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "notification_id", + In: "path", + }: params.NotificationID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = MarkOrganizationNotificationReadParams + Response = MarkOrganizationNotificationReadRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackMarkOrganizationNotificationReadParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.MarkOrganizationNotificationRead(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.MarkOrganizationNotificationRead(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeMarkOrganizationNotificationReadResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleRaiseOrganizationInvitationSalaryRequest handles RaiseOrganizationInvitationSalary operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF @@ -12840,6 +13753,15 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo // empty bank filter searches all otherwise eligible specializations, returning each specialization // separately. // +// A search reveals card content, so it is charged like card reads. The whole visible bank is ranked, +// but each group returns at most the versioned per-group limit and no total is returned. In the order +// `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of +// the organization (a candidate it already viewed inside the window costs nothing again, so repeating +// the search or opening the card afterwards does not charge twice) and appears in the candidate's +// access history with the fields actually returned. When the allowance ends, the entries already +// counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit, +// and it carries no count. No new error is returned for an exhausted allowance. +// // Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks // for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A // confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed @@ -12855,7 +13777,10 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo // Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity // uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 // comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names -// `cohort_below_30`. +// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile +// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, +// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not +// fail. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account // answers 403 forbidden; an unknown organization or account without active membership answers 404 diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index bcd81c7..728371c 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -157,6 +157,10 @@ type ListMyInvitationsRes interface { listMyInvitationsRes() } +type ListMyNotificationsRes interface { + listMyNotificationsRes() +} + type ListMyOrganizationsRes interface { listMyOrganizationsRes() } @@ -177,6 +181,10 @@ type ListOrganizationNeedsRes interface { listOrganizationNeedsRes() } +type ListOrganizationNotificationsRes interface { + listOrganizationNotificationsRes() +} + type LoginRes interface { loginRes() } @@ -185,6 +193,14 @@ type LogoutRes interface { logoutRes() } +type MarkMyNotificationReadRes interface { + markMyNotificationReadRes() +} + +type MarkOrganizationNotificationReadRes interface { + markOrganizationNotificationReadRes() +} + type RaiseOrganizationInvitationSalaryRes interface { raiseOrganizationInvitationSalaryRes() } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index 755be4c..68ca674 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -27401,6 +27401,120 @@ func (s *ListMyInvitationsUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListMyNotificationsBadRequest as json. +func (s *ListMyNotificationsBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyNotificationsBadRequest from json. +func (s *ListMyNotificationsBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyNotificationsBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyNotificationsBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyNotificationsBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyNotificationsBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyNotificationsForbidden as json. +func (s *ListMyNotificationsForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyNotificationsForbidden from json. +func (s *ListMyNotificationsForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyNotificationsForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyNotificationsForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyNotificationsForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyNotificationsForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyNotificationsUnauthorized as json. +func (s *ListMyNotificationsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyNotificationsUnauthorized from json. +func (s *ListMyNotificationsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyNotificationsUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyNotificationsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyNotificationsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyNotificationsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ListMyOrganizationsBadRequest as json. func (s *ListMyOrganizationsBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -28009,6 +28123,158 @@ func (s *ListOrganizationNeedsUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListOrganizationNotificationsBadRequest as json. +func (s *ListOrganizationNotificationsBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListOrganizationNotificationsBadRequest from json. +func (s *ListOrganizationNotificationsBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListOrganizationNotificationsBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListOrganizationNotificationsBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListOrganizationNotificationsBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListOrganizationNotificationsBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListOrganizationNotificationsForbidden as json. +func (s *ListOrganizationNotificationsForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListOrganizationNotificationsForbidden from json. +func (s *ListOrganizationNotificationsForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListOrganizationNotificationsForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListOrganizationNotificationsForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListOrganizationNotificationsForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListOrganizationNotificationsForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListOrganizationNotificationsNotFound as json. +func (s *ListOrganizationNotificationsNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListOrganizationNotificationsNotFound from json. +func (s *ListOrganizationNotificationsNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListOrganizationNotificationsNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListOrganizationNotificationsNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListOrganizationNotificationsNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListOrganizationNotificationsNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListOrganizationNotificationsUnauthorized as json. +func (s *ListOrganizationNotificationsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListOrganizationNotificationsUnauthorized from json. +func (s *ListOrganizationNotificationsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListOrganizationNotificationsUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListOrganizationNotificationsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListOrganizationNotificationsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListOrganizationNotificationsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes LoginBadRequest as json. func (s *LoginBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -28272,6 +28538,310 @@ func (s *LoginUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes MarkMyNotificationReadBadRequest as json. +func (s *MarkMyNotificationReadBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes MarkMyNotificationReadBadRequest from json. +func (s *MarkMyNotificationReadBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode MarkMyNotificationReadBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = MarkMyNotificationReadBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *MarkMyNotificationReadBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *MarkMyNotificationReadBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes MarkMyNotificationReadForbidden as json. +func (s *MarkMyNotificationReadForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes MarkMyNotificationReadForbidden from json. +func (s *MarkMyNotificationReadForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode MarkMyNotificationReadForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = MarkMyNotificationReadForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *MarkMyNotificationReadForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *MarkMyNotificationReadForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes MarkMyNotificationReadNotFound as json. +func (s *MarkMyNotificationReadNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes MarkMyNotificationReadNotFound from json. +func (s *MarkMyNotificationReadNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode MarkMyNotificationReadNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = MarkMyNotificationReadNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *MarkMyNotificationReadNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *MarkMyNotificationReadNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes MarkMyNotificationReadUnauthorized as json. +func (s *MarkMyNotificationReadUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes MarkMyNotificationReadUnauthorized from json. +func (s *MarkMyNotificationReadUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode MarkMyNotificationReadUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = MarkMyNotificationReadUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *MarkMyNotificationReadUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *MarkMyNotificationReadUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes MarkOrganizationNotificationReadBadRequest as json. +func (s *MarkOrganizationNotificationReadBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes MarkOrganizationNotificationReadBadRequest from json. +func (s *MarkOrganizationNotificationReadBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode MarkOrganizationNotificationReadBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = MarkOrganizationNotificationReadBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *MarkOrganizationNotificationReadBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *MarkOrganizationNotificationReadBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes MarkOrganizationNotificationReadForbidden as json. +func (s *MarkOrganizationNotificationReadForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes MarkOrganizationNotificationReadForbidden from json. +func (s *MarkOrganizationNotificationReadForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode MarkOrganizationNotificationReadForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = MarkOrganizationNotificationReadForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *MarkOrganizationNotificationReadForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *MarkOrganizationNotificationReadForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes MarkOrganizationNotificationReadNotFound as json. +func (s *MarkOrganizationNotificationReadNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes MarkOrganizationNotificationReadNotFound from json. +func (s *MarkOrganizationNotificationReadNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode MarkOrganizationNotificationReadNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = MarkOrganizationNotificationReadNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *MarkOrganizationNotificationReadNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *MarkOrganizationNotificationReadNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes MarkOrganizationNotificationReadUnauthorized as json. +func (s *MarkOrganizationNotificationReadUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes MarkOrganizationNotificationReadUnauthorized from json. +func (s *MarkOrganizationNotificationReadUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode MarkOrganizationNotificationReadUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = MarkOrganizationNotificationReadUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *MarkOrganizationNotificationReadUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *MarkOrganizationNotificationReadUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *MatchAppliedConditions) Encode(e *jx.Encoder) { e.ObjStart() @@ -30942,11 +31512,16 @@ func (s *MatchSearchResponse) encodeFields(e *jx.Encoder) { e.FieldStart("groups") s.Groups.Encode(e) } + { + e.FieldStart("truncated") + e.Bool(s.Truncated) + } } -var jsonFieldsNameOfMatchSearchResponse = [2]string{ +var jsonFieldsNameOfMatchSearchResponse = [3]string{ 0: "source", 1: "groups", + 2: "truncated", } // Decode decodes MatchSearchResponse from json. @@ -30978,6 +31553,18 @@ func (s *MatchSearchResponse) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"groups\"") } + case "truncated": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Bool() + s.Truncated = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"truncated\"") + } default: return errors.Errorf("unexpected field %q", k) } @@ -30988,7 +31575,7 @@ func (s *MatchSearchResponse) Decode(d *jx.Decoder) error { // Validate required fields. var failures []validate.FieldError for i, mask := range [1]uint8{ - 0b00000011, + 0b00000111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -31878,6 +32465,8 @@ func (s *MatchUnknownReason) Decode(d *jx.Decoder) error { *s = MatchUnknownReasonNoFreshnessHistory case MatchUnknownReasonNoResponseHistory: *s = MatchUnknownReasonNoResponseHistory + case MatchUnknownReasonPercentileNotComputed: + *s = MatchUnknownReasonPercentileNotComputed default: *s = MatchUnknownReason(v) } @@ -39269,6 +39858,50 @@ func (s *NilNeedVersionLabel) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes NotificationContent as json. +func (o NilNotificationContent) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes NotificationContent from json. +func (o *NilNotificationContent) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilNotificationContent to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v NotificationContent + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilNotificationContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilNotificationContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes OrganizationDescription as json. func (o NilOrganizationDescription) Encode(e *jx.Encoder) { if o.Null { @@ -40901,6 +41534,579 @@ func (s *NilWorkContext) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *Notification) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Notification) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("organization_id") + json.EncodeUUID(e, s.OrganizationID) + } + { + e.FieldStart("delivered_at") + s.DeliveredAt.Encode(e) + } + { + e.FieldStart("read_at") + s.ReadAt.Encode(e) + } + { + e.FieldStart("content") + s.Content.Encode(e) + } +} + +var jsonFieldsNameOfNotification = [6]string{ + 0: "id", + 1: "kind", + 2: "organization_id", + 3: "delivered_at", + 4: "read_at", + 5: "content", +} + +// Decode decodes Notification from json. +func (s *Notification) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Notification to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "kind": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "organization_id": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := json.DecodeUUID(d) + s.OrganizationID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"organization_id\"") + } + case "delivered_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.DeliveredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"delivered_at\"") + } + case "read_at": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.ReadAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"read_at\"") + } + case "content": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Content.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"content\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Notification") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfNotification) { + name = jsonFieldsNameOfNotification[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 *Notification) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Notification) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *NotificationContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *NotificationContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("title") + e.Str(s.Title) + } + { + e.FieldStart("summary") + e.Str(s.Summary) + } + { + e.FieldStart("link_path") + s.LinkPath.Encode(e) + } +} + +var jsonFieldsNameOfNotificationContent = [3]string{ + 0: "title", + 1: "summary", + 2: "link_path", +} + +// Decode decodes NotificationContent from json. +func (s *NotificationContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NotificationContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "title": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Str() + s.Title = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"title\"") + } + case "summary": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Summary = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"summary\"") + } + case "link_path": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.LinkPath.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"link_path\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode NotificationContent") + } + // 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(jsonFieldsNameOfNotificationContent) { + name = jsonFieldsNameOfNotificationContent[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 *NotificationContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NotificationContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes NotificationKind as json. +func (s NotificationKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes NotificationKind from json. +func (s *NotificationKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NotificationKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch NotificationKind(v) { + case NotificationKindInvitationDelivered: + *s = NotificationKindInvitationDelivered + case NotificationKindSynthetic: + *s = NotificationKindSynthetic + default: + *s = NotificationKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NotificationKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NotificationKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *NotificationList) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *NotificationList) encodeFields(e *jx.Encoder) { + { + e.FieldStart("items") + e.ArrStart() + for _, elem := range s.Items { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("page") + s.Page.Encode(e) + } +} + +var jsonFieldsNameOfNotificationList = [2]string{ + 0: "items", + 1: "page", +} + +// Decode decodes NotificationList from json. +func (s *NotificationList) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NotificationList to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "items": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Items = make([]Notification, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem Notification + if err := elem.Decode(d); err != nil { + return err + } + s.Items = append(s.Items, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"items\"") + } + case "page": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Page.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"page\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode NotificationList") + } + // 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(jsonFieldsNameOfNotificationList) { + name = jsonFieldsNameOfNotificationList[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 *NotificationList) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NotificationList) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *NotificationReadReceipt) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *NotificationReadReceipt) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("read_at") + s.ReadAt.Encode(e) + } +} + +var jsonFieldsNameOfNotificationReadReceipt = [2]string{ + 0: "id", + 1: "read_at", +} + +// Decode decodes NotificationReadReceipt from json. +func (s *NotificationReadReceipt) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode NotificationReadReceipt to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "read_at": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.ReadAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"read_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode NotificationReadReceipt") + } + // 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(jsonFieldsNameOfNotificationReadReceipt) { + name = jsonFieldsNameOfNotificationReadReceipt[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 *NotificationReadReceipt) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NotificationReadReceipt) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *NumberAnswer) Encode(e *jx.Encoder) { e.ObjStart() diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index 9a92dd1..1e7949b 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -47,13 +47,17 @@ const ( ListMyEvidenceOperation OperationName = "ListMyEvidence" ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations" ListMyInvitationsOperation OperationName = "ListMyInvitations" + ListMyNotificationsOperation OperationName = "ListMyNotifications" ListMyOrganizationsOperation OperationName = "ListMyOrganizations" ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory" ListMySupportCasesOperation OperationName = "ListMySupportCases" ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations" ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds" + ListOrganizationNotificationsOperation OperationName = "ListOrganizationNotifications" LoginOperation OperationName = "Login" LogoutOperation OperationName = "Logout" + MarkMyNotificationReadOperation OperationName = "MarkMyNotificationRead" + MarkOrganizationNotificationReadOperation OperationName = "MarkOrganizationNotificationRead" RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary" RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals" RegisterAccountOperation OperationName = "RegisterAccount" diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go index ef7d0bd..18d95b9 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -3696,6 +3696,182 @@ func decodeListMyInvitationsParams(args [0]string, argsEscaped bool, r *http.Req return params, nil } +// ListMyNotificationsParams is parameters of ListMyNotifications operation. +type ListMyNotificationsParams struct { + // Maximum number of items in the page. The server may return fewer items even when more remain; use + // `page.has_more` to detect the end. + Limit OptInt32 `json:",omitempty,omitzero"` + // Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the + // first page. A malformed or foreign cursor returns 400 with code validation_failed. + Cursor OptString `json:",omitempty,omitzero"` +} + +func unpackListMyNotificationsParams(packed middleware.Parameters) (params ListMyNotificationsParams) { + { + key := middleware.ParameterKey{ + Name: "limit", + In: "query", + } + if v, ok := packed[key]; ok { + params.Limit = v.(OptInt32) + } + } + { + key := middleware.ParameterKey{ + Name: "cursor", + In: "query", + } + if v, ok := packed[key]; ok { + params.Cursor = v.(OptString) + } + } + return params +} + +func decodeListMyNotificationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyNotificationsParams, _ error) { + q := uri.NewQueryDecoder(r.URL.Query()) + // Set default value for query: limit. + { + val := int32(20) + params.Limit.SetTo(val) + } + // Decode query: limit. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "limit", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotLimitVal int32 + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt32(val) + if err != nil { + return err + } + + paramsDotLimitVal = c + return nil + }(); err != nil { + return err + } + params.Limit.SetTo(paramsDotLimitVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Limit.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 100, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "limit", + In: "query", + Err: err, + } + } + // Decode query: cursor. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "cursor", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotCursorVal string + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + paramsDotCursorVal = c + return nil + }(); err != nil { + return err + } + params.Cursor.SetTo(paramsDotCursorVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Cursor.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 512, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "cursor", + In: "query", + Err: err, + } + } + return params, nil +} + // ListMyOrganizationsParams is parameters of ListMyOrganizations operation. type ListMyOrganizationsParams struct { // Maximum number of items in the page. The server may return fewer items even when more remain; use @@ -4690,6 +4866,432 @@ func decodeListOrganizationNeedsParams(args [1]string, argsEscaped bool, r *http return params, nil } +// ListOrganizationNotificationsParams is parameters of ListOrganizationNotifications operation. +type ListOrganizationNotificationsParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Maximum number of items in the page. The server may return fewer items even when more remain; use + // `page.has_more` to detect the end. + Limit OptInt32 `json:",omitempty,omitzero"` + // Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the + // first page. A malformed or foreign cursor returns 400 with code validation_failed. + Cursor OptString `json:",omitempty,omitzero"` +} + +func unpackListOrganizationNotificationsParams(packed middleware.Parameters) (params ListOrganizationNotificationsParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "limit", + In: "query", + } + if v, ok := packed[key]; ok { + params.Limit = v.(OptInt32) + } + } + { + key := middleware.ParameterKey{ + Name: "cursor", + In: "query", + } + if v, ok := packed[key]; ok { + params.Cursor = v.(OptString) + } + } + return params +} + +func decodeListOrganizationNotificationsParams(args [1]string, argsEscaped bool, r *http.Request) (params ListOrganizationNotificationsParams, _ error) { + q := uri.NewQueryDecoder(r.URL.Query()) + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Set default value for query: limit. + { + val := int32(20) + params.Limit.SetTo(val) + } + // Decode query: limit. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "limit", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotLimitVal int32 + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt32(val) + if err != nil { + return err + } + + paramsDotLimitVal = c + return nil + }(); err != nil { + return err + } + params.Limit.SetTo(paramsDotLimitVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Limit.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 100, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "limit", + In: "query", + Err: err, + } + } + // Decode query: cursor. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "cursor", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotCursorVal string + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + paramsDotCursorVal = c + return nil + }(); err != nil { + return err + } + params.Cursor.SetTo(paramsDotCursorVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Cursor.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 512, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "cursor", + In: "query", + Err: err, + } + } + return params, nil +} + +// MarkMyNotificationReadParams is parameters of MarkMyNotificationRead operation. +type MarkMyNotificationReadParams struct { + // Identifier of an item of the inbox of the current account in the cabinet that the path names. An + // item of another account, an item of another organization context, and an unknown identifier all + // answer 404 not_found, so identifiers cannot be enumerated. + NotificationID uuid.UUID +} + +func unpackMarkMyNotificationReadParams(packed middleware.Parameters) (params MarkMyNotificationReadParams) { + { + key := middleware.ParameterKey{ + Name: "notification_id", + In: "path", + } + params.NotificationID = packed[key].(uuid.UUID) + } + return params +} + +func decodeMarkMyNotificationReadParams(args [1]string, argsEscaped bool, r *http.Request) (params MarkMyNotificationReadParams, _ error) { + // Decode path: notification_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "notification_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.NotificationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "notification_id", + In: "path", + Err: err, + } + } + return params, nil +} + +// MarkOrganizationNotificationReadParams is parameters of MarkOrganizationNotificationRead operation. +type MarkOrganizationNotificationReadParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Identifier of an item of the inbox of the current account in the cabinet that the path names. An + // item of another account, an item of another organization context, and an unknown identifier all + // answer 404 not_found, so identifiers cannot be enumerated. + NotificationID uuid.UUID +} + +func unpackMarkOrganizationNotificationReadParams(packed middleware.Parameters) (params MarkOrganizationNotificationReadParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "notification_id", + In: "path", + } + params.NotificationID = packed[key].(uuid.UUID) + } + return params +} + +func decodeMarkOrganizationNotificationReadParams(args [2]string, argsEscaped bool, r *http.Request) (params MarkOrganizationNotificationReadParams, _ error) { + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Decode path: notification_id. + if err := func() error { + param := args[1] + if argsEscaped { + unescaped, err := url.PathUnescape(args[1]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "notification_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.NotificationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "notification_id", + In: "path", + Err: err, + } + } + return params, nil +} + // RaiseOrganizationInvitationSalaryParams is parameters of RaiseOrganizationInvitationSalary operation. type RaiseOrganizationInvitationSalaryParams struct { // Identifier of an organization. Access comes only from an active membership of the session account in diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index d0b7b2c..fcb7c77 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -3461,6 +3461,77 @@ func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.Respo } } +func encodeListMyNotificationsResponse(response ListMyNotificationsRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *NotificationListHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListMyNotificationsBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListMyNotificationsUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListMyNotificationsForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeListMyOrganizationsResponse(response ListMyOrganizationsRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *MyOrganizationListHeaders: @@ -3828,6 +3899,89 @@ func encodeListOrganizationNeedsResponse(response ListOrganizationNeedsRes, w ht } } +func encodeListOrganizationNotificationsResponse(response ListOrganizationNotificationsRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *NotificationListHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListOrganizationNotificationsBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListOrganizationNotificationsUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListOrganizationNotificationsForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListOrganizationNotificationsNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeLoginResponse(response LoginRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *SessionHeaders: @@ -4014,6 +4168,236 @@ func encodeLogoutResponse(response LogoutRes, w http.ResponseWriter, span trace. } } +func encodeMarkMyNotificationReadResponse(response MarkMyNotificationReadRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *NotificationReadReceiptHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *MarkMyNotificationReadBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *MarkMyNotificationReadUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *MarkMyNotificationReadForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *MarkMyNotificationReadNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeMarkOrganizationNotificationReadResponse(response MarkOrganizationNotificationReadRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *NotificationReadReceiptHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *MarkOrganizationNotificationReadBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *MarkOrganizationNotificationReadUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *MarkOrganizationNotificationReadForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *MarkOrganizationNotificationReadNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeRaiseOrganizationInvitationSalaryResponse(response RaiseOrganizationInvitationSalaryRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *OrganizationInvitationHeaders: diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index 7dc4462..8efaf33 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,43 +11,43 @@ import ( ) var ( - rn74AllowedHeaders = map[string]string{ + rn83AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn9AllowedHeaders = map[string]string{ "POST": "Content-Type,Origin", } - rn70AllowedHeaders = map[string]string{ + rn79AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn66AllowedHeaders = map[string]string{ + rn69AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn27AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } - rn72AllowedHeaders = map[string]string{ + rn81AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } rn11AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn85AllowedHeaders = map[string]string{ + rn94AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn22AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn84AllowedHeaders = map[string]string{ + rn93AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn69AllowedHeaders = map[string]string{ + rn78AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn5AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn76AllowedHeaders = map[string]string{ + rn85AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } rn53AllowedHeaders = map[string]string{ @@ -63,17 +63,20 @@ var ( rn19AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn86AllowedHeaders = map[string]string{ + rn95AllowedHeaders = map[string]string{ + "POST": "X-Csrf-Token", + } + rn72AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } rn56AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "X-Csrf-Token", } - rn81AllowedHeaders = map[string]string{ + rn90AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn82AllowedHeaders = map[string]string{ + rn91AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } rn38AllowedHeaders = map[string]string{ @@ -97,16 +100,16 @@ var ( rn46AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn68AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn79AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn87AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } rn77AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn88AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn96AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn86AllowedHeaders = map[string]string{ "POST": "Content-Type,X-Csrf-Token", } rn18AllowedHeaders = map[string]string{ @@ -115,6 +118,9 @@ var ( rn49AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } + rn75AllowedHeaders = map[string]string{ + "POST": "X-Csrf-Token", + } ) func (s *Server) cutPrefix(path string) (string, bool) { @@ -269,7 +275,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn74AllowedHeaders, + allowedHeaders: rn83AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -346,7 +352,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn70AllowedHeaders, + allowedHeaders: rn79AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -370,7 +376,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn66AllowedHeaders, + allowedHeaders: rn69AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -450,7 +456,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn72AllowedHeaders, + allowedHeaders: rn81AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -572,7 +578,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn85AllowedHeaders, + allowedHeaders: rn94AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -665,7 +671,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn84AllowedHeaders, + allowedHeaders: rn93AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -692,7 +698,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn69AllowedHeaders, + allowedHeaders: rn78AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -903,7 +909,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE", - allowedHeaders: rn76AllowedHeaders, + allowedHeaders: rn85AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1145,7 +1151,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn86AllowedHeaders, + allowedHeaders: rn95AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1160,6 +1166,82 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } + case 'n': // Prefix: "notifications" + + if l := len("notifications"); len(elem) >= l && elem[0:l] == "notifications" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleListMyNotificationsRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "notification_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + break + } + switch elem[0] { + case '/': // Prefix: "/read" + + if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleMarkMyNotificationReadRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn72AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + } + case 'o': // Prefix: "organizations" if l := len("organizations"); len(elem) >= l && elem[0:l] == "organizations" { @@ -1416,7 +1498,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn81AllowedHeaders, + allowedHeaders: rn90AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1443,7 +1525,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn82AllowedHeaders, + allowedHeaders: rn91AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1861,7 +1943,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn68AllowedHeaders, + allowedHeaders: rn77AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1889,7 +1971,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn79AllowedHeaders, + allowedHeaders: rn88AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1919,7 +2001,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn87AllowedHeaders, + allowedHeaders: rn96AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1952,7 +2034,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn77AllowedHeaders, + allowedHeaders: rn86AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1961,77 +2043,170 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - case 'n': // Prefix: "needs" + case 'n': // Prefix: "n" - if l := len("needs"); len(elem) >= l && elem[0:l] == "needs" { + if l := len("n"); len(elem) >= l && elem[0:l] == "n" { elem = elem[l:] } else { break } if len(elem) == 0 { - switch r.Method { - case "GET": - s.handleListOrganizationNeedsRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - case "POST": - s.handleCreateOrganizationNeedRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET,POST", - allowedHeaders: rn18AllowedHeaders, - acceptPost: "application/json", - acceptPatch: "", - }) - } - - return + break } switch elem[0] { - case '/': // Prefix: "/" + case 'e': // Prefix: "eeds" - if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + if l := len("eeds"); len(elem) >= l && elem[0:l] == "eeds" { elem = elem[l:] } else { break } - // Param: "need_id" - // Leaf parameter, slashes are prohibited - idx := strings.IndexByte(elem, '/') - if idx >= 0 { - break - } - args[1] = elem - elem = "" - if len(elem) == 0 { - // Leaf node. switch r.Method { case "GET": - s.handleGetOrganizationNeedRequest([2]string{ + s.handleListOrganizationNeedsRequest([1]string{ args[0], - args[1], }, elemIsEscaped, w, r) - case "PATCH": - s.handleUpdateOrganizationNeedRequest([2]string{ + case "POST": + s.handleCreateOrganizationNeedRequest([1]string{ args[0], - args[1], }, elemIsEscaped, w, r) default: s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET,PATCH", - allowedHeaders: rn49AllowedHeaders, - acceptPost: "", - acceptPatch: "application/json", + allowedMethods: "GET,POST", + allowedHeaders: rn18AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", }) } return } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "need_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[1] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetOrganizationNeedRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + case "PATCH": + s.handleUpdateOrganizationNeedRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,PATCH", + allowedHeaders: rn49AllowedHeaders, + acceptPost: "", + acceptPatch: "application/json", + }) + } + + return + } + + } + + case 'o': // Prefix: "otifications" + + if l := len("otifications"); len(elem) >= l && elem[0:l] == "otifications" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleListOrganizationNotificationsRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "notification_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[1] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + break + } + switch elem[0] { + case '/': // Prefix: "/read" + + if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleMarkOrganizationNotificationReadRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn75AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + } } @@ -3147,6 +3322,80 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } + case 'n': // Prefix: "notifications" + + if l := len("notifications"); len(elem) >= l && elem[0:l] == "notifications" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "GET": + r.name = ListMyNotificationsOperation + r.summary = "List the inbox of the current candidate." + r.operationID = "ListMyNotifications" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/notifications" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "notification_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + break + } + switch elem[0] { + case '/': // Prefix: "/read" + + if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = MarkMyNotificationReadOperation + r.summary = "Mark an item of the inbox of the current candidate as read." + r.operationID = "MarkMyNotificationRead" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/notifications/{notification_id}/read" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + } + + } + case 'o': // Prefix: "organizations" if l := len("organizations"); len(elem) >= l && elem[0:l] == "organizations" { @@ -3957,81 +4206,169 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } - case 'n': // Prefix: "needs" + case 'n': // Prefix: "n" - if l := len("needs"); len(elem) >= l && elem[0:l] == "needs" { + if l := len("n"); len(elem) >= l && elem[0:l] == "n" { elem = elem[l:] } else { break } if len(elem) == 0 { - switch method { - case "GET": - r.name = ListOrganizationNeedsOperation - r.summary = "List the needs of an organization." - r.operationID = "ListOrganizationNeeds" - r.operationGroup = "" - r.pathPattern = "/api/v1/organizations/{org_id}/needs" - r.args = args - r.count = 1 - return r, true - case "POST": - r.name = CreateOrganizationNeedOperation - r.summary = "Create a need of an organization from a form, a text, or both." - r.operationID = "CreateOrganizationNeed" - r.operationGroup = "" - r.pathPattern = "/api/v1/organizations/{org_id}/needs" - r.args = args - r.count = 1 - return r, true - default: - return - } + break } switch elem[0] { - case '/': // Prefix: "/" + case 'e': // Prefix: "eeds" - if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + if l := len("eeds"); len(elem) >= l && elem[0:l] == "eeds" { elem = elem[l:] } else { break } - // Param: "need_id" - // Leaf parameter, slashes are prohibited - idx := strings.IndexByte(elem, '/') - if idx >= 0 { - break - } - args[1] = elem - elem = "" - if len(elem) == 0 { - // Leaf node. switch method { case "GET": - r.name = GetOrganizationNeedOperation - r.summary = "Read the current version of a need of an organization." - r.operationID = "GetOrganizationNeed" + r.name = ListOrganizationNeedsOperation + r.summary = "List the needs of an organization." + r.operationID = "ListOrganizationNeeds" r.operationGroup = "" - r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}" + r.pathPattern = "/api/v1/organizations/{org_id}/needs" r.args = args - r.count = 2 + r.count = 1 return r, true - case "PATCH": - r.name = UpdateOrganizationNeedOperation - r.summary = "Confirm, change, or delete requirements of a need." - r.operationID = "UpdateOrganizationNeed" + case "POST": + r.name = CreateOrganizationNeedOperation + r.summary = "Create a need of an organization from a form, a text, or both." + r.operationID = "CreateOrganizationNeed" r.operationGroup = "" - r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}" + r.pathPattern = "/api/v1/organizations/{org_id}/needs" r.args = args - r.count = 2 + r.count = 1 return r, true default: return } } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "need_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[1] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetOrganizationNeedOperation + r.summary = "Read the current version of a need of an organization." + r.operationID = "GetOrganizationNeed" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}" + r.args = args + r.count = 2 + return r, true + case "PATCH": + r.name = UpdateOrganizationNeedOperation + r.summary = "Confirm, change, or delete requirements of a need." + r.operationID = "UpdateOrganizationNeed" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + } + + case 'o': // Prefix: "otifications" + + if l := len("otifications"); len(elem) >= l && elem[0:l] == "otifications" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "GET": + r.name = ListOrganizationNotificationsOperation + r.summary = "List the inbox of the current employer in one organization." + r.operationID = "ListOrganizationNotifications" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/notifications" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "notification_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[1] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + break + } + switch elem[0] { + case '/': // Prefix: "/read" + + if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = MarkOrganizationNotificationReadOperation + r.summary = "Mark an item of the inbox of the current employer in one organization as read." + r.operationID = "MarkOrganizationNotificationRead" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/notifications/{notification_id}/read" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + } + + } } diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 460a829..0ce86a0 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -12625,6 +12625,18 @@ type ListMyInvitationsUnauthorized Problem func (*ListMyInvitationsUnauthorized) listMyInvitationsRes() {} +type ListMyNotificationsBadRequest Problem + +func (*ListMyNotificationsBadRequest) listMyNotificationsRes() {} + +type ListMyNotificationsForbidden Problem + +func (*ListMyNotificationsForbidden) listMyNotificationsRes() {} + +type ListMyNotificationsUnauthorized Problem + +func (*ListMyNotificationsUnauthorized) listMyNotificationsRes() {} + type ListMyOrganizationsBadRequest Problem func (*ListMyOrganizationsBadRequest) listMyOrganizationsRes() {} @@ -12689,6 +12701,22 @@ type ListOrganizationNeedsUnauthorized Problem func (*ListOrganizationNeedsUnauthorized) listOrganizationNeedsRes() {} +type ListOrganizationNotificationsBadRequest Problem + +func (*ListOrganizationNotificationsBadRequest) listOrganizationNotificationsRes() {} + +type ListOrganizationNotificationsForbidden Problem + +func (*ListOrganizationNotificationsForbidden) listOrganizationNotificationsRes() {} + +type ListOrganizationNotificationsNotFound Problem + +func (*ListOrganizationNotificationsNotFound) listOrganizationNotificationsRes() {} + +type ListOrganizationNotificationsUnauthorized Problem + +func (*ListOrganizationNotificationsUnauthorized) listOrganizationNotificationsRes() {} + type LoginBadRequest Problem func (*LoginBadRequest) loginRes() {} @@ -12747,6 +12775,38 @@ func (s *LogoutNoContent) SetSetCookie(val string) { func (*LogoutNoContent) logoutRes() {} +type MarkMyNotificationReadBadRequest Problem + +func (*MarkMyNotificationReadBadRequest) markMyNotificationReadRes() {} + +type MarkMyNotificationReadForbidden Problem + +func (*MarkMyNotificationReadForbidden) markMyNotificationReadRes() {} + +type MarkMyNotificationReadNotFound Problem + +func (*MarkMyNotificationReadNotFound) markMyNotificationReadRes() {} + +type MarkMyNotificationReadUnauthorized Problem + +func (*MarkMyNotificationReadUnauthorized) markMyNotificationReadRes() {} + +type MarkOrganizationNotificationReadBadRequest Problem + +func (*MarkOrganizationNotificationReadBadRequest) markOrganizationNotificationReadRes() {} + +type MarkOrganizationNotificationReadForbidden Problem + +func (*MarkOrganizationNotificationReadForbidden) markOrganizationNotificationReadRes() {} + +type MarkOrganizationNotificationReadNotFound Problem + +func (*MarkOrganizationNotificationReadNotFound) markOrganizationNotificationReadRes() {} + +type MarkOrganizationNotificationReadUnauthorized Problem + +func (*MarkOrganizationNotificationReadUnauthorized) markOrganizationNotificationReadRes() {} + // Conditions echoed as a complete snapshot; null means no filter. // Ref: #/components/schemas/MatchAppliedConditions type MatchAppliedConditions struct { @@ -13864,6 +13924,11 @@ func NewMatchSearchByBankMatchSearchRequest(v MatchSearchByBank) MatchSearchRequ type MatchSearchResponse struct { Source MatchSearchSource `json:"source"` Groups MatchSearchGroups `json:"groups"` + // True when the groups are not the whole ranked result: a group exceeded the versioned per-group + // limit, or the organization's card-view allowance ended while the entries were being revealed. The + // entries returned are in rank order and already counted as card views. It carries no total, so it + // does not reveal how many candidates match. + Truncated bool `json:"truncated"` } // GetSource returns the value of Source. @@ -13876,6 +13941,11 @@ func (s *MatchSearchResponse) GetGroups() MatchSearchGroups { return s.Groups } +// GetTruncated returns the value of Truncated. +func (s *MatchSearchResponse) GetTruncated() bool { + return s.Truncated +} + // SetSource sets the value of Source. func (s *MatchSearchResponse) SetSource(val MatchSearchSource) { s.Source = val @@ -13886,6 +13956,11 @@ func (s *MatchSearchResponse) SetGroups(val MatchSearchGroups) { s.Groups = val } +// SetTruncated sets the value of Truncated. +func (s *MatchSearchResponse) SetTruncated(val bool) { + s.Truncated = val +} + // MatchSearchResponseHeaders wraps MatchSearchResponse with response headers. type MatchSearchResponseHeaders struct { CacheControl CacheControlNoStore @@ -14392,7 +14467,10 @@ func (s *MatchUnknownFlag) SetReason(val MatchUnknownReason) { type MatchUnknownFlags []MatchUnknownFlag -// Bounded explanation for an unknown component, not a hiding reason. +// Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported +// only while the comparable real cohort of the category is smaller than the versioned minimum; once +// the cohort reaches the minimum but the percentile is still not computed, the reason is +// `percentile_not_computed`. In both cases T is the neutral 0.5. // Ref: #/components/schemas/MatchUnknownReason type MatchUnknownReason string @@ -14404,6 +14482,7 @@ const ( MatchUnknownReasonNeedFieldUnconfirmed MatchUnknownReason = "need_field_unconfirmed" MatchUnknownReasonNoFreshnessHistory MatchUnknownReason = "no_freshness_history" MatchUnknownReasonNoResponseHistory MatchUnknownReason = "no_response_history" + MatchUnknownReasonPercentileNotComputed MatchUnknownReason = "percentile_not_computed" ) // AllValues returns all MatchUnknownReason values. @@ -14416,6 +14495,7 @@ func (MatchUnknownReason) AllValues() []MatchUnknownReason { MatchUnknownReasonNeedFieldUnconfirmed, MatchUnknownReasonNoFreshnessHistory, MatchUnknownReasonNoResponseHistory, + MatchUnknownReasonPercentileNotComputed, } } @@ -14436,6 +14516,8 @@ func (s MatchUnknownReason) MarshalText() ([]byte, error) { return []byte(s), nil case MatchUnknownReasonNoResponseHistory: return []byte(s), nil + case MatchUnknownReasonPercentileNotComputed: + return []byte(s), nil default: return nil, errors.Errorf("invalid value: %q", s) } @@ -14465,6 +14547,9 @@ func (s *MatchUnknownReason) UnmarshalText(data []byte) error { case MatchUnknownReasonNoResponseHistory: *s = MatchUnknownReasonNoResponseHistory return nil + case MatchUnknownReasonPercentileNotComputed: + *s = MatchUnknownReasonPercentileNotComputed + return nil default: return errors.Errorf("invalid value: %q", data) } @@ -18830,6 +18915,51 @@ func (o NilNeedVersionLabel) Or(d NeedVersionLabel) NeedVersionLabel { return d } +// NewNilNotificationContent returns new NilNotificationContent with value set to v. +func NewNilNotificationContent(v NotificationContent) NilNotificationContent { + return NilNotificationContent{ + Value: v, + } +} + +// NilNotificationContent is nullable NotificationContent. +type NilNotificationContent struct { + Value NotificationContent + Null bool +} + +// SetTo sets value to v. +func (o *NilNotificationContent) SetTo(v NotificationContent) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilNotificationContent) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilNotificationContent) SetToNull() { + o.Null = true + var v NotificationContent + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilNotificationContent) Get() (v NotificationContent, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilNotificationContent) Or(d NotificationContent) NotificationContent { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilOrganizationDescription returns new NilOrganizationDescription with value set to v. func NewNilOrganizationDescription(v OrganizationDescription) NilOrganizationDescription { return NilOrganizationDescription{ @@ -20495,6 +20625,301 @@ func (o NilWorkContext) Or(d WorkContext) WorkContext { return d } +// One item of the inbox of the current account. Its identity, kind, organization, delivery time, and +// read state are stored; its content is resolved from the current source on every read. +// Ref: #/components/schemas/Notification +type Notification struct { + // Identifier of the item. It equals the identifier of the event that produced it, so a repeated + // delivery of the same event is the same item. + ID uuid.UUID `json:"id"` + Kind NotificationKind `json:"kind"` + // The organization context of the item: the organization that sent it to a candidate, or the + // organization whose cabinet holds it for an employer. The identifier is not a right to read the + // organization. + OrganizationID uuid.UUID `json:"organization_id"` + DeliveredAt Timestamp `json:"delivered_at"` + // When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the + // first time. + ReadAt NilTimestamp `json:"read_at"` + // The current content, or null when the source is gone or the recipient may not see it now. A client + // then shows a generic line such as "The content is no longer available" and never an old copy. The + // item stays in the list and can be marked read. + Content NilNotificationContent `json:"content"` +} + +// GetID returns the value of ID. +func (s *Notification) GetID() uuid.UUID { + return s.ID +} + +// GetKind returns the value of Kind. +func (s *Notification) GetKind() NotificationKind { + return s.Kind +} + +// GetOrganizationID returns the value of OrganizationID. +func (s *Notification) GetOrganizationID() uuid.UUID { + return s.OrganizationID +} + +// GetDeliveredAt returns the value of DeliveredAt. +func (s *Notification) GetDeliveredAt() Timestamp { + return s.DeliveredAt +} + +// GetReadAt returns the value of ReadAt. +func (s *Notification) GetReadAt() NilTimestamp { + return s.ReadAt +} + +// GetContent returns the value of Content. +func (s *Notification) GetContent() NilNotificationContent { + return s.Content +} + +// SetID sets the value of ID. +func (s *Notification) SetID(val uuid.UUID) { + s.ID = val +} + +// SetKind sets the value of Kind. +func (s *Notification) SetKind(val NotificationKind) { + s.Kind = val +} + +// SetOrganizationID sets the value of OrganizationID. +func (s *Notification) SetOrganizationID(val uuid.UUID) { + s.OrganizationID = val +} + +// SetDeliveredAt sets the value of DeliveredAt. +func (s *Notification) SetDeliveredAt(val Timestamp) { + s.DeliveredAt = val +} + +// SetReadAt sets the value of ReadAt. +func (s *Notification) SetReadAt(val NilTimestamp) { + s.ReadAt = val +} + +// SetContent sets the value of Content. +func (s *Notification) SetContent(val NilNotificationContent) { + s.Content = val +} + +// The text of a notification as the current source shows it to the recipient now. It is computed on +// every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it +// from the next read. It holds no contact, no score, and no result of an assessment. +// Ref: #/components/schemas/NotificationContent +type NotificationContent struct { + // Short heading in Russian. + Title string `json:"title"` + // One or two sentences in Russian. Plain text, never markup. + Summary string `json:"summary"` + // Same-origin absolute path of the screen that the notification opens, or null when there is none. It + // has no origin, query, fragment, or escape; a client opens it only as a path of its own router. + LinkPath NilString `json:"link_path"` +} + +// GetTitle returns the value of Title. +func (s *NotificationContent) GetTitle() string { + return s.Title +} + +// GetSummary returns the value of Summary. +func (s *NotificationContent) GetSummary() string { + return s.Summary +} + +// GetLinkPath returns the value of LinkPath. +func (s *NotificationContent) GetLinkPath() NilString { + return s.LinkPath +} + +// SetTitle sets the value of Title. +func (s *NotificationContent) SetTitle(val string) { + s.Title = val +} + +// SetSummary sets the value of Summary. +func (s *NotificationContent) SetSummary(val string) { + s.Summary = val +} + +// SetLinkPath sets the value of LinkPath. +func (s *NotificationContent) SetLinkPath(val NilString) { + s.LinkPath = val +} + +// Which event put the notification into the inbox. The inbox stores a reference to the event, never +// its text. +// +// - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform +// delivery state of the invitation: it does not depend on any email, and a failed or missing email +// never blocks it. The invitation operations are planned; no invitation produces a notification +// yet. +// - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility +// check, the list, and the read state). It has no product meaning, needs no action, and is never +// produced by a user action. +// +// Adding a value is a contract change; a client shows an unknown kind with the generic text of an item +// without content. +// Ref: #/components/schemas/NotificationKind +type NotificationKind string + +const ( + NotificationKindInvitationDelivered NotificationKind = "invitation_delivered" + NotificationKindSynthetic NotificationKind = "synthetic" +) + +// AllValues returns all NotificationKind values. +func (NotificationKind) AllValues() []NotificationKind { + return []NotificationKind{ + NotificationKindInvitationDelivered, + NotificationKindSynthetic, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s NotificationKind) MarshalText() ([]byte, error) { + switch s { + case NotificationKindInvitationDelivered: + return []byte(s), nil + case NotificationKindSynthetic: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *NotificationKind) UnmarshalText(data []byte) error { + switch NotificationKind(data) { + case NotificationKindInvitationDelivered: + *s = NotificationKindInvitationDelivered + return nil + case NotificationKindSynthetic: + *s = NotificationKindSynthetic + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One page of the inbox, newest delivery first. +// Ref: #/components/schemas/NotificationList +type NotificationList struct { + // Items of the page. + Items []Notification `json:"items"` + Page PageInfo `json:"page"` +} + +// GetItems returns the value of Items. +func (s *NotificationList) GetItems() []Notification { + return s.Items +} + +// GetPage returns the value of Page. +func (s *NotificationList) GetPage() PageInfo { + return s.Page +} + +// SetItems sets the value of Items. +func (s *NotificationList) SetItems(val []Notification) { + s.Items = val +} + +// SetPage sets the value of Page. +func (s *NotificationList) SetPage(val PageInfo) { + s.Page = val +} + +// NotificationListHeaders wraps NotificationList with response headers. +type NotificationListHeaders struct { + CacheControl CacheControlNoStore + Response NotificationList +} + +// GetCacheControl returns the value of CacheControl. +func (s *NotificationListHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *NotificationListHeaders) GetResponse() NotificationList { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *NotificationListHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *NotificationListHeaders) SetResponse(val NotificationList) { + s.Response = val +} + +func (*NotificationListHeaders) listMyNotificationsRes() {} +func (*NotificationListHeaders) listOrganizationNotificationsRes() {} + +// The read state of one item after a mark. It carries no content, so marking never reads the source. +// Ref: #/components/schemas/NotificationReadReceipt +type NotificationReadReceipt struct { + // Identifier of the marked item. + ID uuid.UUID `json:"id"` + ReadAt Timestamp `json:"read_at"` +} + +// GetID returns the value of ID. +func (s *NotificationReadReceipt) GetID() uuid.UUID { + return s.ID +} + +// GetReadAt returns the value of ReadAt. +func (s *NotificationReadReceipt) GetReadAt() Timestamp { + return s.ReadAt +} + +// SetID sets the value of ID. +func (s *NotificationReadReceipt) SetID(val uuid.UUID) { + s.ID = val +} + +// SetReadAt sets the value of ReadAt. +func (s *NotificationReadReceipt) SetReadAt(val Timestamp) { + s.ReadAt = val +} + +// NotificationReadReceiptHeaders wraps NotificationReadReceipt with response headers. +type NotificationReadReceiptHeaders struct { + CacheControl CacheControlNoStore + Response NotificationReadReceipt +} + +// GetCacheControl returns the value of CacheControl. +func (s *NotificationReadReceiptHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *NotificationReadReceiptHeaders) GetResponse() NotificationReadReceipt { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *NotificationReadReceiptHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *NotificationReadReceiptHeaders) SetResponse(val NotificationReadReceipt) { + s.Response = val +} + +func (*NotificationReadReceiptHeaders) markMyNotificationReadRes() {} +func (*NotificationReadReceiptHeaders) markOrganizationNotificationReadRes() {} + // Numeric answer in the unit of the item. Two answers are equal when their decoded values are // numerically equal, so 254 and 254.0 are the same answer. // Ref: #/components/schemas/NumberAnswer @@ -30507,6 +30932,8 @@ func (*TooManyRequestsHeaders) getOrganizationCandidateCardRes() {} func (*TooManyRequestsHeaders) getOrganizationCandidateEvidenceRes() {} func (*TooManyRequestsHeaders) hideOrganizationRes() {} func (*TooManyRequestsHeaders) loginRes() {} +func (*TooManyRequestsHeaders) markMyNotificationReadRes() {} +func (*TooManyRequestsHeaders) markOrganizationNotificationReadRes() {} func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {} func (*TooManyRequestsHeaders) recordMyAssessmentAttemptSignalsRes() {} func (*TooManyRequestsHeaders) registerAccountRes() {} diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index a169ab4..15eca84 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -93,12 +93,16 @@ var operationRolesSessionCookie = map[string][]string{ ListMyEvidenceOperation: []string{}, ListMyHiddenOrganizationsOperation: []string{}, ListMyInvitationsOperation: []string{}, + ListMyNotificationsOperation: []string{}, ListMyOrganizationsOperation: []string{}, ListMyPrivacyHistoryOperation: []string{}, ListMySupportCasesOperation: []string{}, ListOrganizationInvitationsOperation: []string{}, ListOrganizationNeedsOperation: []string{}, + ListOrganizationNotificationsOperation: []string{}, LogoutOperation: []string{}, + MarkMyNotificationReadOperation: []string{}, + MarkOrganizationNotificationReadOperation: []string{}, RaiseOrganizationInvitationSalaryOperation: []string{}, RecordMyAssessmentAttemptSignalsOperation: []string{}, RequestMyAccountDeletionOperation: []string{}, @@ -156,6 +160,8 @@ var operationRolesSessionCsrf = map[string][]string{ GrantMyConsentOperation: []string{}, HideOrganizationOperation: []string{}, LogoutOperation: []string{}, + MarkMyNotificationReadOperation: []string{}, + MarkOrganizationNotificationReadOperation: []string{}, RaiseOrganizationInvitationSalaryOperation: []string{}, RecordMyAssessmentAttemptSignalsOperation: []string{}, RequestMyAccountDeletionOperation: []string{}, diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index 7d267e5..96c4bad 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -1173,6 +1173,27 @@ type Handler interface { // // GET /api/v1/me/invitations ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (ListMyInvitationsRes, error) + // ListMyNotifications implements ListMyNotifications operation. + // + // Requires the session cookie of a candidate account with a confirmed email. The recipient comes from + // the session, never from a request parameter, so the response holds only the caller's own items. + // Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor + // pagination. The response is `Cache-Control: no-store`. + // + // The inbox is the in-platform delivery state of a notification. An item exists as soon as the event + // reached the platform, whether or not any email was sent, and an email that failed or was never sent + // does not block it. The inbox stores a reference to the event, not its text: the `content` of every + // item is resolved from the current source for this recipient on this read. When the source is gone or + // the recipient may not see it now (for example the candidate hid the organization), the item stays in + // the list with `content` null, and no earlier text is shown. An event that is delivered twice is one + // item. + // + // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer + // account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account, + // answers 400 validation_failed. + // + // GET /api/v1/me/notifications + ListMyNotifications(ctx context.Context, params ListMyNotificationsParams) (ListMyNotificationsRes, error) // ListMyOrganizations implements ListMyOrganizations operation. // // Requires the session cookie of an employer account. The account comes from the session, never from a @@ -1278,6 +1299,27 @@ type Handler interface { // // GET /api/v1/organizations/{org_id}/needs ListOrganizationNeeds(ctx context.Context, params ListOrganizationNeedsParams) (ListOrganizationNeedsRes, error) + // ListOrganizationNotifications implements ListOrganizationNotifications operation. + // + // Requires the session cookie of an employer account with a confirmed email and an active membership + // in `org_id`, whatever its role. The recipient comes from the session and the organization from the + // path and the membership that the server holds, never from the request. Returns only the items + // addressed to the caller in this organization, newest delivery first with the identifier as the + // tie-breaker, with cursor pagination. An item of the same account in another organization, and an + // item of another member, are never listed. The response is `Cache-Control: no-store`. + // + // Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email + // never blocks an item, and the `content` of every item is resolved from the current source for this + // recipient on this read. An employer sees content only while the membership is active. + // + // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate + // account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 + // email_not_verified; an account without an active membership in the organization and an unknown + // organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`, + // `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed. + // + // GET /api/v1/organizations/{org_id}/notifications + ListOrganizationNotifications(ctx context.Context, params ListOrganizationNotificationsParams) (ListOrganizationNotificationsRes, error) // Login implements Login operation. // // Public operation that starts a server session. The server verifies the password with Argon2id; for @@ -1312,6 +1354,49 @@ type Handler interface { // // DELETE /api/v1/identity/sessions/current Logout(ctx context.Context) (LogoutRes, error) + // MarkMyNotificationRead implements MarkMyNotificationRead operation. + // + // Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that + // session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request + // has no body. + // + // The command is idempotent by its effect: the first mark stores the read time and every repeat + // returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no + // content, so marking an item whose content is no longer available still works. It changes no other + // item. + // + // The general rate limit can answer 429 with Retry-After before any check. + // + // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or + // wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers + // 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so + // identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400 + // validation_failed with the path pointer. + // + // POST /api/v1/me/notifications/{notification_id}/read + MarkMyNotificationRead(ctx context.Context, params MarkMyNotificationReadParams) (MarkMyNotificationReadRes, error) + // MarkOrganizationNotificationRead implements MarkOrganizationNotificationRead operation. + // + // Requires the session cookie of an employer account with a confirmed email and an active membership + // in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed + // Origin. The recipient comes from the session and the organization from the path and the server-side + // membership. The request has no body. + // + // The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The + // item must belong to the caller in this organization. + // + // The general rate limit can answer 429 with Retry-After before any check. + // + // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or + // wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers + // 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an + // account without an active membership in the organization, an unknown organization, an item of + // another account, an item of another organization, and an unknown identifier all answer 404 + // not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path + // pointer. + // + // POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read + MarkOrganizationNotificationRead(ctx context.Context, params MarkOrganizationNotificationReadParams) (MarkOrganizationNotificationReadRes, error) // RaiseOrganizationInvitationSalary implements RaiseOrganizationInvitationSalary operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF @@ -1585,6 +1670,15 @@ type Handler interface { // empty bank filter searches all otherwise eligible specializations, returning each specialization // separately. // + // A search reveals card content, so it is charged like card reads. The whole visible bank is ranked, + // but each group returns at most the versioned per-group limit and no total is returned. In the order + // `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of + // the organization (a candidate it already viewed inside the window costs nothing again, so repeating + // the search or opening the card afterwards does not charge twice) and appears in the candidate's + // access history with the fields actually returned. When the allowance ends, the entries already + // counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit, + // and it carries no count. No new error is returned for an exhausted allowance. + // // Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks // for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A // confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed @@ -1600,7 +1694,10 @@ type Handler interface { // Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity // uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 // comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names - // `cohort_below_30`. + // `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile + // is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, + // the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not + // fail. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account // answers 403 forbidden; an unknown organization or account without active membership answers 404 diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 8930842..c0fb67c 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -1301,6 +1301,30 @@ func (UnimplementedHandler) ListMyInvitations(ctx context.Context, params ListMy return r, ht.ErrNotImplemented } +// ListMyNotifications implements ListMyNotifications operation. +// +// Requires the session cookie of a candidate account with a confirmed email. The recipient comes from +// the session, never from a request parameter, so the response holds only the caller's own items. +// Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor +// pagination. The response is `Cache-Control: no-store`. +// +// The inbox is the in-platform delivery state of a notification. An item exists as soon as the event +// reached the platform, whether or not any email was sent, and an email that failed or was never sent +// does not block it. The inbox stores a reference to the event, not its text: the `content` of every +// item is resolved from the current source for this recipient on this read. When the source is gone or +// the recipient may not see it now (for example the candidate hid the organization), the item stays in +// the list with `content` null, and no earlier text is shown. An event that is delivered twice is one +// item. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer +// account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account, +// answers 400 validation_failed. +// +// GET /api/v1/me/notifications +func (UnimplementedHandler) ListMyNotifications(ctx context.Context, params ListMyNotificationsParams) (r ListMyNotificationsRes, _ error) { + return r, ht.ErrNotImplemented +} + // ListMyOrganizations implements ListMyOrganizations operation. // // Requires the session cookie of an employer account. The account comes from the session, never from a @@ -1421,6 +1445,30 @@ func (UnimplementedHandler) ListOrganizationNeeds(ctx context.Context, params Li return r, ht.ErrNotImplemented } +// ListOrganizationNotifications implements ListOrganizationNotifications operation. +// +// Requires the session cookie of an employer account with a confirmed email and an active membership +// in `org_id`, whatever its role. The recipient comes from the session and the organization from the +// path and the membership that the server holds, never from the request. Returns only the items +// addressed to the caller in this organization, newest delivery first with the identifier as the +// tie-breaker, with cursor pagination. An item of the same account in another organization, and an +// item of another member, are never listed. The response is `Cache-Control: no-store`. +// +// Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email +// never blocks an item, and the `content` of every item is resolved from the current source for this +// recipient on this read. An employer sees content only while the membership is active. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate +// account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 +// email_not_verified; an account without an active membership in the organization and an unknown +// organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`, +// `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed. +// +// GET /api/v1/organizations/{org_id}/notifications +func (UnimplementedHandler) ListOrganizationNotifications(ctx context.Context, params ListOrganizationNotificationsParams) (r ListOrganizationNotificationsRes, _ error) { + return r, ht.ErrNotImplemented +} + // Login implements Login operation. // // Public operation that starts a server session. The server verifies the password with Argon2id; for @@ -1461,6 +1509,55 @@ func (UnimplementedHandler) Logout(ctx context.Context) (r LogoutRes, _ error) { return r, ht.ErrNotImplemented } +// MarkMyNotificationRead implements MarkMyNotificationRead operation. +// +// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that +// session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request +// has no body. +// +// The command is idempotent by its effect: the first mark stores the read time and every repeat +// returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no +// content, so marking an item whose content is no longer available still works. It changes no other +// item. +// +// The general rate limit can answer 429 with Retry-After before any check. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or +// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers +// 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so +// identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400 +// validation_failed with the path pointer. +// +// POST /api/v1/me/notifications/{notification_id}/read +func (UnimplementedHandler) MarkMyNotificationRead(ctx context.Context, params MarkMyNotificationReadParams) (r MarkMyNotificationReadRes, _ error) { + return r, ht.ErrNotImplemented +} + +// MarkOrganizationNotificationRead implements MarkOrganizationNotificationRead operation. +// +// Requires the session cookie of an employer account with a confirmed email and an active membership +// in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed +// Origin. The recipient comes from the session and the organization from the path and the server-side +// membership. The request has no body. +// +// The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The +// item must belong to the caller in this organization. +// +// The general rate limit can answer 429 with Retry-After before any check. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or +// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers +// 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an +// account without an active membership in the organization, an unknown organization, an item of +// another account, an item of another organization, and an unknown identifier all answer 404 +// not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path +// pointer. +// +// POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read +func (UnimplementedHandler) MarkOrganizationNotificationRead(ctx context.Context, params MarkOrganizationNotificationReadParams) (r MarkOrganizationNotificationReadRes, _ error) { + return r, ht.ErrNotImplemented +} + // RaiseOrganizationInvitationSalary implements RaiseOrganizationInvitationSalary operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF @@ -1761,6 +1858,15 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid // empty bank filter searches all otherwise eligible specializations, returning each specialization // separately. // +// A search reveals card content, so it is charged like card reads. The whole visible bank is ranked, +// but each group returns at most the versioned per-group limit and no total is returned. In the order +// `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of +// the organization (a candidate it already viewed inside the window costs nothing again, so repeating +// the search or opening the card afterwards does not charge twice) and appears in the candidate's +// access history with the fields actually returned. When the allowance ends, the entries already +// counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit, +// and it carries no count. No new error is returned for an exhausted allowance. +// // Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks // for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A // confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed @@ -1776,7 +1882,10 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid // Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity // uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30 // comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names -// `cohort_below_30`. +// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile +// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, +// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not +// fail. // // A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account // answers 403 forbidden; an unknown organization or account without active membership answers 404 diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index f19f3c6..99b8a04 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -11427,6 +11427,30 @@ func (s *ListMyInvitationsUnauthorized) Validate() error { return nil } +func (s *ListMyNotificationsBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyNotificationsForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyNotificationsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ListMyOrganizationsBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -11555,6 +11579,38 @@ func (s *ListOrganizationNeedsUnauthorized) Validate() error { return nil } +func (s *ListOrganizationNotificationsBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListOrganizationNotificationsForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListOrganizationNotificationsNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListOrganizationNotificationsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *LoginBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -11668,6 +11724,70 @@ func (s *LogoutNoContent) Validate() error { return nil } +func (s *MarkMyNotificationReadBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *MarkMyNotificationReadForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *MarkMyNotificationReadNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *MarkMyNotificationReadUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *MarkOrganizationNotificationReadBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *MarkOrganizationNotificationReadForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *MarkOrganizationNotificationReadNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *MarkOrganizationNotificationReadUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *MatchAppliedConditions) Validate() error { if s == nil { return validate.ErrNilPointer @@ -13378,6 +13498,8 @@ func (s MatchUnknownReason) Validate() error { return nil case "no_response_history": return nil + case "percentile_not_computed": + return nil default: return errors.Errorf("invalid value: %v", s) } @@ -16179,6 +16301,262 @@ func (s NewPassword) Validate() error { return nil } +func (s *Notification) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Content.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: "content", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *NotificationContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 120, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Title)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "title", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 500, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Summary)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "summary", + Error: err, + }) + } + if err := func() error { + if value, ok := s.LinkPath.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 256, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^/[A-Za-z0-9/_-]{0,255}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "link_path", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s NotificationKind) Validate() error { + switch s { + case "invitation_delivered": + return nil + case "synthetic": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *NotificationList) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Items == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Items)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Items { + 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: "items", + Error: err, + }) + } + if err := func() error { + if err := s.Page.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "page", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *NotificationListHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *NotificationReadReceiptHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *NumberAnswer) Validate() error { if s == nil { return validate.ErrNilPointer diff --git a/backend/internal/adapter/primary/http/company_context.go b/backend/internal/adapter/primary/http/company_context.go index 9113673..813ce9a 100644 --- a/backend/internal/adapter/primary/http/company_context.go +++ b/backend/internal/adapter/primary/http/company_context.go @@ -36,9 +36,9 @@ var ownerCompanyOperations = map[apiadapter.OperationName]struct{}{ apiadapter.GetOrganizationInvitationContactsOperation: {}, apiadapter.WithdrawOrganizationInvitationOperation: {}, apiadapter.RaiseOrganizationInvitationSalaryOperation: {}, - // The match search contract requires an active owner membership. The - // operation has no handler yet; classifying it here keeps it closed to - // every other role when the handler arrives. + // The match search requires an active owner membership: the minimal + // milestone grants a membership by itself no tenant right, and the usecase + // repeats the owner check inside its transaction. apiadapter.SearchOrganizationMatchesOperation: {}, } diff --git a/backend/internal/adapter/primary/http/company_context_test.go b/backend/internal/adapter/primary/http/company_context_test.go index 790bf40..07a2cdb 100644 --- a/backend/internal/adapter/primary/http/company_context_test.go +++ b/backend/internal/adapter/primary/http/company_context_test.go @@ -53,6 +53,9 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesOtherScopes(t *testing.T) // the owner-only capability does not apply to that operation. apiadapter.GetOrganizationCandidateCardOperation, apiadapter.GetOrganizationCandidateEvidenceOperation, + // The inbox runs the membership check in the read transaction for any role. + apiadapter.ListOrganizationNotificationsOperation, + apiadapter.MarkOrganizationNotificationReadOperation, apiadapter.HideOrganizationOperation, apiadapter.UnhideOrganizationOperation, apiadapter.RevokeMyOrganizationContactConsentOperation, @@ -111,6 +114,13 @@ func TestCompanyContextMiddlewareMapsMembershipFailuresToPublicProblems(t *testi } } +// organizationNotificationPaths are the inbox operations of one organization, +// which check the membership inside their own transaction. +var organizationNotificationPaths = map[string]string{ + "ListOrganizationNotifications": "/api/v1/organizations/{org_id}/notifications", + "MarkOrganizationNotificationRead": "/api/v1/organizations/{org_id}/notifications/{notification_id}/read", +} + func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) { const bundlePath = "../../../../../api/core/openapi.bundle.yml" data, err := os.ReadFile(bundlePath) @@ -137,6 +147,7 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) { seenExceptions := make(map[string]bool, len(candidateExceptions)) seenCardRead := false seenEvidenceRead := false + seenNotifications := map[string]bool{} for path, methods := range document.Paths { for _, operation := range methods { if operation.OperationID == "" { @@ -170,6 +181,13 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) { seenEvidenceRead = true continue } + // The inbox of one organization authorizes any active membership and + // the recipient together with the read, inside the read transaction; + // the owner-only capability does not apply. + if notificationPath, ok := organizationNotificationPaths[operation.OperationID]; ok && notificationPath == path { + seenNotifications[operation.OperationID] = true + continue + } expectedPath, candidateOperation := candidateExceptions[operation.OperationID] if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") { seenExceptions[operation.OperationID] = true @@ -194,6 +212,11 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) { if !seenEvidenceRead { t.Error("transaction-authorized candidate evidence read is absent or moved") } + for operation := range organizationNotificationPaths { + if !seenNotifications[operation] { + t.Errorf("transaction-authorized inbox operation %s is absent or moved", operation) + } + } } type companyContextAuthenticator struct { diff --git a/backend/internal/adapter/primary/http/notification_contract_test.go b/backend/internal/adapter/primary/http/notification_contract_test.go new file mode 100644 index 0000000..b496e16 --- /dev/null +++ b/backend/internal/adapter/primary/http/notification_contract_test.go @@ -0,0 +1,127 @@ +package httpadapter + +import ( + "slices" + "testing" + + "github.com/ogen-go/ogen" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +// The four inbox operations follow the project conventions: the session +// cookie for a read, the session and the CSRF token for a mark, no-store on +// every success, the shared cursor parameters, the anti-enumeration 404 on +// everything keyed by an identifier, and no new problem code. +func TestNotificationOperationsFollowTheConventions(t *testing.T) { + spec := parsePublicContract(t) + for _, test := range []struct { + id string + path string + reads bool + parameters []string + statuses []string + absent []string + }{ + {id: "ListMyNotifications", path: "/api/v1/me/notifications", reads: true, + parameters: []string{"PageLimit", "PageCursor"}, statuses: []string{"400", "401", "403"}, absent: []string{"404"}}, + {id: "ListOrganizationNotifications", path: "/api/v1/organizations/{org_id}/notifications", reads: true, + parameters: []string{"OrganizationId", "PageLimit", "PageCursor"}, statuses: []string{"400", "401", "403", "404"}}, + {id: "MarkMyNotificationRead", path: "/api/v1/me/notifications/{notification_id}/read", + parameters: []string{"NotificationId"}, statuses: []string{"400", "401", "403", "404", "429"}}, + {id: "MarkOrganizationNotificationRead", path: "/api/v1/organizations/{org_id}/notifications/{notification_id}/read", + parameters: []string{"OrganizationId", "NotificationId"}, statuses: []string{"400", "401", "403", "404", "429"}}, + } { + t.Run(test.id, func(t *testing.T) { + operation := operationByID(t, spec, test.id) + if spec.Paths[test.path] == nil { + t.Fatalf("the contract has no path %s", test.path) + } + if !slices.Contains(operation.Tags, "notification") { + t.Errorf("%s is not in the notification tag", test.id) + } + if !hasSecurity(operation, "sessionCookie") || hasSecurity(operation, "sessionCsrf") == test.reads { + t.Errorf("%s security = %v, want the session cookie and a CSRF token only for a mark", test.id, operation.Security) + } + for _, status := range append(test.statuses, "default") { + if operation.Responses[status] == nil { + t.Errorf("%s does not declare %s", test.id, status) + } + } + for _, status := range test.absent { + if operation.Responses[status] != nil { + t.Errorf("%s declares %s", test.id, status) + } + } + if success := operation.Responses["200"]; success == nil || success.Headers["Cache-Control"] == nil { + t.Errorf("%s does not mark its 200 response no-store", test.id) + } + if operation.RequestBody != nil { + t.Errorf("%s takes a body: the item and the recipient come from the path and the session", test.id) + } + names := make([]string, 0, len(operation.Parameters)) + for _, parameter := range operation.Parameters { + names = append(names, parameterName(parameter)) + } + if !slices.Equal(names, test.parameters) { + t.Errorf("%s parameters = %v, want %v", test.id, names, test.parameters) + } + }) + } + // An idempotent command by its effect needs no key. + for _, id := range []string{"MarkMyNotificationRead", "MarkOrganizationNotificationRead"} { + for _, parameter := range operationByID(t, spec, id).Parameters { + if parameterName(parameter) == "IdempotencyKey" || parameterName(parameter) == "IfMatch" { + t.Errorf("%s declares %s", id, parameterName(parameter)) + } + } + } + codes := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProblemCode"})) + for _, code := range []string{"validation_failed", "unauthenticated", "forbidden", "csrf_check_failed", "not_found", "rate_limited"} { + if !slices.Contains(codes, code) { + t.Errorf("ProblemCode has no %s", code) + } + } +} + +// Every inbox object is closed and fully required, an item carries a +// reference and a state but no text of its own, and the text sits in the one +// nullable content object. +func TestNotificationSchemasAreClosedAndKeepTextInTheContent(t *testing.T) { + spec := parsePublicContract(t) + for _, pair := range []struct { + name string + want []string + }{ + {"Notification", []string{"content", "delivered_at", "id", "kind", "organization_id", "read_at"}}, + {"NotificationContent", []string{"link_path", "summary", "title"}}, + {"NotificationList", []string{"items", "page"}}, + {"NotificationReadReceipt", []string{"id", "read_at"}}, + } { + schema := spec.Components.Schemas[pair.name] + if schema == nil { + t.Fatalf("the contract has no schema %s", pair.name) + } + if got := propertyNames(schema); !slices.Equal(got, pair.want) { + t.Errorf("%s properties = %v, want %v", pair.name, got, pair.want) + } + if schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool { + t.Errorf("%s accepts unknown properties", pair.name) + } + if required := slices.Sorted(slices.Values(schema.Required)); !slices.Equal(required, pair.want) { + t.Errorf("%s requires %v, want every property %v", pair.name, required, pair.want) + } + } + if got := enumValues(t, spec.Components.Schemas["NotificationKind"]); !slices.Equal(got, []string{"invitation_delivered", "synthetic"}) { + t.Errorf("NotificationKind = %v", got) + } + assertNoJSONFields(t, api.Notification{}, []string{ + "title", "summary", "body", "text", "email", "name", "contact", "contacts", "recipient_user_id", "user_id", "candidate_id", + }) + assertNoJSONFields(t, api.NotificationReadReceipt{}, []string{"content", "title", "summary", "kind", "organization_id"}) + for _, property := range spec.Components.Schemas["NotificationList"].Properties { + if property.Name == "items" && (property.Schema.MaxItems == nil || *property.Schema.MaxItems != 100) { + t.Errorf("NotificationList.items maxItems = %v, want the page limit 100", property.Schema.MaxItems) + } + } +} diff --git a/backend/internal/adapter/primary/http/v1/api.go b/backend/internal/adapter/primary/http/v1/api.go index 74f7a37..0e5d903 100644 --- a/backend/internal/adapter/primary/http/v1/api.go +++ b/backend/internal/adapter/primary/http/v1/api.go @@ -30,6 +30,8 @@ type Handler struct { assessmentSignals *AssessmentSignalHandler privacy *PrivacyHandler evidence *EvidenceHandler + matches *MatchHandler + notifications *NotificationHandler problems *problem.Responder } @@ -99,6 +101,17 @@ func WithEvidence(evidence *EvidenceHandler) HandlerOption { return func(handler *Handler) { handler.evidence = evidence } } +// WithNotifications serves the inbox of the candidate cabinet and of one +// organization cabinet. +func WithNotifications(notifications *NotificationHandler) HandlerOption { + return func(handler *Handler) { handler.notifications = notifications } +} + +// WithMatches serves the deterministic match search of the visible bank. +func WithMatches(matches *MatchHandler) HandlerOption { + return func(handler *Handler) { handler.matches = matches } +} + func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler { handler := &Handler{health: health, problems: problems} for _, option := range options { diff --git a/backend/internal/adapter/primary/http/v1/matches.go b/backend/internal/adapter/primary/http/v1/matches.go new file mode 100644 index 0000000..d0a370d --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/matches.go @@ -0,0 +1,310 @@ +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/candidateview" + "lincodex/backend/internal/usecase/matching" +) + +// MatchOperations searches and ranks the organization-visible candidate bank. +type MatchOperations interface { + Search(ctx context.Context, request matching.Request) (matching.Result, error) +} + +// MatchHandler binds the match search use case to the v1 API. +type MatchHandler struct { + operations MatchOperations +} + +func NewMatchHandler(operations MatchOperations) *MatchHandler { + if operations == nil { + panic("v1.NewMatchHandler - operations must not be nil") + } + return &MatchHandler{operations: operations} +} + +func (handler *Handler) SearchOrganizationMatches( + ctx context.Context, + request api.MatchSearchRequest, + params api.SearchOrganizationMatchesParams, +) (api.SearchOrganizationMatchesRes, error) { + if handler.matches == nil { + return handler.UnimplementedHandler.SearchOrganizationMatches(ctx, request, params) + } + return handler.matches.SearchOrganizationMatches(ctx, request, params) +} + +func (handler *MatchHandler) SearchOrganizationMatches( + ctx context.Context, + request api.MatchSearchRequest, + params api.SearchOrganizationMatchesParams, +) (api.SearchOrganizationMatchesRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.SearchOrganizationMatchesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + command, err := matchSearchCommand(principal.UserID, params.OrgID, request) + if err != nil { + return nil, err + } + result, err := handler.operations.Search(ctx, command) + if err != nil { + switch { + case errors.Is(err, matching.ErrForbidden), errors.Is(err, candidateview.ErrForbidden), + errors.Is(err, outbound.ErrOrganizationManagerRequired): + return (*api.SearchOrganizationMatchesForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, matching.ErrNeedNotFound): + return (*api.SearchOrganizationMatchesNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + } + return nil, err + } + return &api.MatchSearchResponseHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: matchSearchResponse(result), + }, nil +} + +func matchSearchCommand(actorID, organizationID uuid.UUID, request api.MatchSearchRequest) (matching.Request, error) { + command := matching.Request{ActorID: actorID, OrganizationID: organizationID} + switch { + case request.IsMatchSearchByNeed(): + byNeed := request.MatchSearchByNeed + command.Need = &matching.NeedReference{NeedID: byNeed.NeedID, RequirementsVersion: int64(byNeed.RequirementsVersion)} + if byNeed.Filters.Set { + command.Filters = matchFilters(byNeed.Filters.Value) + } + case request.IsMatchSearchByBank(): + command.Filters = matchFilters(request.MatchSearchByBank.Filters) + default: + return matching.Request{}, errors.New("v1.matchSearchCommand - request variant is not known") + } + return command, nil +} + +func matchFilters(filters api.MatchSearchFilters) matching.Filters { + result := matching.Filters{} + if filters.Specialization.Set { + value := domain.SpecializationCode(filters.Specialization.Value) + result.Specialization = &value + } + if filters.ConfirmedGrade.Set { + value := domain.GradeCode(filters.ConfirmedGrade.Value) + result.ConfirmedGrade = &value + } + if filters.ConfirmedCategory.Set { + category := filters.ConfirmedCategory.Value + result.ConfirmedCategory = &matching.GradeFilter{ + Specialization: domain.SpecializationCode(category.Specialization), Grade: domain.GradeCode(category.Grade), + } + } + if filters.ConfirmationStatus.Set { + value := domain.CandidateViewConfirmationStatus(filters.ConfirmationStatus.Value) + result.ConfirmationStatus = &value + } + if filters.DeclaredGrade.Set { + value := domain.GradeCode(filters.DeclaredGrade.Value) + result.DeclaredGrade = &value + } + for _, tag := range filters.Stack { + result.Stack = append(result.Stack, domain.CandidateViewSkillCode(tag)) + } + if filters.Conditions.Set { + conditions := &matching.Conditions{} + for _, format := range filters.Conditions.Value.WorkFormats { + conditions.WorkFormats = append(conditions.WorkFormats, domain.QuestionnaireWorkFormat(format)) + } + if filters.Conditions.Value.SalaryCompatibility.Set { + value := domain.CandidateViewSalaryCompatibility(filters.Conditions.Value.SalaryCompatibility.Value) + conditions.SalaryCompatibility = &value + } + result.Conditions = conditions + } + return result +} + +func matchSearchResponse(result matching.Result) api.MatchSearchResponse { + response := api.MatchSearchResponse{ + Source: matchSearchSource(result.Source), + Truncated: result.Truncated, + Groups: api.MatchSearchGroups{ + Main: make([]api.MatchConfirmedCandidate, 0, len(result.Main)), + Near: make([]api.MatchConfirmedCandidate, 0, len(result.Near)), + Unconfirmed: make([]api.MatchUnconfirmedCandidate, 0, len(result.Unconfirmed)), + }, + } + for _, entry := range result.Main { + response.Groups.Main = append(response.Groups.Main, matchConfirmedCandidate(entry)) + } + for _, entry := range result.Near { + response.Groups.Near = append(response.Groups.Near, matchConfirmedCandidate(entry)) + } + for _, entry := range result.Unconfirmed { + response.Groups.Unconfirmed = append(response.Groups.Unconfirmed, matchUnconfirmedCandidate(entry)) + } + return response +} + +func matchSearchSource(source matching.Source) api.MatchSearchSource { + var response api.MatchSearchSource + if source.Need != nil { + response.SetMatchSearchNeedSource(api.MatchSearchNeedSource{ + Kind: api.MatchSearchNeedSourceKindNeed, NeedID: source.Need.NeedID, + RequirementsVersion: api.NeedVersion(source.Need.RequirementsVersion), + }) + return response + } + response.SetMatchSearchBankSource(api.MatchSearchBankSource{ + Kind: api.MatchSearchBankSourceKindBank, Filters: matchAppliedFilters(source.Filters), + }) + return response +} + +// matchAppliedFilters writes every key, with null for a filter that was not +// asked for, so the result stays tied to its exact basis. +func matchAppliedFilters(filters matching.Filters) api.MatchAppliedFilters { + var applied api.MatchAppliedFilters + applied.Specialization.SetToNull() + applied.ConfirmedGrade.SetToNull() + applied.ConfirmedCategory.SetToNull() + applied.ConfirmationStatus.SetToNull() + applied.DeclaredGrade.SetToNull() + applied.Conditions.SetToNull() + if filters.Specialization != nil { + applied.Specialization.SetTo(api.SpecializationCode(*filters.Specialization)) + } + if filters.ConfirmedGrade != nil { + applied.ConfirmedGrade.SetTo(api.GradeCode(*filters.ConfirmedGrade)) + } + if filters.ConfirmedCategory != nil { + applied.ConfirmedCategory.SetTo(api.MatchGradeFilter{ + Specialization: api.SpecializationCode(filters.ConfirmedCategory.Specialization), + Grade: api.GradeCode(filters.ConfirmedCategory.Grade), + }) + } + if filters.ConfirmationStatus != nil { + applied.ConfirmationStatus.SetTo(api.MatchConfirmationStatus(*filters.ConfirmationStatus)) + } + if filters.DeclaredGrade != nil { + applied.DeclaredGrade.SetTo(api.GradeCode(*filters.DeclaredGrade)) + } + for _, tag := range filters.Stack { + applied.Stack = append(applied.Stack, api.MatchSearchStackTag(tag)) + } + if filters.Conditions != nil { + conditions := api.MatchAppliedConditions{} + conditions.SalaryCompatibility.SetToNull() + for _, format := range filters.Conditions.WorkFormats { + conditions.WorkFormats = append(conditions.WorkFormats, api.WorkFormat(format)) + } + if filters.Conditions.SalaryCompatibility != nil { + conditions.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*filters.Conditions.SalaryCompatibility)) + } + applied.Conditions.SetTo(conditions) + } + return applied +} + +func matchConfirmedCandidate(entry matching.Entry) api.MatchConfirmedCandidate { + candidate := api.MatchConfirmedCandidate{ + CandidateHandle: api.CandidateHandle(entry.CandidateHandle), + Specialization: api.SpecializationCode(entry.Specialization), + ConfirmationStatus: api.MatchConfirmedCandidateConfirmationStatusConfirmed, + PublicContext: matchPublicContext(entry.PublicContext), + EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary), + UnknownFlags: matchUnknownFlags(entry.UnknownFlags), + } + candidate.DeclaredGrade = matchDeclaredGrade(entry.DeclaredGrade) + if entry.Category != nil { + candidate.Category = api.MatchCategory{ + Specialization: api.SpecializationCode(entry.Category.Specialization), Grade: api.GradeCode(entry.Category.Grade), + } + candidate.Strength = api.MatchStrength(entry.Category.Strength) + } + components := api.MatchConfirmedComponents{ + Fit: api.MatchScore(entry.Components.Fit), Coverage: api.MatchScore(entry.Components.Coverage), + Domain: api.MatchScore(entry.Components.Domain), Semantics: api.MatchScore(entry.Components.Semantics), + Competition: api.MatchScore(entry.Components.Competition), Freshness: api.MatchScore(entry.Components.Freshness), + Responsiveness: api.MatchScore(entry.Components.Responsiveness), RankScore: api.MatchScore(entry.Components.RankScore), + } + components.Percentile.SetToNull() + if entry.Components.Percentile != nil { + components.Percentile.SetTo(*entry.Components.Percentile) + } + candidate.Components = components + return candidate +} + +func matchUnconfirmedCandidate(entry matching.Entry) api.MatchUnconfirmedCandidate { + return api.MatchUnconfirmedCandidate{ + CandidateHandle: api.CandidateHandle(entry.CandidateHandle), + Specialization: api.SpecializationCode(entry.Specialization), + ConfirmationStatus: api.MatchUnconfirmedCandidateConfirmationStatusUnconfirmed, + DeclaredGrade: matchDeclaredGrade(entry.DeclaredGrade), + PublicContext: matchPublicContext(entry.PublicContext), + EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary), + Components: api.MatchUnconfirmedComponents{Fit: entry.Components.Fit, Coverage: entry.Components.Coverage}, + UnknownFlags: matchUnknownFlags(entry.UnknownFlags), + } +} + +func matchDeclaredGrade(grade *domain.GradeCode) api.NilGradeCode { + var declared api.NilGradeCode + declared.SetToNull() + if grade != nil { + declared.SetTo(api.GradeCode(*grade)) + } + return declared +} + +func matchPublicContext(context matching.PublicContext) api.MatchPublicContext { + var response api.MatchPublicContext + response.ExperienceBand.SetToNull() + response.SalaryCompatibility.SetToNull() + if len(context.Stack) > 0 { + response.Stack = make(api.MatchPublicStack, 0, len(context.Stack)) + for _, tag := range context.Stack { + response.Stack = append(response.Stack, api.MatchSearchStackTag(tag)) + } + } + if context.ExperienceBand != nil { + response.ExperienceBand.SetTo(api.CandidateExperienceBand(*context.ExperienceBand)) + } + if len(context.WorkFormats) > 0 { + response.WorkFormats = make([]api.WorkFormat, 0, len(context.WorkFormats)) + for _, format := range context.WorkFormats { + response.WorkFormats = append(response.WorkFormats, api.WorkFormat(format)) + } + } + if context.SalaryCompatibility != nil { + response.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*context.SalaryCompatibility)) + } + return response +} + +func matchEvidenceSummary(items []matching.EvidenceItem) api.MatchEvidenceSummary { + summary := make(api.MatchEvidenceSummary, 0, len(items)) + for _, item := range items { + summary = append(summary, api.MatchEvidenceSummaryItem{ + Code: api.MatchEvidenceCode(item.Code), State: api.MatchEvidenceState(item.State), + }) + } + return summary +} + +func matchUnknownFlags(flags []matching.UnknownFlag) api.MatchUnknownFlags { + response := make(api.MatchUnknownFlags, 0, len(flags)) + for _, flag := range flags { + response = append(response, api.MatchUnknownFlag{ + Component: api.MatchUnknownComponent(flag.Component), Reason: api.MatchUnknownReason(flag.Reason), + }) + } + return response +} diff --git a/backend/internal/adapter/primary/http/v1/matches_test.go b/backend/internal/adapter/primary/http/v1/matches_test.go new file mode 100644 index 0000000..3cc5fed --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/matches_test.go @@ -0,0 +1,221 @@ +package v1 + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/matching" +) + +type matchOperationsStub struct { + result matching.Result + err error + request matching.Request +} + +func (stub *matchOperationsStub) Search(_ context.Context, request matching.Request) (matching.Result, error) { + stub.request = request + return stub.result, stub.err +} + +func TestSearchOrganizationMatchesMapsABankRequestAndEchoesTheNormalizedFilters(t *testing.T) { + userID, organizationID := uuid.New(), uuid.New() + stub := &matchOperationsStub{} + handler := NewMatchHandler(stub) + var request api.MatchSearchRequest + request.SetMatchSearchByBank(api.MatchSearchByBank{Filters: api.MatchSearchFilters{ + Specialization: api.NewOptSpecializationCode(api.SpecializationCodeBackend), + ConfirmedCategory: api.NewOptMatchGradeFilter(api.MatchGradeFilter{Specialization: api.SpecializationCodeBackend, Grade: api.GradeCodeMiddle}), + Stack: []api.MatchSearchStackTag{api.MatchSearchStackTagPostgresql, api.MatchSearchStackTagGo}, + Conditions: api.NewOptMatchSearchConditions(api.MatchSearchConditions{ + WorkFormats: []api.WorkFormat{api.WorkFormatRemote}, + SalaryCompatibility: api.NewOptCandidateSalaryCompatibility(api.CandidateSalaryCompatibilityCompatible), + }), + }}) + stub.result.Truncated = false + stub.result.Source = matching.Source{Filters: matching.Filters{ + Specialization: new(domain.SpecializationCode), Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo}, + }} + *stub.result.Source.Filters.Specialization = domain.SpecializationBackend + + response, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, api.SearchOrganizationMatchesParams{OrgID: organizationID}) + if err != nil { + t.Fatalf("SearchOrganizationMatches() error = %v", err) + } + if stub.request.ActorID != userID || stub.request.OrganizationID != organizationID || stub.request.Need != nil { + t.Fatalf("command scope = %+v, want the session actor and the path organization", stub.request) + } + filters := stub.request.Filters + if filters.Specialization == nil || *filters.Specialization != domain.SpecializationBackend || + filters.ConfirmedCategory == nil || filters.ConfirmedCategory.Grade != domain.GradeMiddle || filters.ConfirmedGrade != nil || + filters.ConfirmationStatus != nil || filters.DeclaredGrade != nil || len(filters.Stack) != 2 || + filters.Conditions == nil || len(filters.Conditions.WorkFormats) != 1 || filters.Conditions.SalaryCompatibility == nil { + t.Fatalf("mapped filters = %+v", filters) + } + body, ok := response.(*api.MatchSearchResponseHeaders) + if !ok || body.CacheControl != api.CacheControlNoStoreNoStore { + t.Fatalf("response = %#v, want a no-store result", response) + } + encoded, err := json.Marshal(body.Response) + if err != nil { + t.Fatalf("encode response: %v", err) + } + want := `{"source":{"kind":"bank","filters":{"specialization":"backend","confirmed_grade":null,"confirmed_category":null,` + + `"confirmation_status":null,"declared_grade":null,"stack":["go"],"conditions":null}},"groups":{"main":[],"near":[],"unconfirmed":[]},"truncated":false}` + if string(encoded) != want { + t.Fatalf("response = %s, want %s", encoded, want) + } +} + +func TestSearchOrganizationMatchesMapsANeedRequestAndKeepsUnconfirmedEntriesStrict(t *testing.T) { + userID, organizationID, needID := uuid.New(), uuid.New(), uuid.New() + handle := "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + junior := domain.GradeJunior + stub := &matchOperationsStub{result: matching.Result{ + Source: matching.Source{Need: &matching.NeedReference{NeedID: needID, RequirementsVersion: 3}}, + Unconfirmed: []matching.Entry{{ + CandidateHandle: handle, Specialization: domain.SpecializationNetworkEngineer, DeclaredGrade: &junior, + Components: matching.Components{Fit: 0.3125, Coverage: 0.25}, + UnknownFlags: []matching.UnknownFlag{ + {Component: matching.UnknownAssessment, Reason: matching.ReasonNoConfirmationForSpecialization}, + }, + EvidenceSummary: []matching.EvidenceItem{{Code: matching.EvidenceDeclaredGrade, State: matching.EvidenceStateDeclaredOnly}}, + }}, + }} + handler := NewMatchHandler(stub) + var request api.MatchSearchRequest + request.SetMatchSearchByNeed(api.MatchSearchByNeed{NeedID: needID, RequirementsVersion: 3}) + + response, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, api.SearchOrganizationMatchesParams{OrgID: organizationID}) + if err != nil { + t.Fatalf("SearchOrganizationMatches() error = %v", err) + } + if stub.request.Need == nil || stub.request.Need.NeedID != needID || stub.request.Need.RequirementsVersion != 3 { + t.Fatalf("need reference = %+v", stub.request.Need) + } + body, ok := response.(*api.MatchSearchResponseHeaders) + if !ok { + t.Fatalf("response = %#v", response) + } + encoded, err := json.Marshal(body.Response.Groups.Unconfirmed) + if err != nil { + t.Fatalf("encode response: %v", err) + } + want := `[{"candidate_handle":"` + handle + `","specialization":"network_engineer","confirmation_status":"unconfirmed","declared_grade":"junior",` + + `"category":null,"strength":null,"public_context":{"stack":null,"experience_band":null,"work_formats":null,"salary_compatibility":null},` + + `"evidence_summary":[{"code":"declared_grade","state":"declared_only"}],"components":{"fit":0.3125,"coverage":0.25},` + + `"unknown_flags":[{"component":"assessment","reason":"no_confirmation_for_specialization"}]}]` + if string(encoded) != want { + t.Fatalf("unconfirmed entries = %s\nwant %s", encoded, want) + } + for _, forbidden := range []string{"percentile", "rank_score", "theta", "freshness"} { + if strings.Contains(string(encoded), forbidden) { + t.Fatalf("an unconfirmed entry exposes %q", forbidden) + } + } +} + +func TestSearchOrganizationMatchesMapsAConfirmedEntryWithANullPercentile(t *testing.T) { + handle := "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + stub := &matchOperationsStub{result: matching.Result{Main: []matching.Entry{{ + CandidateHandle: handle, Specialization: domain.SpecializationBackend, + Category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, Strength: domain.CandidateViewStrengthStrong}, + Components: matching.Components{ + Fit: 0.5, Coverage: 0.5, Domain: 0.5, Semantics: 0.5, Freshness: 0.5, Responsiveness: 0.5, RankScore: 0.45125, + }, + }}}} + response, err := NewMatchHandler(stub).SearchOrganizationMatches(privacyHTTPContext(uuid.New(), ""), + func() api.MatchSearchRequest { + var request api.MatchSearchRequest + request.SetMatchSearchByBank(api.MatchSearchByBank{}) + return request + }(), api.SearchOrganizationMatchesParams{OrgID: uuid.New()}) + if err != nil { + t.Fatalf("SearchOrganizationMatches() error = %v", err) + } + encoded, err := json.Marshal(response.(*api.MatchSearchResponseHeaders).Response.Groups.Main) + if err != nil { + t.Fatalf("encode response: %v", err) + } + for _, want := range []string{ + `"confirmation_status":"confirmed"`, `"declared_grade":null`, `"category":{"specialization":"backend","grade":"middle"}`, `"strength":"strong"`, + `"percentile":null`, `"competition":0`, `"rank_score":0.45125`, + } { + if !strings.Contains(string(encoded), want) { + t.Errorf("confirmed entry %s lacks %s", encoded, want) + } + } +} + +func TestSearchOrganizationMatchesMapsFailuresToTheContractProblems(t *testing.T) { + userID := uuid.New() + var request api.MatchSearchRequest + request.SetMatchSearchByBank(api.MatchSearchByBank{}) + params := api.SearchOrganizationMatchesParams{OrgID: uuid.New()} + stub := &matchOperationsStub{} + handler := NewMatchHandler(stub) + + unauthenticated, err := handler.SearchOrganizationMatches(context.Background(), request, params) + if _, ok := unauthenticated.(*api.SearchOrganizationMatchesUnauthorized); err != nil || !ok { + t.Fatalf("no principal = %#v, %v, want 401", unauthenticated, err) + } + for name, test := range map[string]struct { + err error + want string + }{ + "not an owner": {matching.ErrForbidden, "forbidden"}, + "candidate account": {candidateview.ErrForbidden, "forbidden"}, + "membership is not an owner": {outbound.ErrOrganizationManagerRequired, "forbidden"}, + "no membership": {outbound.ErrOrganizationNotFound, "not_found"}, + "unknown need": {matching.ErrNeedNotFound, "not_found"}, + } { + stub.err = test.err + response, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, params) + if err != nil { + t.Errorf("%s: error = %v", name, err) + continue + } + var got string + switch response.(type) { + case *api.SearchOrganizationMatchesForbidden: + got = "forbidden" + case *api.SearchOrganizationMatchesNotFound: + got = "not_found" + } + if got != test.want { + t.Errorf("%s = %T, want %s", name, response, test.want) + } + } + for _, unexpected := range []error{errors.New("storage failed"), matching.ErrPolicyUnavailable} { + stub.err = unexpected + if _, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, params); err == nil { + t.Fatalf("an unexpected failure %v was answered as a client problem", unexpected) + } + } +} + +func TestSearchOrganizationMatchesReportsATruncatedResultWithoutACount(t *testing.T) { + stub := &matchOperationsStub{result: matching.Result{Truncated: true}} + var request api.MatchSearchRequest + request.SetMatchSearchByBank(api.MatchSearchByBank{}) + response, err := NewMatchHandler(stub).SearchOrganizationMatches(privacyHTTPContext(uuid.New(), ""), request, api.SearchOrganizationMatchesParams{OrgID: uuid.New()}) + if err != nil { + t.Fatalf("SearchOrganizationMatches() error = %v", err) + } + encoded, err := json.Marshal(response.(*api.MatchSearchResponseHeaders).Response) + if err != nil { + t.Fatalf("encode response: %v", err) + } + if !strings.Contains(string(encoded), `"truncated":true`) || strings.Contains(string(encoded), "total") || strings.Contains(string(encoded), "count") { + t.Fatalf("response = %s, want the flag and no count", encoded) + } +} diff --git a/backend/internal/adapter/primary/http/v1/notification_cursor.go b/backend/internal/adapter/primary/http/v1/notification_cursor.go new file mode 100644 index 0000000..26ac4cc --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/notification_cursor.go @@ -0,0 +1,78 @@ +package v1 + +import ( + "encoding/base64" + "encoding/binary" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/port/outbound" +) + +const ( + notificationCursorVersion = 1 + notificationCursorBytes = 61 + // maxNotificationCursorYear keeps the decoded time inside the range that + // PostgreSQL stores and that the contract's RFC 3339 timestamps print. + maxNotificationCursorYear = 9999 +) + +// encodeNotificationCursor binds a page position to the account and the +// organization context of the listing, so a cursor of another account or +// another cabinet fails as malformed instead of continuing a foreign list. +// A nil organization is the candidate cabinet. +func encodeNotificationCursor(recipientID uuid.UUID, organizationID *uuid.UUID, position outbound.NotificationInboxPosition) (string, error) { + at := position.OccurredAt.UTC() + if recipientID == uuid.Nil || position.EventID == uuid.Nil || at.IsZero() || at.Year() > maxNotificationCursorYear { + return "", errors.New("v1.encodeNotificationCursor - a recipient and a valid page position are required") + } + seconds, nanos := at.Unix(), at.Nanosecond() + if seconds < 0 { + return "", errors.New("v1.encodeNotificationCursor - the page position predates the epoch") + } + if nanos < 0 || nanos >= 1_000_000_000 || nanos%1_000 != 0 { + return "", errors.New("v1.encodeNotificationCursor - the page position has no microsecond precision") + } + var value [notificationCursorBytes]byte + value[0] = notificationCursorVersion + copy(value[1:17], recipientID[:]) + if organizationID != nil { + copy(value[17:33], organizationID[:]) + } + binary.BigEndian.PutUint64(value[33:41], uint64(seconds)) + binary.BigEndian.PutUint32(value[41:45], uint32(nanos)) + copy(value[45:61], position.EventID[:]) + return base64.RawURLEncoding.EncodeToString(value[:]), nil +} + +// decodeNotificationCursor reads a cursor made for the same account and +// cabinet by encodeNotificationCursor. +func decodeNotificationCursor(cursor string, recipientID uuid.UUID, organizationID *uuid.UUID) (outbound.NotificationInboxPosition, error) { + const location = "v1.decodeNotificationCursor" + value, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil || len(value) != notificationCursorBytes || recipientID == uuid.Nil || + base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != notificationCursorVersion || + uuid.UUID(value[1:17]) != recipientID { + return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor is invalid") + } + var scope uuid.UUID + if organizationID != nil { + scope = *organizationID + } + if uuid.UUID(value[17:33]) != scope { + return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor belongs to another cabinet") + } + seconds := binary.BigEndian.Uint64(value[33:41]) + nanos := binary.BigEndian.Uint32(value[41:45]) + eventID := uuid.UUID(value[45:61]) + if seconds > uint64(1<<62) || nanos >= 1_000_000_000 || nanos%1_000 != 0 || eventID == uuid.Nil { + return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor position is invalid") + } + at := time.Unix(int64(seconds), int64(nanos)).UTC() + if at.IsZero() || at.Year() > maxNotificationCursorYear { + return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor timestamp is invalid") + } + return outbound.NotificationInboxPosition{OccurredAt: at, EventID: eventID}, nil +} diff --git a/backend/internal/adapter/primary/http/v1/notifications.go b/backend/internal/adapter/primary/http/v1/notifications.go new file mode 100644 index 0000000..79f0eff --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/notifications.go @@ -0,0 +1,277 @@ +package v1 + +import ( + "context" + "errors" + "fmt" + + "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/notification" +) + +const defaultNotificationLimit = 20 + +// NotificationOperations lists and marks the inbox of the authenticated +// account. The candidate cabinet and the cabinet of one organization share +// the operations; the request names which one. +type NotificationOperations interface { + List(ctx context.Context, request notification.InboxListRequest) (notification.InboxPage, error) + MarkRead(ctx context.Context, request notification.InboxMarkReadRequest) (domain.NotificationInboxEntry, error) +} + +// NotificationHandler binds the inbox use cases to the v1 API. +type NotificationHandler struct { + operations NotificationOperations +} + +func NewNotificationHandler(operations NotificationOperations) *NotificationHandler { + if operations == nil { + panic("v1.NewNotificationHandler - operations must not be nil") + } + return &NotificationHandler{operations: operations} +} + +func (handler *Handler) ListMyNotifications(ctx context.Context, params api.ListMyNotificationsParams) (api.ListMyNotificationsRes, error) { + if handler.notifications == nil { + return handler.UnimplementedHandler.ListMyNotifications(ctx, params) + } + return handler.notifications.ListMyNotifications(ctx, params) +} + +func (handler *Handler) MarkMyNotificationRead(ctx context.Context, params api.MarkMyNotificationReadParams) (api.MarkMyNotificationReadRes, error) { + if handler.notifications == nil { + return handler.UnimplementedHandler.MarkMyNotificationRead(ctx, params) + } + return handler.notifications.MarkMyNotificationRead(ctx, params) +} + +func (handler *Handler) ListOrganizationNotifications( + ctx context.Context, + params api.ListOrganizationNotificationsParams, +) (api.ListOrganizationNotificationsRes, error) { + if handler.notifications == nil { + return handler.UnimplementedHandler.ListOrganizationNotifications(ctx, params) + } + return handler.notifications.ListOrganizationNotifications(ctx, params) +} + +func (handler *Handler) MarkOrganizationNotificationRead( + ctx context.Context, + params api.MarkOrganizationNotificationReadParams, +) (api.MarkOrganizationNotificationReadRes, error) { + if handler.notifications == nil { + return handler.UnimplementedHandler.MarkOrganizationNotificationRead(ctx, params) + } + return handler.notifications.MarkOrganizationNotificationRead(ctx, params) +} + +func (handler *NotificationHandler) ListMyNotifications(ctx context.Context, params api.ListMyNotificationsParams) (api.ListMyNotificationsRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.ListMyNotificationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + list, pointer := handler.list(ctx, principal.UserID, nil, params.Limit, params.Cursor) + if pointer != "" { + return (*api.ListMyNotificationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil + } + page, err := list() + switch { + case err == nil: + return page, nil + case errors.Is(err, notification.ErrInboxForbidden): + return (*api.ListMyNotificationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + default: + return nil, err + } +} + +func (handler *NotificationHandler) ListOrganizationNotifications( + ctx context.Context, + params api.ListOrganizationNotificationsParams, +) (api.ListOrganizationNotificationsRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.ListOrganizationNotificationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + organizationID := params.OrgID + list, pointer := handler.list(ctx, principal.UserID, &organizationID, params.Limit, params.Cursor) + if pointer != "" { + return (*api.ListOrganizationNotificationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil + } + page, err := list() + switch { + case err == nil: + return page, nil + case errors.Is(err, notification.ErrInboxEmailNotVerified): + return (*api.ListOrganizationNotificationsForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil + case errors.Is(err, notification.ErrInboxForbidden): + return (*api.ListOrganizationNotificationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, outbound.ErrOrganizationNotFound): + return (*api.ListOrganizationNotificationsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + default: + return nil, err + } +} + +func (handler *NotificationHandler) MarkMyNotificationRead( + ctx context.Context, + params api.MarkMyNotificationReadParams, +) (api.MarkMyNotificationReadRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.MarkMyNotificationReadUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + receipt, err := handler.mark(ctx, principal.UserID, nil, params.NotificationID) + switch { + case err == nil: + return receipt, nil + case errors.Is(err, notification.ErrInboxForbidden): + return (*api.MarkMyNotificationReadForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, outbound.ErrNotificationInboxEntryNotFound): + return (*api.MarkMyNotificationReadNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + default: + return nil, err + } +} + +func (handler *NotificationHandler) MarkOrganizationNotificationRead( + ctx context.Context, + params api.MarkOrganizationNotificationReadParams, +) (api.MarkOrganizationNotificationReadRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.MarkOrganizationNotificationReadUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + organizationID := params.OrgID + receipt, err := handler.mark(ctx, principal.UserID, &organizationID, params.NotificationID) + switch { + case err == nil: + return receipt, nil + case errors.Is(err, notification.ErrInboxEmailNotVerified): + return (*api.MarkOrganizationNotificationReadForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil + case errors.Is(err, notification.ErrInboxForbidden): + return (*api.MarkOrganizationNotificationReadForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrNotificationInboxEntryNotFound): + // A missing membership, an unknown organization, and an item that is + // not the caller's in this organization are one answer. + return (*api.MarkOrganizationNotificationReadNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + default: + return nil, err + } +} + +// list validates the page parameters and returns the deferred read, so the +// two list operations share the mapping of a page to the public type. A +// non-empty pointer names the invalid query parameter. +func (handler *NotificationHandler) list( + ctx context.Context, + recipientID uuid.UUID, + organizationID *uuid.UUID, + limitParam api.OptInt32, + cursorParam api.OptString, +) (func() (*api.NotificationListHeaders, error), string) { + limit, set := limitParam.Get() + if !set { + limit = defaultNotificationLimit + } + if limit < 1 || limit > outbound.MaxNotificationInboxPageSize { + return nil, "limit" + } + request := notification.InboxListRequest{RecipientUserID: recipientID, OrganizationID: organizationID, Limit: limit} + if cursor, set := cursorParam.Get(); set { + position, err := decodeNotificationCursor(cursor, recipientID, organizationID) + if err != nil { + return nil, "cursor" + } + request.After = &position + } + return func() (*api.NotificationListHeaders, error) { + const location = "NotificationHandler.list" + page, err := handler.operations.List(ctx, request) + if err != nil { + return nil, err + } + items := make([]api.Notification, 0, len(page.Items)) + for _, item := range page.Items { + mapped, err := notificationResponse(item) + if err != nil { + return nil, fmt.Errorf("%s - map item: %w", location, err) + } + items = append(items, mapped) + } + next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) { + last := outbound.NotificationInboxPositionOf(page.Items[len(page.Items)-1].Entry) + return encodeNotificationCursor(recipientID, organizationID, last) + }) + if err != nil { + return nil, fmt.Errorf("%s - encode cursor: %w", location, err) + } + return &api.NotificationListHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: api.NotificationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}}, + }, nil + }, "" +} + +func (handler *NotificationHandler) mark( + ctx context.Context, + recipientID uuid.UUID, + organizationID *uuid.UUID, + eventID uuid.UUID, +) (*api.NotificationReadReceiptHeaders, error) { + entry, err := handler.operations.MarkRead(ctx, notification.InboxMarkReadRequest{ + RecipientUserID: recipientID, OrganizationID: organizationID, EventID: eventID, + }) + if err != nil { + return nil, err + } + readAt, isRead := entry.ReadAt() + if !isRead { + return nil, errors.New("NotificationHandler.mark - a marked item has no read time") + } + return &api.NotificationReadReceiptHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: api.NotificationReadReceipt{ID: entry.EventID(), ReadAt: api.Timestamp(readAt)}, + }, nil +} + +func notificationResponse(item notification.InboxItem) (api.Notification, error) { + kind, ok := notificationKind(item.Entry.EventType()) + if !ok { + return api.Notification{}, errors.New("v1.notificationResponse - the stored event type has no public kind") + } + response := api.Notification{ + ID: item.Entry.EventID(), Kind: kind, OrganizationID: item.Entry.OrganizationID(), + DeliveredAt: api.Timestamp(item.Entry.OccurredAt()), + } + response.ReadAt.SetToNull() + if readAt, isRead := item.Entry.ReadAt(); isRead { + response.ReadAt.SetTo(api.Timestamp(readAt)) + } + response.Content.SetToNull() + if item.Content != nil { + content := api.NotificationContent{Title: item.Content.Title(), Summary: item.Content.Summary()} + content.LinkPath.SetToNull() + if path := item.Content.LinkPath(); path != "" { + content.LinkPath.SetTo(path) + } + response.Content.SetTo(content) + } + return response, nil +} + +func notificationKind(eventType domain.NotificationInboxEventType) (api.NotificationKind, bool) { + switch eventType { + case domain.NotificationInboxInvitationDelivered: + return api.NotificationKindInvitationDelivered, true + case domain.NotificationInboxSyntheticDelivered: + return api.NotificationKindSynthetic, true + default: + return "", false + } +} diff --git a/backend/internal/adapter/primary/http/v1/notifications_test.go b/backend/internal/adapter/primary/http/v1/notifications_test.go new file mode 100644 index 0000000..0a56402 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/notifications_test.go @@ -0,0 +1,263 @@ +package v1 + +import ( + "context" + "errors" + "reflect" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" +) + +type notificationOperationsStub struct { + page notification.InboxPage + entry domain.NotificationInboxEntry + err error + listRequest notification.InboxListRequest + markRequest notification.InboxMarkReadRequest +} + +func (stub *notificationOperationsStub) List(_ context.Context, request notification.InboxListRequest) (notification.InboxPage, error) { + stub.listRequest = request + return stub.page, stub.err +} + +func (stub *notificationOperationsStub) MarkRead(_ context.Context, request notification.InboxMarkReadRequest) (domain.NotificationInboxEntry, error) { + stub.markRequest = request + return stub.entry, stub.err +} + +func notificationTestEntry(t *testing.T, recipientID, organizationID uuid.UUID, at time.Time) domain.NotificationInboxEntry { + t.Helper() + entry, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: organizationID, + EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1, + SourceType: domain.NotificationInboxSourceOrganization, SourceID: organizationID, OccurredAt: at, + }) + if err != nil { + t.Fatalf("NewNotificationInboxEntry() error = %v", err) + } + return entry +} + +func TestListMyNotificationsMapsContentAndFallbackAndBindsTheCursor(t *testing.T) { + userID, organizationID := uuid.New(), uuid.New() + at := time.Date(2026, 10, 9, 8, 30, 0, 123000, time.UTC) + withContent := notificationTestEntry(t, userID, organizationID, at) + content, err := notification.NewInboxContent("Тестовое уведомление", "Проверка доставки.", "/candidate/invitations") + if err != nil { + t.Fatalf("NewInboxContent() error = %v", err) + } + withoutContent := notificationTestEntry(t, userID, organizationID, at.Add(-time.Hour)) + read, err := withoutContent.MarkRead(at) + if err != nil { + t.Fatalf("MarkRead() error = %v", err) + } + stub := ¬ificationOperationsStub{page: notification.InboxPage{ + Items: []notification.InboxItem{ + {Entry: withContent, Content: &content}, + {Entry: read, ContentUnavailable: true}, + }, + HasMore: true, + }} + handler := NewNotificationHandler(stub) + ctx := privacyHTTPContext(userID, "") + + response, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{Limit: api.NewOptInt32(2)}) + if err != nil { + t.Fatalf("ListMyNotifications() error = %v", err) + } + page, ok := response.(*api.NotificationListHeaders) + if !ok || page.CacheControl != api.CacheControlNoStoreNoStore || len(page.Response.Items) != 2 { + t.Fatalf("ListMyNotifications() = %#v, want a no-store page of two items", response) + } + if stub.listRequest.RecipientUserID != userID || stub.listRequest.OrganizationID != nil || stub.listRequest.Limit != 2 { + t.Fatalf("list request = %+v, want the session account in the candidate cabinet", stub.listRequest) + } + first, second := page.Response.Items[0], page.Response.Items[1] + if first.ID != withContent.EventID() || first.Kind != api.NotificationKindSynthetic || !first.ReadAt.Null { + t.Fatalf("first item = %+v, want an unread synthetic item", first) + } + if first.Content.Null || first.Content.Value.Title != "Тестовое уведомление" || first.Content.Value.LinkPath.Null || + first.Content.Value.LinkPath.Value != "/candidate/invitations" { + t.Fatalf("first content = %+v, want the resolved text and link", first.Content) + } + if !second.Content.Null || second.ReadAt.Null { + t.Fatalf("second item = %+v, want no content and a read time", second) + } + if !page.Response.Page.HasMore || page.Response.Page.NextCursor.Null { + t.Fatalf("page info = %+v, want a next cursor", page.Response.Page) + } + + // The cursor continues only the same account in the same cabinet. + next := page.Response.Page.NextCursor.Value + if _, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{Cursor: api.NewOptString(next)}); err != nil { + t.Fatalf("ListMyNotifications(cursor) error = %v", err) + } + if stub.listRequest.After == nil || stub.listRequest.After.EventID != read.EventID() { + t.Fatalf("continuation = %+v, want the position of the last item", stub.listRequest.After) + } + foreign, err := handler.ListMyNotifications(privacyHTTPContext(uuid.New(), ""), api.ListMyNotificationsParams{Cursor: api.NewOptString(next)}) + if err != nil { + t.Fatalf("ListMyNotifications(foreign cursor) error = %v", err) + } + if _, ok := foreign.(*api.ListMyNotificationsBadRequest); !ok { + t.Fatalf("ListMyNotifications(foreign cursor) = %#v, want 400", foreign) + } + // A cursor of the candidate cabinet cannot continue an organization cabinet. + crossed, err := handler.ListOrganizationNotifications(ctx, api.ListOrganizationNotificationsParams{ + OrgID: organizationID, Cursor: api.NewOptString(next), + }) + if err != nil { + t.Fatalf("ListOrganizationNotifications(candidate cursor) error = %v", err) + } + if _, ok := crossed.(*api.ListOrganizationNotificationsBadRequest); !ok { + t.Fatalf("ListOrganizationNotifications(candidate cursor) = %#v, want 400", crossed) + } + for _, limit := range []int32{0, 101} { + bad, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{Limit: api.NewOptInt32(limit)}) + if err != nil { + t.Fatalf("ListMyNotifications(limit %d) error = %v", limit, err) + } + if _, ok := bad.(*api.ListMyNotificationsBadRequest); !ok { + t.Fatalf("ListMyNotifications(limit %d) = %#v, want 400", limit, bad) + } + } +} + +func TestNotificationOperationsMapAccessFailuresWithoutRevealingObjects(t *testing.T) { + userID, organizationID, eventID := uuid.New(), uuid.New(), uuid.New() + ctx := privacyHTTPContext(userID, "") + for _, test := range []struct { + name string + err error + list func(*NotificationHandler) (any, error) + mark func(*NotificationHandler) (any, error) + want []any + code api.ProblemCode + }{ + { + name: "an account of the other scenario", + err: notification.ErrInboxForbidden, + list: func(h *NotificationHandler) (any, error) { + return h.ListMyNotifications(ctx, api.ListMyNotificationsParams{}) + }, + mark: func(h *NotificationHandler) (any, error) { + return h.MarkMyNotificationRead(ctx, api.MarkMyNotificationReadParams{NotificationID: eventID}) + }, + want: []any{(*api.ListMyNotificationsForbidden)(nil), (*api.MarkMyNotificationReadForbidden)(nil)}, + }, + { + name: "no active membership", + err: outbound.ErrOrganizationNotFound, + list: func(h *NotificationHandler) (any, error) { + return h.ListOrganizationNotifications(ctx, api.ListOrganizationNotificationsParams{OrgID: organizationID}) + }, + mark: func(h *NotificationHandler) (any, error) { + return h.MarkOrganizationNotificationRead(ctx, api.MarkOrganizationNotificationReadParams{OrgID: organizationID, NotificationID: eventID}) + }, + want: []any{(*api.ListOrganizationNotificationsNotFound)(nil), (*api.MarkOrganizationNotificationReadNotFound)(nil)}, + }, + { + name: "an employer whose email is not confirmed", + err: notification.ErrInboxEmailNotVerified, + list: func(h *NotificationHandler) (any, error) { + return h.ListOrganizationNotifications(ctx, api.ListOrganizationNotificationsParams{OrgID: organizationID}) + }, + mark: func(h *NotificationHandler) (any, error) { + return h.MarkOrganizationNotificationRead(ctx, api.MarkOrganizationNotificationReadParams{OrgID: organizationID, NotificationID: eventID}) + }, + want: []any{(*api.ListOrganizationNotificationsForbidden)(nil), (*api.MarkOrganizationNotificationReadForbidden)(nil)}, + code: api.ProblemCodeEmailNotVerified, + }, + { + name: "an item of another account", + err: outbound.ErrNotificationInboxEntryNotFound, + mark: func(h *NotificationHandler) (any, error) { + return h.MarkMyNotificationRead(ctx, api.MarkMyNotificationReadParams{NotificationID: eventID}) + }, + want: []any{nil, (*api.MarkMyNotificationReadNotFound)(nil)}, + }, + } { + t.Run(test.name, func(t *testing.T) { + handler := NewNotificationHandler(¬ificationOperationsStub{err: test.err}) + if test.list != nil { + got, err := test.list(handler) + if err != nil || !sameResponseType(got, test.want[0]) { + t.Fatalf("list = %#v, %v, want %T", got, err, test.want[0]) + } + requireProblemCode(t, got, test.code) + } + got, err := test.mark(handler) + if err != nil || !sameResponseType(got, test.want[1]) { + t.Fatalf("mark = %#v, %v, want %T", got, err, test.want[1]) + } + requireProblemCode(t, got, test.code) + }) + } + + handler := NewNotificationHandler(¬ificationOperationsStub{err: errors.New("database is down")}) + if _, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{}); err == nil { + t.Fatal("ListMyNotifications() hid an unexpected failure") + } + response, err := handler.ListMyNotifications(context.Background(), api.ListMyNotificationsParams{}) + if err != nil { + t.Fatalf("ListMyNotifications(no session) error = %v", err) + } + if _, ok := response.(*api.ListMyNotificationsUnauthorized); !ok { + t.Fatalf("ListMyNotifications(no session) = %#v, want 401", response) + } +} + +func sameResponseType(got, want any) bool { + return want != nil && reflect.TypeOf(got) == reflect.TypeOf(want) +} + +func TestMarkNotificationReadReturnsTheFirstReadTimeOnly(t *testing.T) { + userID, organizationID := uuid.New(), uuid.New() + readAt := time.Date(2026, 10, 9, 8, 45, 0, 0, time.UTC) + entry, err := notificationTestEntry(t, userID, organizationID, readAt.Add(-time.Hour)).MarkRead(readAt) + if err != nil { + t.Fatalf("MarkRead() error = %v", err) + } + stub := ¬ificationOperationsStub{entry: entry} + handler := NewNotificationHandler(stub) + response, err := handler.MarkOrganizationNotificationRead(privacyHTTPContext(userID, ""), + api.MarkOrganizationNotificationReadParams{OrgID: organizationID, NotificationID: entry.EventID()}) + if err != nil { + t.Fatalf("MarkOrganizationNotificationRead() error = %v", err) + } + receipt, ok := response.(*api.NotificationReadReceiptHeaders) + if !ok || receipt.CacheControl != api.CacheControlNoStoreNoStore || receipt.Response.ID != entry.EventID() || + !time.Time(receipt.Response.ReadAt).Equal(readAt) { + t.Fatalf("MarkOrganizationNotificationRead() = %#v, want the receipt of the first read", response) + } + if stub.markRequest.RecipientUserID != userID || stub.markRequest.OrganizationID == nil || *stub.markRequest.OrganizationID != organizationID { + t.Fatalf("mark request = %+v, want the session account in the path organization", stub.markRequest) + } +} + +func requireProblemCode(t *testing.T, response any, want api.ProblemCode) { + t.Helper() + if want == "" { + return + } + var got api.ProblemCode + switch typed := response.(type) { + case *api.ListOrganizationNotificationsForbidden: + got = typed.Code + case *api.MarkOrganizationNotificationReadForbidden: + got = typed.Code + default: + t.Fatalf("response %T carries no problem code", response) + } + if got != want { + t.Fatalf("problem code = %s, want %s", got, want) + } +} diff --git a/backend/internal/adapter/secondary/postgres/company_quota.go b/backend/internal/adapter/secondary/postgres/company_quota.go index 8bc8340..4717397 100644 --- a/backend/internal/adapter/secondary/postgres/company_quota.go +++ b/backend/internal/adapter/secondary/postgres/company_quota.go @@ -194,6 +194,17 @@ func (repository companyQuotaRepository) reserveNewCardView( return outbound.CompanyQuotaDecision{Allowed: true}, nil } +func (repository companyQuotaRepository) LockOrganization(ctx context.Context, organizationID uuid.UUID) error { + const location = "companyQuotaRepository.LockOrganization" + if _, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID)); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - organization was removed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) + } + return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err)) + } + return nil +} + func (repository companyQuotaRepository) lockAndCheckSnapshot( ctx context.Context, location string, diff --git a/backend/internal/adapter/secondary/postgres/evidence.go b/backend/internal/adapter/secondary/postgres/evidence.go index bce2b34..ffd068d 100644 --- a/backend/internal/adapter/secondary/postgres/evidence.go +++ b/backend/internal/adapter/secondary/postgres/evidence.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgtype" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" @@ -117,6 +118,80 @@ func (repository evidenceRepository) ListOrganizationFacts( return facts, nil } +func (repository evidenceRepository) ListOrganizationFactsBatch( + ctx context.Context, + organizationID uuid.UUID, + requests []outbound.EvidenceCandidateCategories, +) (map[uuid.UUID][]domain.EvidenceOrganizationFact, error) { + const location = "evidenceRepository.ListOrganizationFactsBatch" + if organizationID == uuid.Nil { + return nil, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidEvidence) + } + var candidateIDs []pgtype.UUID + var pairs []string + for _, request := range requests { + if request.CandidateID == uuid.Nil { + return nil, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidEvidence) + } + requested, err := evidenceCategoryPairs(request.Categories) + if err != nil { + return nil, fmt.Errorf("%s - %w", location, err) + } + for _, pair := range requested { + candidateIDs = append(candidateIDs, pgUUID(request.CandidateID)) + pairs = append(pairs, pair) + } + } + facts := make(map[uuid.UUID][]domain.EvidenceOrganizationFact, len(requests)) + if len(pairs) == 0 { + return facts, nil + } + rows, err := repository.queries.ListOrganizationVisibleEvidenceBatch(ctx, sqlc.ListOrganizationVisibleEvidenceBatchParams{ + CandidateIds: candidateIDs, Categories: pairs, OrganizationID: pgUUID(organizationID), + }) + if err != nil { + return nil, fmt.Errorf("%s - select permitted facts: %w", location, markTransactionConflict(sanitizeConnectError(err))) + } + for _, row := range rows { + candidateID, err := optionalUUIDValue(row.CandidateID) + if err != nil { + return nil, fmt.Errorf("%s - %w", location, err) + } + fact, err := restoreEvidenceOrganizationFact(row.Skill, row.Grade, row.Trust, row.Basis, row.CalibrationStatus, row.ObservedYear) + if err != nil { + return nil, fmt.Errorf("%s - %w", location, err) + } + facts[candidateID] = append(facts[candidateID], fact) + } + return facts, nil +} + +func (repository evidenceRepository) CountComparableRealCategories( + ctx context.Context, + categories []outbound.CategoryKey, +) (map[outbound.CategoryKey]int64, error) { + const location = "evidenceRepository.CountComparableRealCategories" + counts := make(map[outbound.CategoryKey]int64, len(categories)) + if len(categories) == 0 { + return counts, nil + } + pairs := make([]string, 0, len(categories)) + for _, category := range categories { + if !category.Specialization.IsKnown() || !category.Grade.IsKnown() { + return nil, fmt.Errorf("%s - category is not known: %w", location, domain.ErrInvalidEvidence) + } + pairs = append(pairs, string(category.Specialization)+"/"+string(category.Grade)) + } + rows, err := repository.queries.CountRealComparableCategories(ctx, pairs) + if err != nil { + return nil, fmt.Errorf("%s - count cohorts: %w", location, markTransactionConflict(sanitizeConnectError(err))) + } + for _, row := range rows { + counts[outbound.CategoryKey{Specialization: domain.SpecializationCode(row.Specialization), Grade: domain.GradeCode(row.Grade)}] = row.Candidates + } + return counts, nil +} + func (repository evidenceRepository) ListPreviewFacts( ctx context.Context, candidateID uuid.UUID, @@ -187,3 +262,10 @@ func evidenceTrust(value int16) (domain.EvidenceTrust, error) { } return domain.EvidenceTrust(value), nil } + +func optionalUUIDValue(value pgtype.UUID) (uuid.UUID, error) { + if !value.Valid || value.Bytes == uuid.Nil { + return uuid.Nil, fmt.Errorf("candidate identity is invalid: %w", domain.ErrInvalidEvidence) + } + return uuid.UUID(value.Bytes), nil +} diff --git a/backend/internal/adapter/secondary/postgres/notification_fixture.go b/backend/internal/adapter/secondary/postgres/notification_fixture.go new file mode 100644 index 0000000..35d8735 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/notification_fixture.go @@ -0,0 +1,94 @@ +//go:build e2e + +package postgres + +import ( + "context" + "errors" + "fmt" + "regexp" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/port/outbound" +) + +// notificationFixtureEmail limits the notification fixture to the synthetic +// accounts of the isolated browser suite. +var notificationFixtureEmail = regexp.MustCompile(`@example\.test$`) + +// syntheticNoticeEventType is the synthetic inbox event the fixture replays. +const syntheticNoticeEventType = "notification.synthetic_delivered" + +// CheckNotificationFixtureScope accepts only a synthetic account and an +// existing organization. It is available only in e2e-tagged builds. +func CheckNotificationFixtureScope(ctx context.Context, pool *pgxpool.Pool, recipientID, organizationID uuid.UUID) error { + const location = "postgres.CheckNotificationFixtureScope" + if pool == nil || recipientID == uuid.Nil || organizationID == uuid.Nil { + return fmt.Errorf("%s - invalid fixture identity: %w", location, ErrCompanyFixtureScope) + } + var email string + err := pool.QueryRow(ctx, `SELECT email FROM users WHERE id = $1`, recipientID).Scan(&email) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - recipient: %w", location, outbound.ErrUserNotFound) + } + if err != nil { + return fmt.Errorf("%s - read recipient: %w", location, sanitizedDatabaseError(err)) + } + if !notificationFixtureEmail.MatchString(email) { + return fmt.Errorf("%s - recipient is outside the fixture scope: %w", location, ErrCompanyFixtureScope) + } + var exists bool + if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM organizations WHERE id = $1)`, organizationID).Scan(&exists); err != nil { + return fmt.Errorf("%s - read organization: %w", location, sanitizedDatabaseError(err)) + } + if !exists { + return fmt.Errorf("%s - organization: %w", location, outbound.ErrOrganizationNotFound) + } + return nil +} + +// NotificationFixtureEvent reads a synthetic inbox event from the outbox as +// the envelope a consumer receives for it, so the fixture can deliver it +// again the way an at-least-once bus does. +func NotificationFixtureEvent(ctx context.Context, pool *pgxpool.Pool, eventID uuid.UUID) (outbound.ConsumedEvent, error) { + const location = "postgres.NotificationFixtureEvent" + var event outbound.ConsumedEvent + var payload []byte + err := pool.QueryRow(ctx, ` + SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at + FROM outbox_events + WHERE event_id = $1 AND event_type = $2`, eventID, syntheticNoticeEventType).Scan( + &event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType, &event.AggregateID, + &event.AggregateVersion, &payload, &event.OccurredAt) + if errors.Is(err, pgx.ErrNoRows) { + return outbound.ConsumedEvent{}, fmt.Errorf("%s - synthetic event: %w", location, outbound.ErrNotificationInboxEntryNotFound) + } + if err != nil { + return outbound.ConsumedEvent{}, fmt.Errorf("%s - read outbox event: %w", location, sanitizedDatabaseError(err)) + } + event.Payload = payload + event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond) + return event, nil +} + +// HideNotificationFixtureOrganization records that a synthetic candidate +// hides an organization, the visibility change that removes the content of a +// synthetic notice. The browser suite cannot use the public operation for an +// organization the candidate has not seen yet. +func HideNotificationFixtureOrganization(ctx context.Context, pool *pgxpool.Pool, recipientID, organizationID uuid.UUID) error { + const location = "postgres.HideNotificationFixtureOrganization" + if err := CheckNotificationFixtureScope(ctx, pool, recipientID, organizationID); err != nil { + return err + } + if _, err := pool.Exec(ctx, ` + INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) + VALUES ($1, $2, now()) + ON CONFLICT DO NOTHING`, recipientID, organizationID); err != nil { + return fmt.Errorf("%s - hide organization: %w", location, sanitizedDatabaseError(err)) + } + return nil +} diff --git a/backend/internal/adapter/secondary/postgres/notification_inbox.go b/backend/internal/adapter/secondary/postgres/notification_inbox.go index 4860c08..b6edc88 100644 --- a/backend/internal/adapter/secondary/postgres/notification_inbox.go +++ b/backend/internal/adapter/secondary/postgres/notification_inbox.go @@ -18,9 +18,13 @@ import ( var _ outbound.NotificationInboxRepository = notificationInboxRepository{} +// notificationInboxRecipientConstraint is the foreign key of the recipient in +// migration 00032; the organization key has its own name. +const notificationInboxRecipientConstraint = "notification_inbox_events_recipient_fkey" + // NewNotificationInboxRepository creates a direct store for inbox operations. -// Transaction-bound callers can construct the same repository around the -// queries of their current UnitOfWork. +// Transaction-bound callers use UnitOfWork.NotificationInbox, which builds +// the same repository around the queries of the current transaction. func NewNotificationInboxRepository(pool *pgxpool.Pool) outbound.NotificationInboxRepository { return notificationInboxRepository{queries: sqlc.New(pool)} } @@ -29,6 +33,11 @@ type notificationInboxRepository struct { queries *sqlc.Queries } +// NotificationInbox binds the inbox repository to this transaction. +func (unit *UnitOfWork) NotificationInbox() outbound.NotificationInboxRepository { + return notificationInboxRepository{queries: unit.queries} +} + func (repository notificationInboxRepository) Store( ctx context.Context, entry domain.NotificationInboxEntry, @@ -52,7 +61,18 @@ func (repository notificationInboxRepository) Store( OccurredAt: pgTime(entry.OccurredAt()), }) if err != nil { - return false, fmt.Errorf("%s - insert recipient event: %w", location, sanitizedDatabaseError(err)) + sanitized := sanitizedDatabaseError(err) + var failure *databaseError + if errors.As(sanitized, &failure) && failure.code == foreignKeyViolationCode { + // The statement failed on the recipient or the organization row, so + // the surrounding transaction is aborted. + reference := outbound.ErrNotificationInboxReferenceMissing + if failure.constraint == notificationInboxRecipientConstraint { + reference = outbound.ErrNotificationInboxRecipientMissing + } + return false, fmt.Errorf("%s - insert recipient event: %w: %w", location, reference, sanitized) + } + return false, fmt.Errorf("%s - insert recipient event: %w", location, sanitized) } if rows == 1 { return true, nil @@ -116,16 +136,16 @@ func (repository notificationInboxRepository) List( func (repository notificationInboxRepository) MarkRead( ctx context.Context, recipientUserID uuid.UUID, - organizationID uuid.UUID, + organizationID *uuid.UUID, eventID uuid.UUID, at time.Time, ) (domain.NotificationInboxEntry, error) { const location = "notificationInboxRepository.MarkRead" - if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil || at.IsZero() { - return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, event, and read time are required: %w", location, domain.ErrInvalidNotificationInboxEntry) + if recipientUserID == uuid.Nil || (organizationID != nil && *organizationID == uuid.Nil) || eventID == uuid.Nil || at.IsZero() { + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, event, and read time are required: %w", location, domain.ErrInvalidNotificationInboxEntry) } row, err := repository.queries.MarkNotificationInboxEventRead(ctx, sqlc.MarkNotificationInboxEventReadParams{ - RecipientUserID: pgUUID(recipientUserID), OrganizationID: pgUUID(organizationID), + RecipientUserID: pgUUID(recipientUserID), OrganizationID: notificationInboxOptionalUUID(organizationID), EventID: pgUUID(eventID), ReadAt: pgTime(at), }) if errors.Is(err, pgx.ErrNoRows) { @@ -141,6 +161,26 @@ func (repository notificationInboxRepository) MarkRead( return entry, nil } +func (repository notificationInboxRepository) OrganizationNameForRecipient( + ctx context.Context, + recipientUserID, organizationID uuid.UUID, +) (string, error) { + const location = "notificationInboxRepository.OrganizationNameForRecipient" + if recipientUserID == uuid.Nil || organizationID == uuid.Nil { + return "", fmt.Errorf("%s - recipient and organization are required: %w", location, domain.ErrInvalidNotificationInboxEntry) + } + name, err := repository.queries.GetNotificationOrganizationNameForRecipient(ctx, sqlc.GetNotificationOrganizationNameForRecipientParams{ + RecipientUserID: pgUUID(recipientUserID), OrganizationID: pgUUID(organizationID), + }) + if errors.Is(err, pgx.ErrNoRows) { + return "", fmt.Errorf("%s - read organization: %w", location, outbound.ErrNotificationInboxSourceNotVisible) + } + if err != nil { + return "", fmt.Errorf("%s - read organization: %w", location, sanitizedDatabaseError(err)) + } + return name, nil +} + func validateInboxEntryForStore(entry domain.NotificationInboxEntry) error { _, err := domain.RestoreNotificationInboxEntry(domain.NotificationInboxEntryInput{ EventID: entry.EventID(), RecipientUserID: entry.RecipientUserID(), OrganizationID: entry.OrganizationID(), diff --git a/backend/internal/adapter/secondary/postgres/sqlc/candidate_search.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/candidate_search.sql.go new file mode 100644 index 0000000..f27e2e5 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/candidate_search.sql.go @@ -0,0 +1,56 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: candidate_search.sql + +package sqlc + +import ( + "context" +) + +const countRealComparableCategories = `-- name: CountRealComparableCategories :many + +SELECT + category.specialization, + category.grade, + count(*)::bigint AS candidates +FROM candidate_assessment_categories AS category +WHERE + category.source <> 'synthetic_demo' + AND (category.specialization || '/' || category.grade) = any($1::text []) +GROUP BY category.specialization, category.grade +` + +type CountRealComparableCategoriesRow struct { + Specialization string + Grade string + Candidates int64 +} + +// Reads that only the match search needs. The visibility of the candidates and +// their permitted evidence come from the card and evidence queries, which are +// the single copy of those barriers; this file adds no candidate-facing read. +// The number of candidates who hold each given category from a source that is +// not a synthetic demonstration, which is the size of the comparable real +// cohort that a percentile needs. It returns counts only, for the pairs the +// caller passes as "specialization/grade", and no row for a pair nobody holds. +func (q *Queries) CountRealComparableCategories(ctx context.Context, categories []string) ([]CountRealComparableCategoriesRow, error) { + rows, err := q.db.Query(ctx, countRealComparableCategories, categories) + if err != nil { + return nil, err + } + defer rows.Close() + var items []CountRealComparableCategoriesRow + for rows.Next() { + var i CountRealComparableCategoriesRow + if err := rows.Scan(&i.Specialization, &i.Grade, &i.Candidates); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/company_quota.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/company_quota.sql.go index f8af7a1..3d3ee16 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/company_quota.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/company_quota.sql.go @@ -186,7 +186,6 @@ func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg Ins } const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one - SELECT id, verification_level, @@ -204,9 +203,6 @@ type LockCompanyQuotaOrganizationRow struct { VerificationChangedAt pgtype.Timestamptz } -// Writers lock the organization first, then invitation/card-view state, and -// finally usage rows. The organization lock serializes quota decisions for -// the tenant and makes the subsequent count and insert atomic. func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) { row := q.db.QueryRow(ctx, lockCompanyQuotaOrganization, organizationID) var i LockCompanyQuotaOrganizationRow @@ -219,6 +215,32 @@ func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organization return i, err } +const lockCompanyQuotaOrganizationFirst = `-- name: LockCompanyQuotaOrganizationFirst :one + +SELECT id +FROM organizations +WHERE id = $1 +FOR NO KEY UPDATE +` + +// Writers lock the organization first, then invitation/card-view state, and +// finally usage rows. The organization lock serializes quota decisions for +// the tenant and makes the subsequent count and insert atomic. +// Takes the organization lock ahead of every share lock of a reader that will +// reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR +// SHARE, so readers of one organization queue up instead of deadlocking on a +// share lock that each then tries to raise, but it does not conflict with the +// FOR KEY SHARE that a foreign key takes, such as the hidden-organization +// insert of a candidate, which holds the candidate's row and then needs this +// one. The reservation itself still takes FOR UPDATE inside the same +// transaction. +func (q *Queries) LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, lockCompanyQuotaOrganizationFirst, organizationID) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows UPDATE company_card_view_quota_usage SET diff --git a/backend/internal/adapter/secondary/postgres/sqlc/evidence.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/evidence.sql.go index 4666f98..9cfb717 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/evidence.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/evidence.sql.go @@ -264,3 +264,93 @@ func (q *Queries) ListOrganizationVisibleEvidence(ctx context.Context, arg ListO } return items, nil } + +const listOrganizationVisibleEvidenceBatch = `-- name: ListOrganizationVisibleEvidenceBatch :many +SELECT DISTINCT ON (wanted.candidate_id, skill.skill_code) + wanted.candidate_id::uuid AS candidate_id, + skill.skill_code AS skill, + fact.grade, + fact.trust, + fact.basis, + fact.calibration_status, + extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year +FROM ( + SELECT + candidate_ids.candidate_id, + wanted_categories.category + FROM unnest($1::uuid []) WITH ORDINALITY AS candidate_ids (candidate_id, position) + INNER JOIN unnest($2::text []) WITH ORDINALITY AS wanted_categories (category, position) + ON candidate_ids.position = wanted_categories.position +) AS wanted +INNER JOIN candidate_effective_publications AS effective + ON wanted.candidate_id = effective.user_id +INNER JOIN skill_evidence_facts AS fact + ON effective.user_id = fact.candidate_id +INNER JOIN skill_evidence_skills AS skill + ON fact.id = skill.fact_id +WHERE + 'categories' = any(effective.fields) + AND (skill.skill_code || '/' || fact.grade) = wanted.category + AND fact.kind = 'measurement' + AND fact.visibility = 'visible' + AND NOT EXISTS ( + SELECT 1 + FROM candidate_hidden_organizations AS hidden + WHERE + hidden.user_id = effective.user_id + AND hidden.organization_id = $3 + ) +ORDER BY wanted.candidate_id, skill.skill_code, fact.occurred_at, fact.id +` + +type ListOrganizationVisibleEvidenceBatchParams struct { + CandidateIds []pgtype.UUID + Categories []string + OrganizationID pgtype.UUID +} + +type ListOrganizationVisibleEvidenceBatchRow struct { + CandidateID pgtype.UUID + Skill string + Grade string + Trust int16 + Basis string + CalibrationStatus string + ObservedYear int32 +} + +// The same organization read for a whole candidate set, so a search reads the +// evidence of every listed candidate in one statement. The pairs come from the +// caller as two parallel arrays, one row per candidate and category of the card +// that was just projected. The statement repeats every barrier of the single +// read: the effective publication view, NOT EXISTS over the candidates that +// hide the organization, the categories field, and only visible measurements. +// The candidate identifier is returned for the caller to group by and never +// leaves the server; the other columns are the same allowlist. +func (q *Queries) ListOrganizationVisibleEvidenceBatch(ctx context.Context, arg ListOrganizationVisibleEvidenceBatchParams) ([]ListOrganizationVisibleEvidenceBatchRow, error) { + rows, err := q.db.Query(ctx, listOrganizationVisibleEvidenceBatch, arg.CandidateIds, arg.Categories, arg.OrganizationID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListOrganizationVisibleEvidenceBatchRow + for rows.Next() { + var i ListOrganizationVisibleEvidenceBatchRow + if err := rows.Scan( + &i.CandidateID, + &i.Skill, + &i.Grade, + &i.Trust, + &i.Basis, + &i.CalibrationStatus, + &i.ObservedYear, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/notification_inbox.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/notification_inbox.sql.go index e71e591..da22c44 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/notification_inbox.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/notification_inbox.sql.go @@ -51,6 +51,49 @@ func (q *Queries) GetNotificationInboxEvent(ctx context.Context, arg GetNotifica return i, err } +const getNotificationOrganizationNameForRecipient = `-- name: GetNotificationOrganizationNameForRecipient :one +SELECT organizations.name +FROM organizations +INNER JOIN users ON users.id = $1 +WHERE organizations.id = $2 + AND ( + ( + users.scenario = 'candidate' + AND NOT EXISTS ( + SELECT 1 FROM candidate_hidden_organizations + WHERE candidate_hidden_organizations.user_id = users.id + AND candidate_hidden_organizations.organization_id = organizations.id + ) + ) + OR ( + users.scenario = 'employer' + AND EXISTS ( + SELECT 1 FROM memberships + WHERE memberships.user_id = users.id + AND memberships.organization_id = organizations.id + AND memberships.state = 'active' + ) + ) + ) +` + +type GetNotificationOrganizationNameForRecipientParams struct { + RecipientUserID pgtype.UUID + OrganizationID pgtype.UUID +} + +// Resolve the sender organization of a synthetic notice under the recipient's +// current standing, so the notice never outlives that standing. A candidate +// sees the name only while the organization is not hidden from them; an +// employer sees it only while they are an active member. No row means the +// content is no longer visible to this recipient. +func (q *Queries) GetNotificationOrganizationNameForRecipient(ctx context.Context, arg GetNotificationOrganizationNameForRecipientParams) (string, error) { + row := q.db.QueryRow(ctx, getNotificationOrganizationNameForRecipient, arg.RecipientUserID, arg.OrganizationID) + var name string + err := row.Scan(&name) + return name, err +} + const insertNotificationInboxEvent = `-- name: InsertNotificationInboxEvent :execrows INSERT INTO notification_inbox_events ( recipient_user_id, @@ -183,7 +226,10 @@ const markNotificationInboxEventRead = `-- name: MarkNotificationInboxEventRead UPDATE notification_inbox_events SET read_at = COALESCE(read_at, $1::timestamptz) WHERE recipient_user_id = $2 - AND organization_id = $3 + AND ( + $3::uuid IS NULL + OR organization_id = $3::uuid + ) AND event_id = $4 RETURNING recipient_user_id, @@ -204,8 +250,11 @@ type MarkNotificationInboxEventReadParams struct { EventID pgtype.UUID } -// Persist the first read time under exact recipient and organization scope. -// Repeated calls preserve the original read timestamp. +// Persist the first read time for the recipient, optionally under one exact +// organization context. A missing organization is the candidate cabinet, +// which spans the organizations that sent to it; the employer cabinet always +// names its organization. Repeated calls preserve the original read +// timestamp. func (q *Queries) MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error) { row := q.db.QueryRow(ctx, markNotificationInboxEventRead, arg.ReadAt, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index a54c637..b7edd35 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -131,6 +131,14 @@ type Querier interface { // Counts the families of a category that have at least one published // version, however many versions each has. CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error) + // Reads that only the match search needs. The visibility of the candidates and + // their permitted evidence come from the card and evidence queries, which are + // the single copy of those barriers; this file adds no candidate-facing read. + // The number of candidates who hold each given category from a source that is + // not a synthetic demonstration, which is the size of the comparable real + // cohort that a percentile needs. It returns counts only, for the pairs the + // caller passes as "specialization/grade", and no row for a pair nobody holds. + CountRealComparableCategories(ctx context.Context, categories []string) ([]CountRealComparableCategoriesRow, error) // New outcomes share the generic idempotency row and are counted for the // attempt's rolling receipt window. Replays bypass this query in the usecase. CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error) @@ -304,6 +312,12 @@ type Querier interface { // Read the existing row after a duplicate insert so the repository can reject // an event ID whose immutable metadata changed on redelivery. GetNotificationInboxEvent(ctx context.Context, arg GetNotificationInboxEventParams) (NotificationInboxEvent, error) + // Resolve the sender organization of a synthetic notice under the recipient's + // current standing, so the notice never outlives that standing. A candidate + // sees the name only while the organization is not hidden from them; an + // employer sees it only while they are an active member. No row means the + // content is no longer visible to this recipient. + GetNotificationOrganizationNameForRecipient(ctx context.Context, arg GetNotificationOrganizationNameForRecipientParams) (string, error) // Reads only the historical result. It intentionally does not join the live // organization or membership, whose profile and state may have since changed. GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error) @@ -615,6 +629,15 @@ type Querier interface { // calibration (the same for every candidate) say that the fact is a synthetic // demonstration. ListOrganizationVisibleEvidence(ctx context.Context, arg ListOrganizationVisibleEvidenceParams) ([]ListOrganizationVisibleEvidenceRow, error) + // The same organization read for a whole candidate set, so a search reads the + // evidence of every listed candidate in one statement. The pairs come from the + // caller as two parallel arrays, one row per candidate and category of the card + // that was just projected. The statement repeats every barrier of the single + // read: the effective publication view, NOT EXISTS over the candidates that + // hide the organization, the categories field, and only visible measurements. + // The candidate identifier is returned for the caller to group by and never + // leaves the server; the other columns are the same allowlist. + ListOrganizationVisibleEvidenceBatch(ctx context.Context, arg ListOrganizationVisibleEvidenceBatchParams) ([]ListOrganizationVisibleEvidenceBatchRow, error) // Lists the organizations where an account has an active membership, // newest membership first. The page continues after the (membership // creation time, organization ID) position of the last item of the @@ -678,10 +701,19 @@ type Querier interface { // canceled, or reclaimed after the lease expired. While the lock is held, // other workers skip the row, so the handler never runs twice at once. LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error) + LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) // Writers lock the organization first, then invitation/card-view state, and // finally usage rows. The organization lock serializes quota decisions for // the tenant and makes the subsequent count and insert atomic. - LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) + // Takes the organization lock ahead of every share lock of a reader that will + // reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR + // SHARE, so readers of one organization queue up instead of deadlocking on a + // share lock that each then tries to raise, but it does not conflict with the + // FOR KEY SHARE that a foreign key takes, such as the hidden-organization + // insert of a candidate, which holds the candidate's row and then needs this + // one. The reservation itself still takes FOR UPDATE inside the same + // transaction. + LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (pgtype.UUID, error) // Lock the current C2 before locking the publication. C2 revocation updates // this row before it locks the publication, so preserving this order avoids // a lock inversion and makes the current consent stable through the read. @@ -743,8 +775,11 @@ type Querier interface { // gate stops admitting sends until the window resets or an operator raises // the limit. The caller holds the row lock. MarkMailQuotaExhausted(ctx context.Context, arg MarkMailQuotaExhaustedParams) (int64, error) - // Persist the first read time under exact recipient and organization scope. - // Repeated calls preserve the original read timestamp. + // Persist the first read time for the recipient, optionally under one exact + // organization context. A missing organization is the candidate cabinet, + // which spans the organizations that sent to it; the employer cabinet always + // names its organization. Repeated calls preserve the original read + // timestamp. MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error) // Marks the events that the broker acknowledged. The relay passes only IDs // whose rows its own transaction locked, so the statement never waits and the diff --git a/backend/internal/bootstrap/consumers.go b/backend/internal/bootstrap/consumers.go index 5e3959e..597b142 100644 --- a/backend/internal/bootstrap/consumers.go +++ b/backend/internal/bootstrap/consumers.go @@ -48,7 +48,10 @@ func eventHandlers(settings config.Config, logger *slog.Logger) ([]inbound.Event time.Now, logger.With(slog.String("component", "notification_delivery")), ) - return []inbound.EventHandler{deliveries}, nil + // The inbox handler stores references only and reads no mail state, so it + // needs no renderer, provider account, or clock. + inbox := notification.NewInboxHandler(logger.With(slog.String("component", "notification_inbox")), settings.NotificationSyntheticEnabled) + return []inbound.EventHandler{deliveries, inbox}, nil } func newEventConsumers( diff --git a/backend/internal/bootstrap/consumers_test.go b/backend/internal/bootstrap/consumers_test.go index c8720a9..f267d3f 100644 --- a/backend/internal/bootstrap/consumers_test.go +++ b/backend/internal/bootstrap/consumers_test.go @@ -14,6 +14,7 @@ import ( "lincodex/backend/config" "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/notification" @@ -77,17 +78,31 @@ func TestBuildEventConsumersSkipsWithoutWork(t *testing.T) { } } -func TestBootstrapRegistersTheDeliveryHandler(t *testing.T) { +func TestBootstrapRegistersTheDeliveryAndInboxHandlers(t *testing.T) { handlers, err := eventHandlers(consumerTestConfig(t), slog.New(slog.DiscardHandler)) if err != nil { t.Fatalf("eventHandlers() error = %v", err) } - if len(handlers) != 1 || handlers[0].ConsumerName() != notification.DeliveryConsumerName { + if len(handlers) != 2 || handlers[0].ConsumerName() != notification.DeliveryConsumerName || + handlers[1].ConsumerName() != notification.InboxConsumerName { t.Fatalf("eventHandlers() = %v; update the documentation when the registered consumers change", handlers) } if !handlers[0].Handles(notification.MailRequestedEventType) { t.Fatalf("the delivery handler does not handle %s", notification.MailRequestedEventType) } + if !handlers[1].Handles(string(domain.NotificationInboxInvitationDelivered)) || + handlers[1].Handles(notification.MailRequestedEventType) { + t.Fatal("the inbox handler must handle the invitation event and no mail request") + } + if handlers[1].Handles(string(domain.NotificationInboxSyntheticDelivered)) { + t.Fatal("the synthetic inbox event is handled although its switch is off by default") + } + settings := consumerTestConfig(t) + settings.NotificationSyntheticEnabled = true + enabled, err := eventHandlers(settings, slog.New(slog.DiscardHandler)) + if err != nil || !enabled[1].Handles(string(domain.NotificationInboxSyntheticDelivered)) { + t.Fatalf("the synthetic inbox event is not handled with its switch on: %v", err) + } } func TestBootstrapRefusesAnInvalidMailAccountForDeliveries(t *testing.T) { diff --git a/backend/internal/bootstrap/identity.go b/backend/internal/bootstrap/identity.go index 08fa8f3..9928a44 100644 --- a/backend/internal/bootstrap/identity.go +++ b/backend/internal/bootstrap/identity.go @@ -46,6 +46,8 @@ func newAPIHandler( assessmentSignalHandler *v1.AssessmentSignalHandler, privacyHandler *v1.PrivacyHandler, evidenceHandler *v1.EvidenceHandler, + notificationHandler *v1.NotificationHandler, + matchHandler *v1.MatchHandler, ) *v1.Handler { return v1.NewHandler(health, problems, v1.WithIdentity(identityHandler), @@ -60,6 +62,8 @@ func newAPIHandler( v1.WithAssessmentSignals(assessmentSignalHandler), v1.WithPrivacy(privacyHandler), v1.WithEvidence(evidenceHandler), + v1.WithNotifications(notificationHandler), + v1.WithMatches(matchHandler), ) } diff --git a/backend/internal/bootstrap/matches.go b/backend/internal/bootstrap/matches.go new file mode 100644 index 0000000..16a8ee5 --- /dev/null +++ b/backend/internal/bootstrap/matches.go @@ -0,0 +1,66 @@ +package bootstrap + +import ( + "context" + "fmt" + "log/slog" + "time" + + "github.com/google/uuid" + + "lincodex/backend/config" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/matching" +) + +const matchesPoolMaxConns = 4 + +func newMatchHandler( + ctx context.Context, + settings config.Config, + logger *slog.Logger, + keyring *identity.Keyring, +) (*v1.MatchHandler, func(), error) { + if settings.DatabaseURL == "" { + logger.Warn("match search is not served because DATABASE_URL is not set") + return nil, func() {}, nil + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - derive projection key: %w", err) + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, matchesPoolMaxConns) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - create pool: %w", err) + } + transactor := postgres.NewTransactor(pool) + views, err := newCandidateViewService(pool, transactor, key) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - create view service: %w", err) + } + service, err := matching.NewService(matching.Dependencies{ + Transactor: transactor, Cards: views.ListVisibleCards, Views: searchViews(views), Clock: time.Now, Logger: logger, + }) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newMatchHandler - create service: %w", err) + } + return v1.NewMatchHandler(service), pool.Close, nil +} + +// searchViews adapts the card view service to the search, which charges and +// records the candidates it reveals like card reads. +func searchViews(views *candidateview.Service) matching.BeginViews { + return func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (matching.ViewSession, error) { + session, err := views.BeginSearchViews(ctx, unit, actorID, organizationID) + if err != nil { + return nil, err + } + return session, nil + } +} diff --git a/backend/internal/bootstrap/notification.go b/backend/internal/bootstrap/notification.go new file mode 100644 index 0000000..deb5755 --- /dev/null +++ b/backend/internal/bootstrap/notification.go @@ -0,0 +1,44 @@ +package bootstrap + +import ( + "context" + "fmt" + "log/slog" + "time" + + "lincodex/backend/config" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/usecase/notification" +) + +const notificationPoolMaxConns = 4 + +// newNotificationHandler builds the inbox operations and the PostgreSQL pool +// they own. Nothing connects here, so an unavailable database never blocks +// startup. It returns no handler when DATABASE_URL is unset, and the +// operations then answer 501. +func newNotificationHandler( + ctx context.Context, + settings config.Config, + logger *slog.Logger, +) (*v1.NotificationHandler, func(), error) { + if settings.DatabaseURL == "" { + logger.Warn("notification inbox operations are not served because DATABASE_URL is not set") + return nil, func() {}, nil + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, notificationPoolMaxConns) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newNotificationHandler - create pool: %w", err) + } + service, err := notification.NewInboxService( + postgres.NewTransactor(pool), + notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(settings.NotificationSyntheticEnabled)), + time.Now, + ) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newNotificationHandler - create service: %w", err) + } + return v1.NewNotificationHandler(service), pool.Close, nil +} diff --git a/backend/internal/bootstrap/policy.go b/backend/internal/bootstrap/policy.go index 0f5fc03..14b6589 100644 --- a/backend/internal/bootstrap/policy.go +++ b/backend/internal/bootstrap/policy.go @@ -9,6 +9,7 @@ import ( "lincodex/backend/config" "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/policy" ) @@ -45,13 +46,34 @@ func seedDemoPolicy(ctx context.Context, settings config.Config, logger *slog.Lo logger.Info("product policy already present; demo seed skipped", slog.String("policy_key", string(domain.ProductPolicyKey)), ) - return nil + } else { + logger.Info("demo product policy published", + slog.String("policy_key", string(result.Version.Key())), + slog.Int("policy_version", int(result.Version.Version())), + slog.String("policy_kind", string(result.Version.Kind())), + slog.String("policy_version_id", result.Version.ID().String()), + ) } - logger.Info("demo product policy published", - slog.String("policy_key", string(result.Version.Key())), - slog.Int("policy_version", int(result.Version.Version())), - slog.String("policy_kind", string(result.Version.Kind())), - slog.String("policy_version_id", result.Version.ID().String()), - ) + warnWithoutMatchingSection(ctx, postgres.NewPolicyStore(pool).Policies(), logger) return nil } + +// warnWithoutMatchingSection tells the operator at startup that the match +// search fails closed: the effective product policy has no matching section, and +// the demo seed publishes only the first version. It only warns; a policy the +// service cannot read must not stop startup either. +func warnWithoutMatchingSection(ctx context.Context, policies outbound.PolicyRepository, logger *slog.Logger) { + version, err := policies.GetEffective(ctx, domain.ProductPolicyKey, time.Now()) + if err != nil { + logger.Warn("the effective product policy could not be checked for the matching section", + slog.String("policy_key", string(domain.ProductPolicyKey)), + ) + return + } + if version.Policy().Matching == nil { + logger.Warn("the effective product policy has no matching section; match search answers with an internal error until an operator publishes it (make -C backend policy-publish ARGS='matching --actor operator:')", + slog.String("policy_key", string(version.Key())), + slog.Int("policy_version", int(version.Version())), + ) + } +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index fb7a617..50c200e 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -58,6 +58,8 @@ func initialize( newAssessmentSignalHandler, newPrivacyHandler, newEvidenceHandler, + newNotificationHandler, + newMatchHandler, newSessionSecurity, newRouter, newOutboxRelay, diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index 7640086..d2101b5 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -202,10 +202,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler) - sessionSecurity := newSessionSecurity(identityHandler) - v := newTrustedProxies(config2) - httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler) + notificationHandler, cleanup16, err := newNotificationHandler(ctx, config2, logger) if err != nil { cleanup15() cleanup14() @@ -224,26 +221,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - relay, cleanup16, err := newOutboxRelay(ctx, config2, logger, metrics) - if err != nil { - cleanup15() - cleanup14() - cleanup13() - cleanup12() - cleanup11() - cleanup10() - cleanup9() - cleanup8() - cleanup7() - cleanup6() - cleanup5() - cleanup4() - cleanup3() - cleanup2() - cleanup() - return nil, nil, err - } - bootstrapEventConsumers, cleanup17, err := newEventConsumers(ctx, config2, logger, metrics) + matchHandler, cleanup17, err := newMatchHandler(ctx, config2, logger, keyring) if err != nil { cleanup16() cleanup15() @@ -263,7 +241,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - worker, cleanup18, err := newJobWorker(ctx, config2, logger, metrics) + handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler) + sessionSecurity := newSessionSecurity(identityHandler) + v := newTrustedProxies(config2) + httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler) if err != nil { cleanup17() cleanup16() @@ -284,7 +265,28 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - mailsenderWorker, cleanup19, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) + relay, cleanup18, err := newOutboxRelay(ctx, config2, logger, metrics) + if err != nil { + cleanup17() + cleanup16() + cleanup15() + cleanup14() + cleanup13() + cleanup12() + cleanup11() + cleanup10() + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + bootstrapEventConsumers, cleanup19, err := newEventConsumers(ctx, config2, logger, metrics) if err != nil { cleanup18() cleanup17() @@ -306,7 +308,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - sampler, cleanup20, err := newDeliveryMetrics(ctx, config2, logger, metrics) + worker, cleanup20, err := newJobWorker(ctx, config2, logger, metrics) if err != nil { cleanup19() cleanup18() @@ -329,8 +331,59 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } + mailsenderWorker, cleanup21, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) + if err != nil { + cleanup20() + cleanup19() + cleanup18() + cleanup17() + cleanup16() + cleanup15() + cleanup14() + cleanup13() + cleanup12() + cleanup11() + cleanup10() + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + sampler, cleanup22, err := newDeliveryMetrics(ctx, config2, logger, metrics) + if err != nil { + cleanup21() + cleanup20() + cleanup19() + cleanup18() + cleanup17() + cleanup16() + cleanup15() + cleanup14() + cleanup13() + cleanup12() + 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() { + cleanup22() + cleanup21() cleanup20() cleanup19() cleanup18() diff --git a/backend/internal/domain/candidate_view_card.go b/backend/internal/domain/candidate_view_card.go new file mode 100644 index 0000000..5dcc6cb --- /dev/null +++ b/backend/internal/domain/candidate_view_card.go @@ -0,0 +1,22 @@ +package domain + +import ( + "log/slog" + + "github.com/google/uuid" +) + +// VisibleCandidateCard pairs the organization-scoped anonymous card with the +// internal candidate identifier of the same read. The identifier is a join and +// ordering key for server-side work such as matching; it must never be +// serialized, logged, or returned to an organization. +type VisibleCandidateCard struct { + CandidateID uuid.UUID + Card AnonymousCandidateViewDTO +} + +func (VisibleCandidateCard) String() string { return "[visible candidate card]" } +func (VisibleCandidateCard) GoString() string { return "[visible candidate card]" } +func (VisibleCandidateCard) LogValue() slog.Value { + return slog.StringValue("[visible candidate card]") +} diff --git a/backend/internal/domain/evidence_relation.go b/backend/internal/domain/evidence_relation.go new file mode 100644 index 0000000..41e832e --- /dev/null +++ b/backend/internal/domain/evidence_relation.go @@ -0,0 +1,19 @@ +package domain + +// EvidenceSkillRelation says how the skill of a piece of evidence relates to +// a skill that a need asks for. +type EvidenceSkillRelation uint8 + +const ( + // EvidenceSkillRelationNone means the evidence says nothing about the + // requested skill. + EvidenceSkillRelationNone EvidenceSkillRelation = iota + // EvidenceSkillRelationExact means the same skill. + EvidenceSkillRelationExact + // EvidenceSkillRelationNarrower means the evidence names a part of the + // requested skill (a technology under a requested specialization). + EvidenceSkillRelationNarrower + // EvidenceSkillRelationBroader means the evidence names a field that + // contains the requested skill (a specialization over a technology). + EvidenceSkillRelationBroader +) diff --git a/backend/internal/domain/notification_inbox.go b/backend/internal/domain/notification_inbox.go index eeb15d1..729e1d3 100644 --- a/backend/internal/domain/notification_inbox.go +++ b/backend/internal/domain/notification_inbox.go @@ -14,13 +14,41 @@ var ErrInvalidNotificationInboxEntry = errors.New("invalid notification inbox en // in the internal inbox. type NotificationInboxEventType string -const NotificationInboxInvitationDelivered NotificationInboxEventType = "invitation.delivered" +const ( + // NotificationInboxInvitationDelivered records that an invitation reached + // the candidate's inbox. Its source is the invitation. + NotificationInboxInvitationDelivered NotificationInboxEventType = "invitation.delivered" + // NotificationInboxSyntheticDelivered is a synthetic event type. It + // carries no product meaning: it exists to exercise the whole inbox path + // (outbox, consumer, read-time visibility check, listing, read state) + // before real producers exist and in browser tests. Its source is the + // sending organization, and its content is a fixed notice that names that + // organization. + NotificationInboxSyntheticDelivered NotificationInboxEventType = "notification.synthetic_delivered" +) // NotificationInboxSourceType identifies the current source-of-truth record // used to resolve an inbox item's content. type NotificationInboxSourceType string -const NotificationInboxSourceInvitation NotificationInboxSourceType = "invitation" +const ( + NotificationInboxSourceInvitation NotificationInboxSourceType = "invitation" + NotificationInboxSourceOrganization NotificationInboxSourceType = "organization" +) + +// NotificationInboxSourceFor returns the only source type that an event type +// may refer to, and false for an event type that is not allowlisted. The +// database repeats the same pairs in a CHECK constraint. +func NotificationInboxSourceFor(eventType NotificationInboxEventType) (NotificationInboxSourceType, bool) { + switch eventType { + case NotificationInboxInvitationDelivered: + return NotificationInboxSourceInvitation, true + case NotificationInboxSyntheticDelivered: + return NotificationInboxSourceOrganization, true + default: + return "", false + } +} // NotificationInboxEntryInput contains identifiers and event metadata only. // It deliberately has no content snapshot: presentation is resolved from the @@ -78,7 +106,8 @@ func restoreNotificationInboxEntryWithLocation( if input.EventID == uuid.Nil || input.RecipientUserID == uuid.Nil || input.OrganizationID == uuid.Nil || input.SourceID == uuid.Nil { return NotificationInboxEntry{}, fmt.Errorf("%s - event, recipient, organization, and source IDs are required: %w", location, ErrInvalidNotificationInboxEntry) } - if input.EventType != NotificationInboxInvitationDelivered || input.SchemaVersion != 1 || input.SourceType != NotificationInboxSourceInvitation { + sourceType, known := NotificationInboxSourceFor(input.EventType) + if !known || input.SchemaVersion != 1 || input.SourceType != sourceType { return NotificationInboxEntry{}, fmt.Errorf("%s - event type, schema version, and source type are unsupported: %w", location, ErrInvalidNotificationInboxEntry) } if input.OccurredAt.IsZero() { diff --git a/backend/internal/domain/notification_inbox_test.go b/backend/internal/domain/notification_inbox_test.go index cf84bf2..791e3c7 100644 --- a/backend/internal/domain/notification_inbox_test.go +++ b/backend/internal/domain/notification_inbox_test.go @@ -57,6 +57,7 @@ func TestRestoreNotificationInboxEntryRejectsInvalidMetadata(t *testing.T) { {name: "unknown event type", mutate: func(input *NotificationInboxEntryInput) { input.EventType = "notification.mail_requested" }}, {name: "unsupported schema version", mutate: func(input *NotificationInboxEntryInput) { input.SchemaVersion = 2 }}, {name: "unknown source type", mutate: func(input *NotificationInboxEntryInput) { input.SourceType = "mail_request" }}, + {name: "source type of another event type", mutate: func(input *NotificationInboxEntryInput) { input.SourceType = NotificationInboxSourceOrganization }}, {name: "missing occurrence time", mutate: func(input *NotificationInboxEntryInput) { input.OccurredAt = time.Time{} }}, {name: "zero read time", mutate: func(input *NotificationInboxEntryInput) { input.ReadAt = &zeroTime }}, } @@ -118,3 +119,21 @@ func TestNotificationInboxEntryMarkReadPreservesFirstTimestamp(t *testing.T) { t.Fatal("MarkRead changed immutable source identity") } } + +func TestNotificationInboxEntryAcceptsTheSyntheticEventOnlyWithItsSource(t *testing.T) { + t.Parallel() + + input := NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(), + EventType: NotificationInboxSyntheticDelivered, SchemaVersion: 1, + SourceType: NotificationInboxSourceOrganization, SourceID: uuid.New(), + OccurredAt: time.Date(2026, time.October, 8, 12, 30, 0, 0, time.UTC), + } + if _, err := NewNotificationInboxEntry(input); err != nil { + t.Fatalf("NewNotificationInboxEntry(synthetic) error = %v", err) + } + input.SourceType = NotificationInboxSourceInvitation + if _, err := NewNotificationInboxEntry(input); !errors.Is(err, ErrInvalidNotificationInboxEntry) { + t.Fatalf("NewNotificationInboxEntry(synthetic with invitation source) error = %v, want ErrInvalidNotificationInboxEntry", err) + } +} diff --git a/backend/internal/domain/policy.go b/backend/internal/domain/policy.go index 89c69a5..7cbe7c2 100644 --- a/backend/internal/domain/policy.go +++ b/backend/internal/domain/policy.go @@ -93,6 +93,10 @@ type ProductPolicy struct { // Support is absent only in immutable policy documents that predate the // support section. New demo policies should set it explicitly. Support *SupportPolicy + // Matching holds the coefficients of the deterministic basic matching. It + // is nil in policy versions that predate it; such a version cannot rank + // and never inherits another version's coefficients. + Matching *MatchingPolicy } // Validate checks every section. A zero value is never valid, so a section @@ -114,6 +118,11 @@ func (policy ProductPolicy) Validate() error { return fmt.Errorf("ProductPolicy.Validate - support section: %w: %w", ErrInvalidPolicy, err) } } + if policy.Matching != nil { + if err := policy.Matching.Validate(); err != nil { + return err + } + } return nil } @@ -138,6 +147,10 @@ func (policy ProductPolicy) clone() ProductPolicy { supportCopy := *support copied.Support = &supportCopy } + if matching := policy.Matching; matching != nil { + matchingCopy := matching.Clone() + copied.Matching = &matchingCopy + } return copied } diff --git a/backend/internal/domain/policy_demo.go b/backend/internal/domain/policy_demo.go index e40aeb3..82ea90c 100644 --- a/backend/internal/domain/policy_demo.go +++ b/backend/internal/domain/policy_demo.go @@ -96,3 +96,13 @@ func DemoProductPolicyV3() ProductPolicy { policy.Assessment.Signals = &signals return policy } + +// DemoProductPolicyV4 returns the demo policy with the matching coefficients +// on top of DemoProductPolicyV3. It is published explicitly; a stored version +// is never rewritten, and startup seeding publishes V1 only. +func DemoProductPolicyV4() ProductPolicy { + policy := DemoProductPolicyV3() + matching := DemoMatchingPolicy() + policy.Matching = &matching + return policy +} diff --git a/backend/internal/domain/policy_document.go b/backend/internal/domain/policy_document.go index eba35f5..160e34c 100644 --- a/backend/internal/domain/policy_document.go +++ b/backend/internal/domain/policy_document.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io" + "slices" ) const ( @@ -36,6 +37,7 @@ type productPolicyDocument struct { Identity *identityPolicyDocument `json:"identity"` SearchStatus *searchStatusDocument `json:"search_status"` Support *supportPolicyDocument `json:"support,omitempty"` + Matching *matchingPolicyDocument `json:"matching,omitempty"` } // productPolicyV1Document deliberately excludes extension keys. Its strict @@ -157,6 +159,39 @@ type identityPolicyDocument struct { SessionAbsoluteLifetimeDays *CalendarDays `json:"session_absolute_lifetime_days"` } +type matchingPolicyDocument struct { + FitCoverageWeightBP *BasisPoints `json:"fit_coverage_weight_bp"` + FitDomainWeightBP *BasisPoints `json:"fit_domain_weight_bp"` + FitSemanticsWeightBP *BasisPoints `json:"fit_semantics_weight_bp"` + RankFitWeightBP *BasisPoints `json:"rank_fit_weight_bp"` + RankStrengthWeightBP *BasisPoints `json:"rank_strength_weight_bp"` + FreshnessFloorBP *BasisPoints `json:"freshness_floor_bp"` + ResponsivenessFloorBP *BasisPoints `json:"responsiveness_floor_bp"` + CompetitionBoostBP *BasisPoints `json:"competition_boost_bp"` + NeutralUnknownBP *BasisPoints `json:"neutral_unknown_bp"` + NearSkillThresholdBP *BasisPoints `json:"near_skill_threshold_bp"` + RequiredSkillWeight *int32 `json:"required_skill_weight"` + DesiredSkillWeight *int32 `json:"desired_skill_weight"` + TrustStatedBP *BasisPoints `json:"trust_stated_bp"` + TrustOnlineBP *BasisPoints `json:"trust_online_bp"` + TrustIdentityBP *BasisPoints `json:"trust_identity_bp"` + TrustInPersonBP *BasisPoints `json:"trust_in_person_bp"` + AttributionPersonalBP *BasisPoints `json:"attribution_personal_bp"` + AttributionTeamRoleBP *BasisPoints `json:"attribution_team_role_bp"` + AttributionTeamUnattributed *BasisPoints `json:"attribution_team_unattributed_bp"` + RelationExactBP *BasisPoints `json:"relation_exact_bp"` + RelationNarrowerBP *BasisPoints `json:"relation_narrower_bp"` + RelationBroaderBP *BasisPoints `json:"relation_broader_bp"` + PercentileMinCohort *int32 `json:"percentile_min_cohort"` + MaxResultsPerGroup *int32 `json:"max_results_per_group"` + SkillTaxonomy *[]matchingSkillGroupDocument `json:"skill_taxonomy"` +} + +type matchingSkillGroupDocument struct { + Specialization *SpecializationCode `json:"specialization"` + Skills *[]CandidateViewSkillCode `json:"skills"` +} + type searchStatusDocument struct { SearchingConfirmationIntervalDays *CalendarDays `json:"searching_confirmation_interval_days"` } @@ -178,7 +213,8 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro } } schemaVersion := int32(productPolicySchemaVersionV1) - if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil || policy.Support != nil { + if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil || + policy.Support != nil || policy.Matching != nil { schemaVersion = productPolicySchemaVersionV2 } document := productPolicyDocument{ @@ -230,7 +266,8 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro SearchStatus: &searchStatusDocument{ SearchingConfirmationIntervalDays: pointer(policy.SearchStatus.SearchingConfirmationInterval), }, - Support: support, + Support: support, + Matching: encodeMatchingPolicy(policy.Matching), } encoded, err := json.Marshal(document) if err != nil { @@ -292,6 +329,49 @@ func encodeAssessmentSignalPolicy(policy *AssessmentSignalPolicy) *assessmentSig } } +func encodeMatchingPolicy(policy *MatchingPolicy) *matchingPolicyDocument { + if policy == nil { + return nil + } + return &matchingPolicyDocument{ + FitCoverageWeightBP: pointer(policy.FitCoverageWeight), + FitDomainWeightBP: pointer(policy.FitDomainWeight), + FitSemanticsWeightBP: pointer(policy.FitSemanticsWeight), + RankFitWeightBP: pointer(policy.RankFitWeight), + RankStrengthWeightBP: pointer(policy.RankStrengthWeight), + FreshnessFloorBP: pointer(policy.FreshnessFloor), + ResponsivenessFloorBP: pointer(policy.ResponsivenessFloor), + CompetitionBoostBP: pointer(policy.CompetitionBoost), + NeutralUnknownBP: pointer(policy.NeutralUnknown), + NearSkillThresholdBP: pointer(policy.NearSkillThreshold), + RequiredSkillWeight: pointer(policy.RequiredSkillWeight), + DesiredSkillWeight: pointer(policy.DesiredSkillWeight), + TrustStatedBP: pointer(policy.TrustStated), + TrustOnlineBP: pointer(policy.TrustOnline), + TrustIdentityBP: pointer(policy.TrustIdentity), + TrustInPersonBP: pointer(policy.TrustInPerson), + AttributionPersonalBP: pointer(policy.AttributionSelf), + AttributionTeamRoleBP: pointer(policy.AttributionTeamRole), + AttributionTeamUnattributed: pointer(policy.AttributionTeamUnattributed), + RelationExactBP: pointer(policy.RelationExact), + RelationNarrowerBP: pointer(policy.RelationNarrower), + RelationBroaderBP: pointer(policy.RelationBroader), + PercentileMinCohort: pointer(policy.PercentileMinCohort), + MaxResultsPerGroup: pointer(policy.MaxResultsPerGroup), + SkillTaxonomy: pointer(encodeMatchingSkillGroups(policy.SkillTaxonomy)), + } +} + +func encodeMatchingSkillGroups(groups []MatchingSkillGroup) []matchingSkillGroupDocument { + documents := make([]matchingSkillGroupDocument, 0, len(groups)) + for _, group := range groups { + documents = append(documents, matchingSkillGroupDocument{ + Specialization: pointer(group.Specialization), Skills: pointer(slices.Clone(group.Skills)), + }) + } + return documents +} + func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument { return &organizationTierQuotaDocument{ Active: pointer(quota.Active), @@ -347,7 +427,7 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) { } assessment := parsed.Assessment hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil || assessment.Signals != nil) - if !hasAssessmentExtension && parsed.Support == nil { + if !hasAssessmentExtension && parsed.Support == nil && parsed.Matching == nil { return ProductPolicy{}, invalidPolicy(location, "schema_version 2 requires at least one policy extension") } default: @@ -493,7 +573,8 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32 SearchStatus: SearchStatusPolicy{ SearchingConfirmationInterval: require(&reader, "search_status.searching_confirmation_interval_days", searchStatus.SearchingConfirmationIntervalDays), }, - Support: decodeOptionalSupportPolicy(&reader, parsed.Support), + Support: decodeOptionalSupportPolicy(&reader, parsed.Support), + Matching: decodeOptionalMatchingPolicy(&reader, parsed.Matching), } if reader.missing != "" { return ProductPolicy{}, invalidPolicy(location, reader.missing+" is required") @@ -501,6 +582,48 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32 return policy, nil } +// decodeOptionalMatchingPolicy keeps documents that predate the matching +// section without it and never fills an omitted section with demo values. +func decodeOptionalMatchingPolicy(reader *documentReader, document *matchingPolicyDocument) *MatchingPolicy { + if document == nil { + return nil + } + taxonomy := make([]MatchingSkillGroup, 0) + for _, group := range require(reader, "matching.skill_taxonomy", document.SkillTaxonomy) { + taxonomy = append(taxonomy, MatchingSkillGroup{ + Specialization: require(reader, "matching.skill_taxonomy.specialization", group.Specialization), + Skills: require(reader, "matching.skill_taxonomy.skills", group.Skills), + }) + } + return &MatchingPolicy{ + FitCoverageWeight: require(reader, "matching.fit_coverage_weight_bp", document.FitCoverageWeightBP), + FitDomainWeight: require(reader, "matching.fit_domain_weight_bp", document.FitDomainWeightBP), + FitSemanticsWeight: require(reader, "matching.fit_semantics_weight_bp", document.FitSemanticsWeightBP), + RankFitWeight: require(reader, "matching.rank_fit_weight_bp", document.RankFitWeightBP), + RankStrengthWeight: require(reader, "matching.rank_strength_weight_bp", document.RankStrengthWeightBP), + FreshnessFloor: require(reader, "matching.freshness_floor_bp", document.FreshnessFloorBP), + ResponsivenessFloor: require(reader, "matching.responsiveness_floor_bp", document.ResponsivenessFloorBP), + CompetitionBoost: require(reader, "matching.competition_boost_bp", document.CompetitionBoostBP), + NeutralUnknown: require(reader, "matching.neutral_unknown_bp", document.NeutralUnknownBP), + NearSkillThreshold: require(reader, "matching.near_skill_threshold_bp", document.NearSkillThresholdBP), + RequiredSkillWeight: require(reader, "matching.required_skill_weight", document.RequiredSkillWeight), + DesiredSkillWeight: require(reader, "matching.desired_skill_weight", document.DesiredSkillWeight), + TrustStated: require(reader, "matching.trust_stated_bp", document.TrustStatedBP), + TrustOnline: require(reader, "matching.trust_online_bp", document.TrustOnlineBP), + TrustIdentity: require(reader, "matching.trust_identity_bp", document.TrustIdentityBP), + TrustInPerson: require(reader, "matching.trust_in_person_bp", document.TrustInPersonBP), + AttributionSelf: require(reader, "matching.attribution_personal_bp", document.AttributionPersonalBP), + AttributionTeamRole: require(reader, "matching.attribution_team_role_bp", document.AttributionTeamRoleBP), + AttributionTeamUnattributed: require(reader, "matching.attribution_team_unattributed_bp", document.AttributionTeamUnattributed), + RelationExact: require(reader, "matching.relation_exact_bp", document.RelationExactBP), + RelationNarrower: require(reader, "matching.relation_narrower_bp", document.RelationNarrowerBP), + RelationBroader: require(reader, "matching.relation_broader_bp", document.RelationBroaderBP), + PercentileMinCohort: require(reader, "matching.percentile_min_cohort", document.PercentileMinCohort), + MaxResultsPerGroup: require(reader, "matching.max_results_per_group", document.MaxResultsPerGroup), + SkillTaxonomy: taxonomy, + } +} + func decodeTierQuota(reader *documentReader, field string, document *organizationTierQuotaDocument) OrganizationTierQuota { tier := require(reader, field, document) return OrganizationTierQuota{ diff --git a/backend/internal/domain/policy_matching.go b/backend/internal/domain/policy_matching.go new file mode 100644 index 0000000..c246dc9 --- /dev/null +++ b/backend/internal/domain/policy_matching.go @@ -0,0 +1,336 @@ +package domain + +import "slices" + +// MatchingPolicy holds the versioned coefficients of the deterministic basic +// matching (FR09). Every share is a BasisPoints value, so a comparison and a +// stored document carry an exact integer instead of a binary fraction. The +// section is optional: a policy version without it cannot rank, and an absent +// section never acquires defaults. +// +// Fit = FitCoverageWeight*Cov + FitDomainWeight*Dom + FitSemanticsWeight*Sem +// P = T + CompetitionBoost*(1-T)*V +// S = (RankFitWeight*Fit + RankStrengthWeight*P) * +// +// (FreshnessFloor + (1-FreshnessFloor)*Fr) * +// (ResponsivenessFloor + (1-ResponsivenessFloor)*Rsp) +// +// A skill contributes the best product of the trust, attribution, and +// relation coefficients over the permitted evidence; Cov is the weighted mean +// of the contributions of the requested skills. +type MatchingPolicy struct { + FitCoverageWeight BasisPoints + FitDomainWeight BasisPoints + FitSemanticsWeight BasisPoints + + RankFitWeight BasisPoints + RankStrengthWeight BasisPoints + // FreshnessFloor and ResponsivenessFloor are the multipliers of a + // component equal to zero; a component equal to one multiplies by 1. + FreshnessFloor BasisPoints + ResponsivenessFloor BasisPoints + // CompetitionBoost is the share of the remaining distance (1-T) that a + // competition contribution of one adds to the strength of the profile. + CompetitionBoost BasisPoints + + // NeutralUnknown replaces a component whose value is unknown. The + // unknown state is reported next to it and is never read as zero ability. + NeutralUnknown BasisPoints + // NearSkillThreshold is the contribution below which a requested + // required skill moves a confirmed profile to the near group. + NearSkillThreshold BasisPoints + + RequiredSkillWeight int32 + DesiredSkillWeight int32 + + // The trust coefficients are indexed by the evidence trust level 0..3. + TrustStated BasisPoints + TrustOnline BasisPoints + TrustIdentity BasisPoints + TrustInPerson BasisPoints + AttributionSelf BasisPoints + // AttributionTeamRole is a relevant role in a team result and + // AttributionTeamUnattributed a team result without a role. + AttributionTeamRole BasisPoints + AttributionTeamUnattributed BasisPoints + + // The relation coefficients apply when the evidence skill equals the + // requested one (or a synonym), is narrower than it, or is broader. + RelationExact BasisPoints + RelationNarrower BasisPoints + RelationBroader BasisPoints + + // PercentileMinCohort is the smallest number of comparable real + // candidates that allows a percentile; below it T is neutral. + PercentileMinCohort int32 + + // MaxResultsPerGroup bounds how many entries of each group one search may + // return. The whole visible bank is ranked and only the output is cut, so + // a search cannot read the whole bank at once. It is a demonstration value + // that stays below the daily card-view allowance of the first tier. + MaxResultsPerGroup int32 + + // SkillTaxonomy lists, for each specialization, the technologies that fall + // inside it. Evidence for a specialization is broader evidence for each of + // them, and evidence for one of them is narrower evidence for the + // specialization. It is part of the version, so the policy version fully + // determines a result. + SkillTaxonomy []MatchingSkillGroup +} + +// MatchingSkillGroup is the technologies that one specialization contains. +type MatchingSkillGroup struct { + Specialization SpecializationCode + Skills []CandidateViewSkillCode +} + +// Clone copies the slices, so a caller cannot change a stored version. +func (policy MatchingPolicy) Clone() MatchingPolicy { + policy.SkillTaxonomy = slices.Clone(policy.SkillTaxonomy) + for index := range policy.SkillTaxonomy { + policy.SkillTaxonomy[index].Skills = slices.Clone(policy.SkillTaxonomy[index].Skills) + } + return policy +} + +// RelateSkill classifies the skill of a piece of evidence against a requested +// skill by the taxonomy of this policy version. Both are taxonomy codes; an +// unmapped code has no relation. +func (policy MatchingPolicy) RelateSkill(requested, evidence string) EvidenceSkillRelation { + switch { + case requested == "" || evidence == "": + return EvidenceSkillRelationNone + case requested == evidence: + return EvidenceSkillRelationExact + case policy.contains(evidence, requested): + return EvidenceSkillRelationBroader + case policy.contains(requested, evidence): + return EvidenceSkillRelationNarrower + default: + return EvidenceSkillRelationNone + } +} + +func (policy MatchingPolicy) contains(specialization, skill string) bool { + for _, group := range policy.SkillTaxonomy { + if string(group.Specialization) != specialization { + continue + } + for _, contained := range group.Skills { + if string(contained) == skill { + return true + } + } + } + return false +} + +// Sanity bounds of the matching section. They reject a value in the wrong +// unit; the demo values themselves are recorded in DemoMatchingPolicy. +const ( + maxMatchingSkillWeight = 100 + maxMatchingCohortMinimum = 100000 + maxMatchingResults = 1000 +) + +// DemoMatchingPolicy returns the initial matching coefficients. They are the +// design values of PRD 4.9 for verifying the flow, not measured results: no +// labelled set supports them, and a calibrated policy must replace them. +func DemoMatchingPolicy() MatchingPolicy { + return MatchingPolicy{ + FitCoverageWeight: 7500, FitDomainWeight: 1500, FitSemanticsWeight: 1000, + RankFitWeight: 5000, RankStrengthWeight: 5000, + FreshnessFloor: 9000, ResponsivenessFloor: 9000, + CompetitionBoost: 3000, + NeutralUnknown: 5000, NearSkillThreshold: 2500, + RequiredSkillWeight: 2, DesiredSkillWeight: 1, + TrustStated: 2500, TrustOnline: 6000, TrustIdentity: 8500, TrustInPerson: 10000, + AttributionSelf: 10000, AttributionTeamRole: 8000, AttributionTeamUnattributed: 5000, + RelationExact: 10000, RelationNarrower: 8000, RelationBroader: 4000, + PercentileMinCohort: 30, + // 10 per group is at most 30 reveals for one search, below the 50 + // distinct card views per day of the first tier, so one search cannot + // spend a whole allowance. + MaxResultsPerGroup: 10, + SkillTaxonomy: []MatchingSkillGroup{ + { + Specialization: SpecializationBackend, + Skills: []CandidateViewSkillCode{ + CandidateViewSkillDocker, CandidateViewSkillGo, CandidateViewSkillKafka, CandidateViewSkillPostgreSQL, + }, + }, + {Specialization: SpecializationDevopsSRE, Skills: []CandidateViewSkillCode{CandidateViewSkillDocker}}, + }, + } +} + +// TrustCoefficient returns the coefficient of an evidence trust level. An +// unknown level has none. +func (policy MatchingPolicy) TrustCoefficient(trust EvidenceTrust) (BasisPoints, bool) { + switch trust { + case EvidenceTrustStated: + return policy.TrustStated, true + case EvidenceTrustOnlineUnconfirmed: + return policy.TrustOnline, true + case EvidenceTrustIdentityTied: + return policy.TrustIdentity, true + case EvidenceTrustInPerson: + return policy.TrustInPerson, true + default: + return 0, false + } +} + +// AttributionCoefficient returns the coefficient of an evidence attribution. +func (policy MatchingPolicy) AttributionCoefficient(attribution EvidenceAttribution) (BasisPoints, bool) { + switch attribution { + case EvidenceAttributionPersonal: + return policy.AttributionSelf, true + case EvidenceAttributionTeamRole: + return policy.AttributionTeamRole, true + case EvidenceAttributionTeamUnattributed: + return policy.AttributionTeamUnattributed, true + default: + return 0, false + } +} + +// RelationCoefficient returns the coefficient of a skill relation. A skill +// that is unrelated to the requested one earns nothing. +func (policy MatchingPolicy) RelationCoefficient(relation EvidenceSkillRelation) BasisPoints { + switch relation { + case EvidenceSkillRelationExact: + return policy.RelationExact + case EvidenceSkillRelationNarrower: + return policy.RelationNarrower + case EvidenceSkillRelationBroader: + return policy.RelationBroader + case EvidenceSkillRelationNone: + return 0 + default: + return 0 + } +} + +// Validate rejects a zero, out-of-range, or inconsistent section. +func (policy MatchingPolicy) Validate() error { + return firstError( + policy.validateShares(), + policy.validateWeights(), + policy.validateOrdering(), + ) +} + +func (policy MatchingPolicy) validateShares() error { + const location = "MatchingPolicy.Validate" + shares := []struct { + field string + value BasisPoints + }{ + {"matching.competition_boost_bp", policy.CompetitionBoost}, + {"matching.neutral_unknown_bp", policy.NeutralUnknown}, + {"matching.near_skill_threshold_bp", policy.NearSkillThreshold}, + {"matching.trust_stated_bp", policy.TrustStated}, + {"matching.trust_online_bp", policy.TrustOnline}, + {"matching.trust_identity_bp", policy.TrustIdentity}, + {"matching.trust_in_person_bp", policy.TrustInPerson}, + {"matching.attribution_personal_bp", policy.AttributionSelf}, + {"matching.attribution_team_role_bp", policy.AttributionTeamRole}, + {"matching.attribution_team_unattributed_bp", policy.AttributionTeamUnattributed}, + {"matching.relation_exact_bp", policy.RelationExact}, + {"matching.relation_narrower_bp", policy.RelationNarrower}, + {"matching.relation_broader_bp", policy.RelationBroader}, + } + for _, share := range shares { + if err := checkRange(location, share.field, share.value, 0, basisPointsPerUnit); err != nil { + return err + } + } + // A floor of zero would let one unknown multiplier erase the score, and a + // floor of one would switch the multiplier off. + return firstError( + checkRange(location, "matching.freshness_floor_bp", policy.FreshnessFloor, 1, basisPointsPerUnit), + checkRange(location, "matching.responsiveness_floor_bp", policy.ResponsivenessFloor, 1, basisPointsPerUnit), + ) +} + +func (policy MatchingPolicy) validateWeights() error { + const location = "MatchingPolicy.Validate" + if err := firstError( + checkRange(location, "matching.required_skill_weight", policy.RequiredSkillWeight, 1, maxMatchingSkillWeight), + checkRange(location, "matching.desired_skill_weight", policy.DesiredSkillWeight, 1, maxMatchingSkillWeight), + checkRange(location, "matching.percentile_min_cohort", policy.PercentileMinCohort, 1, maxMatchingCohortMinimum), + checkRange(location, "matching.max_results_per_group", policy.MaxResultsPerGroup, 1, maxMatchingResults), + policy.validateTaxonomy(), + ); err != nil { + return err + } + for _, sum := range []struct { + field string + values []BasisPoints + }{ + {"matching.fit_*_weight_bp", []BasisPoints{policy.FitCoverageWeight, policy.FitDomainWeight, policy.FitSemanticsWeight}}, + {"matching.rank_*_weight_bp", []BasisPoints{policy.RankFitWeight, policy.RankStrengthWeight}}, + } { + var total BasisPoints + for _, value := range sum.values { + if err := checkRange(location, sum.field, value, 0, basisPointsPerUnit); err != nil { + return err + } + total += value + } + if total != basisPointsPerUnit { + return invalidPolicy(location, sum.field+" must add up to 1.0000") + } + } + return nil +} + +// validateOrdering keeps a stronger confirmation from counting for less than +// a weaker one, and a closer relation from counting for less than a looser one. +func (policy MatchingPolicy) validateOrdering() error { + const location = "MatchingPolicy.Validate" + if policy.TrustStated > policy.TrustOnline || policy.TrustOnline > policy.TrustIdentity || policy.TrustIdentity > policy.TrustInPerson { + return invalidPolicy(location, "matching trust coefficients must not decrease with the trust level") + } + if policy.AttributionTeamUnattributed > policy.AttributionTeamRole || policy.AttributionTeamRole > policy.AttributionSelf { + return invalidPolicy(location, "matching attribution coefficients must not increase from personal to team results") + } + if policy.RelationBroader > policy.RelationNarrower || policy.RelationNarrower > policy.RelationExact { + return invalidPolicy(location, "matching relation coefficients must not increase from broader to exact") + } + return nil +} + +// validateTaxonomy keeps each specialization and technology known and listed +// once, so a relation never depends on the order or a repeat. +func (policy MatchingPolicy) validateTaxonomy() error { + const location = "MatchingPolicy.Validate" + seen := make(map[SpecializationCode]struct{}, len(policy.SkillTaxonomy)) + if len(policy.SkillTaxonomy) > len(specializationCodes) { + return invalidPolicy(location, "matching.skill_taxonomy has more groups than specializations") + } + for _, group := range policy.SkillTaxonomy { + if !group.Specialization.IsKnown() { + return invalidPolicy(location, "matching.skill_taxonomy names an unknown specialization") + } + if _, repeated := seen[group.Specialization]; repeated { + return invalidPolicy(location, "matching.skill_taxonomy repeats a specialization") + } + seen[group.Specialization] = struct{}{} + if len(group.Skills) == 0 || len(group.Skills) > len(candidateViewSkillCodes) { + return invalidPolicy(location, "matching.skill_taxonomy needs between one and every known technology for a specialization") + } + skills := make(map[CandidateViewSkillCode]struct{}, len(group.Skills)) + for _, skill := range group.Skills { + if !skill.IsKnown() { + return invalidPolicy(location, "matching.skill_taxonomy names an unknown technology") + } + if _, repeated := skills[skill]; repeated { + return invalidPolicy(location, "matching.skill_taxonomy repeats a technology") + } + skills[skill] = struct{}{} + } + } + return nil +} diff --git a/backend/internal/domain/policy_matching_test.go b/backend/internal/domain/policy_matching_test.go new file mode 100644 index 0000000..c37e457 --- /dev/null +++ b/backend/internal/domain/policy_matching_test.go @@ -0,0 +1,187 @@ +package domain + +import ( + "bytes" + "errors" + "reflect" + "testing" +) + +func TestDemoProductPolicyV4CarriesTheMatchingSection(t *testing.T) { + policy := DemoProductPolicyV4() + if err := policy.Validate(); err != nil { + t.Fatalf("DemoProductPolicyV4().Validate() error = %v", err) + } + if policy.Matching == nil || policy.Assessment.Signals == nil || policy.Support == nil { + t.Fatalf("DemoProductPolicyV4() sections = matching:%v signals:%v support:%v, want all", policy.Matching != nil, policy.Assessment.Signals != nil, policy.Support != nil) + } + if DemoProductPolicyV3().Matching != nil { + t.Fatal("DemoProductPolicyV3() gained a matching section: a stored version must not change") + } + encoded, _, err := encodeProductPolicy(policy) + if err != nil { + t.Fatalf("encodeProductPolicy() error = %v", err) + } + decoded, err := decodeProductPolicy(encoded) + if err != nil { + t.Fatalf("decodeProductPolicy() error = %v", err) + } + if decoded.Matching == nil || !reflect.DeepEqual(*decoded.Matching, *policy.Matching) { + t.Fatalf("decoded matching policy = %+v, want %+v", decoded.Matching, policy.Matching) + } +} + +func TestMatchingPolicyIsAnIndependentSchemaTwoExtension(t *testing.T) { + policy := DemoProductPolicyV1() + matching := DemoMatchingPolicy() + policy.Matching = &matching + encoded, _, err := encodeProductPolicy(policy) + if err != nil { + t.Fatalf("encodeProductPolicy() error = %v", err) + } + decoded, err := decodeProductPolicy(encoded) + if err != nil { + t.Fatalf("decodeProductPolicy() error = %v", err) + } + if decoded.Matching == nil || decoded.Assessment.Attempt != nil || decoded.Assessment.Training != nil || + decoded.Assessment.Signals != nil || decoded.Support != nil { + t.Fatalf("decoded extensions = matching:%v attempt:%v training:%v signals:%v support:%v, want only matching", + decoded.Matching != nil, decoded.Assessment.Attempt != nil, decoded.Assessment.Training != nil, + decoded.Assessment.Signals != nil, decoded.Support != nil) + } + legacy := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) { + document["matching"] = nil + }) + if _, err := decodeProductPolicy(legacy); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("decodeProductPolicy(schema 1 with a matching key) error = %v, want ErrInvalidPolicy", err) + } +} + +func TestMatchingPolicyDocumentRequiresEveryFieldAndRejectsUnknownOnes(t *testing.T) { + encoded, _, err := encodeProductPolicy(DemoProductPolicyV4()) + if err != nil { + t.Fatalf("encodeProductPolicy() error = %v", err) + } + missing := bytes.Replace(encoded, []byte(`"neutral_unknown_bp":5000,`), nil, 1) + if bytes.Equal(missing, encoded) { + t.Fatal("encoded matching section did not contain neutral_unknown_bp") + } + if _, err := decodeProductPolicy(missing); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("decodeProductPolicy(missing neutral_unknown_bp) error = %v, want ErrInvalidPolicy", err) + } + unknown := bytes.Replace(encoded, []byte(`"neutral_unknown_bp":5000`), []byte(`"neutral_unknown_bp":5000,"unknown":1`), 1) + if _, err := decodeProductPolicy(unknown); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("decodeProductPolicy(unknown matching field) error = %v, want ErrInvalidPolicy", err) + } +} + +func TestMatchingPolicyRejectsInconsistentValues(t *testing.T) { + tests := []struct { + name string + change func(*MatchingPolicy) + }{ + {name: "fit weights do not add up", change: func(policy *MatchingPolicy) { policy.FitCoverageWeight = 7000 }}, + {name: "rank weights do not add up", change: func(policy *MatchingPolicy) { policy.RankFitWeight = 6000 }}, + {name: "share above one", change: func(policy *MatchingPolicy) { policy.NeutralUnknown = 10001 }}, + {name: "zero freshness floor", change: func(policy *MatchingPolicy) { policy.FreshnessFloor = 0 }}, + {name: "zero responsiveness floor", change: func(policy *MatchingPolicy) { policy.ResponsivenessFloor = 0 }}, + {name: "trust falls with the level", change: func(policy *MatchingPolicy) { policy.TrustOnline = 2000 }}, + {name: "team result above a personal one", change: func(policy *MatchingPolicy) { policy.AttributionTeamRole = 10001 }}, + {name: "broader relation above exact", change: func(policy *MatchingPolicy) { + policy.RelationBroader = 10000 + policy.RelationNarrower = 9000 + policy.RelationExact = 8000 + }}, + {name: "zero required weight", change: func(policy *MatchingPolicy) { policy.RequiredSkillWeight = 0 }}, + {name: "zero cohort minimum", change: func(policy *MatchingPolicy) { policy.PercentileMinCohort = 0 }}, + {name: "no results allowed", change: func(policy *MatchingPolicy) { policy.MaxResultsPerGroup = 0 }}, + {name: "unbounded results", change: func(policy *MatchingPolicy) { policy.MaxResultsPerGroup = 1001 }}, + {name: "unknown specialization in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[0].Specialization = "chef" }}, + {name: "unknown technology in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[0].Skills[0] = "cobol" }}, + {name: "repeated technology in a group", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[0].Skills = []CandidateViewSkillCode{"go", "go"} }}, + {name: "repeated specialization in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[1].Specialization = SpecializationBackend }}, + {name: "empty group in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[1].Skills = nil }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + policy := DemoProductPolicyV4() + test.change(policy.Matching) + if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("ProductPolicy.Validate() error = %v, want ErrInvalidPolicy", err) + } + }) + } +} + +func TestMatchingPolicyDemoValuesAreTheDesignValuesOfThePRD(t *testing.T) { + policy := DemoMatchingPolicy() + for level, want := range map[EvidenceTrust]BasisPoints{ + EvidenceTrustStated: 2500, EvidenceTrustOnlineUnconfirmed: 6000, EvidenceTrustIdentityTied: 8500, EvidenceTrustInPerson: 10000, + } { + if got, ok := policy.TrustCoefficient(level); !ok || got != want { + t.Errorf("TrustCoefficient(%d) = %d, %v, want %d", level, got, ok, want) + } + } + if _, ok := policy.TrustCoefficient(EvidenceTrust(4)); ok { + t.Error("TrustCoefficient(4) reported a coefficient for an unknown level") + } + for attribution, want := range map[EvidenceAttribution]BasisPoints{ + EvidenceAttributionPersonal: 10000, EvidenceAttributionTeamRole: 8000, EvidenceAttributionTeamUnattributed: 5000, + } { + if got, ok := policy.AttributionCoefficient(attribution); !ok || got != want { + t.Errorf("AttributionCoefficient(%s) = %d, %v, want %d", attribution, got, ok, want) + } + } + for relation, want := range map[EvidenceSkillRelation]BasisPoints{ + EvidenceSkillRelationExact: 10000, EvidenceSkillRelationNarrower: 8000, EvidenceSkillRelationBroader: 4000, EvidenceSkillRelationNone: 0, + } { + if got := policy.RelationCoefficient(relation); got != want { + t.Errorf("RelationCoefficient(%d) = %d, want %d", relation, got, want) + } + } +} + +func TestMatchingPolicyRelatesSkillsByItsOwnTaxonomy(t *testing.T) { + policy := DemoMatchingPolicy() + tests := []struct { + name string + requested, offered string + want EvidenceSkillRelation + }{ + {"same technology", "go", "go", EvidenceSkillRelationExact}, + {"specialization evidence for a technology", "go", "backend", EvidenceSkillRelationBroader}, + {"technology evidence for a specialization", "backend", "go", EvidenceSkillRelationNarrower}, + {"another technology", "go", "kafka", EvidenceSkillRelationNone}, + {"unrelated specialization", "go", "frontend", EvidenceSkillRelationNone}, + {"devops covers docker only", "go", "devops_sre", EvidenceSkillRelationNone}, + {"devops covers docker", "docker", "devops_sre", EvidenceSkillRelationBroader}, + {"unmapped requested skill", "", "backend", EvidenceSkillRelationNone}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := policy.RelateSkill(test.requested, test.offered); got != test.want { + t.Fatalf("RelateSkill(%q, %q) = %d, want %d", test.requested, test.offered, got, test.want) + } + }) + } + // A version without a taxonomy relates nothing but equal codes, and a + // changed version changes the relation: the version decides the result. + policy.SkillTaxonomy = nil + if got := policy.RelateSkill("go", "backend"); got != EvidenceSkillRelationNone { + t.Fatalf("RelateSkill without a taxonomy = %d, want none", got) + } + policy.SkillTaxonomy = []MatchingSkillGroup{{Specialization: SpecializationFrontend, Skills: []CandidateViewSkillCode{"docker"}}} + if got := policy.RelateSkill("docker", "frontend"); got != EvidenceSkillRelationBroader { + t.Fatalf("RelateSkill with a changed taxonomy = %d, want broader", got) + } +} + +func TestMatchingPolicyCloneDoesNotShareTheTaxonomy(t *testing.T) { + original := DemoMatchingPolicy() + copied := original.Clone() + copied.SkillTaxonomy[0].Skills[0] = "kafka" + copied.SkillTaxonomy[1].Specialization = SpecializationQA + if original.SkillTaxonomy[0].Skills[0] == "kafka" || original.SkillTaxonomy[1].Specialization == SpecializationQA { + t.Fatal("a clone of the matching policy shares its taxonomy with the original") + } +} diff --git a/backend/internal/port/outbound/company_quota.go b/backend/internal/port/outbound/company_quota.go index a8d81fc..89a64a6 100644 --- a/backend/internal/port/outbound/company_quota.go +++ b/backend/internal/port/outbound/company_quota.go @@ -46,6 +46,17 @@ type CompanyQuotaDecision struct { // Repeated views update last_seen monotonically with the greater of the // stored and current times. type CompanyQuotaRepository interface { + // LockOrganization takes the organization lock that serializes the + // reservations of one organization (FOR NO KEY UPDATE, which does not block + // the foreign-key lock of a candidate's own hide), ahead of the share locks + // of a membership check. A + // caller that checks the membership first and reserves later would hold a + // share lock and then ask for the exclusive one, and two such callers of one + // organization deadlock. A caller that reserves after a share lock takes + // this lock first, in the documented order. It returns + // ErrCompanyQuotaSnapshotChanged for a removed organization. + LockOrganization(ctx context.Context, organizationID uuid.UUID) error + // ReserveInvitation counts a new invitation against the current policy // limit. An existing invitation ID is returned as allowed and reused // without a second charge, regardless of its age or the request key. A diff --git a/backend/internal/port/outbound/evidence.go b/backend/internal/port/outbound/evidence.go index 497ec34..51c02ff 100644 --- a/backend/internal/port/outbound/evidence.go +++ b/backend/internal/port/outbound/evidence.go @@ -37,6 +37,20 @@ func EvidencePositionOf(fact domain.EvidenceFact) EvidencePosition { return EvidencePosition{OccurredAt: snapshot.OccurredAt, ID: snapshot.ID} } +// EvidenceCandidateCategories names the categories that the card of one +// candidate shows, which are the categories whose supporting facts a batch +// read may return. +type EvidenceCandidateCategories struct { + CandidateID uuid.UUID + Categories []domain.CandidateViewCategory +} + +// CategoryKey is a specialization and a grade. +type CategoryKey struct { + Specialization domain.SpecializationCode + Grade domain.GradeCode +} + // EvidenceRepository reads the skill evidence projection. It never reads an // assessment result, answer, attempt, or review: the projection is the only // source, so no answer, failure, or anti-cheat datum can reach a caller. @@ -59,6 +73,24 @@ type EvidenceRepository interface { categories []domain.CandidateViewCategory, ) ([]domain.EvidenceOrganizationFact, error) + // ListOrganizationFactsBatch is ListOrganizationFacts for many candidates in + // one statement, with the same barriers: the effective publication view, + // the exclusion of the candidates that hide the organization, the + // categories field, and only visible measurements. A candidate with no + // permitted fact has no entry in the result. The result is for the caller's + // grouping and is never returned as it is. + ListOrganizationFactsBatch( + ctx context.Context, + organizationID uuid.UUID, + requests []EvidenceCandidateCategories, + ) (map[uuid.UUID][]domain.EvidenceOrganizationFact, error) + + // CountComparableRealCategories returns, for each given category, how many + // candidates hold it from a source that is not a synthetic demonstration: + // the size of the comparable real cohort. A category nobody holds from a + // real source is absent. It returns counts only. + CountComparableRealCategories(ctx context.Context, categories []CategoryKey) (map[CategoryKey]int64, error) + // ListPreviewFacts returns the same selection for the candidate's own card // preview. It applies no organization and no cohort, and the caller has // locked the effective C2 and publication. diff --git a/backend/internal/port/outbound/notification_inbox.go b/backend/internal/port/outbound/notification_inbox.go index 443c442..5a891b0 100644 --- a/backend/internal/port/outbound/notification_inbox.go +++ b/backend/internal/port/outbound/notification_inbox.go @@ -17,6 +17,17 @@ var ( // ErrNotificationInboxEventConflict reports an event ID reused with // different immutable recipient or source metadata. ErrNotificationInboxEventConflict = errors.New("notification inbox event metadata conflicts") + // ErrNotificationInboxReferenceMissing reports an event that names an + // organization that does not exist. A retry cannot fix it. + ErrNotificationInboxReferenceMissing = errors.New("notification inbox event references a missing record") + // ErrNotificationInboxRecipientMissing reports a recipient account that + // does not exist now. The recipient may have been deleted a moment ago, + // so a handler retries and then skips instead of rejecting the event. + ErrNotificationInboxRecipientMissing = errors.New("notification inbox recipient does not exist") + // ErrNotificationInboxSourceNotVisible reports a source that does not + // exist or is not visible to the recipient now. The two cases are one on + // purpose. + ErrNotificationInboxSourceNotVisible = errors.New("notification source is not visible to the recipient") ) const MaxNotificationInboxPageSize = 100 @@ -33,15 +44,25 @@ type NotificationInboxRepository interface { // OrganizationID means all organization contexts of that recipient. List(ctx context.Context, query NotificationInboxListQuery) (NotificationInboxPage, error) - // MarkRead records the first read time in exact recipient and organization - // context. Missing and unauthorized identities share one not-found result. + // MarkRead records the first read time for the recipient. A non-nil + // organizationID narrows the match to that organization context; nil + // matches any context of the recipient, which is the candidate cabinet. + // Missing and unauthorized identities share one not-found result. MarkRead( ctx context.Context, recipientUserID uuid.UUID, - organizationID uuid.UUID, + organizationID *uuid.UUID, eventID uuid.UUID, at time.Time, ) (domain.NotificationInboxEntry, error) + + // OrganizationNameForRecipient returns the current name of an + // organization under the recipient's current standing: a candidate who has + // not hidden it, or an employer with an active membership in it. It + // returns ErrNotificationInboxSourceNotVisible otherwise. Content that + // names an organization is resolved through it at read time, so a hiding + // or a revoked membership removes the name from every later read. + OrganizationNameForRecipient(ctx context.Context, recipientUserID, organizationID uuid.UUID) (string, error) } // NotificationInboxListQuery selects a bounded recipient-owned page. diff --git a/backend/internal/port/outbound/privacy_view.go b/backend/internal/port/outbound/privacy_view.go index 8b5b39d..df0f094 100644 --- a/backend/internal/port/outbound/privacy_view.go +++ b/backend/internal/port/outbound/privacy_view.go @@ -14,6 +14,9 @@ var ( ErrCandidateCardAccessNotFound = errors.New("candidate card access not found") ErrCandidateC2Unavailable = errors.New("candidate C2 publication is unavailable") ErrContactAccessClosed = errors.New("contact access is closed") + // ErrConcurrentVisibilityChange reports that the visible cohort changed + // while a read was locking it. The read can be repeated. + ErrConcurrentVisibilityChange = errors.New("candidate visibility changed during read") ) const MaxCandidateCardAccessPageSize = 100 diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index a1b2c3c..69b9da9 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -63,6 +63,7 @@ type UnitOfWork interface { PrivacyView() PrivacyViewRepository PrivacySettings() PrivacySettingsRepository Evidence() EvidenceRepository + NotificationInbox() NotificationInboxRepository AccountDeletionRequests() AccountDeletionRequests ConsentRevocationEffects() ConsentRevocationEffects OrganizationRepositories diff --git a/backend/internal/usecase/candidateview/contact_access_test.go b/backend/internal/usecase/candidateview/contact_access_test.go index 3329e33..ba047b6 100644 --- a/backend/internal/usecase/candidateview/contact_access_test.go +++ b/backend/internal/usecase/candidateview/contact_access_test.go @@ -174,6 +174,16 @@ func (unit contactAccessUnit) Organizations() outbound.OrganizationRepository { return unit.organizations } func (unit contactAccessUnit) PrivacyView() outbound.PrivacyViewRepository { return unit.view } +func (unit contactAccessUnit) CompanyQuotas() outbound.CompanyQuotaRepository { + return organizationLockStub{} +} + +// organizationLockStub accepts the organization lock and is not used for more. +type organizationLockStub struct { + outbound.CompanyQuotaRepository +} + +func (organizationLockStub) LockOrganization(context.Context, uuid.UUID) error { return nil } type contactAccessUsers struct { outbound.UserRepository diff --git a/backend/internal/usecase/candidateview/service.go b/backend/internal/usecase/candidateview/service.go index 0470f4c..6adca80 100644 --- a/backend/internal/usecase/candidateview/service.go +++ b/backend/internal/usecase/candidateview/service.go @@ -19,7 +19,7 @@ var ( ErrForbidden = errors.New("candidate view is forbidden") ErrCandidateCardNotFound = errors.New("candidate card not found") ErrInvalidCandidateHandle = errors.New("candidate handle is invalid") - ErrConcurrentVisibilityChange = errors.New("candidate visibility changed during read") + ErrConcurrentVisibilityChange = outbound.ErrConcurrentVisibilityChange ErrCandidateViewServiceMissing = errors.New("candidate view service is unavailable") ErrCandidateViewQuotaExceeded = errors.New("candidate view quota is exhausted") ) @@ -92,6 +92,9 @@ func (service *Service) GetOrganizationCard( } var result domain.AnonymousCandidateViewDTO err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil { + return err + } view, err := service.getOrganizationCardInTransaction(ctx, unit, actorID, organizationID, handle, location) if err != nil { return err @@ -153,6 +156,114 @@ func (service *Service) reserveCardView( return nil } +// ListVisibleCards returns the cards of the current, locked, +// organization-visible cohort, built by the same projection as a card read, so +// a handle in the list is a handle that GetOrganizationCard opens. It runs the +// membership, effective C2 publication, hiding, and minimum-cohort checks of a +// card read under the same locks, inside the caller's transaction. A candidate +// whose card is suppressed by the cohort rules is not in the list. +// +// Listing itself consumes nothing. The caller charges and records each +// candidate that it reveals through BeginSearchViews, because an entry holds +// card content. +func (service *Service) ListVisibleCards( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID uuid.UUID, +) ([]domain.VisibleCandidateCard, error) { + const location = "candidateview.Service.ListVisibleCards" + if actorID == uuid.Nil || organizationID == uuid.Nil { + return nil, ErrForbidden + } + _, _, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location) + if err != nil { + return nil, err + } + candidateByAlias := make(map[string]uuid.UUID, len(sources)) + for _, source := range sources { + alias, err := service.sourceAlias(organizationID, source) + if err != nil { + return nil, fmt.Errorf("%s - derive current alias: %w", location, err) + } + candidateByAlias[alias] = source.CandidateID() + } + views, err := service.projector.ProjectSources(organizationID, sources) + if err != nil { + return nil, fmt.Errorf("%s - build current candidate views: %w", location, err) + } + cards := make([]domain.VisibleCandidateCard, 0, len(views)) + for _, view := range views { + candidateID, exists := candidateByAlias[view.Pseudonym] + if !exists { + return nil, fmt.Errorf("%s - projected view has no source: %w", location, domain.ErrInvalidAnonymousCandidateView) + } + cards = append(cards, domain.VisibleCandidateCard{CandidateID: candidateID, Card: view}) + } + return cards, nil +} + +// SearchViews charges and records the candidates that one search reveals. It is +// bound to the caller's transaction and to the organization that was already +// authorized, so a failure of the search leaves neither a charge nor a record. +type SearchViews struct { + service *Service + unit outbound.UnitOfWork + organization domain.Organization + repository outbound.PrivacyViewRepository + actorID uuid.UUID +} + +// BeginSearchViews prepares the charging of a search inside the caller's +// transaction. The actor must have an active membership of the organization. +func (service *Service) BeginSearchViews( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID uuid.UUID, +) (*SearchViews, error) { + const location = "candidateview.Service.BeginSearchViews" + if actorID == uuid.Nil || organizationID == uuid.Nil { + return nil, ErrForbidden + } + organization, err := authorizeEmployer(ctx, unit, actorID, organizationID) + if err != nil { + return nil, err + } + repository, err := privacyViewRepository(unit) + if err != nil { + return nil, fmt.Errorf("%s - open the access repository: %w", location, err) + } + return &SearchViews{service: service, unit: unit, organization: organization, repository: repository, actorID: actorID}, nil +} + +// Reserve counts the candidate as a distinct card view of the organization. A +// candidate that the organization already viewed inside the window is allowed +// again without another charge. It reports false, writing nothing, when the +// allowance is used up. +func (views *SearchViews) Reserve(ctx context.Context, candidateID uuid.UUID) (bool, error) { + decision, err := views.service.quota(ctx, views.unit, views.organization, candidateID) + if err != nil { + return false, fmt.Errorf("candidateview.SearchViews.Reserve - reserve card view: %w", err) + } + return decision.Allowed, nil +} + +// Record appends the access history entry for the fields that a search +// actually returned about the candidate, so the candidate sees the read. +func (views *SearchViews) Record(ctx context.Context, candidateID uuid.UUID, fields []domain.CardField) error { + const location = "candidateview.SearchViews.Record" + event, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{ + CandidateID: candidateID, OrganizationID: views.organization.ID(), ActorID: views.actorID, + Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: fields, OccurredAt: views.service.clock(), + }) + if err != nil { + return fmt.Errorf("%s - build access audit: %w", location, err) + } + if err := views.repository.RecordCandidateCardAccess(ctx, event); err != nil { + return fmt.Errorf("%s - record access audit: %w", location, err) + } + return nil +} + // AuthorizeCategoriesSection runs the checks of an organization card read // inside the caller's transaction and reports which candidate, and which // categories (specialization and grade), the card shows. It exists for the sections @@ -180,6 +291,10 @@ func (service *Service) AuthorizeCategoriesSection( if !domain.IsCandidateViewPseudonym(handle) { return uuid.Nil, nil, ErrInvalidCandidateHandle } + // The caller's transaction has taken no share lock of the organization yet. + if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil { + return uuid.Nil, nil, err + } organization, repository, candidateID, view, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location) if err != nil { return uuid.Nil, nil, err @@ -429,6 +544,26 @@ func (service *Service) CurrentContactFields( return fields, nil } +// lockOrganizationFirst takes the exclusive organization lock that the card-view +// reservation takes later. The membership check holds only a share lock on the +// same row, and two readers of one organization that each hold a share lock +// and then ask for the exclusive one deadlock. Taking the exclusive lock before +// any share lock follows the documented lock order and serializes the charges +// of one organization. +func lockOrganizationFirst(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID) error { + repository := unit.CompanyQuotas() + if repository == nil { + return fmt.Errorf("candidateview.lockOrganizationFirst - quota repository is missing: %w", ErrCandidateViewServiceMissing) + } + if err := repository.LockOrganization(ctx, organizationID); err != nil { + if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) { + return outbound.ErrOrganizationNotFound + } + return fmt.Errorf("candidateview.lockOrganizationFirst - lock organization: %w", err) + } + return nil +} + func authorizeEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (domain.Organization, error) { user, err := unit.Users().GetByID(ctx, actorID) if errors.Is(err, outbound.ErrUserNotFound) { diff --git a/backend/internal/usecase/candidateview/visible_cards_test.go b/backend/internal/usecase/candidateview/visible_cards_test.go new file mode 100644 index 0000000..2b8bb61 --- /dev/null +++ b/backend/internal/usecase/candidateview/visible_cards_test.go @@ -0,0 +1,108 @@ +package candidateview + +import ( + "context" + "errors" + "slices" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func (fixture *categoriesSectionFixture) listVisible(t *testing.T) ([]domain.VisibleCandidateCard, error) { + t.Helper() + var cards []domain.VisibleCandidateCard + err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + cards, err = fixture.service.ListVisibleCards(ctx, unit, fixture.actorID, fixture.organizationID) + return err + }) + return cards, err +} + +func TestListVisibleCardsReturnsTheCardsOfTheCurrentCohortWithoutAViewTrace(t *testing.T) { + t.Parallel() + + shown := []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStandard}} + fixture := newCategoriesSectionFixture(t, shown, true, domain.ScenarioEmployer) + + cards, err := fixture.listVisible(t) + if err != nil { + t.Fatalf("ListVisibleCards() error = %v", err) + } + if len(cards) != 1 || cards[0].CandidateID == uuid.Nil || cards[0].Card.Pseudonym != fixture.handle || + !slices.Equal(cards[0].Card.Categories, shown) { + t.Fatalf("cards = %v, want the one visible card under the organization handle", cards) + } + if fixture.quotaCalls != 0 || len(fixture.contact.audits) != 0 { + t.Fatalf("quota calls = %d, audits = %v, want a listing that is not a card view", fixture.quotaCalls, fixture.contact.audits) + } +} + +func TestListVisibleCardsRefusesAnActorWithoutAnEmployerRole(t *testing.T) { + t.Parallel() + + fixture := newCategoriesSectionFixture(t, nil, true, domain.ScenarioCandidate) + if _, err := fixture.listVisible(t); !errors.Is(err, ErrForbidden) { + t.Fatalf("ListVisibleCards() error = %v, want ErrForbidden", err) + } + if fixture.quotaCalls != 0 || len(fixture.contact.audits) != 0 { + t.Fatalf("quota calls = %d, audits = %v, want no trace", fixture.quotaCalls, fixture.contact.audits) + } +} + +func TestSearchViewsChargeAndRecordWhatTheSearchReveals(t *testing.T) { + t.Parallel() + + fixture := newCategoriesSectionFixture(t, nil, true, domain.ScenarioEmployer) + candidateID := uuid.New() + err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error { + views, err := fixture.service.BeginSearchViews(ctx, unit, fixture.actorID, fixture.organizationID) + if err != nil { + return err + } + allowed, err := views.Reserve(ctx, candidateID) + if err != nil || !allowed { + t.Fatalf("Reserve() = %v, %v, want allowed", allowed, err) + } + return views.Record(ctx, candidateID, []domain.CardField{domain.CardFieldCategories, domain.CardFieldStack}) + }) + if err != nil { + t.Fatalf("search views error = %v", err) + } + if fixture.quotaCalls != 1 || len(fixture.contact.audits) != 1 || fixture.contact.audits[0].Kind() != domain.CandidateCardAccessCardViewed || + !slices.Equal(fixture.contact.audits[0].FieldCodes(), []string{"categories", "stack"}) { + t.Fatalf("quota calls = %d, audits = %v, want one charge and one view of the returned fields", fixture.quotaCalls, fixture.contact.audits) + } +} + +func TestSearchViewsReportAnExhaustedAllowanceWithoutAWrite(t *testing.T) { + t.Parallel() + + fixture := newCategoriesSectionFixture(t, nil, false, domain.ScenarioEmployer) + err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error { + views, err := fixture.service.BeginSearchViews(ctx, unit, fixture.actorID, fixture.organizationID) + if err != nil { + return err + } + allowed, err := views.Reserve(ctx, uuid.New()) + if err != nil || allowed { + t.Fatalf("Reserve() = %v, %v, want a refusal without an error", allowed, err) + } + return nil + }) + if err != nil || len(fixture.contact.audits) != 0 { + t.Fatalf("error = %v, audits = %v, want no record for a refused view", err, fixture.contact.audits) + } + candidate := newCategoriesSectionFixture(t, nil, true, domain.ScenarioCandidate) + err = candidate.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := candidate.service.BeginSearchViews(ctx, unit, candidate.actorID, candidate.organizationID) + return err + }) + if !errors.Is(err, ErrForbidden) { + t.Fatalf("BeginSearchViews(candidate) error = %v, want ErrForbidden", err) + } +} diff --git a/backend/internal/usecase/companyquota/service_test.go b/backend/internal/usecase/companyquota/service_test.go index 9131391..571a90c 100644 --- a/backend/internal/usecase/companyquota/service_test.go +++ b/backend/internal/usecase/companyquota/service_test.go @@ -47,6 +47,8 @@ func (repository *quotaTestRepository) ReserveInvitation(_ context.Context, quot return repository.decision, repository.err } +func (repository *quotaTestRepository) LockOrganization(context.Context, uuid.UUID) error { return nil } + func (repository *quotaTestRepository) ReserveCardView(_ context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { repository.cardViewCalls++ repository.cardViewQuota = quota diff --git a/backend/internal/usecase/evidence/read_test.go b/backend/internal/usecase/evidence/read_test.go index 48f0467..e0d388f 100644 --- a/backend/internal/usecase/evidence/read_test.go +++ b/backend/internal/usecase/evidence/read_test.go @@ -67,6 +67,18 @@ func (repository *evidenceTestRepository) ListOrganizationFacts( return nil, nil } +func (repository *evidenceTestRepository) ListOrganizationFactsBatch( + context.Context, uuid.UUID, []outbound.EvidenceCandidateCategories, +) (map[uuid.UUID][]domain.EvidenceOrganizationFact, error) { + return nil, errors.New("the single organization read must not use the batch read") +} + +func (repository *evidenceTestRepository) CountComparableRealCategories( + context.Context, []outbound.CategoryKey, +) (map[outbound.CategoryKey]int64, error) { + return nil, errors.New("the evidence read must not count cohorts") +} + func (repository *evidenceTestRepository) ListPreviewFacts(context.Context, uuid.UUID, []domain.CandidateViewCategory) ([]domain.EvidenceOrganizationFact, error) { return nil, errors.New("the organization read must not read the preview") } diff --git a/backend/internal/usecase/matching/explain.go b/backend/internal/usecase/matching/explain.go new file mode 100644 index 0000000..0395444 --- /dev/null +++ b/backend/internal/usecase/matching/explain.go @@ -0,0 +1,150 @@ +package matching + +import ( + "slices" + + "lincodex/backend/internal/domain" +) + +// explanationInput is what the explanation reads: the computed scores of the +// entry and the facts of the card. It builds nothing that the scores did not +// compute, so a change of the requirements moves the numbers and the +// explanation together. +type explanationInput struct { + confirmed bool + declaredGrade *domain.GradeCode + policy domain.MatchingPolicy + scores scores + context PublicContext + // requestedFormats are the work formats that the search asks for; it is + // empty when neither the need nor a filter names any. + requestedFormats []domain.QuestionnaireWorkFormat + // needDomainConfirmed tells why the domain is unknown: the card has no + // domain, and the need may not have confirmed one either. + needDomainConfirmed bool + // percentileReason is the reason that the percentile is null; the zero + // value means the cohort is below the minimum. + percentileReason UnknownReason +} + +// explain builds the bounded, templated explanation and the unknown flags. +// An unknown component appears only in the flags and is never shown as a +// verdict about the person, and the absence of FSP data is neither a gap nor +// an unknown here: the competition component is zero by definition. +func explain(input explanationInput) ([]EvidenceItem, []UnknownFlag) { + return evidenceSummary(input), unknownFlags(input) +} + +func evidenceSummary(input explanationInput) []EvidenceItem { + items := make([]EvidenceItem, 0, 6) + if input.confirmed { + items = append(items, EvidenceItem{Code: EvidenceConfirmedCategory, State: EvidenceStateSupports}) + } + if input.declaredGrade != nil { + items = append(items, EvidenceItem{Code: EvidenceDeclaredGrade, State: EvidenceStateDeclaredOnly}) + } + if state, ok := skillGroupState(input, true); ok { + items = append(items, EvidenceItem{Code: EvidenceRequiredSkill, State: state}) + } + if state, ok := skillGroupState(input, false); ok { + items = append(items, EvidenceItem{Code: EvidenceDesiredSkill, State: state}) + } + if len(input.requestedFormats) > 0 && len(input.context.WorkFormats) > 0 { + state := EvidenceStateGap + for _, format := range input.context.WorkFormats { + if slices.Contains(input.requestedFormats, format) { + state = EvidenceStateSupports + break + } + } + items = append(items, EvidenceItem{Code: EvidenceWorkConditionsMatch, State: state}) + } + if compatibility := input.context.SalaryCompatibility; compatibility != nil { + state := EvidenceStateGap + if *compatibility == domain.CandidateViewSalaryCompatible { + state = EvidenceStateSupports + } + items = append(items, EvidenceItem{Code: EvidenceSalaryCompatibility, State: state}) + } + return items +} + +// skillGroupState summarizes the skills of one weight class from their +// computed contributions. A skill is supported by a measurement that reaches +// the policy threshold, declared when only a stated claim carries it, partial +// when a measurement exists but stays below the threshold, and a gap when +// nothing counts. The group is supported or a gap only when every skill is. +func skillGroupState(input explanationInput, required bool) (EvidenceState, bool) { + threshold := int64(input.policy.NearSkillThreshold) * picoPerBasisPoint + var total, supported, declared, gaps int + for _, skill := range input.scores.skills { + if skill.required != required { + continue + } + total++ + switch { + case skill.pico == 0: + gaps++ + case skill.measured && skill.pico >= threshold: + supported++ + case !skill.measured: + declared++ + } + } + switch { + case total == 0: + return "", false + case supported == total: + return EvidenceStateSupports, true + case gaps == total: + return EvidenceStateGap, true + case declared == total: + return EvidenceStateDeclaredOnly, true + default: + return EvidenceStatePartial, true + } +} + +// unknownFlags lists, in the order of the contract's component list, every +// value that is neutral or absent. A confirmed entry shows the neutral T and +// the neutral freshness and responsiveness; an unconfirmed entry shows that +// the specialization has no confirmation instead. +func unknownFlags(input explanationInput) []UnknownFlag { + flags := make([]UnknownFlag, 0, 9) + flags = append(flags, UnknownFlag{Component: UnknownSemantics, Reason: ReasonMLUnavailable}) + if input.confirmed { + reason := input.percentileReason + if reason == "" { + reason = ReasonCohortBelow30 + } + flags = append(flags, UnknownFlag{Component: UnknownPercentile, Reason: reason}) + } else { + flags = append(flags, UnknownFlag{Component: UnknownAssessment, Reason: ReasonNoConfirmationForSpecialization}) + } + if input.confirmed { + flags = append(flags, + UnknownFlag{Component: UnknownFreshness, Reason: ReasonNoFreshnessHistory}, + UnknownFlag{Component: UnknownResponsiveness, Reason: ReasonNoResponseHistory}, + ) + } + if input.context.ExperienceBand == nil { + flags = append(flags, UnknownFlag{Component: UnknownExperienceBand, Reason: ReasonNotInPublicCard}) + } + if len(input.context.WorkFormats) == 0 { + flags = append(flags, UnknownFlag{Component: UnknownWorkFormats, Reason: ReasonNotInPublicCard}) + } + if input.context.SalaryCompatibility == nil { + flags = append(flags, UnknownFlag{Component: UnknownSalaryCompatibility, Reason: ReasonNotInPublicCard}) + } + flags = append(flags, domainFlag(input)) + return flags +} + +// domainFlag says why Dom is the neutral value. The anonymous card never +// carries a domain, so a confirmed need domain cannot be compared with it. +func domainFlag(input explanationInput) UnknownFlag { + if input.needDomainConfirmed { + return UnknownFlag{Component: UnknownDomain, Reason: ReasonNotInPublicCard} + } + return UnknownFlag{Component: UnknownDomain, Reason: ReasonNeedFieldUnconfirmed} +} diff --git a/backend/internal/usecase/matching/filter.go b/backend/internal/usecase/matching/filter.go new file mode 100644 index 0000000..4926429 --- /dev/null +++ b/backend/internal/usecase/matching/filter.go @@ -0,0 +1,67 @@ +package matching + +import ( + "slices" + + "lincodex/backend/internal/domain" +) + +// accepts reports whether one candidate specialization passes every explicit +// filter and the effective specialization. A filter that names a confirmed +// grade or category excludes every unconfirmed specialization, and a +// declaration never satisfies a confirmed filter. An unknown card value never +// satisfies a condition. +func (filters Filters) accepts(entry candidateEntry, specialization *domain.SpecializationCode) bool { + if specialization != nil && entry.specialization != *specialization { + return false + } + return filters.acceptsConfirmation(entry) && filters.acceptsCard(entry) +} + +func (filters Filters) acceptsConfirmation(entry candidateEntry) bool { + confirmed := entry.category != nil + if filters.ConfirmedGrade != nil && (!confirmed || entry.category.Grade != *filters.ConfirmedGrade) { + return false + } + if category := filters.ConfirmedCategory; category != nil { + if !confirmed || entry.category.Specialization != category.Specialization || entry.category.Grade != category.Grade { + return false + } + } + if status := filters.ConfirmationStatus; status != nil && (*status == domain.CandidateViewConfirmationConfirmed) != confirmed { + return false + } + return filters.DeclaredGrade == nil || (entry.declaredGrade != nil && *entry.declaredGrade == *filters.DeclaredGrade) +} + +func (filters Filters) acceptsCard(entry candidateEntry) bool { + for _, tag := range filters.Stack { + if !slices.Contains(entry.card.Skills, tag) { + return false + } + } + return filters.Conditions.accepts(entry.card) +} + +func (conditions *Conditions) accepts(card domain.AnonymousCandidateViewDTO) bool { + if conditions == nil { + return true + } + if len(conditions.WorkFormats) > 0 { + offered := false + for _, format := range card.WorkFormats { + if slices.Contains(conditions.WorkFormats, format) { + offered = true + break + } + } + if !offered { + return false + } + } + if conditions.SalaryCompatibility != nil && + (card.SalaryCompatibility == nil || *card.SalaryCompatibility != *conditions.SalaryCompatibility) { + return false + } + return true +} diff --git a/backend/internal/usecase/matching/filter_test.go b/backend/internal/usecase/matching/filter_test.go new file mode 100644 index 0000000..eb99ff9 --- /dev/null +++ b/backend/internal/usecase/matching/filter_test.go @@ -0,0 +1,119 @@ +package matching + +import ( + "slices" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +func gradePointer(grade domain.GradeCode) *domain.GradeCode { return &grade } + +func TestEntriesOfKeepsEverySpecializationSeparate(t *testing.T) { + middle, junior := domain.GradeMiddle, domain.GradeJunior + card := domain.AnonymousCandidateViewDTO{ + Pseudonym: "handle", + Categories: []domain.CandidateViewCategory{ + {Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard}, + }, + SelfAssessment: []domain.CandidateViewSelfAssessment{ + {Specialization: domain.SpecializationBackend, ConfirmationStatus: domain.CandidateViewConfirmationConfirmed, DeclaredGrade: &junior}, + {Specialization: domain.SpecializationNetworkEngineer, ConfirmationStatus: domain.CandidateViewConfirmationUnconfirmed, DeclaredGrade: &middle}, + // Confirmed in the self-assessment but not shown as a category: + // the card does not publish that confirmation, so no entry claims it. + {Specialization: domain.SpecializationQA, ConfirmationStatus: domain.CandidateViewConfirmationConfirmed}, + }, + } + entries := entriesOf(domain.VisibleCandidateCard{CandidateID: uuid.New(), Card: card}) + got := make([]string, 0, len(entries)) + for _, entry := range entries { + state := "unconfirmed" + if entry.category != nil { + state = "confirmed" + } + got = append(got, string(entry.specialization)+":"+state) + } + if want := []string{"backend:confirmed", "network_engineer:unconfirmed"}; !slices.Equal(got, want) { + t.Fatalf("entries = %v, want %v", got, want) + } + if entries[0].declaredGrade == nil || *entries[0].declaredGrade != domain.GradeJunior || + entries[1].declaredGrade == nil || *entries[1].declaredGrade != domain.GradeMiddle { + t.Fatalf("declared grades = %v and %v, want each specialization's own", entries[0].declaredGrade, entries[1].declaredGrade) + } +} + +func TestFiltersKeepTheConfirmedAndDeclaredClaimsApart(t *testing.T) { + remote := []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote} + compatible := domain.CandidateViewSalaryCompatible + confirmed := candidateEntry{ + specialization: domain.SpecializationBackend, + category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle}, + declaredGrade: gradePointer(domain.GradeJunior), + card: domain.AnonymousCandidateViewDTO{Skills: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo, domain.CandidateViewSkillKafka}, WorkFormats: remote, SalaryCompatibility: &compatible}, + } + unconfirmed := candidateEntry{ + specialization: domain.SpecializationBackend, declaredGrade: gradePointer(domain.GradeMiddle), + card: domain.AnonymousCandidateViewDTO{WorkFormats: remote}, + } + backend := domain.SpecializationBackend + frontend := domain.SpecializationFrontend + status := func(value domain.CandidateViewConfirmationStatus) *domain.CandidateViewConfirmationStatus { + return &value + } + tests := []struct { + name string + filters Filters + specialization *domain.SpecializationCode + wantConfirmed, wantUnconf bool + }{ + {name: "no filter", filters: Filters{}, wantConfirmed: true, wantUnconf: true}, + {name: "specialization", filters: Filters{}, specialization: &backend, wantConfirmed: true, wantUnconf: true}, + {name: "another specialization", filters: Filters{}, specialization: &frontend}, + {name: "confirmed grade excludes the unconfirmed", filters: Filters{ConfirmedGrade: gradePointer(domain.GradeMiddle)}, wantConfirmed: true}, + {name: "a declared grade never satisfies a confirmed grade", filters: Filters{ConfirmedGrade: gradePointer(domain.GradeJunior)}}, + { + name: "confirmed category", + filters: Filters{ConfirmedCategory: &GradeFilter{Specialization: backend, Grade: domain.GradeMiddle}}, + wantConfirmed: true, + }, + {name: "confirmation status confirmed", filters: Filters{ConfirmationStatus: status(domain.CandidateViewConfirmationConfirmed)}, wantConfirmed: true}, + {name: "confirmation status unconfirmed", filters: Filters{ConfirmationStatus: status(domain.CandidateViewConfirmationUnconfirmed)}, wantUnconf: true}, + {name: "declared grade", filters: Filters{DeclaredGrade: gradePointer(domain.GradeMiddle)}, wantUnconf: true}, + { + name: "every stack tag is required", + filters: Filters{Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo, domain.CandidateViewSkillKafka}}, + wantConfirmed: true, + }, + {name: "a stack tag the card lacks", filters: Filters{Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillDocker}}}, + {name: "work format", filters: Filters{Conditions: &Conditions{WorkFormats: remote}}, wantConfirmed: true, wantUnconf: true}, + { + name: "an unknown salary compatibility never satisfies the condition", + filters: Filters{Conditions: &Conditions{SalaryCompatibility: &compatible}}, wantConfirmed: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := test.filters.accepts(confirmed, test.specialization); got != test.wantConfirmed { + t.Errorf("accepts(confirmed) = %v, want %v", got, test.wantConfirmed) + } + if got := test.filters.accepts(unconfirmed, test.specialization); got != test.wantUnconf { + t.Errorf("accepts(unconfirmed) = %v, want %v", got, test.wantUnconf) + } + }) + } +} + +func TestEffectiveSpecializationNeverMergesTwoDifferentOnes(t *testing.T) { + backend, frontend := domain.SpecializationBackend, domain.SpecializationFrontend + if got, ok := effectiveSpecialization(&backend, &frontend); ok || got != nil { + t.Fatalf("effectiveSpecialization(backend, frontend) = %v, %v, want an empty search", got, ok) + } + if got, ok := effectiveSpecialization(nil, &frontend); !ok || got == nil || *got != frontend { + t.Fatalf("effectiveSpecialization(nil, frontend) = %v, %v, want the need specialization", got, ok) + } + if got, ok := effectiveSpecialization(nil, nil); !ok || got != nil { + t.Fatalf("effectiveSpecialization(nil, nil) = %v, %v, want no restriction", got, ok) + } +} diff --git a/backend/internal/usecase/matching/rank_test.go b/backend/internal/usecase/matching/rank_test.go new file mode 100644 index 0000000..ca4f442 --- /dev/null +++ b/backend/internal/usecase/matching/rank_test.go @@ -0,0 +1,126 @@ +package matching + +import ( + "bytes" + "context" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// cohortEvidence answers the cohort count and no fact. +type cohortEvidence struct { + outbound.EvidenceRepository + + counts map[outbound.CategoryKey]int64 + asked [][]outbound.CategoryKey +} + +func (evidence *cohortEvidence) CountComparableRealCategories( + _ context.Context, categories []outbound.CategoryKey, +) (map[outbound.CategoryKey]int64, error) { + evidence.asked = append(evidence.asked, categories) + return evidence.counts, nil +} + +type cohortUnit struct { + outbound.UnitOfWork + + evidence *cohortEvidence +} + +func (unit cohortUnit) Evidence() outbound.EvidenceRepository { return unit.evidence } + +func confirmedCard(specialization domain.SpecializationCode, grade domain.GradeCode) domain.VisibleCandidateCard { + return domain.VisibleCandidateCard{CandidateID: uuid.New(), Card: domain.AnonymousCandidateViewDTO{ + Pseudonym: "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + Categories: []domain.CandidateViewCategory{{Specialization: specialization, Grade: grade, Strength: domain.CandidateViewStrengthStandard}}, + }} +} + +func TestRankKeepsTheNeutralTWhenTheRealCohortReachesTheMinimum(t *testing.T) { + policy := domain.DemoMatchingPolicy() + backendIntern := outbound.CategoryKey{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern} + frontendJunior := outbound.CategoryKey{Specialization: domain.SpecializationFrontend, Grade: domain.GradeJunior} + evidence := &cohortEvidence{counts: map[outbound.CategoryKey]int64{ + backendIntern: int64(policy.PercentileMinCohort), + frontendJunior: int64(policy.PercentileMinCohort) - 1, + }} + var logs bytes.Buffer + service := &Service{logger: slog.New(slog.NewTextHandler(&logs, nil))} + cards := []domain.VisibleCandidateCard{ + confirmedCard(domain.SpecializationBackend, domain.GradeIntern), + confirmedCard(domain.SpecializationBackend, domain.GradeIntern), + confirmedCard(domain.SpecializationFrontend, domain.GradeJunior), + } + ranked, err := service.rank(context.Background(), cohortUnit{evidence: evidence}, Request{}, searchBasis{}, policy, cards) + if err != nil { + t.Fatalf("rank() error = %v, want a result whatever the real cohort size", err) + } + if len(ranked.main) != 3 { + t.Fatalf("main = %d entries, want 3", len(ranked.main)) + } + // Only the categories of the accepted entries are counted, each once. + if len(evidence.asked) != 1 || len(evidence.asked[0]) != 2 { + t.Fatalf("cohort questions = %v, want one question for the two categories of the entries", evidence.asked) + } + reasons := map[domain.SpecializationCode]UnknownReason{} + for _, item := range ranked.main { + for _, flag := range item.entry.UnknownFlags { + if flag.Component == UnknownPercentile { + reasons[item.entry.Specialization] = flag.Reason + } + } + if item.entry.Components.Percentile != nil || microToFloat(item.rank) != item.entry.Components.RankScore { + t.Fatalf("entry %+v has a percentile or a rank that is not the neutral-T rank", item.entry.Components) + } + // T is the neutral 0.5 in every case: Cov, Dom, Sem 0.5 give S = 0.45125. + if item.entry.Components.RankScore != 0.45125 { + t.Fatalf("rank score = %v, want 0.45125 with the neutral T", item.entry.Components.RankScore) + } + } + if reasons[domain.SpecializationBackend] != ReasonPercentileNotComputed || reasons[domain.SpecializationFrontend] != ReasonCohortBelow30 { + t.Fatalf("percentile reasons = %v, want not computed at the minimum and below 30 under it", reasons) + } + if strings.Count(logs.String(), "reached the percentile minimum") != 1 || !strings.Contains(logs.String(), "specialization=backend") { + t.Fatalf("log = %q, want one warning for the one category that reached the minimum", logs.String()) + } +} + +// repeatingTransactor fails with a visibility change a number of times and then +// succeeds without running the work. +type repeatingTransactor struct { + failures int + calls int +} + +func (transactor *repeatingTransactor) WithinTransaction(context.Context, func(context.Context, outbound.UnitOfWork) error) error { + transactor.calls++ + if transactor.calls <= transactor.failures { + return fmt.Errorf("lock the cohort: %w", outbound.ErrConcurrentVisibilityChange) + } + return nil +} + +func TestSearchRepeatsAfterAConcurrentVisibilityChangeAFewTimes(t *testing.T) { + request := Request{ActorID: uuid.New(), OrganizationID: uuid.New()} + for _, test := range []struct { + failures, calls int + wantErr bool + }{{0, 1, false}, {2, 3, false}, {3, 3, true}} { + transactor := &repeatingTransactor{failures: test.failures} + service := &Service{transactor: transactor} + _, err := service.Search(context.Background(), request) + if transactor.calls != test.calls || (err != nil) != test.wantErr || + (err != nil && !errors.Is(err, outbound.ErrConcurrentVisibilityChange)) { + t.Errorf("%d failures: %d attempts, error %v; want %d attempts, error %v", test.failures, transactor.calls, err, test.calls, test.wantErr) + } + } +} diff --git a/backend/internal/usecase/matching/reveal_test.go b/backend/internal/usecase/matching/reveal_test.go new file mode 100644 index 0000000..4b0c6c3 --- /dev/null +++ b/backend/internal/usecase/matching/reveal_test.go @@ -0,0 +1,129 @@ +package matching + +import ( + "context" + "slices" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// viewsFake charges a fixed number of distinct candidates and records what it +// is asked to write. +type viewsFake struct { + allowance int + reserved map[uuid.UUID]bool + attempts []uuid.UUID + recorded map[uuid.UUID][]domain.CardField + order []uuid.UUID +} + +func newViewsFake(allowance int) *viewsFake { + return &viewsFake{allowance: allowance, reserved: map[uuid.UUID]bool{}, recorded: map[uuid.UUID][]domain.CardField{}} +} + +func (views *viewsFake) Reserve(_ context.Context, candidateID uuid.UUID) (bool, error) { + views.attempts = append(views.attempts, candidateID) + if views.reserved[candidateID] { + return true, nil + } + if len(views.reserved) >= views.allowance { + return false, nil + } + views.reserved[candidateID] = true + return true, nil +} + +func (views *viewsFake) Record(_ context.Context, candidateID uuid.UUID, fields []domain.CardField) error { + views.recorded[candidateID] = fields + views.order = append(views.order, candidateID) + return nil +} + +func revealService(views *viewsFake) *Service { + return &Service{views: func(context.Context, outbound.UnitOfWork, uuid.UUID, uuid.UUID) (ViewSession, error) { + return views, nil + }} +} + +func confirmedItem(id uuid.UUID) rankedEntry { + band := domain.CandidateExperienceBandOneToThree + return rankedEntry{candidate: id, entry: Entry{ + Specialization: domain.SpecializationBackend, + Category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior}, + PublicContext: PublicContext{ExperienceBand: &band, Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo}}, + }} +} + +func declaredItem(id uuid.UUID, specialization domain.SpecializationCode) rankedEntry { + return rankedEntry{candidate: id, entry: Entry{Specialization: specialization}} +} + +func TestRevealCutsEachGroupAndRecordsTheFieldsReturned(t *testing.T) { + first, second := uuid.New(), uuid.New() + policy := domain.DemoMatchingPolicy() + policy.MaxResultsPerGroup = 2 + views := newViewsFake(10) + result, err := revealService(views).reveal(context.Background(), nil, Request{}, policy, groups{ + main: []rankedEntry{confirmedItem(first), confirmedItem(second), confirmedItem(uuid.New())}, + unconfirmed: []rankedEntry{declaredItem(first, domain.SpecializationNetworkEngineer)}, + }) + if err != nil { + t.Fatalf("reveal() error = %v", err) + } + if len(result.Main) != 2 || len(result.Unconfirmed) != 1 || !result.Truncated { + t.Fatalf("result = %d main, %d unconfirmed, truncated %v, want the group cut at 2 and flagged", len(result.Main), len(result.Unconfirmed), result.Truncated) + } + // The first candidate appears twice and is charged once; the dropped third + // entry is never charged. + if len(views.reserved) != 2 || !views.reserved[first] || !views.reserved[second] { + t.Fatalf("reserved = %v, want the two returned candidates", views.reserved) + } + // The fields are those that the returned entries show: the category, the + // stack, and the experience of the Backend entry plus the self-assessment of + // the Networks entry. + want := []domain.CardField{domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, domain.CardFieldSelfAssessment} + if !slices.Equal(views.recorded[first], want) { + t.Fatalf("recorded fields of the first candidate = %v, want %v", views.recorded[first], want) + } + if got := views.recorded[second]; !slices.Equal(got, want[:3]) { + t.Fatalf("recorded fields of the second candidate = %v, want %v", got, want[:3]) + } +} + +func TestRevealReturnsThePrefixThatIsPaidForWhenTheAllowanceEnds(t *testing.T) { + ids := []uuid.UUID{uuid.New(), uuid.New(), uuid.New(), uuid.New()} + views := newViewsFake(2) + result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{ + main: []rankedEntry{confirmedItem(ids[0])}, + near: []rankedEntry{confirmedItem(ids[1]), confirmedItem(ids[2])}, + unconfirmed: []rankedEntry{declaredItem(ids[0], domain.SpecializationNetworkEngineer), declaredItem(ids[3], domain.SpecializationQA)}, + }) + if err != nil { + t.Fatalf("reveal() error = %v", err) + } + if len(result.Main) != 1 || len(result.Near) != 1 || len(result.Unconfirmed) != 0 || !result.Truncated { + t.Fatalf("result = %d/%d/%d truncated %v, want the entries before the refusal and nothing after it", + len(result.Main), len(result.Near), len(result.Unconfirmed), result.Truncated) + } + if len(views.reserved) != 2 || len(views.recorded) != 2 || views.reserved[ids[2]] || views.reserved[ids[3]] { + t.Fatalf("reserved %v, recorded %v, want only the two paid candidates", views.reserved, views.recorded) + } +} + +func TestRevealDoesNotFlagACompleteResult(t *testing.T) { + views := newViewsFake(5) + result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{ + main: []rankedEntry{confirmedItem(uuid.New())}, + }) + if err != nil || result.Truncated || len(result.Main) != 1 { + t.Fatalf("reveal() = %+v, %v, want one entry that is not truncated", result, err) + } + empty, err := revealService(newViewsFake(0)).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{}) + if err != nil || empty.Truncated || len(empty.Main)+len(empty.Near)+len(empty.Unconfirmed) != 0 { + t.Fatalf("an empty search = %+v, %v, want an empty result that is not truncated", empty, err) + } +} diff --git a/backend/internal/usecase/matching/score.go b/backend/internal/usecase/matching/score.go new file mode 100644 index 0000000..be2c7d8 --- /dev/null +++ b/backend/internal/usecase/matching/score.go @@ -0,0 +1,171 @@ +package matching + +import ( + "lincodex/backend/internal/domain" +) + +// Scores are computed in integers so that the same data and policy always give +// the same order on every platform. A policy share is BasisPoints (1e-4); a +// component is stored in micro units (1e-6), the precision at which results +// are rounded and compared; a skill contribution keeps the exact product of +// three shares in pico units (1e-12). +const ( + microPerUnit int64 = 1_000_000 + bpPerUnit int64 = 10_000 + picoPerBasisPoint int64 = 100_000_000 + microPerBasisPoint int64 = 100 +) + +// requestedSkill is one skill that a need or a stack filter asks for. A skill +// without a taxonomy code cannot match any evidence: the platform has no +// reviewed mapping for it, so it stays a gap and never an invented match. +type requestedSkill struct { + code string + required bool +} + +// evidenceSource is one permitted piece of evidence of a candidate: either a +// stated stack tag of the card (trust 0, a claim) or the one assessment fact +// that supports the confirmed category. +type evidenceSource struct { + code string + trust domain.EvidenceTrust + attribution domain.EvidenceAttribution + measured bool +} + +// skillOutcome is the contribution of one requested skill and what it rests +// on. The explanation reads these exact values. +type skillOutcome struct { + required bool + pico int64 + // measured is true when the best evidence is a measurement and false when + // it is a stated claim or when there is none. + measured bool +} + +// scores are the computed components of one entry, in micro units. +type scores struct { + skills []skillOutcome + coverage int64 + domain int64 + semantics int64 + fit int64 + t int64 + competition int64 + strength int64 + freshness int64 + responsive int64 + rank int64 +} + +// scoreInput is everything a score depends on. +type scoreInput struct { + // confirmed selects the confirmed-profile model. An unconfirmed profile + // gets only coverage and fit: it has no theta, T, P, or rank score, so + // those values are never computed for it. + confirmed bool + policy domain.MatchingPolicy + skills []requestedSkill + evidence []evidenceSource +} + +// computeScores applies the FR09 model. Unknown components are neutral: Dom, +// Sem, Fr, and Rsp use the neutral value, T is neutral because there is no +// comparable real cohort, and V is zero because no competition evidence +// exists, which is not a penalty. +func computeScores(input scoreInput) scores { + policy := input.policy + neutral := int64(policy.NeutralUnknown) * microPerBasisPoint + result := scores{ + domain: neutral, semantics: neutral, t: neutral, freshness: neutral, responsive: neutral, + } + result.skills = make([]skillOutcome, 0, len(input.skills)) + var weighted, weights int64 + for _, skill := range input.skills { + pico, measured := skillContribution(policy, skill, input.evidence) + weight := int64(policy.DesiredSkillWeight) + if skill.required { + weight = int64(policy.RequiredSkillWeight) + } + weighted += weight * pico + weights += weight + result.skills = append(result.skills, skillOutcome{required: skill.required, pico: pico, measured: measured}) + } + // An empty request has nothing to cover; it uses the neutral value instead + // of dividing by zero. + result.coverage = neutral + if weights > 0 { + result.coverage = roundedQuotient(weighted, weights*microPerUnit) + } + result.fit = roundedQuotient( + int64(policy.FitCoverageWeight)*result.coverage+ + int64(policy.FitDomainWeight)*result.domain+ + int64(policy.FitSemanticsWeight)*result.semantics, + bpPerUnit) + if !input.confirmed { + result.t, result.freshness, result.responsive = 0, 0, 0 + return result + } + // P = T + boost * (1 - T) * V, with V = 0 without competition evidence. + result.strength = result.t + roundedQuotient( + int64(policy.CompetitionBoost)*(microPerUnit-result.t)*result.competition, bpPerUnit*microPerUnit) + rank := roundedQuotient( + int64(policy.RankFitWeight)*result.fit+int64(policy.RankStrengthWeight)*result.strength, bpPerUnit) + rank = multiplyMicro(rank, blendedMultiplier(policy.FreshnessFloor, result.freshness)) + result.rank = multiplyMicro(rank, blendedMultiplier(policy.ResponsivenessFloor, result.responsive)) + return result +} + +// skillContribution is the best product of the trust, attribution, and +// relation coefficients over the evidence, not their sum, so a repeated tag or +// a second piece of the same kind never raises the contribution. A tie goes to +// the measurement, so the explanation names the stronger basis. +func skillContribution(policy domain.MatchingPolicy, skill requestedSkill, evidence []evidenceSource) (int64, bool) { + if skill.code == "" { + return 0, false + } + var best int64 + var measured bool + for _, source := range evidence { + trust, trustOK := policy.TrustCoefficient(source.trust) + attribution, attributionOK := policy.AttributionCoefficient(source.attribution) + if !trustOK || !attributionOK { + continue + } + relation := policy.RelationCoefficient(policy.RelateSkill(skill.code, source.code)) + value := int64(trust) * int64(attribution) * int64(relation) + if value > best || (value == best && value > 0 && source.measured && !measured) { + best, measured = value, source.measured + } + } + return best, measured +} + +// belongsToNearGroup reports whether a requested required skill earns less +// than the policy threshold, which moves a confirmed profile to "near". +func (result scores) belongsToNearGroup(policy domain.MatchingPolicy) bool { + threshold := int64(policy.NearSkillThreshold) * picoPerBasisPoint + for _, skill := range result.skills { + if skill.required && skill.pico < threshold { + return true + } + } + return false +} + +// blendedMultiplier is floor + (1 - floor) * x, in micro units. +func blendedMultiplier(floor domain.BasisPoints, x int64) int64 { + return int64(floor)*microPerBasisPoint + roundedQuotient((bpPerUnit-int64(floor))*x, bpPerUnit) +} + +func multiplyMicro(left, right int64) int64 { + return roundedQuotient(left*right, microPerUnit) +} + +// roundedQuotient divides non-negative integers and rounds half up. +func roundedQuotient(numerator, denominator int64) int64 { + return (numerator + denominator/2) / denominator +} + +func microToFloat(value int64) float64 { return float64(value) / float64(microPerUnit) } diff --git a/backend/internal/usecase/matching/score_test.go b/backend/internal/usecase/matching/score_test.go new file mode 100644 index 0000000..4c82362 --- /dev/null +++ b/backend/internal/usecase/matching/score_test.go @@ -0,0 +1,283 @@ +package matching + +import ( + "slices" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + onlineBackendFact = evidenceSource{code: "backend", trust: domain.EvidenceTrustOnlineUnconfirmed, attribution: domain.EvidenceAttributionPersonal, measured: true} + statedGo = evidenceSource{code: "go", trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal} + statedKafka = evidenceSource{code: "kafka", trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal} +) + +func required(code string) requestedSkill { return requestedSkill{code: code, required: true} } +func desired(code string) requestedSkill { return requestedSkill{code: code} } + +func TestComputeScoresFollowsTheFR09Formulas(t *testing.T) { + policy := domain.DemoMatchingPolicy() + tests := []struct { + name string + confirmed bool + skills []requestedSkill + evidence []evidenceSource + coverage int64 + fit int64 + rank int64 + near bool + }{ + { + // 0.6 online trust * 1.0 personal * 0.4 broader relation = 0.24: + // Cov 0.24, Fit 0.75*0.24+0.15*0.5+0.10*0.5 = 0.305, P = T = 0.5, + // S = (0.5*0.305+0.5*0.5) * 0.95 * 0.95 = 0.363256. + name: "a broad measurement under a requested technology is below the near threshold", confirmed: true, + skills: []requestedSkill{required("go")}, evidence: []evidenceSource{onlineBackendFact}, + coverage: 240000, fit: 305000, rank: 363256, near: true, + }, + { + // A stated tag is a claim with trust 0.25. + name: "a stated tag reaches the threshold exactly", confirmed: true, + skills: []requestedSkill{required("go")}, evidence: []evidenceSource{statedGo}, + coverage: 250000, fit: 312500, rank: 366641, near: false, + }, + { + name: "the best evidence counts once, not the sum of duplicates", confirmed: true, + skills: []requestedSkill{required("go")}, evidence: []evidenceSource{statedGo, statedGo, onlineBackendFact, onlineBackendFact}, + coverage: 250000, fit: 312500, rank: 366641, near: false, + }, + { + name: "weights are 2 for required and 1 for desired", confirmed: true, + skills: []requestedSkill{required("go"), desired("kafka")}, + evidence: []evidenceSource{onlineBackendFact, statedKafka}, + coverage: 243333, fit: 307500, rank: 364385, near: true, + }, + { + name: "an empty request is neutral and never divides by zero", confirmed: true, + skills: nil, evidence: []evidenceSource{onlineBackendFact}, + coverage: 500000, fit: 500000, rank: 451250, near: false, + }, + { + // Cov 0: Fit 0.125, S = (0.5*0.125+0.25) * 0.9025 = 0.282031. + name: "a skill without a taxonomy mapping is a gap", confirmed: true, + skills: []requestedSkill{required("")}, evidence: []evidenceSource{onlineBackendFact, statedGo}, + coverage: 0, fit: 125000, rank: 282031, near: true, + }, + { + name: "an unconfirmed profile has fit and coverage only", confirmed: false, + skills: []requestedSkill{required("go")}, evidence: []evidenceSource{statedGo}, + coverage: 250000, fit: 312500, rank: 0, near: false, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := computeScores(scoreInput{confirmed: test.confirmed, policy: policy, skills: test.skills, evidence: test.evidence}) + if got.coverage != test.coverage || got.fit != test.fit { + t.Fatalf("coverage/fit = %d/%d, want %d/%d", got.coverage, got.fit, test.coverage, test.fit) + } + if test.confirmed && got.rank != test.rank { + t.Fatalf("rank = %d, want %d", got.rank, test.rank) + } + if got.belongsToNearGroup(policy) != test.near { + t.Fatalf("near = %v, want %v", got.belongsToNearGroup(policy), test.near) + } + }) + } +} + +func TestComputeScoresNeverGivesAnUnconfirmedProfileStrength(t *testing.T) { + got := computeScores(scoreInput{ + confirmed: false, policy: domain.DemoMatchingPolicy(), skills: []requestedSkill{required("go")}, + evidence: []evidenceSource{statedGo}, + }) + if got.t != 0 || got.strength != 0 || got.rank != 0 || got.freshness != 0 || got.responsive != 0 { + t.Fatalf("unconfirmed scores = %+v, want no T, P, S, or rank multipliers", got) + } +} + +func TestComputeScoresIsRepeatable(t *testing.T) { + input := scoreInput{ + confirmed: true, policy: domain.DemoMatchingPolicy(), + skills: []requestedSkill{required("go"), required("postgresql"), desired("kafka"), desired("docker")}, + evidence: []evidenceSource{onlineBackendFact, statedGo, statedKafka}, + } + first := computeScores(input) + for range 20 { + if again := computeScores(input); !slices.Equal(again.skills, first.skills) || again.rank != first.rank || again.fit != first.fit { + t.Fatalf("computeScores() changed between runs: %+v then %+v", first, again) + } + } +} + +func TestSkillContributionPrefersAMeasurementOnATie(t *testing.T) { + policy := domain.DemoMatchingPolicy() + policy.TrustStated = policy.TrustOnline + measured := evidenceSource{code: "go", trust: domain.EvidenceTrustOnlineUnconfirmed, attribution: domain.EvidenceAttributionPersonal, measured: true} + stated := evidenceSource{code: "go", trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal} + for _, evidence := range [][]evidenceSource{{stated, measured}, {measured, stated}} { + if _, isMeasured := skillContribution(policy, required("go"), evidence); !isMeasured { + t.Fatalf("skillContribution(%v) reported a claim although an equal measurement exists", evidence) + } + } +} + +func TestRequestedSkillsCountEachCodeOnce(t *testing.T) { + goCode, kafkaCode := "go", "kafka" + confirmedSkill := func(name string, code *string) domain.NeedSkill { + return domain.NeedSkill{Name: name, TaxonomyCode: code, Status: domain.NeedItemConfirmed} + } + skills := requestedSkills( + []domain.NeedSkill{ + confirmedSkill("Go", &goCode), confirmedSkill("Golang", &goCode), confirmedSkill("Temporal", nil), confirmedSkill(" temporal ", nil), + {Name: "Rust", Status: domain.NeedItemExtracted}, + }, + []domain.NeedSkill{confirmedSkill("Kafka", &kafkaCode), confirmedSkill("Go again", &goCode)}, + []domain.CandidateViewSkillCode{domain.CandidateViewSkillKafka, domain.CandidateViewSkillDocker}, + ) + want := []requestedSkill{ + {code: "go", required: true}, {required: true}, {code: "kafka", required: true}, {code: "docker", required: true}, + } + if !slices.Equal(skills, want) { + t.Fatalf("requestedSkills() = %+v, want %+v", skills, want) + } +} + +func TestExplanationReadsTheComputedContributions(t *testing.T) { + policy := domain.DemoMatchingPolicy() + explainWith := func(confirmed bool, skills []requestedSkill, evidence []evidenceSource, context PublicContext, formats []domain.QuestionnaireWorkFormat) []EvidenceItem { + computed := computeScores(scoreInput{confirmed: confirmed, policy: policy, skills: skills, evidence: evidence}) + items, _ := explain(explanationInput{confirmed: confirmed, policy: policy, scores: computed, context: context, requestedFormats: formats}) + return items + } + remote := []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote} + office := []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatOffice} + tests := []struct { + name string + got []EvidenceItem + want []EvidenceItem + }{ + { + name: "all required skills carried by measurements", + got: explainWith(true, []requestedSkill{required("backend")}, []evidenceSource{onlineBackendFact}, PublicContext{}, nil), + want: []EvidenceItem{{EvidenceConfirmedCategory, EvidenceStateSupports}, {EvidenceRequiredSkill, EvidenceStateSupports}}, + }, + { + name: "a measurement below the threshold is partial", + got: explainWith(true, []requestedSkill{required("go")}, []evidenceSource{onlineBackendFact}, PublicContext{}, nil), + want: []EvidenceItem{{EvidenceConfirmedCategory, EvidenceStateSupports}, {EvidenceRequiredSkill, EvidenceStatePartial}}, + }, + { + name: "only stated tags are declared", + got: explainWith(false, []requestedSkill{required("go")}, []evidenceSource{statedGo}, PublicContext{}, nil), + want: []EvidenceItem{{EvidenceRequiredSkill, EvidenceStateDeclaredOnly}}, + }, + { + name: "nothing carries the skills", + got: explainWith(false, []requestedSkill{required("go"), desired("kafka")}, nil, PublicContext{}, nil), + want: []EvidenceItem{{EvidenceRequiredSkill, EvidenceStateGap}, {EvidenceDesiredSkill, EvidenceStateGap}}, + }, + { + name: "a mix of covered and missing skills is partial", + got: explainWith(false, []requestedSkill{required("go"), required("kafka")}, []evidenceSource{statedGo}, PublicContext{}, nil), + want: []EvidenceItem{{EvidenceRequiredSkill, EvidenceStatePartial}}, + }, + { + name: "work formats are compared with the request", + got: explainWith(false, nil, nil, PublicContext{WorkFormats: remote}, office), + want: []EvidenceItem{{EvidenceWorkConditionsMatch, EvidenceStateGap}}, + }, + { + name: "no request for skills or formats gives no item", + got: explainWith(false, nil, nil, PublicContext{WorkFormats: remote}, nil), + want: []EvidenceItem{}, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if len(test.got) == 0 && len(test.want) == 0 { + return + } + if !slices.Equal(test.got, test.want) { + t.Fatalf("evidence summary = %+v, want %+v", test.got, test.want) + } + }) + } +} + +func TestUnknownFlagsNameNeutralValuesAndNeverFSP(t *testing.T) { + policy := domain.DemoMatchingPolicy() + computed := computeScores(scoreInput{confirmed: true, policy: policy}) + _, confirmedFlags := explain(explanationInput{confirmed: true, policy: policy, scores: computed}) + wantConfirmed := []UnknownFlag{ + {UnknownSemantics, ReasonMLUnavailable}, {UnknownPercentile, ReasonCohortBelow30}, + {UnknownFreshness, ReasonNoFreshnessHistory}, {UnknownResponsiveness, ReasonNoResponseHistory}, + {UnknownExperienceBand, ReasonNotInPublicCard}, {UnknownWorkFormats, ReasonNotInPublicCard}, + {UnknownSalaryCompatibility, ReasonNotInPublicCard}, {UnknownDomain, ReasonNeedFieldUnconfirmed}, + } + if !slices.Equal(confirmedFlags, wantConfirmed) { + t.Fatalf("confirmed unknown flags = %+v, want %+v", confirmedFlags, wantConfirmed) + } + band := domain.CandidateExperienceBandOneToThree + compatible := domain.CandidateViewSalaryCompatible + _, unconfirmedFlags := explain(explanationInput{ + policy: policy, needDomainConfirmed: true, + context: PublicContext{ExperienceBand: &band, SalaryCompatibility: &compatible, WorkFormats: []domain.QuestionnaireWorkFormat{domain.QuestionnaireWorkFormatRemote}}, + }) + wantUnconfirmed := []UnknownFlag{ + {UnknownSemantics, ReasonMLUnavailable}, {UnknownAssessment, ReasonNoConfirmationForSpecialization}, + {UnknownDomain, ReasonNotInPublicCard}, + } + if !slices.Equal(unconfirmedFlags, wantUnconfirmed) { + t.Fatalf("unconfirmed unknown flags = %+v, want %+v", unconfirmedFlags, wantUnconfirmed) + } +} + +func TestOrderingIsStableAndSeparateForEachGroup(t *testing.T) { + lowID := uuid.MustParse("00000000-0000-0000-0000-000000000001") + highID := uuid.MustParse("00000000-0000-0000-0000-000000000002") + entry := func(id uuid.UUID, specialization domain.SpecializationCode, fit, coverage, rank int64) rankedEntry { + return rankedEntry{ + entry: Entry{Specialization: specialization}, + candidate: id, fit: fit, coverage: coverage, rank: rank, + } + } + ids := func(items []rankedEntry) []uuid.UUID { + result := make([]uuid.UUID, len(items)) + for index, item := range items { + result[index] = item.candidate + } + return result + } + t.Run("equal rank is resolved by coverage and then by the internal identifier", func(t *testing.T) { + items := []rankedEntry{ + entry(highID, "backend", 0, 400000, 500000), + entry(lowID, "backend", 0, 400000, 500000), + entry(highID, "devops_sre", 0, 450000, 500000), + } + slices.SortStableFunc(items, compareByRank) + if got := ids(items); !slices.Equal(got, []uuid.UUID{highID, lowID, highID}) || items[0].entry.Specialization != "devops_sre" { + t.Fatalf("order = %v, want higher coverage first, then ascending identifiers", got) + } + }) + t.Run("the unconfirmed group uses fit, then coverage, then the identifier", func(t *testing.T) { + items := []rankedEntry{ + entry(highID, "qa", 300000, 100000, 999999), + entry(lowID, "qa", 300000, 100000, 1), + entry(highID, "frontend", 400000, 0, 0), + } + slices.SortStableFunc(items, compareByFit) + if items[0].entry.Specialization != "frontend" || items[1].candidate != lowID || items[2].candidate != highID { + t.Fatalf("order = %+v, want fit first and the rank score ignored", items) + } + }) + t.Run("two entries of one candidate keep a stable order", func(t *testing.T) { + items := []rankedEntry{entry(lowID, "qa", 0, 0, 0), entry(lowID, "backend", 0, 0, 0)} + slices.SortStableFunc(items, compareByRank) + if items[0].entry.Specialization != "backend" { + t.Fatalf("order = %+v, want the specialization to separate equal entries", items) + } + }) +} diff --git a/backend/internal/usecase/matching/search.go b/backend/internal/usecase/matching/search.go new file mode 100644 index 0000000..b25bc68 --- /dev/null +++ b/backend/internal/usecase/matching/search.go @@ -0,0 +1,697 @@ +// Package matching ranks the organization-visible candidate bank +// deterministically. It filters by the current visibility rules first, scores +// each candidate specialization with the versioned matching policy, and builds +// the explanation from the same computed components. It reads no contact, no +// raw assessment data, and no hidden minimum, and it consumes no ML result. +package matching + +import ( + "cmp" + "context" + "errors" + "fmt" + "log/slog" + "slices" + "strings" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// VisibleCards returns the current organization-visible cards inside the +// caller's transaction. candidateview.Service.ListVisibleCards provides it; +// bootstrap passes it in so this package depends on no other usecase. +type VisibleCards func( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID uuid.UUID, +) ([]domain.VisibleCandidateCard, error) + +// ViewSession charges and records the candidates that one search reveals, +// inside the caller's transaction. +type ViewSession interface { + // Reserve counts the candidate as a distinct card view of the organization. + // A candidate already viewed inside the window is allowed without another + // charge. It reports false and writes nothing once the allowance is used up. + Reserve(ctx context.Context, candidateID uuid.UUID) (bool, error) + // Record appends the access history entry for the fields that were returned. + Record(ctx context.Context, candidateID uuid.UUID, fields []domain.CardField) error +} + +// BeginViews opens a ViewSession for an authorized actor and organization. +// candidateview.Service.BeginSearchViews provides it through bootstrap. +type BeginViews func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (ViewSession, error) + +// Dependencies configure the search service. +type Dependencies struct { + Transactor outbound.Transactor + Cards VisibleCards + Views BeginViews + Clock func() time.Time + // Logger receives the warnings of a search. A nil logger discards them. + Logger *slog.Logger +} + +// Service searches and ranks the visible bank. +type Service struct { + transactor outbound.Transactor + cards VisibleCards + views BeginViews + clock func() time.Time + logger *slog.Logger +} + +func NewService(deps Dependencies) (*Service, error) { + if deps.Transactor == nil || deps.Cards == nil || deps.Views == nil || deps.Clock == nil { + return nil, fmt.Errorf("matching.NewService - dependencies are missing: %w", ErrServiceMissing) + } + logger := deps.Logger + if logger == nil { + logger = slog.New(slog.DiscardHandler) + } + return &Service{transactor: deps.Transactor, cards: deps.Cards, views: deps.Views, clock: deps.Clock, logger: logger}, nil +} + +// Search returns the groups for one request. Everything runs in one +// transaction: the owner role, the membership, and the candidate visibility are +// checked and locked before any card is read, the need snapshot and the policy +// are read from storage, and the permitted evidence is read through the +// organization-safe projection queries, so no later read can widen what the +// first one allowed. +// +// A search reveals card content, so it is charged like card reads. The whole +// visible bank is ranked, but each group is cut to the policy's +// MaxResultsPerGroup, and no total is returned. Walking the output in the +// order main, near, unconfirmed, each newly revealed candidate is reserved as a +// distinct card view of the organization (a candidate already viewed inside the +// window costs nothing again) and recorded in the candidate's access history +// with the fields actually returned, in the same transaction. When the +// allowance runs out the entries already paid for are returned with Truncated +// set, and nothing is written for the rest. +func (service *Service) Search(ctx context.Context, request Request) (Result, error) { + const location = "matching.Service.Search" + if request.ActorID == uuid.Nil || request.OrganizationID == uuid.Nil { + return Result{}, ErrForbidden + } + var result Result + var err error + // The visible cohort can change while it is locked. The whole search is + // then repeated, a bounded number of times, and the writes of a failed + // attempt roll back with it. + for range maxSearchAttempts { + result, err = service.searchOnce(ctx, request) + if !errors.Is(err, outbound.ErrConcurrentVisibilityChange) { + break + } + } + if err != nil { + return Result{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +// maxSearchAttempts bounds the repeats after a concurrent visibility change. +const maxSearchAttempts = 3 + +func (service *Service) searchOnce(ctx context.Context, request Request) (Result, error) { + const location = "matching.Service.searchOnce" + var result Result + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + // The MVP milestone allows only the active owner; a membership alone + // grants nothing here. The HTTP boundary checks the same rule, and the + // repeat keeps the usecase closed when it is called another way. The + // role is settled before the cohort is read and locked. + // The reservations below take the exclusive organization lock. Taking it + // first, before the share lock of the membership check, keeps two + // searches of one organization from deadlocking on the upgrade, and it + // serializes their charges. + if err := unit.CompanyQuotas().LockOrganization(ctx, request.OrganizationID); err != nil { + if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) { + return outbound.ErrOrganizationNotFound + } + return fmt.Errorf("%s - lock organization: %w", location, err) + } + membership, err := unit.Organizations().LockActiveMembership(ctx, request.OrganizationID, request.ActorID) + if err != nil { + return fmt.Errorf("%s - lock active membership: %w", location, err) + } + if membership.Role() != domain.OrganizationRoleOwner { + return ErrForbidden + } + cards, err := service.cards(ctx, unit, request.ActorID, request.OrganizationID) + if err != nil { + return err + } + policy, err := service.matchingPolicy(ctx, unit) + if err != nil { + return err + } + basis, err := loadBasis(ctx, unit, request) + if err != nil { + return err + } + ranked, err := service.rank(ctx, unit, request, basis, policy, cards) + if err != nil { + return err + } + result, err = service.reveal(ctx, unit, request, policy, ranked) + return err + }) + if err != nil { + return Result{}, fmt.Errorf("%s - run transaction: %w", location, err) + } + return result, nil +} + +func (service *Service) matchingPolicy(ctx context.Context, unit outbound.UnitOfWork) (domain.MatchingPolicy, error) { + const location = "matching.Service.matchingPolicy" + version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, service.clock().UTC()) + if err != nil { + return domain.MatchingPolicy{}, fmt.Errorf("%s - read effective product policy: %w", location, err) + } + policy := version.Policy().Matching + if policy == nil { + return domain.MatchingPolicy{}, fmt.Errorf("%s - the effective product policy has no matching section, publish it with the policy-publish command: %w", location, ErrPolicyUnavailable) + } + return *policy, nil +} + +// searchBasis is what a need snapshot contributes to the search. A bank search +// has an empty basis. +type searchBasis struct { + specialization *domain.SpecializationCode + skills []requestedSkill + requestedFormats []domain.QuestionnaireWorkFormat + needDomainConfirmed bool +} + +func loadBasis(ctx context.Context, unit outbound.UnitOfWork, request Request) (searchBasis, error) { + const location = "matching.loadBasis" + var needSkills, needDesired []domain.NeedSkill + basis := searchBasis{} + if request.Need != nil { + need, err := unit.Needs().GetVersion(ctx, request.OrganizationID, request.Need.NeedID, request.Need.RequirementsVersion) + if err != nil { + if errors.Is(err, outbound.ErrNeedNotFound) { + return searchBasis{}, ErrNeedNotFound + } + return searchBasis{}, fmt.Errorf("%s - read need snapshot: %w", location, err) + } + // A version that only edited a title or a suggestion is not a + // requirements snapshot of its own. + if need.RequirementsVersion() != request.Need.RequirementsVersion { + return searchBasis{}, ErrNeedNotFound + } + requirements := need.Snapshot().Requirements + if requirements.Specialization.Status == domain.NeedValueConfirmed && requirements.Specialization.Value != nil { + specialization := *requirements.Specialization.Value + basis.specialization = &specialization + } + if requirements.WorkFormats.Status == domain.NeedValueConfirmed && requirements.WorkFormats.Value != nil { + for _, format := range *requirements.WorkFormats.Value { + basis.requestedFormats = append(basis.requestedFormats, domain.QuestionnaireWorkFormat(format)) + } + } + basis.needDomainConfirmed = requirements.Domain.Status == domain.NeedValueConfirmed + needSkills, needDesired = requirements.RequiredSkills, requirements.DesiredSkills + } + basis.skills = requestedSkills(needSkills, needDesired, request.Filters.Stack) + return basis, nil +} + +// requestedSkills lists each distinct requested skill once. A confirmed +// required skill weighs more than a desired one, a stack filter tag counts as +// required, and a repeated code never counts twice, so repeating a skill in a +// need cannot raise or lower a score. +func requestedSkills(required, desired []domain.NeedSkill, stack []domain.CandidateViewSkillCode) []requestedSkill { + var skills []requestedSkill + byCode := make(map[string]int) + seenUnmapped := make(map[string]struct{}) + add := func(code, name string, isRequired bool) { + if code == "" { + key := strings.ToLower(strings.TrimSpace(name)) + if _, repeated := seenUnmapped[key]; repeated { + return + } + seenUnmapped[key] = struct{}{} + skills = append(skills, requestedSkill{required: isRequired}) + return + } + if index, repeated := byCode[code]; repeated { + skills[index].required = skills[index].required || isRequired + return + } + byCode[code] = len(skills) + skills = append(skills, requestedSkill{code: code, required: isRequired}) + } + for _, group := range []struct { + skills []domain.NeedSkill + isRequired bool + }{{required, true}, {desired, false}} { + for _, skill := range group.skills { + if skill.Status != domain.NeedItemConfirmed { + continue + } + code := "" + if skill.TaxonomyCode != nil { + code = *skill.TaxonomyCode + } + add(code, skill.Name, group.isRequired) + } + } + for _, tag := range stack { + add(string(tag), "", true) + } + return skills +} + +// candidateEntry is one candidate specialization before scoring. +type candidateEntry struct { + candidateID uuid.UUID + card domain.AnonymousCandidateViewDTO + specialization domain.SpecializationCode + category *domain.CandidateViewCategory + declaredGrade *domain.GradeCode +} + +// entriesOf derives the specializations that a card shows. A specialization is +// confirmed only when the card shows its category; one specialization never +// confirms another. A specialization that the self-assessment marks confirmed +// but whose category the card does not show is left out: a result cannot +// claim a confirmation that the candidate did not publish. +func entriesOf(visible domain.VisibleCandidateCard) []candidateEntry { + card := visible.Card + declared := make(map[domain.SpecializationCode]*domain.GradeCode, len(card.SelfAssessment)) + for _, assessment := range card.SelfAssessment { + declared[assessment.Specialization] = assessment.DeclaredGrade + } + entries := make([]candidateEntry, 0, len(card.Categories)+len(card.SelfAssessment)) + confirmed := make(map[domain.SpecializationCode]struct{}, len(card.Categories)) + for index := range card.Categories { + category := card.Categories[index] + confirmed[category.Specialization] = struct{}{} + entries = append(entries, candidateEntry{ + candidateID: visible.CandidateID, card: card, specialization: category.Specialization, + category: &category, declaredGrade: declared[category.Specialization], + }) + } + for _, assessment := range card.SelfAssessment { + if _, isConfirmed := confirmed[assessment.Specialization]; isConfirmed || + assessment.ConfirmationStatus != domain.CandidateViewConfirmationUnconfirmed { + continue + } + entries = append(entries, candidateEntry{ + candidateID: visible.CandidateID, card: card, specialization: assessment.Specialization, + declaredGrade: assessment.DeclaredGrade, + }) + } + return entries +} + +// rankedEntry carries the sort keys next to the entry that leaves. +type rankedEntry struct { + entry Entry + candidate uuid.UUID + fit int64 + coverage int64 + rank int64 + near bool +} + +// groups holds the ranked entries of the three groups before the output is cut. +type groups struct { + main, near, unconfirmed []rankedEntry +} + +func (service *Service) rank( + ctx context.Context, + unit outbound.UnitOfWork, + request Request, + basis searchBasis, + policy domain.MatchingPolicy, + cards []domain.VisibleCandidateCard, +) (groups, error) { + specialization, compatible := effectiveSpecialization(request.Filters.Specialization, basis.specialization) + if !compatible { + return groups{}, nil + } + requestedFormats := basis.requestedFormats + if conditions := request.Filters.Conditions; conditions != nil && len(conditions.WorkFormats) > 0 { + requestedFormats = conditions.WorkFormats + } + var accepted []candidateEntry + for _, visible := range cards { + for _, entry := range entriesOf(visible) { + if request.Filters.accepts(entry, specialization) { + accepted = append(accepted, entry) + } + } + } + reachedCohorts, err := service.reachedPercentileCohorts(ctx, unit, policy, accepted) + if err != nil { + return groups{}, err + } + facts, err := service.permittedFacts(ctx, unit, request, basis, accepted) + if err != nil { + return groups{}, err + } + var result groups + for _, entry := range accepted { + ranked := scoreEntry(entry, policy, basis, requestedFormats, facts[entry.candidateID], reachedCohorts) + switch { + case entry.category == nil: + result.unconfirmed = append(result.unconfirmed, ranked) + case ranked.near: + result.near = append(result.near, ranked) + default: + result.main = append(result.main, ranked) + } + } + slices.SortStableFunc(result.main, compareByRank) + slices.SortStableFunc(result.near, compareByRank) + slices.SortStableFunc(result.unconfirmed, compareByFit) + return result, nil +} + +// reachedPercentileCohorts returns the categories among the accepted entries +// whose comparable real cohort has reached the policy minimum. The cohort of a +// category is the number of candidates who hold it from a source that is not a +// synthetic demonstration; only the categories of the accepted entries are +// counted. A percentile would need the theta of those members, which the +// organization-safe projection does not carry, so T stays the neutral value and +// the percentile stays null, but the reason is then "not computed" instead of +// "cohort below the minimum". The search never fails for it and logs one +// warning for each such category. +func (service *Service) reachedPercentileCohorts( + ctx context.Context, + unit outbound.UnitOfWork, + policy domain.MatchingPolicy, + accepted []candidateEntry, +) (map[outbound.CategoryKey]bool, error) { + seen := make(map[outbound.CategoryKey]struct{}) + var categories []outbound.CategoryKey + for _, entry := range accepted { + if entry.category == nil { + continue + } + key := outbound.CategoryKey{Specialization: entry.category.Specialization, Grade: entry.category.Grade} + if _, repeated := seen[key]; !repeated { + seen[key] = struct{}{} + categories = append(categories, key) + } + } + counts, err := unit.Evidence().CountComparableRealCategories(ctx, categories) + if err != nil { + return nil, fmt.Errorf("matching.Service.reachedPercentileCohorts - count real cohorts: %w", err) + } + reached := make(map[outbound.CategoryKey]bool) + for _, key := range categories { + if counts[key] >= int64(policy.PercentileMinCohort) { + reached[key] = true + service.logger.WarnContext(ctx, "the real cohort of a category reached the percentile minimum, but the percentile is not computed", + slog.String("specialization", string(key.Specialization)), + slog.String("grade", string(key.Grade)), + slog.Int64("cohort_size", counts[key]), + slog.Int("minimum", int(policy.PercentileMinCohort)), + ) + } + } + return reached, nil +} + +// permittedFacts reads the permitted evidence of every candidate with a +// confirmed entry in one statement, and only when the request names skills. +func (service *Service) permittedFacts( + ctx context.Context, + unit outbound.UnitOfWork, + request Request, + basis searchBasis, + accepted []candidateEntry, +) (map[uuid.UUID][]evidenceSource, error) { + sources := make(map[uuid.UUID][]evidenceSource) + if len(basis.skills) == 0 { + return sources, nil + } + seen := make(map[uuid.UUID]struct{}) + var requests []outbound.EvidenceCandidateCategories + for _, entry := range accepted { + if _, repeated := seen[entry.candidateID]; repeated || entry.category == nil { + continue + } + seen[entry.candidateID] = struct{}{} + requests = append(requests, outbound.EvidenceCandidateCategories{CandidateID: entry.candidateID, Categories: entry.card.Categories}) + } + facts, err := unit.Evidence().ListOrganizationFactsBatch(ctx, request.OrganizationID, requests) + if err != nil { + return nil, fmt.Errorf("matching.Service.permittedFacts - read permitted evidence: %w", err) + } + for candidateID, candidateFacts := range facts { + sources[candidateID] = factSources(candidateFacts) + } + return sources, nil +} + +// reveal cuts each group to the policy bound and charges the output in order. +func (service *Service) reveal( + ctx context.Context, + unit outbound.UnitOfWork, + request Request, + policy domain.MatchingPolicy, + ranked groups, +) (Result, error) { + result := Result{Source: sourceOf(request), Main: []Entry{}, Near: []Entry{}, Unconfirmed: []Entry{}} + limit := int(policy.MaxResultsPerGroup) + for _, group := range []*[]rankedEntry{&ranked.main, &ranked.near, &ranked.unconfirmed} { + if len(*group) > limit { + *group = (*group)[:limit] + result.Truncated = true + } + } + views, err := service.views(ctx, unit, request.ActorID, request.OrganizationID) + if err != nil { + return Result{}, fmt.Errorf("matching.Service.reveal - open card views: %w", err) + } + revealed := make(map[uuid.UUID]map[domain.CardField]struct{}) + var order []uuid.UUID + charge := func(entries []rankedEntry) ([]Entry, bool, error) { + kept := make([]Entry, 0, len(entries)) + for _, item := range entries { + if _, paid := revealed[item.candidate]; !paid { + allowed, err := views.Reserve(ctx, item.candidate) + if err != nil { + return nil, false, fmt.Errorf("matching.Service.reveal - reserve card view: %w", err) + } + if !allowed { + return kept, false, nil + } + revealed[item.candidate] = make(map[domain.CardField]struct{}) + order = append(order, item.candidate) + } + for _, field := range entryFields(item.entry) { + revealed[item.candidate][field] = struct{}{} + } + kept = append(kept, item.entry) + } + return kept, true, nil + } + complete := true + for _, step := range []struct { + entries []rankedEntry + target *[]Entry + }{{ranked.main, &result.Main}, {ranked.near, &result.Near}, {ranked.unconfirmed, &result.Unconfirmed}} { + if !complete { + break + } + kept, ok, err := charge(step.entries) + if err != nil { + return Result{}, err + } + *step.target, complete = kept, ok + } + if !complete { + result.Truncated = true + } + for _, candidateID := range order { + if err := views.Record(ctx, candidateID, orderedFields(revealed[candidateID])); err != nil { + return Result{}, fmt.Errorf("matching.Service.reveal - record card view: %w", err) + } + } + return result, nil +} + +// entryFields lists the card fields that an entry actually shows, so the +// candidate's history names what the search returned about them. +func entryFields(entry Entry) []domain.CardField { + var fields []domain.CardField + if entry.Category != nil { + fields = append(fields, domain.CardFieldCategories) + } + if len(entry.PublicContext.Stack) > 0 { + fields = append(fields, domain.CardFieldStack) + } + if entry.PublicContext.ExperienceBand != nil { + fields = append(fields, domain.CardFieldExperience) + } + // An unconfirmed entry exists only because the self-assessment is published. + if entry.Category == nil || entry.DeclaredGrade != nil { + fields = append(fields, domain.CardFieldSelfAssessment) + } + if len(entry.PublicContext.WorkFormats) > 0 { + fields = append(fields, domain.CardFieldWorkFormats) + } + if entry.PublicContext.SalaryCompatibility != nil { + fields = append(fields, domain.CardFieldSalaryCompatibility) + } + return fields +} + +func orderedFields(set map[domain.CardField]struct{}) []domain.CardField { + fields := make([]domain.CardField, 0, len(set)) + for _, field := range []domain.CardField{ + domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, + domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility, + } { + if _, shown := set[field]; shown { + fields = append(fields, field) + } + } + return fields +} + +// effectiveSpecialization combines the filter with the specialization of the +// need. Two different specializations leave nothing to show. +func effectiveSpecialization(filter, need *domain.SpecializationCode) (*domain.SpecializationCode, bool) { + switch { + case filter != nil && need != nil && *filter != *need: + return nil, false + case filter != nil: + return filter, true + default: + return need, true + } +} + +// factSources turns the permitted assessment facts into evidence. Each fact is +// the one measurement that supports a confirmed category, tagged with that +// category's specialization. +func factSources(facts []domain.EvidenceOrganizationFact) []evidenceSource { + sources := make([]evidenceSource, 0, len(facts)) + for _, fact := range facts { + input := fact.Input() + sources = append(sources, evidenceSource{ + code: string(input.Skill), trust: input.Trust, attribution: domain.EvidenceAttributionPersonal, measured: true, + }) + } + return sources +} + +func scoreEntry( + entry candidateEntry, + policy domain.MatchingPolicy, + basis searchBasis, + requestedFormats []domain.QuestionnaireWorkFormat, + facts []evidenceSource, + reachedCohorts map[outbound.CategoryKey]bool, +) rankedEntry { + evidence := make([]evidenceSource, 0, len(entry.card.Skills)+len(facts)) + for _, skill := range entry.card.Skills { + evidence = append(evidence, evidenceSource{code: string(skill), trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal}) + } + confirmed := entry.category != nil + if confirmed { + for _, fact := range facts { + // A fact supports only its own specialization's category. + if fact.code == string(entry.specialization) { + evidence = append(evidence, fact) + } + } + } + computed := computeScores(scoreInput{confirmed: confirmed, policy: policy, skills: basis.skills, evidence: evidence}) + context := PublicContext{ + ExperienceBand: entry.card.ExperienceBand, SalaryCompatibility: entry.card.SalaryCompatibility, + } + if len(entry.card.Skills) > 0 { + context.Stack = slices.Clone(entry.card.Skills) + } + if len(entry.card.WorkFormats) > 0 { + context.WorkFormats = slices.Clone(entry.card.WorkFormats) + } + summary, flags := explain(explanationInput{ + confirmed: confirmed, declaredGrade: entry.declaredGrade, policy: policy, scores: computed, context: context, + requestedFormats: requestedFormats, needDomainConfirmed: basis.needDomainConfirmed, + percentileReason: percentileReason(entry, reachedCohorts), + }) + components := Components{Fit: microToFloat(computed.fit), Coverage: microToFloat(computed.coverage)} + if confirmed { + components.Domain = microToFloat(computed.domain) + components.Semantics = microToFloat(computed.semantics) + components.Competition = microToFloat(computed.competition) + components.Freshness = microToFloat(computed.freshness) + components.Responsiveness = microToFloat(computed.responsive) + components.RankScore = microToFloat(computed.rank) + } + return rankedEntry{ + entry: Entry{ + CandidateHandle: entry.card.Pseudonym, Specialization: entry.specialization, + DeclaredGrade: entry.declaredGrade, Category: entry.category, + PublicContext: context, EvidenceSummary: summary, Components: components, UnknownFlags: flags, + }, + candidate: entry.candidateID, fit: computed.fit, coverage: computed.coverage, rank: computed.rank, + near: confirmed && computed.belongsToNearGroup(policy), + } +} + +// compareByRank orders a confirmed group: S descending, then coverage +// descending, then the internal identifier ascending. The identifier is the +// stable tie-breaker and never leaves the server; the specialization only +// separates two entries of the same candidate. +func compareByRank(left, right rankedEntry) int { + return cmp.Or( + cmp.Compare(right.rank, left.rank), + cmp.Compare(right.coverage, left.coverage), + slices.Compare(left.candidate[:], right.candidate[:]), + strings.Compare(string(left.entry.Specialization), string(right.entry.Specialization)), + ) +} + +// compareByFit orders the unconfirmed group: Fit descending, then coverage +// descending, then the internal identifier ascending. It never uses a +// confirmed-profile score. +func compareByFit(left, right rankedEntry) int { + return cmp.Or( + cmp.Compare(right.fit, left.fit), + cmp.Compare(right.coverage, left.coverage), + slices.Compare(left.candidate[:], right.candidate[:]), + strings.Compare(string(left.entry.Specialization), string(right.entry.Specialization)), + ) +} + +// sourceOf echoes the search basis. A bank search carries its normalized +// filters, so the result stays tied to what was asked. +func sourceOf(request Request) Source { + if request.Need != nil { + need := *request.Need + return Source{Need: &need} + } + filters := request.Filters + filters.Stack = slices.Clone(filters.Stack) + slices.Sort(filters.Stack) + if conditions := filters.Conditions; conditions != nil { + normalized := *conditions + normalized.WorkFormats = slices.Clone(conditions.WorkFormats) + slices.Sort(normalized.WorkFormats) + filters.Conditions = &normalized + } + return Source{Filters: filters} +} + +// percentileReason says why the percentile of a confirmed entry is null. +func percentileReason(entry candidateEntry, reachedCohorts map[outbound.CategoryKey]bool) UnknownReason { + if entry.category != nil && reachedCohorts[outbound.CategoryKey{Specialization: entry.category.Specialization, Grade: entry.category.Grade}] { + return ReasonPercentileNotComputed + } + return ReasonCohortBelow30 +} diff --git a/backend/internal/usecase/matching/types.go b/backend/internal/usecase/matching/types.go new file mode 100644 index 0000000..fd04ba1 --- /dev/null +++ b/backend/internal/usecase/matching/types.go @@ -0,0 +1,187 @@ +package matching + +import ( + "errors" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrForbidden reports an actor that may not search: not a verified + // employer, or not the active owner of the organization. + ErrForbidden = errors.New("match search is forbidden") + // ErrNeedNotFound reports a need of another organization, an unknown need, + // or a requirements version that no confirmed-requirements change created. + ErrNeedNotFound = errors.New("match search need snapshot not found") + // ErrPolicyUnavailable reports an effective product policy without the + // matching section. The search fails closed instead of using defaults. + ErrPolicyUnavailable = errors.New("match search policy is unavailable") + // ErrServiceMissing reports an incomplete service wiring. + ErrServiceMissing = errors.New("match search service is unavailable") +) + +// NeedReference selects one immutable confirmed-requirements snapshot. +type NeedReference struct { + NeedID uuid.UUID + RequirementsVersion int64 +} + +// GradeFilter is a confirmed category that a filter asks for. +type GradeFilter struct { + Specialization domain.SpecializationCode + Grade domain.GradeCode +} + +// Conditions filter by the safe, coarse card conditions. An unknown card value +// never satisfies a condition. +type Conditions struct { + WorkFormats []domain.QuestionnaireWorkFormat + SalaryCompatibility *domain.CandidateViewSalaryCompatibility +} + +// Filters narrow the organization-visible bank. A nil field is no filter. +type Filters struct { + Specialization *domain.SpecializationCode + ConfirmedGrade *domain.GradeCode + ConfirmedCategory *GradeFilter + ConfirmationStatus *domain.CandidateViewConfirmationStatus + DeclaredGrade *domain.GradeCode + Stack []domain.CandidateViewSkillCode + Conditions *Conditions +} + +// Request is one search. The actor and the organization come from the +// authenticated session and the path, never from the body. +type Request struct { + ActorID uuid.UUID + OrganizationID uuid.UUID + // Need selects a requirements snapshot. It is nil for a search of the + // whole organization-visible bank. + Need *NeedReference + Filters Filters +} + +// Source is the search basis that the result carries. +type Source struct { + Need *NeedReference + // Filters are the normalized bank filters; they are set for a bank search. + Filters Filters +} + +// EvidenceCode names a templated explanation item. +type EvidenceCode string + +const ( + EvidenceConfirmedCategory EvidenceCode = "confirmed_category" + EvidenceRequiredSkill EvidenceCode = "required_skill_evidence" + EvidenceDesiredSkill EvidenceCode = "desired_skill_evidence" + EvidenceWorkConditionsMatch EvidenceCode = "work_conditions_match" + EvidenceSalaryCompatibility EvidenceCode = "salary_compatibility" + EvidenceDeclaredGrade EvidenceCode = "declared_grade" +) + +// EvidenceState is the verdict of one explanation item. +type EvidenceState string + +const ( + EvidenceStateSupports EvidenceState = "supports" + EvidenceStatePartial EvidenceState = "partial" + EvidenceStateGap EvidenceState = "gap" + EvidenceStateDeclaredOnly EvidenceState = "declared_only" +) + +// EvidenceItem is one bounded explanation item without free text. +type EvidenceItem struct { + Code EvidenceCode + State EvidenceState +} + +// UnknownComponent names a component whose value is unknown. +type UnknownComponent string + +const ( + UnknownSemantics UnknownComponent = "semantics" + UnknownPercentile UnknownComponent = "percentile" + UnknownAssessment UnknownComponent = "assessment" + UnknownFreshness UnknownComponent = "freshness" + UnknownResponsiveness UnknownComponent = "responsiveness" + UnknownExperienceBand UnknownComponent = "experience_band" + UnknownWorkFormats UnknownComponent = "work_formats" + UnknownSalaryCompatibility UnknownComponent = "salary_compatibility" + UnknownDomain UnknownComponent = "domain" +) + +// UnknownReason is the bounded reason of an unknown component. +type UnknownReason string + +const ( + ReasonMLUnavailable UnknownReason = "ml_unavailable" + ReasonCohortBelow30 UnknownReason = "cohort_below_30" + ReasonNoConfirmationForSpecialization UnknownReason = "no_confirmation_for_specialization" + ReasonNotInPublicCard UnknownReason = "not_in_public_card" + ReasonNeedFieldUnconfirmed UnknownReason = "need_field_unconfirmed" + ReasonNoFreshnessHistory UnknownReason = "no_freshness_history" + ReasonNoResponseHistory UnknownReason = "no_response_history" + ReasonPercentileNotComputed UnknownReason = "percentile_not_computed" +) + +// UnknownFlag reports one unavailable component and why. +type UnknownFlag struct { + Component UnknownComponent + Reason UnknownReason +} + +// PublicContext is the safe part of the anonymous card that a result shows. A +// nil or empty value means the card does not show it. +type PublicContext struct { + Stack []domain.CandidateViewSkillCode + ExperienceBand *domain.CandidateExperienceBand + WorkFormats []domain.QuestionnaireWorkFormat + SalaryCompatibility *domain.CandidateViewSalaryCompatibility +} + +// Components are the computed scores of an entry, each rounded to six +// decimals. An unconfirmed entry has only Fit and Coverage: it has no theta, +// T, P, percentile, or rank score. +type Components struct { + Fit float64 + Coverage float64 + Domain float64 + Semantics float64 + Competition float64 + Freshness float64 + Responsiveness float64 + RankScore float64 + // Percentile is nil while there are fewer comparable real candidates than + // the policy needs, and then T is the neutral value. + Percentile *float64 +} + +// Entry is one candidate specialization of a result. The handle is the +// organization-scoped pseudonym; no account or profile identifier leaves. +type Entry struct { + CandidateHandle string + Specialization domain.SpecializationCode + DeclaredGrade *domain.GradeCode + // Category and Strength are set only for a confirmed entry. + Category *domain.CandidateViewCategory + PublicContext PublicContext + EvidenceSummary []EvidenceItem + Components Components + UnknownFlags []UnknownFlag +} + +// Result holds the three separate groups. Their scores are never merged into +// one scale. +type Result struct { + Source Source + Main []Entry + Near []Entry + Unconfirmed []Entry + // Truncated is true when the output is not the whole ranked bank: a group + // exceeded the policy bound, or the card-view allowance of the organization + // ended. It carries no count. + Truncated bool +} diff --git a/backend/internal/usecase/notification/inbox.go b/backend/internal/usecase/notification/inbox.go index 63f500c..7d2e294 100644 --- a/backend/internal/usecase/notification/inbox.go +++ b/backend/internal/usecase/notification/inbox.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "net/url" + "regexp" "strings" "time" "unicode/utf8" @@ -17,6 +17,13 @@ import ( var ( ErrInboxUnavailable = errors.New("notification inbox is unavailable") + // ErrInboxForbidden reports an account that may not use the requested + // cabinet inbox: a missing or unverified account, or an account of the + // other scenario. + ErrInboxForbidden = errors.New("notification inbox is forbidden") + // ErrInboxEmailNotVerified reports an employer account whose email is not + // confirmed; the organization operations answer it as email_not_verified. + ErrInboxEmailNotVerified = errors.New("notification inbox requires a confirmed email") // ErrInboxContentUnavailable means the referenced source is missing or its // current visibility no longer permits the original presentation. ErrInboxContentUnavailable = errors.New("notification content is unavailable") @@ -27,6 +34,12 @@ const ( maxInboxSummaryRunes = 500 ) +// inboxLinkPathPattern is the shape of a content link: a same-origin +// absolute path of at most 256 characters from a narrow alphabet, so it has +// no query, fragment, escape, dot segment, or backslash. The public contract +// states the same pattern. +var inboxLinkPathPattern = regexp.MustCompile(`^/[A-Za-z0-9/_-]{0,255}$`) + // InboxContent is resolved from the current source at read time. It is never // written to notification_inbox_events. type InboxContent struct { @@ -66,26 +79,15 @@ func validInboxText(value string, maxRunes int, allowNewlines bool) bool { } func validInboxLinkPath(value string) bool { - if !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") || strings.ContainsAny(value, "\\?#%") { - return false - } - parsed, err := url.ParseRequestURI(value) - if err != nil || parsed.IsAbs() || parsed.Host != "" || parsed.Path != value { - return false - } - for _, segment := range strings.Split(value, "/") { - if segment == "." || segment == ".." { - return false - } - } - return true + return inboxLinkPathPattern.MatchString(value) && !strings.HasPrefix(value, "//") } // InboxContentResolver reads the current source under its current visibility -// rules. It must return ErrInboxContentUnavailable when that source is gone or -// no longer safe to present. +// rules, inside the read transaction that also authorized the viewer. It must +// return ErrInboxContentUnavailable when that source is gone or no longer +// safe to present to the recipient. type InboxContentResolver interface { - Resolve(ctx context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) + Resolve(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) } // InboxItem pairs immutable event metadata with content resolved for this @@ -96,9 +98,11 @@ type InboxItem struct { ContentUnavailable bool } -// InboxListRequest is built from the authenticated recipient and optional -// organization context. The organization ID filters items but grants no -// authorization by itself. +// InboxListRequest is built from the authenticated recipient. A nil +// OrganizationID is the candidate cabinet: every organization that sent to +// the recipient. A set OrganizationID is the employer cabinet of that +// organization and requires the recipient's current active membership. The +// organization ID filters items but is never authorization by itself. type InboxListRequest struct { RecipientUserID uuid.UUID OrganizationID *uuid.UUID @@ -106,111 +110,163 @@ type InboxListRequest struct { Limit int32 } +// InboxMarkReadRequest names one inbox item in the same cabinet scope as +// InboxListRequest. +type InboxMarkReadRequest struct { + RecipientUserID uuid.UUID + OrganizationID *uuid.UUID + EventID uuid.UUID +} + type InboxPage struct { Items []InboxItem HasMore bool } -// InboxService coordinates recipient-scoped storage and read-time content -// resolution. A caller for employer-scoped notices must authorize current -// membership before constructing the request; invitation recipients need not -// belong to the sender's organization. +// InboxService lists and marks the inbox of the authenticated recipient. +// Every operation authorizes the recipient for the requested cabinet and +// reads the inbox in one transaction, so a membership revoked a moment ago +// cannot authorize a later read. The inbox stores references only: the text +// of an item is resolved from its current source at each list, so a hiding, a +// revoked membership, or a withdrawn source removes the content from every +// later read. Mail delivery is a separate concern: an item exists whether or +// not any email was sent, and an email failure never blocks it. type InboxService struct { - repository outbound.NotificationInboxRepository + transactor outbound.Transactor resolver InboxContentResolver clock func() time.Time } func NewInboxService( - repository outbound.NotificationInboxRepository, + transactor outbound.Transactor, resolver InboxContentResolver, clock func() time.Time, ) (*InboxService, error) { - if repository == nil || resolver == nil || clock == nil { - return nil, fmt.Errorf("notification.NewInboxService - repository, resolver, and clock are required: %w", ErrInboxUnavailable) + if transactor == nil || resolver == nil || clock == nil { + return nil, fmt.Errorf("notification.NewInboxService - transactor, resolver, and clock are required: %w", ErrInboxUnavailable) } - return &InboxService{repository: repository, resolver: resolver, clock: clock}, nil + return &InboxService{transactor: transactor, resolver: resolver, clock: clock}, nil } -// StoreInvitationDelivered stores the recipient-specific reference to an -// invitation-delivered event. A transaction-bound repository lets a future -// event handler commit this row with the invitation state and consumer marker. -func (service *InboxService) StoreInvitationDelivered( - ctx context.Context, - input domain.NotificationInboxEntryInput, -) (bool, error) { - const location = "InboxService.StoreInvitationDelivered" - entry, err := domain.NewNotificationInboxEntry(input) - if err != nil { - return false, err - } - created, err := service.repository.Store(ctx, entry) - if err != nil { - return false, fmt.Errorf("%s - store event: %w", location, err) - } - return created, nil -} - -// List resolves each stored reference against its current source. A source -// that is missing or no longer visible is returned without source content. +// List returns one newest-first page and resolves each stored reference +// against its current source. A source that is missing or no longer visible +// is returned without content. func (service *InboxService) List(ctx context.Context, request InboxListRequest) (InboxPage, error) { const location = "InboxService.List" if err := validateInboxListRequest(request); err != nil { return InboxPage{}, err } - stored, err := service.repository.List(ctx, outbound.NotificationInboxListQuery{ - RecipientUserID: request.RecipientUserID, - OrganizationID: request.OrganizationID, - After: request.After, - Limit: request.Limit, + var page InboxPage + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil { + return err + } + stored, err := unit.NotificationInbox().List(ctx, outbound.NotificationInboxListQuery{ + RecipientUserID: request.RecipientUserID, + OrganizationID: request.OrganizationID, + After: request.After, + Limit: request.Limit, + }) + if err != nil { + return fmt.Errorf("%s - list recipient events: %w", location, err) + } + resolved := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore} + for _, entry := range stored.Items { + if !inboxEntryMatchesRequest(entry, request) { + return fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable) + } + item := InboxItem{Entry: entry} + content, resolveErr := service.resolver.Resolve(ctx, unit, entry) + switch { + case errors.Is(resolveErr, ErrInboxContentUnavailable): + item.ContentUnavailable = true + case resolveErr != nil: + return fmt.Errorf("%s - resolve current event content: %w", location, resolveErr) + default: + item.Content = &content + } + resolved.Items = append(resolved.Items, item) + } + page = resolved + return nil }) if err != nil { - return InboxPage{}, fmt.Errorf("%s - list recipient events: %w", location, err) - } - page := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore} - for _, entry := range stored.Items { - if !inboxEntryMatchesRequest(entry, request) { - return InboxPage{}, fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable) - } - item := InboxItem{Entry: entry} - content, resolveErr := service.resolver.Resolve(ctx, entry) - switch { - case errors.Is(resolveErr, ErrInboxContentUnavailable): - item.ContentUnavailable = true - case resolveErr != nil: - return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr) - default: - item.Content = &content - } - page.Items = append(page.Items, item) + return InboxPage{}, fmt.Errorf("%s - run transaction: %w", location, err) } return page, nil } -// MarkRead persists the first read timestamp for one recipient and exact -// organization context. The source is not read and no private content is -// returned by this command. -func (service *InboxService) MarkRead( - ctx context.Context, - recipientUserID uuid.UUID, - organizationID uuid.UUID, - eventID uuid.UUID, -) (domain.NotificationInboxEntry, error) { +// MarkRead persists the first read timestamp of one item of the recipient. A +// repeat keeps the first timestamp. The source is not read and no content is +// returned. An item of another recipient, of another organization context, +// or an unknown item all return outbound.ErrNotificationInboxEntryNotFound. +func (service *InboxService) MarkRead(ctx context.Context, request InboxMarkReadRequest) (domain.NotificationInboxEntry, error) { const location = "InboxService.MarkRead" - if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil { - return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, and event IDs are required: %w", location, ErrInboxUnavailable) + if request.RecipientUserID == uuid.Nil || request.EventID == uuid.Nil || + (request.OrganizationID != nil && *request.OrganizationID == uuid.Nil) { + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient and event IDs are required: %w", location, ErrInboxUnavailable) } at := service.clock() if at.IsZero() { return domain.NotificationInboxEntry{}, fmt.Errorf("%s - clock returned zero: %w", location, ErrInboxUnavailable) } - entry, err := service.repository.MarkRead(ctx, recipientUserID, organizationID, eventID, at) + var entry domain.NotificationInboxEntry + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil { + return err + } + marked, err := unit.NotificationInbox().MarkRead(ctx, request.RecipientUserID, request.OrganizationID, request.EventID, at) + if err != nil { + return fmt.Errorf("%s - mark event read: %w", location, err) + } + entry = marked + return nil + }) if err != nil { - return domain.NotificationInboxEntry{}, fmt.Errorf("%s - mark event read: %w", location, err) + return domain.NotificationInboxEntry{}, fmt.Errorf("%s - run transaction: %w", location, err) } return entry, nil } +// authorizeInboxViewer checks the account against the requested cabinet. The +// candidate cabinet needs a verified candidate account. The employer cabinet +// needs an employer account with a verified email (otherwise +// ErrInboxEmailNotVerified, like the other organization operations) and an +// active membership of any role in the named organization. The membership is +// locked FOR SHARE until the transaction ends, like the card reads, so a +// revocation cannot commit between this check and the read that follows. A +// missing or inactive membership returns outbound.ErrOrganizationNotFound, so +// an organization that exists cannot be told from one that does not. +func authorizeInboxViewer(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, organizationID *uuid.UUID) error { + const location = "notification.authorizeInboxViewer" + user, err := unit.Users().GetByID(ctx, userID) + if errors.Is(err, outbound.ErrUserNotFound) { + return fmt.Errorf("%s - account does not exist: %w", location, ErrInboxForbidden) + } + if err != nil { + return fmt.Errorf("%s - read account: %w", location, err) + } + if organizationID == nil { + if user.Scenario != domain.ScenarioCandidate || !user.EmailVerified() { + return fmt.Errorf("%s - the candidate inbox needs a verified candidate account: %w", location, ErrInboxForbidden) + } + return nil + } + if user.Scenario != domain.ScenarioEmployer { + return fmt.Errorf("%s - the organization inbox needs an employer account: %w", location, ErrInboxForbidden) + } + if !user.EmailVerified() { + return fmt.Errorf("%s - email is not verified: %w", location, ErrInboxEmailNotVerified) + } + if _, err := unit.Organizations().LockActiveMembership(ctx, *organizationID, userID); err != nil { + if errors.Is(err, outbound.ErrOrganizationNotFound) { + return fmt.Errorf("%s - no active membership: %w", location, outbound.ErrOrganizationNotFound) + } + return fmt.Errorf("%s - lock active membership: %w", location, err) + } + return nil +} + func validateInboxListRequest(request InboxListRequest) error { const location = "notification.validateInboxListRequest" if request.RecipientUserID == uuid.Nil || request.Limit < 1 || request.Limit > outbound.MaxNotificationInboxPageSize { diff --git a/backend/internal/usecase/notification/inbox_content.go b/backend/internal/usecase/notification/inbox_content.go new file mode 100644 index 0000000..ae55d2b --- /dev/null +++ b/backend/internal/usecase/notification/inbox_content.go @@ -0,0 +1,82 @@ +package notification + +import ( + "context" + "errors" + "fmt" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// InboxSourceResolver resolves the content of the entries of one source +// type from the current state of that source, for the entry's recipient. It +// returns ErrInboxContentUnavailable when the source is gone or the recipient +// may not see it now. +type InboxSourceResolver func(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) + +// sourceContentResolver dispatches by source type. A source type without a +// resolver is unavailable, never guessed, so a new event type shows nothing +// until its resolver is registered. +type sourceContentResolver map[domain.NotificationInboxSourceType]InboxSourceResolver + +var _ InboxContentResolver = sourceContentResolver(nil) + +// NewInboxContentResolver combines the resolvers of the source types. +func NewInboxContentResolver(resolvers map[domain.NotificationInboxSourceType]InboxSourceResolver) InboxContentResolver { + return sourceContentResolver(resolvers) +} + +// DefaultInboxSourceResolvers lists the source types that have a resolver +// today. The synthetic notice resolver is registered only when +// syntheticEnabled is true (development and browser-test stands); a stored +// synthetic row is then listed without content. The invitation module adds +// domain.NotificationInboxSourceInvitation with its own resolver; the +// handler, the table, and the API need no change. +func DefaultInboxSourceResolvers(syntheticEnabled bool) map[domain.NotificationInboxSourceType]InboxSourceResolver { + resolvers := map[domain.NotificationInboxSourceType]InboxSourceResolver{} + if syntheticEnabled { + resolvers[domain.NotificationInboxSourceOrganization] = ResolveSyntheticNotice + } + return resolvers +} + +func (resolvers sourceContentResolver) Resolve( + ctx context.Context, + unit outbound.UnitOfWork, + entry domain.NotificationInboxEntry, +) (InboxContent, error) { + resolve, ok := resolvers[entry.SourceType()] + if !ok { + return InboxContent{}, ErrInboxContentUnavailable + } + return resolve(ctx, unit, entry) +} + +const ( + syntheticNoticeTitle = "Тестовое уведомление" + // syntheticNoticeSummary has one verb slot for the organization name. + syntheticNoticeSummary = "Организация «%s» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий." +) + +// ResolveSyntheticNotice resolves a synthetic notice. The text is fixed and +// names the sending organization by its current name, which is read under the +// recipient's current standing: a candidate sees it until they hide the +// organization, an employer while they are an active member. Afterwards the +// entry stays in the list without content. +func ResolveSyntheticNotice(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) { + const location = "notification.ResolveSyntheticNotice" + name, err := unit.NotificationInbox().OrganizationNameForRecipient(ctx, entry.RecipientUserID(), entry.SourceID()) + if errors.Is(err, outbound.ErrNotificationInboxSourceNotVisible) { + return InboxContent{}, ErrInboxContentUnavailable + } + if err != nil { + return InboxContent{}, fmt.Errorf("%s - read sender organization: %w", location, err) + } + content, err := NewInboxContent(syntheticNoticeTitle, fmt.Sprintf(syntheticNoticeSummary, name), "") + if err != nil { + // A stored name that does not fit the presentation is not shown. + return InboxContent{}, ErrInboxContentUnavailable + } + return content, nil +} diff --git a/backend/internal/usecase/notification/inbox_handler.go b/backend/internal/usecase/notification/inbox_handler.go new file mode 100644 index 0000000..75a6098 --- /dev/null +++ b/backend/internal/usecase/notification/inbox_handler.go @@ -0,0 +1,213 @@ +package notification + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +// InboxConsumerName names the consumer group and scopes deduplication of the +// inbox handler. Renaming it makes the consumer process every retained event +// again; the inbox key keeps the rows unique, but do not rename it lightly. +const InboxConsumerName = "notification_inbox" + +// inboxPayloadSchemaVersion is the only supported schema version of the +// inbox events. Version 1 is inboxEventPayload. +const inboxPayloadSchemaVersion = 1 + +// inboxEventPayload is version 1 of the payload of every event the inbox +// stores. It names the recipient and the organization context and nothing +// else: the text is resolved from the source when the inbox is read, so +// neither the outbox nor the event bus keeps content that could outlive a +// revocation. +type inboxEventPayload struct { + RecipientUserID uuid.UUID `json:"recipient_user_id"` + OrganizationID uuid.UUID `json:"organization_id"` +} + +// inboxProjection describes how one event type becomes an inbox row: the +// aggregate the event must come from and where the content source is. +type inboxProjection struct { + aggregateType string + // source returns the source record of the content for a decoded event. + source func(event outbound.ConsumedEvent, payload inboxEventPayload) uuid.UUID +} + +// inboxProjections is the allowlist of events the inbox stores. A producer +// plugs in by appending an event of one of these types in its own +// transaction; adding a type here also needs the same pair in +// domain.NotificationInboxSourceFor, the CHECK constraint of the table, and a +// content resolver for its source type. +// +// - invitation.delivered: the aggregate is the invitation, which is also +// the source. Invitations are a later module; the projection and the +// payload contract are fixed here so that it needs no inbox change. +// - notification.synthetic_delivered: a synthetic event for tests and +// probes. Its aggregate is a one-off notice and its source is the +// organization of the payload. +var inboxProjections = map[domain.NotificationInboxEventType]inboxProjection{ + domain.NotificationInboxInvitationDelivered: { + aggregateType: "invitation", + source: func(event outbound.ConsumedEvent, _ inboxEventPayload) uuid.UUID { + return event.AggregateID + }, + }, + domain.NotificationInboxSyntheticDelivered: { + aggregateType: SyntheticNoticeAggregateType, + source: func(_ outbound.ConsumedEvent, payload inboxEventPayload) uuid.UUID { + return payload.OrganizationID + }, + }, +} + +// SyntheticNoticeAggregateType is the aggregate type of a synthetic inbox +// event. Every notice is its own aggregate at version 1. +const SyntheticNoticeAggregateType = "synthetic_notice" + +// SyntheticNoticeAggregateVersion is the version of a synthetic notice. +const SyntheticNoticeAggregateVersion = 1 + +// SyntheticNoticeEventPayload builds the version 1 payload of a synthetic +// inbox event for the outbox. It is the single writer of the contract that +// the inbox handler reads. +func SyntheticNoticeEventPayload(recipientUserID, organizationID uuid.UUID) ([]byte, error) { + payload, err := json.Marshal(inboxEventPayload{RecipientUserID: recipientUserID, OrganizationID: organizationID}) + if err != nil { + return nil, fmt.Errorf("notification.SyntheticNoticeEventPayload - encode payload: %w", err) + } + return payload, nil +} + +// InboxHandler stores one inbox row for each inbox event, in the consumer +// transaction that records the event as processed. The row key is the +// recipient and the event ID, so a repeated delivery, a replayed dead letter, +// or a renamed consumer still stores one row, and a redelivery that changed +// the immutable metadata is refused instead of overwritten. +// +// The inbox is the in-platform delivery state of a notification: a stored row +// means delivered. Nothing here reads mail state, so an unverified address, a +// missing mail provider, or a failed email never blocks a notification. +type InboxHandler struct { + logger *slog.Logger + syntheticEnabled bool +} + +var _ inbound.EventHandler = (*InboxHandler)(nil) + +// NewInboxHandler creates the handler. The synthetic event type is handled +// only when syntheticEnabled is true, which a development or browser-test +// stand sets; otherwise such an event is acknowledged and ignored. +func NewInboxHandler(logger *slog.Logger, syntheticEnabled bool) *InboxHandler { + return &InboxHandler{logger: logger, syntheticEnabled: syntheticEnabled} +} + +func (*InboxHandler) ConsumerName() string { return InboxConsumerName } + +func (handler *InboxHandler) Handles(eventType string) bool { + return handler.handles(domain.NotificationInboxEventType(eventType)) +} + +func (handler *InboxHandler) handles(eventType domain.NotificationInboxEventType) bool { + if eventType == domain.NotificationInboxSyntheticDelivered && !handler.syntheticEnabled { + return false + } + _, known := inboxProjections[eventType] + return known +} + +// Handle turns the event into an inbox row: +// +// - A payload or envelope that breaks the contract, a recipient or +// organization that does not exist, or an event ID that already holds +// different metadata is rejected for good (inbound.ErrEventRejected). +// - A recipient account that was deleted is skipped: its private inbox +// went with it. An account deleted between the check and the insert +// aborts the insert; the error is returned for a retry, and the retry +// finds the account gone and skips. +// - Storage errors, including a recipient that disappeared, are returned +// for a retry. +// +// Errors and logs carry event IDs, never the payload. +func (handler *InboxHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error { + const location = "InboxHandler.Handle" + eventType := domain.NotificationInboxEventType(event.EventType) + projection := inboxProjections[eventType] + if !handler.handles(eventType) { + return fmt.Errorf("%s - event type is not an inbox event: %w", location, inbound.ErrEventRejected) + } + payload, err := decodeInboxPayload(event, projection) + if err != nil { + return err + } + if _, err := unit.Users().GetByID(ctx, payload.RecipientUserID); err != nil { + if errors.Is(err, outbound.ErrUserNotFound) { + handler.logger.InfoContext(ctx, "inbox event skipped because the recipient account does not exist", + slog.String("event_id", event.EventID.String())) + return nil + } + return fmt.Errorf("%s - read recipient account: %w", location, err) + } + sourceType, _ := domain.NotificationInboxSourceFor(eventType) + entry, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{ + EventID: event.EventID, + RecipientUserID: payload.RecipientUserID, + OrganizationID: payload.OrganizationID, + EventType: eventType, + SchemaVersion: event.SchemaVersion, + SourceType: sourceType, + SourceID: projection.source(event, payload), + OccurredAt: event.OccurredAt, + }) + if err != nil { + return fmt.Errorf("%s - build inbox entry: %w: %w", location, inbound.ErrEventRejected, err) + } + if _, err := unit.NotificationInbox().Store(ctx, entry); err != nil { + // A vanished recipient (ErrNotificationInboxRecipientMissing) is not + // the event's fault: it is retried and then skipped above. + if errors.Is(err, outbound.ErrNotificationInboxEventConflict) || errors.Is(err, outbound.ErrNotificationInboxReferenceMissing) { + return fmt.Errorf("%s - store inbox entry: %w: %w", location, inbound.ErrEventRejected, err) + } + return fmt.Errorf("%s - store inbox entry: %w", location, err) + } + return nil +} + +// decodeInboxPayload checks the envelope and the version 1 payload. Errors +// name the broken rule and never quote the payload. +func decodeInboxPayload(event outbound.ConsumedEvent, projection inboxProjection) (inboxEventPayload, error) { + const location = "notification.decodeInboxPayload" + rejected := func(reason string) error { + return fmt.Errorf("%s - %s: %w", location, reason, inbound.ErrEventRejected) + } + if event.SchemaVersion != inboxPayloadSchemaVersion { + return inboxEventPayload{}, rejected(fmt.Sprintf("schema version %d is not supported", event.SchemaVersion)) + } + if event.AggregateType != projection.aggregateType || event.AggregateID == uuid.Nil { + return inboxEventPayload{}, rejected("aggregate does not match the event type") + } + var payload inboxEventPayload + decoder := json.NewDecoder(bytes.NewReader(event.Payload)) + decoder.DisallowUnknownFields() + // The decoder error can quote a fragment of the payload, so it is not + // wrapped. A second value after the object is refused as well. + if err := decoder.Decode(&payload); err != nil { + return inboxEventPayload{}, rejected("payload is not a valid inbox event") + } + if _, err := decoder.Token(); !errors.Is(err, io.EOF) { + return inboxEventPayload{}, rejected("payload has data after the inbox event") + } + if payload.RecipientUserID == uuid.Nil || payload.OrganizationID == uuid.Nil { + return inboxEventPayload{}, rejected("recipient and organization IDs are required") + } + return payload, nil +} diff --git a/backend/internal/usecase/notification/inbox_handler_test.go b/backend/internal/usecase/notification/inbox_handler_test.go new file mode 100644 index 0000000..9a496dc --- /dev/null +++ b/backend/internal/usecase/notification/inbox_handler_test.go @@ -0,0 +1,201 @@ +package notification + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +func newInboxHandlerFixture(t *testing.T) (*InboxHandler, *inboxFixture, outbound.ConsumedEvent) { + t.Helper() + fixture := newInboxFixture(t, domain.ScenarioCandidate) + payload, err := SyntheticNoticeEventPayload(fixture.user.ID, fixture.organizationID) + if err != nil { + t.Fatalf("SyntheticNoticeEventPayload() error = %v", err) + } + event := outbound.ConsumedEvent{ + EventID: uuid.New(), EventType: string(domain.NotificationInboxSyntheticDelivered), SchemaVersion: 1, + AggregateType: SyntheticNoticeAggregateType, AggregateID: uuid.New(), AggregateVersion: SyntheticNoticeAggregateVersion, + OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), Payload: payload, + } + return NewInboxHandler(slog.New(slog.DiscardHandler), true), fixture, event +} + +func TestInboxHandlerStoresOneRowForARepeatedEvent(t *testing.T) { + t.Parallel() + + handler, fixture, event := newInboxHandlerFixture(t) + if !handler.Handles(event.EventType) || handler.Handles("notification.mail_requested") { + t.Fatal("Handles() must accept inbox events only") + } + for range 2 { + if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil { + t.Fatalf("Handle() error = %v", err) + } + } + if len(fixture.repository.entries) != 1 { + t.Fatalf("stored rows = %d, want one for a repeated event ID", len(fixture.repository.entries)) + } + entry := fixture.repository.entries[0] + if entry.EventID() != event.EventID || entry.RecipientUserID() != fixture.user.ID || + entry.OrganizationID() != fixture.organizationID || entry.SourceID() != fixture.organizationID || + entry.SourceType() != domain.NotificationInboxSourceOrganization { + t.Fatalf("stored entry = %+v, want the references of the event", entry) + } + if _, isRead := entry.ReadAt(); isRead { + t.Fatal("a delivered row starts as read") + } +} + +func TestInboxHandlerRejectsEventsThatBreakTheContract(t *testing.T) { + t.Parallel() + + for _, test := range []struct { + name string + mutate func(*outbound.ConsumedEvent, *inboxFixture) + }{ + {name: "schema version", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.SchemaVersion = 2 }}, + {name: "aggregate type", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.AggregateType = "mail_request" }}, + {name: "unknown field", mutate: func(event *outbound.ConsumedEvent, fixture *inboxFixture) { + event.Payload = json.RawMessage(`{"recipient_user_id":"` + fixture.user.ID.String() + `","organization_id":"` + fixture.organizationID.String() + `","email":"a@example.test"}`) + }}, + {name: "missing organization", mutate: func(event *outbound.ConsumedEvent, fixture *inboxFixture) { + event.Payload = json.RawMessage(`{"recipient_user_id":"` + fixture.user.ID.String() + `"}`) + }}, + {name: "not an object", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.Payload = json.RawMessage(`[]`) }}, + {name: "trailing data", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { + event.Payload = append(append(json.RawMessage{}, event.Payload...), []byte(` {}`)...) + }}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + handler, fixture, event := newInboxHandlerFixture(t) + test.mutate(&event, fixture) + err := handler.Handle(context.Background(), fixture.unit(), event) + if !errors.Is(err, inbound.ErrEventRejected) { + t.Fatalf("Handle() error = %v, want ErrEventRejected", err) + } + if len(fixture.repository.entries) != 0 { + t.Fatal("a rejected event stored a row") + } + }) + } +} + +func TestInboxHandlerRejectsAnEventIDReusedWithOtherMetadata(t *testing.T) { + t.Parallel() + + handler, fixture, event := newInboxHandlerFixture(t) + if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil { + t.Fatalf("Handle(first) error = %v", err) + } + event.OccurredAt = event.OccurredAt.Add(time.Hour) + if err := handler.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) { + t.Fatalf("Handle(changed replay) error = %v, want ErrEventRejected", err) + } +} + +func TestInboxHandlerSkipsADeletedRecipientAndKeepsStoreErrorsRetryable(t *testing.T) { + t.Parallel() + + handler, fixture, event := newInboxHandlerFixture(t) + delete(fixture.users, fixture.user.ID) + if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil { + t.Fatalf("Handle(deleted recipient) error = %v, want a skip", err) + } + if len(fixture.repository.entries) != 0 { + t.Fatal("a deleted recipient got a row") + } + + handler, fixture, event = newInboxHandlerFixture(t) + fixture.repository.storeErr = errors.New("connection reset") + err := handler.Handle(context.Background(), fixture.unit(), event) + if err == nil || errors.Is(err, inbound.ErrEventRejected) { + t.Fatalf("Handle(store failure) error = %v, want a retryable error", err) + } + fixture.repository.storeErr = outbound.ErrNotificationInboxReferenceMissing + if err := handler.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) { + t.Fatalf("Handle(missing organization) error = %v, want ErrEventRejected", err) + } + // A recipient deleted between the check and the insert is not the event's + // fault: the attempt is retried, and the retry skips the deleted account. + fixture.repository.storeErr = outbound.ErrNotificationInboxRecipientMissing + if err := handler.Handle(context.Background(), fixture.unit(), event); err == nil || errors.Is(err, inbound.ErrEventRejected) { + t.Fatalf("Handle(vanished recipient) error = %v, want a retryable error", err) + } + delete(fixture.users, fixture.user.ID) + if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil { + t.Fatalf("Handle(retry after the recipient vanished) error = %v, want a skip", err) + } +} + +func TestInboxHandlerPlugsInInvitationEventsWithTheSameContract(t *testing.T) { + t.Parallel() + + handler, fixture, _ := newInboxHandlerFixture(t) + invitationID := uuid.New() + payload, err := json.Marshal(inboxEventPayload{RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID}) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + event := outbound.ConsumedEvent{ + EventID: uuid.New(), EventType: string(domain.NotificationInboxInvitationDelivered), SchemaVersion: 1, + AggregateType: "invitation", AggregateID: invitationID, AggregateVersion: 3, + OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), Payload: payload, + } + if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil { + t.Fatalf("Handle(invitation.delivered) error = %v", err) + } + entry := fixture.repository.entries[0] + if entry.SourceType() != domain.NotificationInboxSourceInvitation || entry.SourceID() != invitationID { + t.Fatalf("invitation entry source = %s %s, want the invitation aggregate", entry.SourceType(), entry.SourceID()) + } +} + +func TestInboxHandlerStoresARowWhateverTheStateOfTheAddress(t *testing.T) { + t.Parallel() + + // A mail delivery skips an address that is not verified. The inbox is the + // delivery state inside the platform and reads no mail state. + handler, fixture, event := newInboxHandlerFixture(t) + unverified := fixture.user + unverified.EmailVerifiedAt = nil + fixture.users[unverified.ID] = unverified + if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil { + t.Fatalf("Handle(unverified address) error = %v", err) + } + if len(fixture.repository.entries) != 1 { + t.Fatalf("stored rows = %d, want 1: an address state must not block a notification", len(fixture.repository.entries)) + } +} + +func TestInboxHandlerIgnoresTheSyntheticEventWhileItIsSwitchedOff(t *testing.T) { + t.Parallel() + + _, fixture, event := newInboxHandlerFixture(t) + off := NewInboxHandler(slog.New(slog.DiscardHandler), false) + if off.Handles(event.EventType) { + t.Fatal("the synthetic event is handled while the switch is off") + } + if !off.Handles(string(domain.NotificationInboxInvitationDelivered)) { + t.Fatal("the invitation event must not depend on the synthetic switch") + } + if err := off.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) || len(fixture.repository.entries) != 0 { + t.Fatalf("Handle(synthetic, off) error = %v, rows = %d, want a rejection and no row", err, len(fixture.repository.entries)) + } + if _, ok := DefaultInboxSourceResolvers(false)[domain.NotificationInboxSourceOrganization]; ok { + t.Fatal("the synthetic resolver is registered while the switch is off") + } + if _, ok := DefaultInboxSourceResolvers(true)[domain.NotificationInboxSourceOrganization]; !ok { + t.Fatal("the synthetic resolver is missing while the switch is on") + } +} diff --git a/backend/internal/usecase/notification/inbox_test.go b/backend/internal/usecase/notification/inbox_test.go index ce5f809..36fd4ff 100644 --- a/backend/internal/usecase/notification/inbox_test.go +++ b/backend/internal/usecase/notification/inbox_test.go @@ -3,6 +3,7 @@ package notification import ( "context" "errors" + "strings" "testing" "time" @@ -12,78 +13,168 @@ import ( "lincodex/backend/internal/port/outbound" ) -func TestInboxServiceStoreInvitationDeliveredDeduplicatesRecipientEvent(t *testing.T) { - t.Parallel() - - repository := &memoryInboxRepository{} - service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now) - input := inboxTestEntryInput() - created, err := service.StoreInvitationDelivered(context.Background(), input) - if err != nil || !created { - t.Fatalf("StoreInvitationDelivered(first) = %t, %v, want true, nil", created, err) - } - created, err = service.StoreInvitationDelivered(context.Background(), input) - if err != nil || created { - t.Fatalf("StoreInvitationDelivered(retry) = %t, %v, want false, nil", created, err) - } - if len(repository.entries) != 1 { - t.Fatalf("stored entries = %d, want one", len(repository.entries)) - } - - changed := input - changed.SourceID = uuid.New() - if _, err := service.StoreInvitationDelivered(context.Background(), changed); !errors.Is(err, outbound.ErrNotificationInboxEventConflict) { - t.Fatalf("StoreInvitationDelivered(changed replay) error = %v, want ErrNotificationInboxEventConflict", err) - } -} - func TestInboxServiceListRechecksContentAndFallsBackSafely(t *testing.T) { t.Parallel() - first := mustInboxTestEntry(t, inboxTestEntryInput()) - secondInput := inboxTestEntryInput() - secondInput.RecipientUserID = first.RecipientUserID() - secondInput.OrganizationID = first.OrganizationID() - secondInput.EventID = uuid.New() - second := mustInboxTestEntry(t, secondInput) - wrongOrganizationInput := inboxTestEntryInput() - wrongOrganizationInput.RecipientUserID = first.RecipientUserID() - wrongOrganizationInput.EventID = uuid.New() - wrongOrganizationInput.OrganizationID = uuid.New() - wrongOrganization := mustInboxTestEntry(t, wrongOrganizationInput) - repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{first, second, wrongOrganization}} - resolver := &memoryInboxResolver{unavailable: map[uuid.UUID]bool{second.EventID(): true}} - service := newInboxTestService(t, repository, resolver, time.Now) - orgID := first.OrganizationID() - page, err := service.List(context.Background(), InboxListRequest{ - RecipientUserID: first.RecipientUserID(), OrganizationID: &orgID, Limit: 10, - }) + fixture := newInboxFixture(t, domain.ScenarioCandidate) + first := fixture.add(t, fixture.entryInput()) + second := fixture.add(t, fixture.entryInput()) + fixture.resolver.unavailable[second.EventID()] = true + otherRecipient := fixtureEntryInput(uuid.New(), fixture.organizationID) + fixture.add(t, otherRecipient) + + page, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10}) if err != nil { t.Fatalf("List() error = %v", err) } if len(page.Items) != 2 { - t.Fatalf("List() returned %d items, want 2", len(page.Items)) + t.Fatalf("List() returned %d items, want only the recipient's 2", len(page.Items)) } - if page.Items[0].Content == nil || page.Items[0].ContentUnavailable { - t.Fatalf("visible item = %+v, want current content", page.Items[0]) + byID := map[uuid.UUID]InboxItem{} + for _, item := range page.Items { + byID[item.Entry.EventID()] = item } - if page.Items[1].Content != nil || !page.Items[1].ContentUnavailable { - t.Fatalf("hidden item = %+v, want safe fallback without source content", page.Items[1]) + if item := byID[first.EventID()]; item.Content == nil || item.ContentUnavailable { + t.Fatalf("visible item = %+v, want current content", item) } - if resolver.calls != 2 { - t.Fatalf("resolver calls = %d, want one current visibility check per returned item", resolver.calls) + if item := byID[second.EventID()]; item.Content != nil || !item.ContentUnavailable { + t.Fatalf("hidden item = %+v, want safe fallback without source content", item) + } + if fixture.resolver.calls != 2 { + t.Fatalf("resolver calls = %d, want one current visibility check per returned item", fixture.resolver.calls) + } +} + +func TestInboxServiceAuthorizesTheCabinetInTheReadTransaction(t *testing.T) { + t.Parallel() + + t.Run("the candidate inbox refuses an employer", func(t *testing.T) { + t.Parallel() + fixture := newInboxFixture(t, domain.ScenarioEmployer) + _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10}) + if !errors.Is(err, ErrInboxForbidden) { + t.Fatalf("List(employer in the candidate cabinet) error = %v, want ErrInboxForbidden", err) + } + if fixture.repository.listCalls != 0 { + t.Fatal("the repository was read before the account was authorized") + } + }) + t.Run("the organization inbox refuses a candidate", func(t *testing.T) { + t.Parallel() + fixture := newInboxFixture(t, domain.ScenarioCandidate) + _, err := fixture.service.List(context.Background(), InboxListRequest{ + RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10, + }) + if !errors.Is(err, ErrInboxForbidden) { + t.Fatalf("List(candidate in the organization cabinet) error = %v, want ErrInboxForbidden", err) + } + }) + t.Run("an unknown or unverified account is refused", func(t *testing.T) { + t.Parallel() + fixture := newInboxFixture(t, domain.ScenarioCandidate) + if _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: uuid.New(), Limit: 10}); !errors.Is(err, ErrInboxForbidden) { + t.Fatalf("List(unknown account) error = %v, want ErrInboxForbidden", err) + } + fixture.user.EmailVerifiedAt = nil + fixture.users[fixture.user.ID] = fixture.user + if _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10}); !errors.Is(err, ErrInboxForbidden) { + t.Fatalf("List(unverified account) error = %v, want ErrInboxForbidden", err) + } + }) + t.Run("a revoked membership answers like an unknown organization", func(t *testing.T) { + t.Parallel() + fixture := newInboxFixture(t, domain.ScenarioEmployer) + fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateActive) + entry := fixture.add(t, fixture.entryInput()) + request := InboxListRequest{RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10} + page, err := fixture.service.List(context.Background(), request) + if err != nil || len(page.Items) != 1 { + t.Fatalf("List(active member) = %d items, %v, want 1 item", len(page.Items), err) + } + fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateRemoved) + if _, err := fixture.service.List(context.Background(), request); !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("List(revoked member) error = %v, want ErrOrganizationNotFound", err) + } + _, err = fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{ + RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: entry.EventID(), + }) + if !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("MarkRead(revoked member) error = %v, want ErrOrganizationNotFound", err) + } + if _, isRead := fixture.repository.entries[0].ReadAt(); isRead { + t.Fatal("a revoked member marked an item read") + } + unknown := uuid.New() + _, err = fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, OrganizationID: &unknown, Limit: 10}) + if !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("List(unknown organization) error = %v, want the same ErrOrganizationNotFound", err) + } + }) +} + +func TestInboxServiceOrganizationCabinetServesEveryRoleItsOwnItems(t *testing.T) { + t.Parallel() + + for _, role := range []domain.OrganizationRole{ + domain.OrganizationRoleOwner, domain.OrganizationRoleRecruiter, + domain.OrganizationRoleHiringManager, domain.OrganizationRoleTechnicalExpert, + } { + t.Run(string(role), func(t *testing.T) { + t.Parallel() + fixture := newInboxFixture(t, domain.ScenarioEmployer) + fixture.addMembership(t, role, domain.MembershipStateActive) + own := fixture.add(t, fixture.entryInput()) + otherMember := fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID)) + otherOrganization := fixture.add(t, fixtureEntryInput(fixture.user.ID, uuid.New())) + + page, err := fixture.service.List(context.Background(), InboxListRequest{ + RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10, + }) + if err != nil || len(page.Items) != 1 || page.Items[0].Entry.EventID() != own.EventID() { + t.Fatalf("List(%s) = %d items, %v, want only its own item", role, len(page.Items), err) + } + if fixture.locks == 0 { + t.Fatal("the membership was not locked for the read") + } + for _, foreign := range []domain.NotificationInboxEntry{otherMember, otherOrganization} { + _, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{ + RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: foreign.EventID(), + }) + if !errors.Is(err, outbound.ErrNotificationInboxEntryNotFound) { + t.Fatalf("MarkRead(%s, foreign item) error = %v, want ErrNotificationInboxEntryNotFound", role, err) + } + } + if _, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{ + RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: own.EventID(), + }); err != nil { + t.Fatalf("MarkRead(%s, own item) error = %v", role, err) + } + }) + } +} + +func TestInboxServiceOrganizationCabinetNeedsAConfirmedEmail(t *testing.T) { + t.Parallel() + + fixture := newInboxFixture(t, domain.ScenarioEmployer) + fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateActive) + fixture.user.EmailVerifiedAt = nil + fixture.users[fixture.user.ID] = fixture.user + _, err := fixture.service.List(context.Background(), InboxListRequest{ + RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10, + }) + if !errors.Is(err, ErrInboxEmailNotVerified) { + t.Fatalf("List(unverified employer) error = %v, want ErrInboxEmailNotVerified", err) } } func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T) { t.Parallel() - entry := mustInboxTestEntry(t, inboxTestEntryInput()) - repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}, ignoreListScope: true} - service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now) - _, err := service.List(context.Background(), InboxListRequest{ - RecipientUserID: uuid.New(), OrganizationID: uuidPointer(entry.OrganizationID()), Limit: 10, - }) + fixture := newInboxFixture(t, domain.ScenarioCandidate) + fixture.repository.ignoreListScope = true + fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID)) + _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10}) if !errors.Is(err, ErrInboxUnavailable) { t.Fatalf("List(out-of-scope repository row) error = %v, want ErrInboxUnavailable", err) } @@ -92,21 +183,17 @@ func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) { t.Parallel() - entry := mustInboxTestEntry(t, inboxTestEntryInput()) firstRead := time.Date(2026, time.October, 8, 13, 0, 0, 1000, time.UTC) - secondRead := firstRead.Add(time.Hour) clockCalls := 0 - clock := func() time.Time { + fixture := newInboxFixtureWithClock(t, domain.ScenarioCandidate, func() time.Time { clockCalls++ - if clockCalls == 1 { - return firstRead - } - return secondRead - } - repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}} - service := newInboxTestService(t, repository, &memoryInboxResolver{}, clock) + return firstRead.Add(time.Duration(clockCalls-1) * time.Hour) + }) + entry := fixture.add(t, fixture.entryInput()) for range 2 { - read, err := service.MarkRead(context.Background(), entry.RecipientUserID(), entry.OrganizationID(), entry.EventID()) + read, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{ + RecipientUserID: fixture.user.ID, EventID: entry.EventID(), + }) if err != nil { t.Fatalf("MarkRead() error = %v", err) } @@ -117,6 +204,22 @@ func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) { } } +func TestInboxServiceMarkReadRefusesAnotherRecipientsItem(t *testing.T) { + t.Parallel() + + fixture := newInboxFixture(t, domain.ScenarioCandidate) + foreign := fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID)) + _, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{ + RecipientUserID: fixture.user.ID, EventID: foreign.EventID(), + }) + if !errors.Is(err, outbound.ErrNotificationInboxEntryNotFound) { + t.Fatalf("MarkRead(foreign item) error = %v, want ErrNotificationInboxEntryNotFound", err) + } + if _, isRead := fixture.repository.entries[0].ReadAt(); isRead { + t.Fatal("another recipient's item was marked read") + } +} + func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) { t.Parallel() @@ -129,6 +232,9 @@ func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) { {name: "query string", path: "/candidate/invitations?token=secret"}, {name: "fragment", path: "/candidate/invitations#current"}, {name: "backslash", path: `/candidate\\invitations`}, + {name: "escape", path: "/candidate/%2e%2e/invitations"}, + {name: "dot segment", path: "/candidate/../invitations"}, + {name: "too long", path: "/" + strings.Repeat("a", 300)}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -138,32 +244,112 @@ func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) { } }) } + if _, err := NewInboxContent("Приглашение", "Проверьте новое приглашение.", "/candidate/invitations/01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b"); err != nil { + t.Fatalf("NewInboxContent(same-origin path) error = %v", err) + } } -func newInboxTestService( - t *testing.T, - repository outbound.NotificationInboxRepository, - resolver InboxContentResolver, - clock func() time.Time, -) *InboxService { +func TestSyntheticNoticeResolverFollowsTheRecipientStanding(t *testing.T) { + t.Parallel() + + fixture := newInboxFixture(t, domain.ScenarioCandidate) + entry := fixture.add(t, fixture.entryInput()) + unit := fixture.unit() + content, err := ResolveSyntheticNotice(context.Background(), unit, entry) + if err != nil { + t.Fatalf("ResolveSyntheticNotice(visible) error = %v", err) + } + if content.Title() != syntheticNoticeTitle || content.LinkPath() != "" || content.Summary() == "" { + t.Fatalf("synthetic content = %+v", content) + } + fixture.repository.organizationName = "" + if _, err := ResolveSyntheticNotice(context.Background(), unit, entry); !errors.Is(err, ErrInboxContentUnavailable) { + t.Fatalf("ResolveSyntheticNotice(not visible) error = %v, want ErrInboxContentUnavailable", err) + } + resolvers := NewInboxContentResolver(DefaultInboxSourceResolvers(true)) + invitation := fixtureEntry(t, domain.NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID, + EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1, + SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(), + OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), + }) + if _, err := resolvers.Resolve(context.Background(), unit, invitation); !errors.Is(err, ErrInboxContentUnavailable) { + t.Fatalf("Resolve(source without a resolver) error = %v, want ErrInboxContentUnavailable", err) + } +} + +type inboxFixture struct { + service *InboxService + repository *memoryInboxRepository + resolver *memoryInboxResolver + users map[uuid.UUID]domain.User + memberships map[uuid.UUID]domain.Membership + user domain.User + organizationID uuid.UUID + locks int +} + +func newInboxFixture(t *testing.T, scenario domain.Scenario) *inboxFixture { t.Helper() - service, err := NewInboxService(repository, resolver, clock) + return newInboxFixtureWithClock(t, scenario, time.Now) +} + +func newInboxFixtureWithClock(t *testing.T, scenario domain.Scenario, clock func() time.Time) *inboxFixture { + t.Helper() + verifiedAt := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC) + fixture := &inboxFixture{ + repository: &memoryInboxRepository{organizationName: "Север"}, + resolver: &memoryInboxResolver{unavailable: map[uuid.UUID]bool{}}, + users: map[uuid.UUID]domain.User{}, + memberships: map[uuid.UUID]domain.Membership{}, + user: domain.User{ID: uuid.New(), Scenario: scenario, EmailVerifiedAt: &verifiedAt}, + organizationID: uuid.New(), + } + fixture.users[fixture.user.ID] = fixture.user + service, err := NewInboxService(inboxTestTransactor{fixture: fixture}, fixture.resolver, clock) if err != nil { t.Fatalf("NewInboxService() error = %v", err) } - return service + fixture.service = service + return fixture } -func inboxTestEntryInput() domain.NotificationInboxEntryInput { +func (fixture *inboxFixture) unit() outbound.UnitOfWork { return inboxTestUnit{fixture: fixture} } + +func (fixture *inboxFixture) entryInput() domain.NotificationInboxEntryInput { + return fixtureEntryInput(fixture.user.ID, fixture.organizationID) +} + +func (fixture *inboxFixture) add(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry { + t.Helper() + entry := fixtureEntry(t, input) + fixture.repository.entries = append(fixture.repository.entries, entry) + return entry +} + +func (fixture *inboxFixture) addMembership(t *testing.T, role domain.OrganizationRole, state domain.MembershipState) { + t.Helper() + now := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC) + membership, err := domain.RestoreMembership(domain.StoredMembership{ + ID: uuid.New(), OrganizationID: fixture.organizationID, UserID: fixture.user.ID, + Role: string(role), State: string(state), CreatedAt: now, UpdatedAt: now, + }) + if err != nil { + t.Fatalf("RestoreMembership() error = %v", err) + } + fixture.memberships[fixture.user.ID] = membership +} + +func fixtureEntryInput(recipientID, organizationID uuid.UUID) domain.NotificationInboxEntryInput { return domain.NotificationInboxEntryInput{ - EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(), - EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1, - SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(), + EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: organizationID, + EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1, + SourceType: domain.NotificationInboxSourceOrganization, SourceID: organizationID, OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), } } -func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry { +func fixtureEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry { t.Helper() entry, err := domain.NewNotificationInboxEntry(input) if err != nil { @@ -172,14 +358,71 @@ func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput) return entry } -func uuidPointer(value uuid.UUID) *uuid.UUID { return &value } +type inboxTestTransactor struct{ fixture *inboxFixture } + +func (transactor inboxTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error { + return fn(ctx, transactor.fixture.unit()) +} + +type inboxTestUnit struct { + outbound.UnitOfWork + + fixture *inboxFixture +} + +func (unit inboxTestUnit) Users() outbound.UserRepository { + return inboxTestUsers{fixture: unit.fixture} +} +func (unit inboxTestUnit) Organizations() outbound.OrganizationRepository { + return inboxTestOrganizations{fixture: unit.fixture} +} +func (unit inboxTestUnit) NotificationInbox() outbound.NotificationInboxRepository { + return unit.fixture.repository +} + +type inboxTestUsers struct { + outbound.UserRepository + + fixture *inboxFixture +} + +func (repository inboxTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) { + user, ok := repository.fixture.users[id] + if !ok { + return domain.User{}, outbound.ErrUserNotFound + } + return user, nil +} + +type inboxTestOrganizations struct { + outbound.OrganizationRepository + + fixture *inboxFixture +} + +// LockActiveMembership answers like the real repository: only an active +// membership of the account in the organization is returned. +func (repository inboxTestOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) { + repository.fixture.locks++ + membership, ok := repository.fixture.memberships[userID] + if !ok || membership.OrganizationID() != organizationID || !membership.GrantsAccess() { + return domain.Membership{}, outbound.ErrOrganizationNotFound + } + return membership, nil +} type memoryInboxRepository struct { - entries []domain.NotificationInboxEntry - ignoreListScope bool + entries []domain.NotificationInboxEntry + ignoreListScope bool + listCalls int + organizationName string + storeErr error } func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.NotificationInboxEntry) (bool, error) { + if repository.storeErr != nil { + return false, repository.storeErr + } for _, existing := range repository.entries { if existing.RecipientUserID() != entry.RecipientUserID() || existing.EventID() != entry.EventID() { continue @@ -194,6 +437,7 @@ func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.N } func (repository *memoryInboxRepository) List(_ context.Context, query outbound.NotificationInboxListQuery) (outbound.NotificationInboxPage, error) { + repository.listCalls++ page := outbound.NotificationInboxPage{} for _, entry := range repository.entries { if !repository.ignoreListScope && (entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID)) { @@ -207,12 +451,13 @@ func (repository *memoryInboxRepository) List(_ context.Context, query outbound. func (repository *memoryInboxRepository) MarkRead( _ context.Context, recipientUserID uuid.UUID, - organizationID uuid.UUID, + organizationID *uuid.UUID, eventID uuid.UUID, at time.Time, ) (domain.NotificationInboxEntry, error) { for index, entry := range repository.entries { - if entry.RecipientUserID() != recipientUserID || entry.OrganizationID() != organizationID || entry.EventID() != eventID { + if entry.RecipientUserID() != recipientUserID || entry.EventID() != eventID || + (organizationID != nil && entry.OrganizationID() != *organizationID) { continue } read, err := entry.MarkRead(at) @@ -225,6 +470,13 @@ func (repository *memoryInboxRepository) MarkRead( return domain.NotificationInboxEntry{}, outbound.ErrNotificationInboxEntryNotFound } +func (repository *memoryInboxRepository) OrganizationNameForRecipient(context.Context, uuid.UUID, uuid.UUID) (string, error) { + if repository.organizationName == "" { + return "", outbound.ErrNotificationInboxSourceNotVisible + } + return repository.organizationName, nil +} + func sameInboxEvent(left, right domain.NotificationInboxEntry) bool { return left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() && left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() && @@ -236,7 +488,7 @@ type memoryInboxResolver struct { calls int } -func (resolver *memoryInboxResolver) Resolve(_ context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) { +func (resolver *memoryInboxResolver) Resolve(_ context.Context, _ outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) { resolver.calls++ if resolver.unavailable[entry.EventID()] { return InboxContent{}, ErrInboxContentUnavailable diff --git a/backend/internal/usecase/policy/matching.go b/backend/internal/usecase/policy/matching.go new file mode 100644 index 0000000..f921aa4 --- /dev/null +++ b/backend/internal/usecase/policy/matching.go @@ -0,0 +1,74 @@ +package policy + +import ( + "context" + "errors" + "fmt" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// ErrNotDemoPolicy reports a latest product policy that is not a demonstration +// version. The operator command never builds on a calibrated version. +var ErrNotDemoPolicy = errors.New("the latest product policy is not a demonstration version") + +// ErrPolicyChanged reports that another publication took the next version +// number while the section was being added. Nothing was stored; the command +// can be run again. +var ErrPolicyChanged = errors.New("the product policy changed during publication, run the command again") + +// MatchingResult reports what EnsureDemoMatchingSection did. Version is the +// version that carries the matching section: the new one when Created, the +// latest one otherwise. +type MatchingResult struct { + Created bool + Version domain.PolicyVersion +} + +// EnsureDemoMatchingSection makes the latest demonstration version carry the +// demo matching section. A version that already has the section is left alone. +// Otherwise it publishes the next version: a copy of the latest one with +// domain.DemoMatchingPolicy added, so no other value changes. It refuses a +// latest version that is not a demonstration version and a family without a +// version, because the section is only an addition to a policy that exists. +func (publisher *Publisher) EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (MatchingResult, error) { + const location = "Publisher.EnsureDemoMatchingSection" + latest, err := publisher.policies.GetLatest(ctx, domain.ProductPolicyKey) + if errors.Is(err, outbound.ErrPolicyVersionNotFound) { + return MatchingResult{}, fmt.Errorf("%s - the product policy has no version to extend: %w", location, err) + } + if err != nil { + return MatchingResult{}, fmt.Errorf("%s - read latest version: %w", location, err) + } + current := latest.Policy() + if current.Matching != nil { + return MatchingResult{Version: latest}, nil + } + if latest.Kind() != domain.PolicyKindDemo { + return MatchingResult{}, fmt.Errorf("%s - latest version %d is %s: %w", location, latest.Version(), latest.Kind(), ErrNotDemoPolicy) + } + matching := domain.DemoMatchingPolicy() + current.Matching = &matching + // The new version is built on the version that was read, so it takes the + // next number exactly once. A taken number means the base is no longer the + // latest, and the operator decides again instead of the command retrying. + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: author, Policy: current, + }) + if err != nil { + return MatchingResult{}, fmt.Errorf("%s - build the extended version: %w", location, err) + } + numbered, err := draft.WithVersion(latest.Version() + 1) + if err != nil { + return MatchingResult{}, fmt.Errorf("%s - number the extended version: %w", location, err) + } + published, err := publisher.policies.Create(ctx, numbered) + if errors.Is(err, outbound.ErrPolicyVersionConflict) { + return MatchingResult{}, fmt.Errorf("%s - version %d is taken: %w", location, numbered.Version(), ErrPolicyChanged) + } + if err != nil { + return MatchingResult{}, fmt.Errorf("%s - store the extended version: %w", location, err) + } + return MatchingResult{Created: true, Version: published}, nil +} diff --git a/backend/internal/usecase/policy/matching_test.go b/backend/internal/usecase/policy/matching_test.go new file mode 100644 index 0000000..d47be3e --- /dev/null +++ b/backend/internal/usecase/policy/matching_test.go @@ -0,0 +1,83 @@ +package policy + +import ( + "context" + "errors" + "testing" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func seedVersion(t *testing.T, store *memoryPolicies, kind domain.PolicyKind, product domain.ProductPolicy) { + t.Helper() + publisher := NewPublisher(store, testClock) + if _, err := publisher.Publish(context.Background(), PublishInput{ + Key: domain.ProductPolicyKey, Kind: kind, Author: domain.DemoPolicySeedAuthor, Policy: product, + }); err != nil { + t.Fatalf("Publish() error = %v", err) + } +} + +func TestEnsureDemoMatchingSectionAddsOnlyTheSection(t *testing.T) { + store := &memoryPolicies{} + seedVersion(t, store, domain.PolicyKindDemo, domain.DemoProductPolicyV2()) + publisher := NewPublisher(store, testClock) + + result, err := publisher.EnsureDemoMatchingSection(context.Background(), "operator:night") + if err != nil || !result.Created || result.Version.Version() != 2 { + t.Fatalf("EnsureDemoMatchingSection() = %+v, %v, want version 2 created", result, err) + } + extended := result.Version.Policy() + want := domain.DemoProductPolicyV2() + if extended.Matching == nil || extended.Support == nil || extended.Assessment.Attempt == nil || + extended.Invitations.MaxPendingPerNeed != want.Invitations.MaxPendingPerNeed { + t.Fatalf("extended policy = %+v, want the earlier sections kept and the matching section added", extended) + } + if result.Version.Kind() != domain.PolicyKindDemo || string(result.Version.Author()) != "operator:night" { + t.Fatalf("version kind/author = %s/%s", result.Version.Kind(), result.Version.Author()) + } + + again, err := publisher.EnsureDemoMatchingSection(context.Background(), "operator:night") + if err != nil || again.Created || again.Version.Version() != 2 || len(store.versions) != 2 { + t.Fatalf("second call = %+v, %v with %d versions, want no new version", again, err, len(store.versions)) + } +} + +func TestEnsureDemoMatchingSectionRefusesWhatItCannotExtend(t *testing.T) { + empty := &memoryPolicies{} + if _, err := NewPublisher(empty, testClock).EnsureDemoMatchingSection(context.Background(), "operator:night"); !errors.Is(err, outbound.ErrPolicyVersionNotFound) { + t.Fatalf("empty family error = %v, want ErrPolicyVersionNotFound", err) + } + calibrated := &memoryPolicies{} + product := domain.DemoProductPolicyV2() + product.Assessment.Calibration = domain.AssessmentCalibrationCalibrated + seedVersion(t, calibrated, domain.PolicyKindCalibrated, product) + if _, err := NewPublisher(calibrated, testClock).EnsureDemoMatchingSection(context.Background(), "operator:night"); !errors.Is(err, ErrNotDemoPolicy) { + t.Fatalf("calibrated family error = %v, want ErrNotDemoPolicy", err) + } + if len(calibrated.versions) != 1 { + t.Fatalf("versions = %d, want the calibrated family untouched", len(calibrated.versions)) + } +} + +func TestEnsureDemoMatchingSectionDoesNotRetryAfterAConcurrentPublication(t *testing.T) { + store := &memoryPolicies{} + seedVersion(t, store, domain.PolicyKindDemo, domain.DemoProductPolicyV2()) + store.beforeCreate = func(domain.PolicyVersionDraft) { + store.beforeCreate = nil + // Another operator publishes version 2 first. + if _, err := NewPublisher(store, testClock).Publish(context.Background(), PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: "operator:other", Policy: domain.DemoProductPolicyV2(), + }); err != nil { + t.Errorf("concurrent Publish() error = %v", err) + } + } + _, err := NewPublisher(store, testClock).EnsureDemoMatchingSection(context.Background(), "operator:night") + if !errors.Is(err, ErrPolicyChanged) { + t.Fatalf("EnsureDemoMatchingSection() error = %v, want ErrPolicyChanged", err) + } + if len(store.versions) != 2 || store.versions[1].Policy().Matching != nil { + t.Fatalf("versions = %d, want only the concurrent publication stored and no built-on-stale version", len(store.versions)) + } +} diff --git a/deploy/docker/docker-compose.e2e-mail.yml b/deploy/docker/docker-compose.e2e-mail.yml index 8ca7d4b..319eb8a 100644 --- a/deploy/docker/docker-compose.e2e-mail.yml +++ b/deploy/docker/docker-compose.e2e-mail.yml @@ -15,6 +15,9 @@ services: # Keep real resend coverage bounded within this isolated test stand. VERIFICATION_MAIL_MIN_INTERVAL: 1s E2E_CONSENT_FIXTURE: "1" + # The browser suite delivers the synthetic inbox event through the real + # pipeline; the production default is off. + NOTIFICATION_SYNTHETIC_ENABLED: "true" depends_on: mail-fixture: condition: service_healthy diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 21c26c6..8ff5fcd 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -6,7 +6,7 @@ This document separates the target product architecture from the technical scaff The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port. -Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. Other product workflows are not implemented: roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, and FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. +Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks synthetic notices, and no product module produces a real one yet (see [Internal notifications](#internal-notifications)). Other product workflows are not implemented: roles, profiles, assessments, grades, invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage. @@ -50,7 +50,7 @@ Redis is part of the core Compose project and connects through `backend/internal SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. The shared file layer and the access controls of the SeaweedFS container are described in [Private file storage](#private-file-storage). Resume uploads, authorization, product content rules, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup. -The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; one product consumer is registered, `notification_delivery` for mail deliveries. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. +The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; two product consumers are registered, `notification_delivery` for mail deliveries and `notification_inbox` for the [internal notifications](#internal-notifications). Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. ### HTTP perimeter and client address @@ -134,7 +134,7 @@ The metric `lincodex_outbox_relay_events_total{outcome}` counts published and fa ### Event consumers -Implemented: the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. One product handler is registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in the group `.notification_delivery`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers). +Implemented: the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. Two product handlers are registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries) and the inbox handler `notification_inbox` described in [Internal notifications](#internal-notifications), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in each of the groups `.notification_delivery` and `.notification_inbox`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers). A handler implements three methods: @@ -410,6 +410,25 @@ Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`rese Open points. Sending product notifications and the permission check they need are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume. +### Internal notifications + +Implemented: the inbox of delivered events with a read state, the consumer that fills it, and four operations that list and mark it. No product module produces a notification yet. Invitations, the first planned producer, are not implemented, so the only event that reaches the inbox today is a synthetic one and a real recipient sees an empty list. + +Code: migrations `backend/db/migrations/00032_create_notification_inbox.sql` and `00036_allow_synthetic_notification_event.sql`, queries `backend/db/queries/notification_inbox.sql`, the model `backend/internal/domain/notification_inbox.go`, the port `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), the adapter `adapter/secondary/postgres/notification_inbox.go`, the usecase files `usecase/notification/inbox.go`, `inbox_handler.go`, and `inbox_content.go`, the HTTP handler `adapter/primary/http/v1/notifications.go` with its cursor `notification_cursor.go`, the wiring in `bootstrap/notification.go` and `eventHandlers()`, and the frontend feature `frontend/src/features/notifications/` with the page `frontend/src/pages/notifications/`. The operations are in [api/README.en.md](../../api/README.en.md#notifications). + +- The inbox is the delivery state inside the platform. A row means that the notification reached the recipient's cabinet, and `read_at` says that the recipient read it. Mail is another channel with its own state in `deliveries` ([Mail deliveries](#mail-deliveries)), and neither reads the other. The inbox handler never reads `deliveries`, `mail_requests`, or the verification state of an address, so an unverified address, `EMAIL_PROVIDER=disabled`, or a failed send never blocks a notification, and a sent email never counts as seen. When invitations arrive, the delivered state of an invitation is the existence of its inbox row. +- A row holds references, not text. `notification_inbox_events` has the key `(recipient_user_id, event_id)` and the columns `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at`, and `read_at`. It stores no title, summary, name, contact, or score. Triggers keep the reference immutable (only the first `read_at` may be set) and refuse a direct delete; deleting the recipient's account removes the rows by cascade, and the organization foreign key is `RESTRICT`. A CHECK allows only the pairs of event type and source type that `domain.NotificationInboxSourceFor` allows, both at schema version 1: `invitation.delivered` with `invitation`, and the synthetic `notification.synthetic_delivered` with `organization`. Migration 00032 is deployed and unchanged; 00036 only widened the CHECK, and its rollback refuses while a synthetic row exists. +- Producer contract. A producer appends, in its own transaction, an event of an allowlisted type with the payload `{"recipient_user_id": ..., "organization_id": ...}` (two identifiers, no unknown field, schema version 1) and the aggregate that the type names. For `invitation.delivered` the aggregate is the `invitation`, which is also the content source. The synthetic event uses a one-off `synthetic_notice` aggregate at version 1, and its source is the organization of the payload; `notification.SyntheticNoticeEventPayload` is the single writer of that payload. The invitation module therefore needs no change in the table, the consumer, or the API: it appends `invitation.delivered` and registers a content resolver for the source `invitation` in `notification.DefaultInboxSourceResolvers()`. Until a resolver exists, an item of that source is listed without content. +- Synthetic event type. `notification.synthetic_delivered` has no product meaning. It exists so that the whole path (outbox, relay, Kafka, consumer, read-time check, list, read state) can be exercised before a real producer exists and in browser tests. It is off by default: the consumer handles it and the inbox renders it only when `NOTIFICATION_SYNTHETIC_ENABLED=true` (a development or browser-test stand; the e2e overlay sets it). With the switch off the event is acknowledged and ignored and a stored synthetic row is listed without content; the database CHECK allows the type either way, so turning the switch on needs no migration. Only code that can append to the outbox can produce it, and its content is a fixed text that names the sending organization. The browser suite appends it through the `company-fixture` (Go build tag `e2e`), never through a user operation. +- Consumer `notification_inbox`. `InboxHandler` handles the allowlisted types. In the transaction of the dedup marker it checks the envelope and the payload and rejects a broken event for good (`ErrEventRejected`), skips a recipient whose account was deleted, and stores the row with `ON CONFLICT DO NOTHING` on the key. A recipient deleted between the check and the insert aborts the insert with a foreign-key error that names the recipient; the handler returns it as a retryable error, and the retry finds the account gone and skips, while a foreign-key error on the organization is rejected for good. Three layers keep one row per recipient and event ID: the consumer marker, the key, and the comparison of a duplicate with the stored metadata, which rejects an event ID that comes again with other metadata instead of overwriting it. A replay under a renamed consumer therefore stores no second row. `occurred_at` is the informational insert time of the outbox row; it orders the list together with the event ID. The consumer group `.notification_inbox` is new, so it starts at the earliest retained event; events of other types are counted as ignored. +- Content is resolved at read time. `InboxService` lists a page and calls the resolver of each item's source type in the transaction that authorized the viewer; the result is never stored. A resolver returns `ErrInboxContentUnavailable` when the source is gone or the recipient may not see it now. The item then stays in the list with `content` null, the client shows a generic line, and an earlier text is never shown. A source type without a resolver is unavailable, never guessed. The one resolver today belongs to the synthetic notice: its fixed Russian text names the sending organization by its current name, which `OrganizationNameForRecipient` reads under the recipient's current standing. A candidate sees the name until they hide the organization, and an employer while their membership is active. A name that does not fit the presentation limits is not shown. A content link is a same-origin path of a narrow alphabet, and the client opens it only inside its own cabinet. +- Scope. The candidate cabinet needs a verified candidate account and lists every organization context of the caller. The cabinet of one organization needs an employer account with a verified email (otherwise 403 `email_not_verified`, like the other organization operations) and an active membership of any role in the organization of the path. The membership is locked `FOR SHARE` with `LockActiveMembership` in the transaction of the list or the mark, like the card reads, so a revocation cannot commit between the check and the read and stops the next request. The recipient always comes from the session; the organization of the path narrows the rows and a path identifier alone grants nothing. A candidate on an organization route and an employer on the candidate route get 403. A missing membership, an unknown organization, an item of another account, an item of another organization, and an unknown ID all get the same 404 `not_found`. The organization routes are not in the owner-only list of `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` names them as authorized in their own transaction. +- Reading and marking. `GET /api/v1/me/notifications` and `GET /api/v1/organizations/{org_id}/notifications` return a newest-first page with a cursor bound to the account and the cabinet; a cursor of another account or cabinet is a 400. `POST .../{notification_id}/read` stores the first read time and returns it again on every repeat. It reads no source and returns no content, so an item without content can still be marked. All four are `Cache-Control: no-store`; a mark needs the session, the CSRF token, and an allowed Origin, and no Idempotency-Key because it is idempotent by its effect. No problem code was added. +- Frontend. `features/notifications` exports `NotificationInbox` (candidate or one organization) and `OrganizationNotificationInbox` (the chooser of the organization in the `organization_id` parameter plus the inbox). The pages `/candidate/notifications` and `/employer/notifications` and an entry "Уведомления" in each shell use them. The list is read on every visit and never kept (`gcTime: 0`), is keyed by account and cabinet, and is dropped when the account or the session changes or when access is refused. States: loading, empty, error with retry, forbidden, an item without content, and "show more". The read state is a word, not only a style, the mark is a native button, and focus moves to the item's heading after it succeeds. +- Trade-off: eventual consistency. The row is written by the consumer after the relay and Kafka, so a notification appears seconds after the producer committed, not inside the producer's transaction. The alternative, writing the row in the producer's transaction through `UnitOfWork.NotificationInbox()`, would make it immediate but would tie every producer to the inbox and drop the replay and dead-letter handling that the consumer gives. The browser suite therefore waits for the item and then replays the event. +- Tests. Unit: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` and `inbox_handler_test.go` (cabinet checks, membership revocation, resolver fallback, idempotent handler, rejected events, an `invitation.delivered` event under the same contract), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go`, and the feature tests in `frontend/src/features/notifications/`. Integration: `TestNotificationInboxOverHTTP` and `TestSyntheticNotificationMigration*`. Browser: `frontend/e2e/notifications.spec.ts` in the registration mode ([TESTING.md](TESTING.md#browser-e2e-suite)). +- Not implemented: the invitation producer and its content resolver, an unread counter or badge in the shells, live updates (the list is read on a visit and on window focus), archiving or deleting an item, retention of old rows, per-role filtering of employer notifications, a mail preference, and a metric for the inbox. The rows of the synthetic type are never removed by the application. + ### Product policy versions Implemented as storage, a publisher, and a startup seed: migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented. @@ -430,7 +449,7 @@ Typed policy, `domain.ProductPolicy`: every value is a named field whose type ca The MVP attempt accounting decision is candidate-wide: `MaxAttemptsPerWindow` counts root attempts across specializations in the rolling `AttemptWindow`. A corrective attempt shares its root slot, and training does not consume it. Retry and promotion timers remain independent by specialization. -Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, `assessment.signals`, and `support`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility. +Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, `assessment.signals`, `support`, and `matching`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility. The port `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and outside a transaction through `postgres.PolicyStore`. Methods that take a family reject an unknown one before reading storage. @@ -455,6 +474,26 @@ Demo and calibrated policy: `domain.DemoProductPolicyV1()` is the accepted initi The identity lifetimes in this table are the values of the identity contract ([api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). They come from the versioned product policy, not from configuration: the registration, verification, and session usecases will read them from the effective policy version. The grade rules in [Assessment and grade verification](#assessment-and-grade-verification) use the same assessment values. +Matching coefficients (`matching`, schema 2, `domain.MatchingPolicy` in `policy_matching.go`, demo version `domain.DemoProductPolicyV4()`): every field is required once the section is present, and the units are basis points except the two skill weights and the cohort size. The demo values are the design values of PRD 4.9 for checking the flow, not measured results; they are published explicitly (the isolated browser fixture publishes V4; startup still seeds V1 only), and a policy version without the section makes the search fail closed instead of ranking with defaults. + +| Field | Demo value | Meaning | +| --- | --- | --- | +| `fit_coverage_weight_bp`, `fit_domain_weight_bp`, `fit_semantics_weight_bp` | 7500, 1500, 1000 | `Fit = 0.75 * Cov + 0.15 * Dom + 0.10 * Sem`; the three add up to 1 | +| `rank_fit_weight_bp`, `rank_strength_weight_bp` | 5000, 5000 | `S = (0.5 * Fit + 0.5 * P) * freshness * responsiveness`; the two add up to 1 | +| `freshness_floor_bp`, `responsiveness_floor_bp` | 9000, 9000 | the multiplier `0.9 + 0.1 * x` of Fr and Rsp; a floor of zero is refused | +| `competition_boost_bp` | 3000 | `P = T + 0.3 * (1 - T) * V` | +| `neutral_unknown_bp` | 5000 | the neutral 0.5 for an unknown component (Dom, Sem, T, Fr, Rsp, and Cov of an empty request) | +| `near_skill_threshold_bp` | 2500 | a required skill that contributes less moves a confirmed profile to the near group | +| `required_skill_weight`, `desired_skill_weight` | 2, 1 | weights of the skills in Cov | +| `trust_stated_bp`, `trust_online_bp`, `trust_identity_bp`, `trust_in_person_bp` | 2500, 6000, 8500, 10000 | coefficients of the evidence trust levels 0 to 3 | +| `attribution_personal_bp`, `attribution_team_role_bp`, `attribution_team_unattributed_bp` | 10000, 8000, 5000 | personal result, team role, team result without a role | +| `relation_exact_bp`, `relation_narrower_bp`, `relation_broader_bp` | 10000, 8000, 4000 | evidence for the same skill, a narrower one, a broader one | +| `percentile_min_cohort` | 30 | the smallest comparable real cohort that allows a percentile; the search compares the real cohort of each returned category with it | +| `max_results_per_group` | 10 | entries of each group that one search may return; the whole bank is ranked and only the output is cut | +| `skill_taxonomy` | backend over docker, go, kafka, postgresql; devops_sre over docker | the technologies inside each specialization, which decide whether evidence is broader or narrower than a requested skill | + +The validation keeps each share in 0..1, the fit and rank weights at a sum of 1, the trust and relation coefficients ordered, and the floors above zero. Not in the policy yet: the competition half-life of 24 months and the embedding-only relation 0.3, because no competition data and no embeddings exist. + Seeding: at startup, after migrations and under the same condition (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set), bootstrap calls `Publisher.EnsureDemoProductPolicy`. It checks only whether `product` has any version and never decodes one, so a stored version of a newer or unknown layout cannot block startup. When the family is empty, it publishes demo version 1 effective at publication; otherwise it changes nothing and logs that the seed was skipped. Instances that start together race for version 1, and the loser skips. The log line names only the key, number, kind, and ID. A database error stops startup. The seed is not a data insert in a migration, so the schema and the policy values change independently. Referencing a version (planned): tables that record a decision built under a policy, such as grade decisions, selection snapshots, and invitations, carry `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` and store the version used when the decision was made. An existing decision reads that version with `GetByID` and is never recomputed through `GetEffective`, whose answer for a given time changes when a scheduled version is superseded. A referenced version cannot be deleted, by the foreign key and by the trigger, and a new version never rewrites past decisions. @@ -540,7 +579,7 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate. Outside the implemented identity and consent flows, domain types and usecases for other product workflows are not implemented. SMTP and FSP adapters, and product worker jobs, remain planned. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` and `notification_inbox` handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. `backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/`: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; `ServiceMailer` creates verification mail during registration and resend. Password reset mail belongs to the planned reset flow. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. @@ -625,7 +664,7 @@ Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql ### Skill evidence -Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. It feeds nothing yet: no ranking, matching, or percentile reads it. +Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. The match search reads the organization projection (see [Matching and explanations](#matching-and-explanations)); no percentile reads it yet. Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries `backend/db/queries/evidence.sql`, the model in `backend/internal/domain/evidence.go`, the port `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), the adapter `adapter/secondary/postgres/evidence.go`, the usecase `backend/internal/usecase/evidence/read.go`, the handler `adapter/primary/http/v1/evidence.go`, and the operations `ListMyEvidence` and `GetOrganizationCandidateEvidence` ([api/README.en.md](../../api/README.en.md#skill-evidence)). @@ -639,25 +678,32 @@ Code: migration `backend/db/migrations/00035_create_skill_evidence.sql`, queries - Scope of the consent C2. Publishing the `categories` field now sends an organization the confirmed category and one supporting assessment fact for it (skill, grade, trust level, year, and the demonstration labels). The candidate sees the same section in `GetMyCardPreview` (`evidence`), which applies no organization or cohort, so an organization can receive less. The C2 consent text was written before this section existed, and whether it needs a new version for it is a decision for the owner and the lawyer; this change does not touch the consent texts. - Express and failure. Reading the evidence before and after an express run shows the same list, the database refuses a fact whose result is an express run or a failed attempt, and an express run is not in the category, hence not in the card cohort. There is no percentile or ranking cohort in this release; when they appear they must read the same predicate. - Contract checks. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData`, and `TestEvidenceWalkReachesTheEvidenceFamily` (Go) and `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) walk every organization operation and the candidate list through all references and fail on an assessment, signal, or review schema, or on a raw answer, score, or failure property. -- Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in ranking or in the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open. +- Not implemented: an operation to hide or show a fact (the column and the guard exist; no HTTP operation changes it), claims from the profile as facts, facts from FSP or other sources, revocation of a source, a trust level above 1, the use of evidence in the Passport PDF, and retention. Whether the evidence should need its own card field instead of `categories` is open. ## Matching and explanations -Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. +Implemented as a deterministic search without ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.en.md](../../api/README.en.md#match-search)). Code: the usecase `backend/internal/usecase/matching/` (`search.go` the flow, `filter.go` the filters, `score.go` the integer scoring, `explain.go` the explanation), the card list `candidateview.Service.ListVisibleCards`, the policy section `domain.MatchingPolicy` (`policy_matching.go`), the skill relations `domain.RelateEvidenceSkill` (`evidence_relation.go`), the handler `adapter/primary/http/v1/matches.go`, and the wiring `bootstrap/matches.go`. There is no new table, migration, or query file: the search reuses the barrier queries that the card and the evidence already use, so there is one copy of the visibility rule. -Initial baseline after filtering: +- Access before ranking. The search is one transaction. The owner role is checked under the membership lock before any card is read. `ListVisibleCards` then runs the checks of a card read: verified employer, then `ListVisibleCandidateViewSources`, which selects from `candidate_effective_publications` (published and backed by an unrevoked C2) and excludes the candidates that hide the reading organization with `NOT EXISTS` over `candidate_hidden_organizations`; then the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five. The list is therefore exactly the set of handles that `GetOrganizationCandidateCard` opens at that moment: a card that the cohort rules suppress is not searched, a revoked C2, a closed publication, or a hidden organization takes effect on the next request, and nothing is cached or stored. The permitted evidence is read only through the organization-safe batch query `ListOrganizationVisibleEvidenceBatch` (one statement for the whole candidate set, with the barriers of the single read: the effective publication view, `NOT EXISTS` over the hiding, the `categories` field, visible measurements), and only when the request names skills. The locks are those of the card read and nothing else is locked; the writes of the search are limited to the candidates it returns. +- Owner only. For the MVP milestone the active owner of the organization searches. The HTTP boundary refuses every other role (`ownerCompanyOperations`), and the usecase repeats the role check under the membership lock, so a membership alone grants nothing. The full role and assignment matrix is later work and must not widen rights by one membership. +- Charged like card reads. A search returns card content (the confirmed category with its strength, the declared grade, the stack, the experience band, the work formats, and the explanation), so it passes through the same allowance as a card read. The whole visible bank is ranked, and then each group is cut to `max_results_per_group` of the policy version (demo value 10, so at most 30 reveals for one search, below the 50 distinct card views per day of tier E0); no total is returned. Walking the output in the order `main`, `near`, `unconfirmed`, each newly revealed candidate is reserved through the company quota port (`candidateview.SearchViews.Reserve`, the same `ReserveCardView` as a card read: idempotent per organization and candidate inside the window, so repeating the search or opening the card afterwards does not charge twice), and the candidate's access history gets one `card_viewed` entry per search with the fields actually returned (`SearchViews.Record`), all in the transaction of the search. When the allowance ends, the output stops at the first refusal: the entries already paid for are returned, `truncated` is true, nothing is written for the rest, and there is no error. `truncated` is also true when a group exceeded its limit; it carries no count. Opening a card is still the read for the full card. +- One entry per candidate specialization, built from the card the organization is allowed to see. A specialization is confirmed only when the card shows its category (`categories` published and not generalized away); a role that the self-assessment lists as unconfirmed is an unconfirmed entry; a role marked confirmed whose category the card does not show gives no entry, because a result cannot claim a confirmation the candidate did not publish. The same handle can therefore be confirmed in Backend and unconfirmed in Networks, and a Backend confirmation never changes the Networks entry. The status of an entry follows the specialization of the request: a need with a confirmed specialization and a `specialization` filter both restrict it, and two different values leave nothing. A need without a confirmed specialization searches all of them and returns each specialization separately. +- Filters, all applied before scoring. `confirmed_grade`, `confirmed_category`, and `confirmation_status: confirmed` keep only confirmed entries; a declared grade never satisfies them. `declared_grade` is a separate claim. `stack` requires every named tag in the card and also counts as a required skill of the request. `conditions.work_formats` needs one common format, and `conditions.salary_compatibility` needs the same value; an unknown card value never satisfies a condition. An unconfirmed category alone hides nothing: without a confirmed filter the declared specializations are listed. +- Requested skills. The skills of the Cov come from the confirmed required (weight 2) and desired (weight 1) skills of the need snapshot, with the tags of the `stack` filter as required. A code is counted once however often it is repeated. A skill without a taxonomy code has no reviewed mapping, matches nothing, and is a gap. An empty request uses the neutral Cov 0.5 instead of dividing by zero. The need is read by `requirements_version` (`GetVersion`); a general version that only changed the title is not a requirements snapshot and answers 404, and the snapshot of an older requirements version stays searchable and unchanged. +- Evidence of a skill. Each requested skill takes the best product of the trust, attribution, and relation coefficients over the permitted evidence, not their sum. The evidence is the stated stack tags of the card (trust 0, a claim) and, for a confirmed entry, the one assessment fact that supports its category (trust 1, personal). The relation is exact for the same code, broader for a specialization over a technology, and narrower the other way, by the `skill_taxonomy` of the policy version (demo: `backend` over `docker`, `go`, `kafka`, `postgresql`; `devops_sre` over `docker`); a version without a taxonomy relates only equal codes, so the version fully determines the result. The taxonomy is a demonstration mapping, not a measured one. An online Backend result is worth 0.6 * 1.0 * 0.4 = 0.24 for a requested Go and a stated Go tag 0.25; the near threshold is 0.25, so a candidate whose only evidence for a required technology is a Backend assessment is always in `near` for it, and a stated tag alone is enough to be in `main`. That consequence of the PRD values is an owner question. Repeating a tag or a skill adds nothing. +- Components and groups. `Cov` is the weighted mean of the contributions; `Dom = 0.5` (the anonymous card carries no domain) and `Sem = 0.5` for every entry (no ML), both named in `unknown_flags`; `T = 0.5` with a null percentile and the flag `cohort_below_30`, which the search proves instead of declaring: it counts the candidates who hold each returned category from a source other than a synthetic demonstration (`CountRealComparableCategories`, counts only) and compares the count with `percentile_min_cohort`; today the count is 0 because every stored category is a synthetic demonstration, which is never mixed with real results. A real cohort at the minimum would need the theta of its members, which the organization-safe projection does not carry, so the search never fails for it: T stays the neutral 0.5, the percentile stays null, the reason becomes `percentile_not_computed` instead of `cohort_below_30`, and the search logs one warning for each such category. Only the categories of the entries that passed the filters are counted; `V = 0` because no competition data exists, which is neither a penalty nor an unknown; `Fr = Rsp = 0.5` with the flags `no_freshness_history` and `no_response_history`. A confirmed entry with a required skill below the near threshold (0.25) is in `near`, otherwise in `main`; an unconfirmed entry is in `unconfirmed` with only Fit and Coverage, computed by a separate path that never calculates theta, T, P, a percentile, or S. The absence of FSP is not scored anywhere. +- Order and rounding. Scores are integers in micro units (six decimals), the shares are basis points, and the products are exact integers, so the same data and policy give the same order on every platform. `main` and `near` sort by S, then Cov (both descending), then the internal candidate identifier ascending (then the specialization code, which only separates two entries of one candidate); `unconfirmed` sorts by Fit, then Cov, then the identifier. The identifier never leaves the server, and the groups are not merged on one scale. +- Explanation. The summary and the flags are built from the same computed contributions: per skill group `supports` (every skill carried by a measurement at or above the threshold), `declared_only` (only stated tags), `partial` (a mix, or measurements below the threshold), or `gap` (nothing), plus the confirmed category, the declared grade, the work-format match against the need or the filter, and the salary compatibility. It uses bounded codes only, never free text, a contact, a candidate location, a salary value or minimum, a failed attempt, or a reason for withheld data. An unknown component appears only in `unknown_flags`. +- Policy. The search reads the effective `product` policy at the application time and its `matching` section. A policy without the section fails closed with an internal error (the ProblemCode enum has no code for a temporarily unavailable dependency, and none is added); the error log says that the effective product policy has no matching section and names the `policy-publish` operator command, the backend logs a warning at startup while the section is missing, and [DEPLOY.md](DEPLOY.md#match-search-policy-on-a-stand) describes the command. The response does not name the policy version, and no search is stored. +- Concurrency. The reservations take the exclusive organization lock of the company quota port. A membership check before them holds only a share lock on the same row, and two searches of one organization would deadlock on the upgrade, so the search takes the organization lock first (`CompanyQuotaRepository.LockOrganization`, the documented order; it is FOR NO KEY UPDATE, so readers queue behind each other but the foreign-key lock of a candidate's own hide, which holds the candidate row and then needs the organization row, is not blocked, and the reservation itself still takes FOR UPDATE in the same transaction) and the charges of one organization are serialized. A change of the visible cohort while it is being locked (`ErrConcurrentVisibilityChange`) repeats the whole search up to three times, and its writes roll back with the failed attempt. The card read (`GetOrganizationCard`) and the evidence section (`AuthorizeCategoriesSection`) take the same exclusive lock first, before any share lock, for the same reason: before this order two simultaneous card reads of one organization deadlocked (SQLSTATE 40P01). `TestMatchSearchOverHTTP` runs concurrent card reads, evidence reads, and searches of one organization and checks for no deadlock and one quota row for each candidate. +- Accepted residual risks. `truncated` is one bit about the size of the visible bank (it says that more than the limit or the allowance exists) and the response time grows with the bank, so both leak a coarse size to the owner. The bit is bounded by the group limit and no count is returned; the risk is accepted for the demonstration and is listed with the owner questions. +- Checks. `internal/usecase/matching` unit tests (formulas with hand-computed values, ties and ordering, filters, explanation, the cut and the charge of the output), `internal/domain/policy_matching_test.go` (document round trip, strictness, validation), `v1/matches_test.go` (mapping and problems), and the integration test `TestMatchSearchOverHTTP` against PostgreSQL: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, Backend confirmed and Networks unconfirmed for one handle, a profile published without a grade through the real profile, consent, and publication operations and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the batch evidence read, two concurrent searches under one allowance, the demo group limit, the policy taxonomy, the denials, and the policy without the section. - score = 0.50 * skill_fit - + 0.40 * assessment_score - + 0.10 * fsp_evidence +Not implemented: the percentile and a real T (they need the theta of a comparable real cohort of at least 30 people); the competition value V and the FSP data; the domain of a candidate; freshness and responsiveness histories; semantic similarity and the ML fallback flag beyond the neutral value; the stored `search_run` snapshots, refinement, comparison, and the shortlist; paging beyond the group limit; and the use of the grade of a need as a filter. The invitation from a search result is not implemented either, so the revocation of C2 after an invitation is not checked here. -Each component ranges from 0 to 1. skill_fit is weighted coverage of verified requested skills. assessment_score is the result for relevant assessment sections. fsp_evidence is a small bonus for relevant verified achievements. An empty skill set uses a predefined neutral value and avoids division by zero. Use a stable ID tie-break, never personal characteristics. +Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. This is the first model, not an optimized or measured ranking: the plan compares keyword search, the verified-skill baseline, and an ML variant, adds a semantic signal only after an experiment, and never treats its score as a probability of hiring success. -No FSP history gives a zero bonus without excluding the candidate. Synthetic achievements are marked and affect demo data only. Results include score_components, reason_codes, evidence, and gaps. A candidate with a verified Middle grade and 4 of 5 covered skills still fails a filter that requires confirmation of all five. - -This is an initial baseline, not an optimized or measured ranking model. The plan compares keyword search, the verified-skill baseline, and an ML variant. Add a semantic signal only after an experiment; never treat its score as a probability of hiring success. - -Store each search as a search_run with its company, original need, filters, ranking version, and parent version. Refinement creates another snapshot. search_items stores order, scores, and profile versions without contacts. An old snapshot does not preserve access: hidden or removed profiles disappear, stale ranking is marked, and retention is bounded. +Store each search as a search_run with its company, original need, filters, ranking version, and parent version. Refinement creates another snapshot. search_items stores order, scores, and profile versions without contacts. An old snapshot does not preserve access: hidden or removed profiles disappear, stale ranking is marked, and retention is bounded. This is planned; the implemented search stores nothing. ## ML, documents, and background jobs @@ -953,7 +999,7 @@ Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailabl | Questionnaire, grade, test, category, pp. 1-3 | assessment, variants, grade history | Not implemented | | Comparable tests and leak resistance, pp. 1-2 | Families, blueprint, rubrics, rotation, pilot | Planned | | No forced grade decrease and change frequency, pp. 2-3 | verified/claimed, retry, cooldown, eligibility | Planned | -| Candidate search and explanation, pp. 3-4 | Hard filters, matching evidence, score components | Not implemented | +| Candidate search and explanation, pp. 3-4 | Hard filters, matching evidence, score components | Basic deterministic search implemented; ML, competition data, and snapshots are not | | Refine search without losing prior results, p. 4 | Versioned search runs and server snapshots | Planned | | Invitation without a vacancy, p. 3 | Optional vacancy_id | Not implemented | | RUB salary range and employer contact, p. 4 | Required bounds and explicit period/tax basis | Not implemented | diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index f589dd6..2881786 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -120,11 +120,12 @@ The internal /metrics endpoint shows the backlog: `lincodex_outbox_relay_pending ### Event consumers -The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads `KAFKA_EVENTS_TOPIC` as a member of the group `.`, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers). Current state: one product handler is registered, `notification_delivery` (mail deliveries), so the backend runs one consumer in the group `.notification_delivery` (`lincodex.notification_delivery` by default) when `CONSUMER_ENABLED` is true and `DATABASE_URL` is set. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. An invalid value stops startup, also with consumers disabled. +The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads `KAFKA_EVENTS_TOPIC` as a member of the group `.`, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers). Current state: two product handlers are registered, `notification_delivery` (mail deliveries) and `notification_inbox` (internal notifications), so the backend runs one consumer in each of the groups `.notification_delivery` and `.notification_inbox` (`lincodex.notification_delivery` and `lincodex.notification_inbox` by default) when `CONSUMER_ENABLED` is true and `DATABASE_URL` is set. A new group starts at the earliest retained event of the topic, so the first start of `notification_inbox` after a deployment reads the retained events and ignores those of other types. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. An invalid value stops startup, also with consumers disabled. | Variable | Default | Meaning | | --- | --- | --- | | `CONSUMER_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, no consumer runs, and events wait in Kafka for as long as the topic retains them. | +| `NOTIFICATION_SYNTHETIC_ENABLED` | `false` | `true` or `false`. Turns on the synthetic inbox event `notification.synthetic_delivered`: the `notification_inbox` consumer stores it and the inbox renders its fixed text. Leave it off in production; the browser E2E stand sets it. With `false` such an event is acknowledged and ignored, and a stored synthetic row is listed without content. The database CHECK allows the type either way. | | `CONSUMER_GROUP_PREFIX` | `lincodex` | Prefix of every consumer group ID, up to 128 letters, digits, dots, underscores, or hyphens. Changing it starts new groups that read the topic from its earliest retained record; the dedup markers turn events that were already applied into duplicates. | | `CONSUMER_MAX_ATTEMPTS` | `5` | Handler attempts for one event before it becomes a dead letter, from 1 to 20. Database failures outside the handler do not count. Must fit the rebalance budget below. | | `CONSUMER_BACKOFF_INITIAL` | `500ms` | Wait after the first failed attempt; it doubles with each consecutive failure. | @@ -345,6 +346,19 @@ make -C backend assessment-category-attest ARGS='attest --specialization backend - The attestation trigger accepts a policy of kind `demo` with `real_mode = demo_basic`. When a category is assigned, the database compares the threshold of the result with `basic_pass_mark_bp` of the policy version pinned to the attempt, so a 9000 threshold in an accepted policy works like 8000. A result decided before the attestation gets no category; only a result decided after it can assign one. - Without either step a result that reached the threshold is stored as `not_eligible`: the candidate sees the score and no category. `demo_express` never creates a category under any setting. `make -C backend assessment-category-attest-build` builds `backend/bin/assessment-category-attest`. +## Match search policy on a stand + +The match search ranks with the `matching` section of the effective `product` policy and fails closed without it: a search answers 500 `internal`, the log holds an error line that says the effective product policy has no matching section and names the command below, and no default is used. The startup seed publishes only the first demonstration version, which has no such section, so at startup the backend logs the warning `the effective product policy has no matching section` while the section is missing. Publish it once per stand as an operator: + +```sh +make -C backend policy-publish ARGS='matching --actor operator:' +``` + +- The command takes the latest product policy version, which must be a demonstration version (kind `demo`), and publishes the next version as a copy of it with the demo matching section added. No other value changes. A latest version that already has the section changes nothing and prints `already present`; if another publication takes the next version number meanwhile, the command stores nothing and asks to run it again; a calibrated latest version, or a family without a version, is refused. `make -C backend policy-publish-build` builds `backend/bin/policy-publish`. +- It needs only `DATABASE_URL`, reads no dotenv file, validates its arguments first, and prints the version number only. The author of the version is the `operator:` label, an audit label and not authentication: local database access is the operator boundary. +- The new version takes effect at once for new searches and changes no stored result. It is also a new version of the whole product policy, so a category opening pinned to the earlier version has to be opened again (and attested again on a demonstration stand, see above) before new assessment attempts are created. Publish it before the candidates start attempts, or repeat the opening and the attestation afterwards. +- The demo values (the coefficients of the PRD, the limit of 10 entries per group, and the small specialization-to-technology taxonomy) are in [architecture](ARCHITECTURE.md#product-policy-versions); they are not calibrated. The isolated browser fixture publishes the same section itself. + ## Separate ML Compose project ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 3c8e324..4e8d093 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -53,7 +53,7 @@ What exists now: - Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA uses the generated API client; MSW handlers provide test data. Implemented forms are listed below, while remaining routes still show placeholders. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). -- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs one product handler, the mail delivery consumer, and no product flow emits its event yet; see [Event consumers](#event-consumers). +- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs two product handlers, the mail delivery consumer and the inbox consumer, and no product flow emits their events yet; see [Event consumers](#event-consumers). - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. @@ -195,7 +195,7 @@ A directly launched backend with `DATABASE_URL` set runs the relay against `KAFK The consumer runtime applies events from Kafka to this service's own state, once per consumer. The loop lives in `backend/internal/worker/eventconsumer/`; it depends on the `inbound.EventHandler` port (`backend/internal/port/inbound/event_handler.go`) and on the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` is the franz-go group member that decodes the envelope and commits offsets, and `postgres.EventConsumerStore` runs the dedup transaction with the queries in `backend/db/queries/event_consumer.sql`. The backoff is shared with the relay in `backend/internal/worker/retry/`. -One product handler is registered: `notification.DeliveryHandler` stores mail deliveries (see [Mail deliveries](#mail-deliveries)). To add another, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does. +Two product handlers are registered: `notification.DeliveryHandler` stores mail deliveries (see [Mail deliveries](#mail-deliveries)) and `notification.InboxHandler` stores inbox references (see [Internal notifications](#internal-notifications)). To add another, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does. A directly launched backend with a registered handler and `DATABASE_URL` set consumes from `KAFKA_BROKERS`; set `CONSUMER_ENABLED=false` when you do not need it. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers); settings, metrics, and the dead letter procedure are in [DEPLOY.md](DEPLOY.md#event-consumers); tests are in [TESTING.md](TESTING.md#event-consumer-tests). @@ -205,6 +205,10 @@ To send a notification from a usecase, call `notification.MailRequester.RequestN Every send must pass `notification.QuotaGate`: build it with the configured account and limits and the transport's idempotency window (`resend.IdempotencyWindow`, or zero for SMTP); call `PrepareSend` in the transaction that claims the delivery and commit before calling `MailSender.Send`; then call `SettleSend` in the transaction that records the attempt, and use the time it returns as the attempt's `next_attempt_at` for a `quota_exhausted` rejection. A transport sets `SendResult.QuotaPeriod` from the provider's own error name for a quota rejection. Never call a transport without a permit, and never fall back to another transport or account when the quota is used up. To show an account its own mail status, call `notification.DeliveryStatusReader.LatestForUser` with the authenticated account's ID only. The rules are in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas). +### Internal notifications + +To put a notification into a recipient's inbox, append an event with `unit.Outbox().Append` in the usecase's own transaction. The type must be allowlisted (`domain.NotificationInboxSourceFor`), the payload must be exactly `recipient_user_id` and `organization_id`, and the aggregate must be the one the type names (`invitation` for `invitation.delivered`). Never put text or contacts in the payload. The `notification_inbox` consumer stores a reference. The text is produced when the recipient reads the list, by a resolver that you register for your source type in `notification.DefaultInboxSourceResolvers()`: an `InboxSourceResolver` that reads the current state through the `UnitOfWork`, applies the recipient's current visibility, and returns `ErrInboxContentUnavailable` when the content must not be shown. For a new event type add the pair to `domain.NotificationInboxSourceFor`, the entry to `inboxProjections` in `usecase/notification/inbox_handler.go`, a migration that widens the CHECK constraint of `notification_inbox_events` (never edit a deployed migration), a `NotificationKind` value to the contract, and the mapping in `adapter/primary/http/v1/notifications.go`. A producer needs no email: mail is requested separately with `MailRequester`, and the inbox state does not depend on it. The path can be tried end to end with the synthetic event `notification.synthetic_delivered` (`notification.SyntheticNoticeEventPayload` builds its payload); it has no product meaning and is handled only when `NOTIFICATION_SYNTHETIC_ENABLED=true`. See [Internal notifications](ARCHITECTURE.md#internal-notifications). + ### Scheduled jobs To run something when it falls due, such as an expiry or a reminder, schedule a job in the usecase's own transaction: build it with `domain.NewScheduledJob` (a kind such as `invitation.response_deadline`, a key that identifies the logical job, for example the aggregate ID, the due time from the injected clock, and a payload of identifiers only) and call `unit.ScheduledJobs().Schedule(ctx, job)`. The first schedule of a kind and key wins and a repeat is ignored, so use a new key, for example `:`, for a new occurrence. Cancel with `unit.ScheduledJobs().Cancel(ctx, kind, key)` before locking the product rows that the handler touches. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index b6d2bfb..498ad0b 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -174,7 +174,7 @@ Unit tests (`make -C backend test`) cover the delivery model and its creation pa - `internal/usecase/notification/`: a request stores its text under the event's aggregate ID and the event payload carries only `mail_request_id` and `kind`; invalid requests write nothing; the handler stores one delivery under the request ID with the source event, the account address, the rendered content, the configured provider account, and the clock time, and deletes the request; the same event again finds no request; an existing delivery under the request ID is accepted for the same recipient and kind and rejected otherwise; broken events (another schema version or aggregate, a malformed payload, trailing data, a request ID that is not the aggregate ID, a token mail kind) and text the template refuses are rejected without quoting the payload; a request that is gone, an account that is gone, and an unverified address are skipped with a log line that names only the delivery and event IDs; storage failures, including an account deleted between its read and the insert, stay retryable and keep the request; and no error or log line holds the address, subject, or body. - `internal/adapter/secondary/postgres/`: delivery and mail request constraint errors map to their sentinels (`deliveries_content_immutable` and `delivery_attempts_immutable` to `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` to `ErrDeliveryProviderPinned`, the user foreign keys to `ErrUserNotFound`), and any other PostgreSQL error, such as a check violation, keeps only its SQLSTATE and constraint without the message or detail. - `internal/usecase/notification/mailtemplate/`: a rendering converts to the stored content with the same kind, version, parts, and hash. -- `config/` and `internal/bootstrap/`: `EMAIL_ACCOUNT` defaults to `default`, accepts labels up to 64 characters, and refuses empty, mixed-case, key-like, and oversized values without echoing them; bootstrap registers exactly the `notification_delivery` handler and refuses an invalid account label. +- `config/` and `internal/bootstrap/`: `EMAIL_ACCOUNT` defaults to `default`, accepts labels up to 64 characters, and refuses empty, mixed-case, key-like, and oversized values without echoing them; bootstrap registers exactly the `notification_delivery` and `notification_inbox` handlers and refuses an invalid account label. `TestMailDelivery` in `backend/integration_test/delivery_test.go` uses `bootstrap(t, postgresService, kafkaService)` and the real request usecase, handler, relay, consumer runtime, and stores. Its sequential cases are: @@ -463,6 +463,22 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas The tests prove the stored facts, the policy pinning, the job-based computation, and the absence of the band from the contract and from candidate reads. They do not prove detection quality: the thresholds are uncalibrated, the false-positive measurement covers four drafted families, and no study of real candidates exists. The employer reads are covered by the contract walk, not by an HTTP call per operation. +## Internal notification tests + +Unit tests (`make -C backend test`, `make -C frontend test`): + +- `domain/notification_inbox_test.go`: an entry accepts only the allowlisted pairs of event type and source type (the synthetic event with the organization, `invitation.delivered` with the invitation), a new entry starts unread, and `MarkRead` keeps the first time. +- `usecase/notification/inbox_test.go` with an in-memory repository and a fake unit of work: the list resolves each item against its current source and falls back to no content; a candidate cabinet refuses an employer, the organization cabinet refuses a candidate, an unknown or unverified account, and a revoked membership (which answers like an unknown organization, for the list and for the mark); a repository row outside the recipient scope is an internal error; an owner and a recruiter (and the other roles) read and mark only their own items of the organization, with the membership locked for the read; an unverified employer gets `ErrInboxEmailNotVerified`; a mark keeps the first time and cannot touch another recipient's item; content links reject an external URL, a protocol-relative URL, a query, a fragment, a backslash, an escape, a dot segment, and a long path; the synthetic resolver follows the recipient's standing and an unregistered source type is unavailable. +- `usecase/notification/inbox_handler_test.go`: a repeated event stores one row; a broken schema version, aggregate, unknown field, missing organization, non-object payload, trailing data, and an event ID reused with other metadata are rejected for good; a deleted recipient is skipped; a store failure stays retryable; an unverified address still gets its row (the inbox reads no mail state); a recipient that vanished between the check and the insert is retried and then skipped, not rejected; the synthetic event is ignored while its switch is off; an `invitation.delivered` event with the same payload contract stores the invitation as its source. +- `adapter/primary/http/v1/notifications_test.go` and `adapter/primary/http/notification_contract_test.go`: the mapping of content and fallback, the cursor bound to the account and the cabinet (a foreign or crossed cursor is a 400), the refusals, the conventions of the four operations, and closed schemas. `bootstrap/consumers_test.go` pins the two registered consumers. +- Frontend: `features/notifications/` tests the link check, the retry of a mark once after a 403 (and no retry of a 401, 404, or 500), the labels, the wording of an item without content, the query keys and their removal by account, and the rendered list (read state as a word, a mark button only for unread items, no unsafe link, the empty state, the refusal of the other cabinet). + +Integration tests (`make -C backend test-int`; PostgreSQL and Redis, no Kafka): `TestNotificationInboxOverHTTP` writes a synthetic event through the real outbox writer and delivers it through the consumer store with the real handler. One event delivered twice and once more by a renamed consumer stores one row. The same router then checks the candidate list, a foreign candidate, the wrong cabinet, a missing CSRF token and a foreign Origin, the mark and its repeat (the first time is kept), the persistence of the read state, the loss of content when the candidate hides the organization, paging with a cursor bound to the account, the employer cabinet with only its own items of the organization, a recruiter with its own items, a non-member, an item of another organization, and the 404 for the list and the mark after the membership is revoked. `TestSyntheticNotificationMigrationAllowlistAndGuardedRollback` and `TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows` check the allowlist of migration 00036, the refused rollback with a synthetic row, and the restored constraint. `TestNotificationInboxStoreNamesTheMissingReference` checks that a missing recipient and a missing organization are told apart. `TestPostgresMigrations` covers up and down to zero. + +Browser test: `frontend/e2e/notifications.spec.ts` runs in `make -C deploy test-e2e-registration`, whose overlay sets `NOTIFICATION_SYNTHETIC_ENABLED=true`. The `company-fixture` (Go build tag `e2e`, bearer token, synthetic `@example.test` recipients only) appends a synthetic event to the real outbox, so the relay, Kafka, and the `notification_inbox` consumer deliver it; the test waits for the item. It then replays the event through the fixture, which must report that the real consumer had already applied it, and checks that the list still has one item. A candidate then opens the list, marks the item with the keyboard, reloads and sees the state kept, and a second candidate gets an empty list and a 404 for the same ID. After the organization is hidden the item stays without content. A second test reads the organization inbox as an owner, checks a non-member, revokes the membership through the fixture, and checks that the same ID is refused and that the page shows no content. + +What these tests do not show: a real invitation (none produces an event yet), the behavior of the inbox when the mail provider fails (the handler reads no mail state by construction, and the unit test covers an unverified address), delivery latency or load, push or live updates, and the layout and the screen-reader behavior of the page (no automated check). + ## Future software validation Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index ea7f446..f9eaff7 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -6,7 +6,7 @@ Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту. -Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, поиск, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. +Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Внутренний inbox уведомлений в обоих кабинетах показывает и отмечает синтетические уведомления, а настоящие пока не создает ни один продуктовый модуль (см. [Внутренние уведомления](#внутренние-уведомления)). Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований, снимков и приглашений (см. [Подбор и объяснение](#подбор-и-объяснение)). ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md). @@ -50,7 +50,7 @@ Redis входит в основной Compose и подключен через SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Общий файловый слой и контроль доступа в контейнере SeaweedFS описаны в разделе [Закрытое файловое хранилище](#закрытое-файловое-хранилище). Загрузка резюме, проверка прав, продуктовые правила содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование. -Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; зарегистрирован один продуктовый обработчик - `notification_delivery` для доставок писем. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. +Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; зарегистрированы два продуктовых обработчика - `notification_delivery` для доставок писем и `notification_inbox` для [внутренних уведомлений](#внутренние-уведомления). Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. ### HTTP-периметр и адрес клиента @@ -134,7 +134,7 @@ Producer требует подтверждения от всех in-sync реп ### Обработчики событий -Реализовано: runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Зарегистрирован один продуктовый обработчик: `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает обработчик доставки писем `notification_delivery`, описанный в разделе [Доставки писем](#доставки-писем), поэтому backend с `CONSUMER_ENABLED` и `DATABASE_URL` запускает один обработчик в группе `.notification_delivery`. Интеграционные тесты runtime используют тестовый обработчик, который пишет в таблицу, созданную самим тестом. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий). +Реализовано: runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Зарегистрированы два продуктовых обработчика: `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает обработчик доставки писем `notification_delivery`, описанный в разделе [Доставки писем](#доставки-писем), и обработчик inbox `notification_inbox`, описанный в разделе [Внутренние уведомления](#внутренние-уведомления), поэтому backend с `CONSUMER_ENABLED` и `DATABASE_URL` запускает по одному обработчику в группах `.notification_delivery` и `.notification_inbox`. Интеграционные тесты runtime используют тестовый обработчик, который пишет в таблицу, созданную самим тестом. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий). Обработчик реализует три метода: @@ -410,6 +410,25 @@ Offsets и партиции. Каждый обработчик - один уча Открытые вопросы. Отправка продуктовых уведомлений и нужная ей проверка разрешений запланированы; до их реализации уведомления ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема. +### Внутренние уведомления + +Реализовано: inbox доставленных событий с состоянием прочтения, обработчик, который его наполняет, и четыре операции для списка и отметки. Ни один продуктовый модуль пока не создает уведомления. Приглашения, первый запланированный источник, не реализованы, поэтому единственное событие, которое сегодня попадает в inbox, синтетическое, и у настоящего получателя список пуст. + +Код: миграции `backend/db/migrations/00032_create_notification_inbox.sql` и `00036_allow_synthetic_notification_event.sql`, запросы `backend/db/queries/notification_inbox.sql`, модель `backend/internal/domain/notification_inbox.go`, порт `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), адаптер `adapter/secondary/postgres/notification_inbox.go`, файлы usecase `usecase/notification/inbox.go`, `inbox_handler.go` и `inbox_content.go`, HTTP-обработчик `adapter/primary/http/v1/notifications.go` с курсором `notification_cursor.go`, подключение в `bootstrap/notification.go` и `eventHandlers()` и frontend-функция `frontend/src/features/notifications/` со страницей `frontend/src/pages/notifications/`. Операции описаны в [api/README.md](../../api/README.md#уведомления). + +- Inbox - состояние доставки внутри платформы. Строка означает, что уведомление дошло до кабинета получателя, а `read_at` - что получатель его прочитал. Почта - другой канал со своим состоянием в `deliveries` ([Доставки писем](#доставки-писем)), и ни один из них не читает другой. Обработчик inbox никогда не читает `deliveries`, `mail_requests` и состояние подтверждения адреса, поэтому неподтвержденный адрес, `EMAIL_PROVIDER=disabled` или неудачная отправка не блокируют уведомление, а отправленное письмо не считается увиденным. Когда появятся приглашения, состояние "доставлено" у приглашения - это существование его строки в inbox. +- Строка хранит ссылки, а не текст. В `notification_inbox_events` ключ `(recipient_user_id, event_id)` и столбцы `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at` и `read_at`. Заголовка, текста, названия, контакта и оценки там нет. Триггеры делают ссылку неизменяемой (можно только один раз задать `read_at`) и запрещают прямое удаление; удаление аккаунта получателя удаляет строки каскадом, а внешний ключ организации - `RESTRICT`. CHECK пропускает только пары типа события и типа источника из `domain.NotificationInboxSourceFor`, обе в версии схемы 1: `invitation.delivered` с `invitation` и синтетическое `notification.synthetic_delivered` с `organization`. Миграция 00032 уже развернута и не менялась; 00036 только расширила CHECK, а ее откат отказывает, пока есть синтетическая строка. +- Контракт источника. Источник в своей транзакции добавляет событие разрешенного типа с payload `{"recipient_user_id": ..., "organization_id": ...}` (два идентификатора, без неизвестных полей, версия схемы 1) и агрегатом, который назван для типа. У `invitation.delivered` агрегат - это `invitation`, он же источник содержимого. Синтетическое событие использует одноразовый агрегат `synthetic_notice` версии 1, а источник - организация из payload; единственный автор этого payload - `notification.SyntheticNoticeEventPayload`. Поэтому модулю приглашений не нужны изменения в таблице, обработчике и API: он добавляет `invitation.delivered` и регистрирует преобразователь содержимого для источника `invitation` в `notification.DefaultInboxSourceResolvers()`. Пока преобразователя нет, элемент такого источника показывается без содержимого. +- Синтетический тип события. `notification.synthetic_delivered` не имеет продуктового смысла. Он нужен, чтобы пройти весь путь (outbox, relay, Kafka, обработчик, проверка при чтении, список, прочтение) до появления настоящего источника и в браузерных тестах. По умолчанию он выключен: обработчик обрабатывает его, а inbox показывает, только при `NOTIFICATION_SYNTHETIC_ENABLED=true` (стенд разработки или браузерных тестов; overlay e2e включает его). При выключенном флаге событие подтверждается и игнорируется, а сохраненная синтетическая строка показывается без содержимого; CHECK в базе разрешает тип в любом случае, поэтому для включения миграция не нужна. Создать событие может только код, который умеет писать в outbox, а содержимое - фиксированный текст с названием отправляющей организации. Браузерный набор добавляет его через `company-fixture` (тег сборки Go `e2e`), а не через операцию пользователя. +- Обработчик `notification_inbox`. `InboxHandler` обрабатывает разрешенные типы. В транзакции dedup-маркера он проверяет конверт и payload и окончательно отклоняет сломанное событие (`ErrEventRejected`), пропускает получателя, чей аккаунт удален, и пишет строку с `ON CONFLICT DO NOTHING` по ключу. Получатель, удаленный между проверкой и вставкой, прерывает вставку внешним ключом получателя; обработчик возвращает это как повторяемую ошибку, и повтор видит, что аккаунта нет, и пропускает событие, а ошибка внешнего ключа организации отклоняет событие окончательно. Одну строку на получателя и ID события держат три слоя: маркер обработчика, ключ и сравнение дубликата с сохраненными метаданными; ID события, который пришел снова с другими метаданными, отклоняется, а не перезаписывается. Поэтому повтор под переименованным обработчиком второй строки не создает. `occurred_at` - информационное время вставки строки outbox; вместе с ID события оно упорядочивает список. Группа `.notification_inbox` новая, поэтому читает с самого раннего сохраненного события; события других типов считаются пропущенными. +- Содержимое вычисляется при чтении. `InboxService` читает страницу и вызывает преобразователь типа источника каждого элемента в той же транзакции, где проверен зритель; результат не сохраняется. Преобразователь возвращает `ErrInboxContentUnavailable`, когда источника нет или получатель сейчас не вправе его видеть. Тогда элемент остается в списке с `content` равным null, клиент показывает общую строку, а прежний текст не показывается никогда. Тип источника без преобразователя недоступен, а не угадывается. Единственный преобразователь сегодня - у синтетического уведомления: его фиксированный русский текст называет организацию-отправителя по ее текущему названию, которое `OrganizationNameForRecipient` читает с учетом текущего положения получателя. Кандидат видит название, пока не скрыл организацию, а работодатель - пока его членство активно. Название, которое не умещается в пределы представления, не показывается. Ссылка в содержимом - путь того же origin из узкого алфавита, и клиент открывает ее только внутри своего кабинета. +- Область доступа. Кабинет кандидата требует подтвержденный аккаунт кандидата и показывает все организации, которые писали вызывающему. Кабинет одной организации требует аккаунт работодателя с подтвержденной почтой (иначе 403 `email_not_verified`, как у других операций организации) и активное членство любой роли в организации из пути. Членство блокируется `FOR SHARE` через `LockActiveMembership` в транзакции списка или отметки, как в чтениях карточки, поэтому отзыв не может зафиксироваться между проверкой и чтением и останавливает следующий же запрос. Получатель всегда берется из сессии; организация из пути только сужает строки, а один идентификатор в пути ничего не дает. Кандидат на маршруте организации и работодатель на маршруте кандидата получают 403. Нет членства, неизвестная организация, элемент другого аккаунта, элемент другой организации и неизвестный ID дают один и тот же 404 `not_found`. Маршруты организации не входят в список только для владельца в `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` называет их проверяемыми в собственной транзакции. +- Чтение и отметка. `GET /api/v1/me/notifications` и `GET /api/v1/organizations/{org_id}/notifications` возвращают страницу от новых к старым с курсором, привязанным к аккаунту и кабинету; курсор другого аккаунта или кабинета - 400. `POST .../{notification_id}/read` сохраняет первое время прочтения и возвращает его при каждом повторе. Он не читает источник и не возвращает содержимое, поэтому элемент без содержимого тоже можно отметить. Все четыре - `Cache-Control: no-store`; отметка требует сессию, CSRF-токен и разрешенный Origin, а Idempotency-Key не нужен, потому что операция идемпотентна по эффекту. Новых кодов problem нет. +- Frontend. `features/notifications` экспортирует `NotificationInbox` (кандидат или одна организация) и `OrganizationNotificationInbox` (выбор организации в параметре `organization_id` и сам inbox). Их используют страницы `/candidate/notifications` и `/employer/notifications` и пункт "Уведомления" в каждой оболочке. Список читается при каждом заходе и не сохраняется (`gcTime: 0`), ключ зависит от аккаунта и кабинета, а кэш сбрасывается при смене аккаунта или сессии и при отказе в доступе. Состояния: загрузка, пусто, ошибка с повтором, нет доступа, элемент без содержимого и "Показать еще". Состояние прочтения выражено словом, а не только стилем, отметка - нативная кнопка, и после успеха фокус переходит на заголовок элемента. +- Компромисс: согласованность в конечном счете. Строку пишет обработчик после relay и Kafka, поэтому уведомление появляется через секунды после фиксации у источника, а не внутри его транзакции. Альтернатива - писать строку в транзакции источника через `UnitOfWork.NotificationInbox()` - дала бы мгновенность, но привязала бы каждый источник к inbox и лишила бы повторов и dead-letter, которые дает обработчик. Поэтому браузерный набор ждет появления элемента и затем повторяет доставку. +- Тесты. Модульные: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` и `inbox_handler_test.go` (проверки кабинета, отзыв членства, запасной вариант преобразователя, идемпотентный обработчик, отклоненные события, событие `invitation.delivered` по тому же контракту), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go` и тесты функции в `frontend/src/features/notifications/`. Интеграционные: `TestNotificationInboxOverHTTP` и `TestSyntheticNotificationMigration*`. Браузерный: `frontend/e2e/notifications.spec.ts` в режиме регистрации ([TESTING.md](TESTING.md#браузерный-e2e-набор)). +- Не реализовано: источник приглашений и его преобразователь содержимого, счетчик непрочитанного или значок в оболочках, живые обновления (список читается при заходе и при фокусе окна), архивирование и удаление элемента, срок хранения старых строк, фильтрация уведомлений работодателя по ролям, настройка почты и метрика inbox. Строки синтетического типа приложение не удаляет. + ### Версии продуктовой политики Реализованы хранение, публикация и начальное заполнение при старте: миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач. @@ -430,7 +449,7 @@ Offsets и партиции. Каждый обработчик - один уча Решение для учета попыток MVP: `MaxAttemptsPerWindow` считает корневые попытки кандидата по всем специализациям в скользящем окне `AttemptWindow`. Корректирующая попытка использует место своего корня, учебная его не расходует. Таймеры пересдачи и повышения остаются независимыми по специализациям. -Старые документы используют `schema_version` 1 с разделами `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`. Схема 2 добавляет независимые необязательные разделы `assessment.attempt`, `assessment.training`, `assessment.signals` и `support` и требует хотя бы один из них. Кодирование выбирает схему 1 без расширений и схему 2 при наличии любого расширения. У каждой схемы строгий декодер: старый отклоняет ключи расширений даже с null, а отсутствующий необязательный раздел не получает значений по умолчанию. Обязательные поля отклоняют отсутствие/null, неверные типы, дроби и значения вне int32; оба декодера отклоняют неизвестные поля, неизвестную версию схемы, данные после объекта и документы больше 64 KiB. Имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). Каноническая форма - компактный Go JSON в порядке объявления полей. `domain.RestorePolicyVersion` разбирает, проверяет, повторно кодирует документ и сравнивает SHA-256 с `document_sha256`; несовпадение дает `domain.ErrPolicyDocumentIntegrity`. Эталонные байты и хеш схемы 1 не меняются. Читающие процессы с поддержкой схемы 2 нужно развернуть до ее публикации; прежний бинарный файл не читает схему 2, поэтому после публикации откат к нему невозможен. Сохраненные политики ради совместимости не переписываются. +Старые документы используют `schema_version` 1 с разделами `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`. Схема 2 добавляет независимые необязательные разделы `assessment.attempt`, `assessment.training`, `assessment.signals`, `support` и `matching` и требует хотя бы один из них. Кодирование выбирает схему 1 без расширений и схему 2 при наличии любого расширения. У каждой схемы строгий декодер: старый отклоняет ключи расширений даже с null, а отсутствующий необязательный раздел не получает значений по умолчанию. Обязательные поля отклоняют отсутствие/null, неверные типы, дроби и значения вне int32; оба декодера отклоняют неизвестные поля, неизвестную версию схемы, данные после объекта и документы больше 64 KiB. Имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). Каноническая форма - компактный Go JSON в порядке объявления полей. `domain.RestorePolicyVersion` разбирает, проверяет, повторно кодирует документ и сравнивает SHA-256 с `document_sha256`; несовпадение дает `domain.ErrPolicyDocumentIntegrity`. Эталонные байты и хеш схемы 1 не меняются. Читающие процессы с поддержкой схемы 2 нужно развернуть до ее публикации; прежний бинарный файл не читает схему 2, поэтому после публикации откат к нему невозможен. Сохраненные политики ради совместимости не переписываются. Порт `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`. Методы, принимающие семейство, отклоняют неизвестное до обращения к хранилищу. @@ -455,6 +474,26 @@ Offsets и партиции. Каждый обработчик - один уча Сроки identity в этой таблице - значения контракта identity ([api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Они берутся из версионированной продуктовой политики, а не из конфигурации: usecase регистрации, подтверждения и сессий будут читать их из действующей версии политики. Правила грейда в разделе [Оценивание и подтверждение грейда](#оценивание-и-подтверждение-грейда) используют те же значения оценивания. +Коэффициенты подбора (`matching`, схема 2, `domain.MatchingPolicy` в `policy_matching.go`, демонстрационная версия `domain.DemoProductPolicyV4()`): при наличии раздела все поля обязательны, единицы - базисные пункты, кроме двух весов навыков и размера когорты. Демонстрационные значения - проектные значения PRD 4.9 для проверки сценария, а не измеренные результаты; они публикуются явно (изолированный браузерный стенд публикует V4, а при старте по-прежнему создается только V1), и версия политики без раздела приводит к закрытому отказу поиска вместо ранжирования по умолчаниям. + +| Поле | Демо-значение | Смысл | +| --- | --- | --- | +| `fit_coverage_weight_bp`, `fit_domain_weight_bp`, `fit_semantics_weight_bp` | 7500, 1500, 1000 | `Fit = 0.75 * Cov + 0.15 * Dom + 0.10 * Sem`; сумма равна 1 | +| `rank_fit_weight_bp`, `rank_strength_weight_bp` | 5000, 5000 | `S = (0.5 * Fit + 0.5 * P) * свежесть * своевременность`; сумма равна 1 | +| `freshness_floor_bp`, `responsiveness_floor_bp` | 9000, 9000 | множитель `0.9 + 0.1 * x` для Fr и Rsp; нулевая нижняя граница отклоняется | +| `competition_boost_bp` | 3000 | `P = T + 0.3 * (1 - T) * V` | +| `neutral_unknown_bp` | 5000 | нейтральное 0.5 для неизвестного компонента (Dom, Sem, T, Fr, Rsp и Cov пустого запроса) | +| `near_skill_threshold_bp` | 2500 | обязательный навык с меньшим вкладом переводит подтвержденный профиль в группу близких | +| `required_skill_weight`, `desired_skill_weight` | 2, 1 | веса навыков в Cov | +| `trust_stated_bp`, `trust_online_bp`, `trust_identity_bp`, `trust_in_person_bp` | 2500, 6000, 8500, 10000 | коэффициенты уровней доверия доказательства 0-3 | +| `attribution_personal_bp`, `attribution_team_role_bp`, `attribution_team_unattributed_bp` | 10000, 8000, 5000 | личный результат, роль в команде, командный результат без роли | +| `relation_exact_bp`, `relation_narrower_bp`, `relation_broader_bp` | 10000, 8000, 4000 | доказательство того же навыка, более узкого, более широкого | +| `percentile_min_cohort` | 30 | наименьшая сопоставимая реальная когорта, при которой допустим перцентиль; поиск сравнивает с ним реальную когорту каждой возвращаемой категории | +| `max_results_per_group` | 10 | записей каждой группы, которые может вернуть один поиск; ранжируется весь банк, обрезается только вывод | +| `skill_taxonomy` | backend над docker, go, kafka, postgresql; devops_sre над docker | технологии внутри каждой специализации, определяющие, шире или уже доказательство запрошенного навыка | + +Проверка держит каждую долю в пределах 0..1, суммы весов Fit и ранга равными 1, коэффициенты доверия и связи упорядоченными, а нижние границы выше нуля. В политику пока не вошли полураспад соревнований в 24 месяца и связь «только embedding» 0.3, так как данных о соревнованиях и embeddings нет. + Начальное заполнение: при старте, после миграций и при том же условии (`DATABASE_MIGRATE_ON_START` равен true и задан `DATABASE_URL`), bootstrap вызывает `Publisher.EnsureDemoProductPolicy`. Он проверяет только, есть ли у `product` хотя бы одна версия, и никогда не разбирает ее, поэтому сохраненная версия более новой или неизвестной структуры не может остановить запуск. Если семейство пусто, он публикует демонстрационную версию 1, действующую с момента публикации; иначе ничего не меняет и пишет в лог, что заполнение пропущено. Экземпляры, стартующие одновременно, состязаются за версию 1, и проигравший пропускает заполнение. Строка лога содержит только ключ, номер, вид и ID. Ошибка базы данных останавливает запуск. Заполнение не является вставкой данных в миграции, поэтому схема и значения политики меняются независимо. Ссылка на версию (запланировано): таблицы, которые фиксируют решение по политике, например решения о грейде, снимки подбора и приглашения, получают `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` и хранят версию, использованную в момент решения. Существующее решение читает эту версию через `GetByID` и никогда не пересчитывается через `GetEffective`, ответ которого для заданного момента меняется, когда запланированную версию заменяет более новая. Удалить версию, на которую есть ссылка, нельзя ни через внешний ключ, ни через триггер, и новая версия не переписывает прошлые решения. @@ -540,7 +579,7 @@ backend/ За пределами реализованных потоков identity и согласий доменные типы и usecase других продуктовых сценариев пока не реализованы. Адаптеры SMTP и FSP, а также продуктовые задания worker остаются планом. `main.go` запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки, подтверждения и входа identity, PostgreSQL сессии и security boundary для всех операций, защищенных API-контрактом, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации, подтверждении и входе, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Профили, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиками `notification_delivery` и `notification_inbox`, внутренний inbox уведомлений с операциями списка и прочтения, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки, подтверждения и входа identity, PostgreSQL сессии и security boundary для всех операций, защищенных API-контрактом, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации, подтверждении и входе, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Профили, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; `ServiceMailer` создает письма подтверждения при регистрации и повторной отправке. Письма сброса пароля относятся к будущему потоку сброса. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. @@ -625,7 +664,7 @@ contact_grant относится к паре кандидат-компания ### Доказательства навыков -Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию пока никто не использует: ни ранжирование, ни подбор, ни перцентиль ее не читают. +Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию для организации читает поиск (см. [Подбор и объяснение](#подбор-и-объяснение)); перцентиль ее пока не читает. Код: миграция `backend/db/migrations/00035_create_skill_evidence.sql`, запросы `backend/db/queries/evidence.sql`, модель `backend/internal/domain/evidence.go`, порт `port/outbound/evidence.go` (`UnitOfWork.Evidence()`), адаптер `adapter/secondary/postgres/evidence.go`, usecase `backend/internal/usecase/evidence/read.go`, обработчик `adapter/primary/http/v1/evidence.go` и операции `ListMyEvidence` и `GetOrganizationCandidateEvidence` ([api/README.md](../../api/README.md#доказательства-навыков)). @@ -639,25 +678,32 @@ contact_grant относится к паре кандидат-компания - Область согласия C2. Публикация поля `categories` теперь отправляет организации подтвержденную категорию и один подтверждающий ее факт оценки (навык, грейд, уровень доверия, год и метки демонстрации). Кандидат видит тот же раздел в `GetMyCardPreview` (`evidence`); предпросмотр не применяет организацию и когорту, поэтому организация может получить меньше. Текст согласия C2 написан до появления этого раздела, и нужна ли для него новая версия, решают владелец продукта и юрист; это изменение тексты согласий не трогает. - Экспресс и провал. Чтение доказательств до и после экспресс-прогона дает один и тот же список, база отказывает факту, чей результат - экспресс-прогон или проваленная попытка, а экспресс не входит в категорию и потому в когорту карточки. Перцентиля и ранжирования в этом выпуске нет; когда они появятся, они обязаны читать тот же предикат. - Проверки контракта. `TestEvidenceOperationsFollowTheConventions`, `TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements`, `TestNoOrganizationOperationReachesRawAssessmentData` и `TestEvidenceWalkReachesTheEvidenceFamily` (Go) и `test_evidence_is_closed_and_no_organization_operation_reaches_raw_assessment_data` (Python) обходят все организационные операции и список кандидата по всем ссылкам и падают на схеме оценки, сигнала или проверки, а также на свойстве с сырым ответом, баллом или провалом. -- Не реализовано: операция скрыть или показать факт (колонка и охранник есть, HTTP-операции для изменения нет), заявления профиля как факты, факты из ФСП и других источников, отзыв источника, уровень доверия выше 1, использование доказательств в ранжировании и в PDF "Паспорт навыков", срок хранения. Нужно ли доказательствам отдельное поле карточки вместо `categories`, остается открытым вопросом. +- Не реализовано: операция скрыть или показать факт (колонка и охранник есть, HTTP-операции для изменения нет), заявления профиля как факты, факты из ФСП и других источников, отзыв источника, уровень доверия выше 1, использование доказательств в PDF "Паспорт навыков", срок хранения. Нужно ли доказательствам отдельное поле карточки вместо `categories`, остается открытым вопросом. ## Подбор и объяснение -До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия. +Реализован как детерминированный поиск без ML: `POST /api/v1/organizations/{org_id}/matches` (`SearchOrganizationMatches`, [api/README.md](../../api/README.md#подбор)). Код: usecase `backend/internal/usecase/matching/` (`search.go` - порядок работы, `filter.go` - фильтры, `score.go` - целочисленный расчет, `explain.go` - объяснение), список карточек `candidateview.Service.ListVisibleCards`, раздел политики `domain.MatchingPolicy` (`policy_matching.go`), связи навыков `domain.RelateEvidenceSkill` (`evidence_relation.go`), обработчик `adapter/primary/http/v1/matches.go` и сборка `bootstrap/matches.go`. Новых таблиц, миграций и файлов запросов нет: поиск использует барьерные запросы, которыми уже пользуются карточка и доказательства, поэтому правило видимости существует в одном экземпляре. -Начальная baseline формула после фильтров: +- Доступ до ранжирования. Поиск выполняется в одной транзакции. Роль владельца проверяется под блокировкой членства до чтения любых карточек. Затем `ListVisibleCards` проводит проверки чтения карточки: подтвержденный работодатель, затем `ListVisibleCandidateViewSources`, который выбирает из `candidate_effective_publications` (опубликовано и подкреплено неотозванным C2) и исключает кандидатов, скрывших читающую организацию, через `NOT EXISTS` по `candidate_hidden_organizations`; затем блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти. Поэтому список - это ровно те handle, которые в этот момент открывает `GetOrganizationCandidateCard`: карточка, скрытая правилами когорты, не ищется, отзыв C2, закрытая публикация или скрытая организация действуют со следующего запроса, ничего не кешируется и не хранится. Разрешенные доказательства читаются только организационно безопасным пакетным запросом `ListOrganizationVisibleEvidenceBatch` (один запрос на весь набор кандидатов с барьерами одиночного чтения: представление действующих публикаций, `NOT EXISTS` по скрытию, поле `categories`, видимые измерения) и только если запрос называет навыки. Блокировки - те же, что у чтения карточки, ничего больше не блокируется; записи поиска ограничены кандидатами, которых он возвращает. +- Только владелец. Для MVP ищет действующий владелец организации. HTTP-граница отклоняет любую другую роль (`ownerCompanyOperations`), а usecase повторяет проверку роли под блокировкой членства, поэтому само членство ничего не дает. Полная матрица ролей и назначений - более поздняя работа и не должна расширять права по одному членству. +- Оплата как чтение карточек. Поиск возвращает содержимое карточки (подтвержденную категорию с силой, заявленный грейд, стек, диапазон стажа, форматы работы и объяснение), поэтому проходит через тот же лимит, что чтение карточки. Ранжируется весь видимый банк, затем каждая группа обрезается до `max_results_per_group` версии политики (демо 10, то есть не более 30 показов за один поиск, меньше 50 уникальных просмотров в сутки уровня E0); итог не возвращается. В порядке `main`, `near`, `unconfirmed` каждый впервые показанный кандидат резервируется через порт квоты компании (`candidateview.SearchViews.Reserve`, тот же `ReserveCardView`, что у чтения карточки: идемпотентно на организацию и кандидата внутри окна, поэтому повтор поиска или открытие карточки после него не списывает дважды), а в истории доступа кандидата появляется по одной записи `card_viewed` за поиск с фактически возвращенными полями (`SearchViews.Record`); все это в транзакции поиска. Когда лимит заканчивается, вывод останавливается на первом отказе: возвращаются уже оплаченные записи, `truncated` истинно, для остальных ничего не пишется, ошибки нет. `truncated` истинно и когда группа превысила предел; числа оно не несет. Полная карточка по-прежнему открывается своим чтением. +- Одна запись на специализацию кандидата, из карточки, которую организации разрешено видеть. Специализация подтверждена, только когда карточка показывает ее категорию (`categories` опубликованы и не обобщены до пустоты); роль, помеченная в самооценке как неподтвержденная, - неподтвержденная запись; роль, помеченная подтвержденной, чью категорию карточка не показывает, записи не дает, потому что результат не может заявлять подтверждение, которое кандидат не опубликовал. Один и тот же handle может быть подтвержден по Backend и не подтвержден по сетям, и подтверждение Backend никогда не меняет запись по сетям. Статус записи следует специализации запроса: подтвержденная специализация потребности и фильтр `specialization` оба ограничивают поиск, а два разных значения не оставляют ничего. Потребность без подтвержденной специализации ищет по всем и возвращает каждую специализацию отдельно. +- Фильтры, все до расчета. `confirmed_grade`, `confirmed_category` и `confirmation_status: confirmed` оставляют только подтвержденные записи; заявленный грейд их не удовлетворяет. `declared_grade` - отдельное заявление. `stack` требует каждый названный тег в карточке и одновременно считается обязательным навыком запроса. `conditions.work_formats` требует один общий формат, `conditions.salary_compatibility` - то же значение; неизвестное значение карточки условие не удовлетворяет. Одна неподтвержденная категория ничего не скрывает: без подтвержденного фильтра заявленные специализации выводятся. +- Запрошенные навыки. Навыки для Cov берутся из подтвержденных обязательных (вес 2) и желательных (вес 1) навыков снимка потребности, теги фильтра `stack` считаются обязательными. Код считается один раз, сколько бы раз он ни повторялся. Навык без таксономического кода не имеет проверенного соответствия, ничему не соответствует и остается пробелом. Пустой запрос использует нейтральное Cov 0.5 вместо деления на ноль. Потребность читается по `requirements_version` (`GetVersion`); общая версия, изменившая только название, не является снимком требований и дает 404, а снимок прежней версии требований остается доступным и неизменным. +- Доказательство навыка. Для каждого запрошенного навыка берется лучшее произведение коэффициентов доверия, атрибуции и связи среди разрешенных доказательств, а не их сумма. Доказательства - заявленные теги стека карточки (доверие 0, заявление) и для подтвержденной записи единственный факт оценки, подтверждающий ее категорию (доверие 1, личный). Связь точная для того же кода, широкая для специализации над технологией и узкая в обратную сторону, по `skill_taxonomy` версии политики (демо: `backend` над `docker`, `go`, `kafka`, `postgresql`; `devops_sre` над `docker`); версия без таксономии связывает только равные коды, так что версия политики полностью определяет результат. Таксономия - демонстрационное соответствие, а не измеренное. Онлайн-результат Backend стоит 0.6 * 1.0 * 0.4 = 0.24 для запрошенного Go, заявленный тег Go - 0.25; порог близости 0.25, поэтому кандидат, у которого единственное доказательство обязательной технологии - оценка Backend, для нее всегда в `near`, а одного заявленного тега достаточно для `main`. Это следствие значений PRD - вопрос владельцу продукта. Повтор тега или навыка ничего не добавляет. +- Компоненты и группы. `Cov` - взвешенное среднее вкладов; `Dom = 0.5` (анонимная карточка не несет домен) и `Sem = 0.5` для каждой записи (ML нет), оба названы в `unknown_flags`; `T = 0.5` с null-перцентилем и признаком `cohort_below_30`, который поиск доказывает, а не декларирует: он считает кандидатов, имеющих каждую возвращаемую категорию из источника, отличного от синтетической демонстрации (`CountRealComparableCategories`, только числа), и сравнивает число с `percentile_min_cohort`; сегодня оно равно 0, так как каждая сохраненная категория - синтетическая демонстрация, которая никогда не смешивается с реальными результатами. Реальной когорте на уровне минимума понадобилась бы theta ее участников, которой нет в организационно безопасной проекции, поэтому поиск из-за этого никогда не падает: T остается нейтральным 0.5, перцентиль остается null, причина становится `percentile_not_computed` вместо `cohort_below_30`, и поиск пишет одно предупреждение на каждую такую категорию. Считаются только категории записей, прошедших фильтры; `V = 0`, так как данных о соревнованиях нет, - это ни штраф, ни неизвестность; `Fr = Rsp = 0.5` с признаками `no_freshness_history` и `no_response_history`. Подтвержденная запись с обязательным навыком ниже порога близости (0.25) попадает в `near`, иначе в `main`; неподтвержденная запись попадает в `unconfirmed` только с Fit и Coverage, считается отдельным путем и никогда не вычисляет theta, T, P, перцентиль или S. Отсутствие ФСП нигде не оценивается. +- Порядок и округление. Баллы - целые числа в микроединицах (шесть знаков), доли - базисные пункты, произведения точные целые, поэтому одни и те же данные и политика дают один порядок на любой платформе. `main` и `near` сортируются по S, затем Cov (оба по убыванию), затем по внутреннему идентификатору кандидата по возрастанию (затем по коду специализации, который лишь разделяет две записи одного кандидата); `unconfirmed` - по Fit, затем Cov, затем по идентификатору. Идентификатор не покидает сервер, группы не объединяются общей шкалой. +- Объяснение. Сводка и признаки строятся из тех же рассчитанных вкладов: для каждой группы навыков `supports` (каждый навык подкреплен измерением не ниже порога), `declared_only` (только заявленные теги), `partial` (смесь или измерения ниже порога) или `gap` (ничего), а также подтвержденная категория, заявленный грейд, совпадение форматов работы с потребностью или фильтром и совместимость зарплаты. Только ограниченные коды, никогда свободный текст, контакт, локация кандидата, значение или минимум зарплаты, проваленная попытка или причина скрытых данных. Неизвестный компонент виден только в `unknown_flags`. +- Политика. Поиск читает действующую политику `product` на время приложения и ее раздел `matching`. Политика без раздела дает закрытый отказ с внутренней ошибкой (в перечислении ProblemCode нет кода для временно недоступной зависимости, и новый не добавляется); в логе ошибка говорит, что в действующей политике нет раздела подбора, и называет команду оператора `policy-publish`, при старте backend пишет предупреждение, пока раздела нет, а [DEPLOY.md](DEPLOY.md#политика-подбора-на-стенде) описывает команду. Ответ не называет версию политики, поиск не сохраняется. +- Параллельность. Резервирования берут исключительную блокировку организации порта квоты компании. Проверка членства до них держит на той же строке только разделяемую блокировку, и два поиска одной организации взаимно блокировались бы при ее повышении, поэтому поиск сначала берет блокировку организации (`CompanyQuotaRepository.LockOrganization`, документированный порядок; это FOR NO KEY UPDATE, поэтому читатели встают в очередь друг за другом, но блокировка внешнего ключа при собственном скрытии кандидата, которое держит строку кандидата и затем требует строку организации, не блокируется, а само резервирование по-прежнему берет FOR UPDATE в той же транзакции), а оплата одной организации сериализуется. Изменение видимой когорты во время ее блокировки (`ErrConcurrentVisibilityChange`) повторяет весь поиск до трех раз, а записи неудачной попытки откатываются вместе с ней. Чтение карточки (`GetOrganizationCard`) и раздел доказательств (`AuthorizeCategoriesSection`) по той же причине берут эту исключительную блокировку первой, до любой разделяемой: до такого порядка два одновременных чтения карточек одной организации взаимно блокировались (SQLSTATE 40P01). `TestMatchSearchOverHTTP` запускает одновременные чтения карточек, чтения доказательств и поиски одной организации и проверяет отсутствие взаимной блокировки и одну строку квоты на кандидата. +- Принятые остаточные риски. `truncated` - один бит о размере видимого банка (он говорит, что существует больше, чем предел или лимит), а время ответа растет с банком, поэтому оба раскрывают владельцу грубый размер. Бит ограничен пределом группы, число не возвращается; риск принят для демонстрации и внесен в вопросы владельцу. +- Проверки. Модульные тесты `internal/usecase/matching` (формулы с рассчитанными вручную значениями, равенства и порядок, фильтры, объяснение, обрезка и оплата вывода), `internal/domain/policy_matching_test.go` (круговой проход документа, строгость, проверка значений), `v1/matches_test.go` (отображение и ошибки) и интеграционный тест `TestMatchSearchOverHTTP` на PostgreSQL: скрытые кандидаты и две организации, потребность и ее измененные требования, повторные одинаковые ответы, Backend подтвержден и сети не подтверждены для одного handle, профиль без грейда, опубликованный настоящими операциями профиля, согласия и публикации и убранный отзывом C2, кандидат один в своей когорте, отсутствие контактов и идентификаторов в теле, оплата и история доступа за поиск, организация с лимитом меньше ее банка, предел группы, пакетное чтение доказательств, два одновременных поиска под одним лимитом, демонстрационный предел группы, таксономия политики, отказы доступа и политика без раздела. - score = 0.50 * skill_fit - + 0.40 * assessment_score - + 0.10 * fsp_evidence +Не реализовано: перцентиль и настоящий T (нужны theta сопоставимой реальной когорты не менее 30 человек); соревновательное значение V и данные ФСП; домен кандидата; истории свежести и своевременности; семантическая близость и признак недоступности ML сверх нейтрального значения; сохраняемые снимки `search_run`, уточнение, сравнение и шортлист; продолжение выдачи сверх предела группы; использование грейда потребности как фильтра. Приглашение из результата поиска тоже не реализовано, поэтому отзыв C2 после приглашения здесь не проверяется. -Все компоненты лежат в диапазоне 0..1. skill_fit - взвешенное покрытие подтвержденных навыков. assessment_score - результат по соответствующим разделам теста. fsp_evidence - небольшой бонус за релевантные проверенные достижения. При пустом наборе навыков применяется заранее определенное нейтральное значение, без деления на ноль. Равные значения сортируются стабильным tie-break по ID, а не по персональным признакам. +До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия. Это первая модель, а не оптимальное или измеренное ранжирование: планируется сравнить ключевые слова, baseline подтвержденных навыков и ML-вариант, семантический сигнал добавлять только после эксперимента и не считать его балл вероятностью успешного найма. -Нет истории ФСП - нулевой бонус, но кандидат остается в выдаче. Синтетические достижения помечаются и влияют только на демонстрационный набор. Результат включает score_components, reason_codes, подтверждающие факты и пробелы. Например, кандидат может иметь подтвержденный Middle и покрыть 4 из 5 навыков, но не пройдет фильтр, требующий все пять подтверждений. - -Формула - исходная baseline, не оптимальная или измеренная модель. До финала планируется сравнить ключевые слова, baseline подтвержденных навыков и ML-вариант. Семантический сигнал добавляется только после эксперимента и не становится вероятностью успешного найма. - -Каждая подборка сохраняется как search_run с компанией, исходной потребностью, фильтрами, версией ранжирования и родительской версией. Уточнение создает новый снимок. search_items фиксирует позиции, score и версии профилей без контактов. Старый снимок не сохраняет доступ: скрытые/удаленные профили из него исключаются, устаревший расчет помечается, срок хранения ограничен. +Каждая подборка сохраняется как search_run с компанией, исходной потребностью, фильтрами, версией ранжирования и родительской версией. Уточнение создает новый снимок. search_items фиксирует позиции, score и версии профилей без контактов. Старый снимок не сохраняет доступ: скрытые/удаленные профили из него исключаются, устаревший расчет помечается, срок хранения ограничен. Это запланировано; реализованный поиск ничего не сохраняет. ## ML, документы и фоновые задания @@ -953,7 +999,7 @@ Go экспортирует стандартные Go/process метрики и | Опрос, грейд, тест и категория, с. 1-3 | assessment, варианты задач, grade history | Не реализовано | | Сопоставимость тестов и защита от утечек, с. 1-2 | Семейства, blueprint, рубрики, ротация и пилот | Только план | | Не понижать грейд при провале, частота изменений, с. 2-3 | verified/claimed, retry правила, cooldown и eligibility | Только план | -| Поиск и объяснение, с. 3-4 | Жесткие фильтры, matching, evidence и score components | Не реализовано | +| Поиск и объяснение, с. 3-4 | Жесткие фильтры, matching, evidence и score components | Реализован базовый детерминированный поиск; ML, данных соревнований и снимков нет | | Уточнение поиска без потери старой выдачи, с. 4 | Версионные search_run и серверные снимки | Только план | | Приглашение без вакансии, с. 3 | Необязательный vacancy_id | Не реализовано | | Зарплата от-до в RUB, компания и связь, с. 4 | Обязательные границы зарплаты и явный формат периода/налогов | Не реализовано | diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 7ba89cb..8e596ee 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -122,11 +122,12 @@ Relay создает отсутствующий топик и никогда н ### Обработчики событий -Backend запускает по одному обработчику событий на каждый зарегистрированный handler в своем процессе рядом с HTTP-серверами и relay. Обработчик читает `KAFKA_EVENTS_TOPIC` как участник группы `.<имя обработчика>`, применяет каждое событие один раз и фиксирует offset только после того, как эффект зафиксирован в PostgreSQL. Устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий). Текущее состояние: зарегистрирован один продуктовый обработчик, `notification_delivery` (доставки писем), поэтому при `CONSUMER_ENABLED` и заданном `DATABASE_URL` backend запускает один обработчик в группе `.notification_delivery` (по умолчанию `lincodex.notification_delivery`). Compose не передает ни одну из них, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` сервиса backend в `deploy/docker/docker-compose.yml`. Недопустимое значение останавливает старт, даже если обработчики выключены. +Backend запускает по одному обработчику событий на каждый зарегистрированный handler в своем процессе рядом с HTTP-серверами и relay. Обработчик читает `KAFKA_EVENTS_TOPIC` как участник группы `.<имя обработчика>`, применяет каждое событие один раз и фиксирует offset только после того, как эффект зафиксирован в PostgreSQL. Устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий). Текущее состояние: зарегистрированы два продуктовых обработчика, `notification_delivery` (доставки писем) и `notification_inbox` (внутренние уведомления), поэтому при `CONSUMER_ENABLED` и заданном `DATABASE_URL` backend запускает по одному обработчику в группах `.notification_delivery` и `.notification_inbox` (по умолчанию `lincodex.notification_delivery` и `lincodex.notification_inbox`). Новая группа начинает с самого раннего сохраненного события топика, поэтому первый запуск `notification_inbox` после развертывания читает сохраненные события и пропускает события других типов. Compose не передает ни одну из них, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` сервиса backend в `deploy/docker/docker-compose.yml`. Недопустимое значение останавливает старт, даже если обработчики выключены. | Переменная | По умолчанию | Назначение | | --- | --- | --- | | `CONSUMER_ENABLED` | `true` | `true` или `false`. При `false` или без `DATABASE_URL` обработчики не работают, и события ждут в Kafka, пока их хранит топик. | +| `NOTIFICATION_SYNTHETIC_ENABLED` | `false` | `true` или `false`. Включает синтетическое событие inbox `notification.synthetic_delivered`: обработчик `notification_inbox` его сохраняет, а inbox показывает его фиксированный текст. В боевой среде держите выключенным; браузерный стенд E2E включает его. При `false` такое событие подтверждается и игнорируется, а сохраненная синтетическая строка показывается без содержимого. CHECK в базе разрешает этот тип в любом случае. | | `CONSUMER_GROUP_PREFIX` | `lincodex` | Префикс ID каждой consumer group, до 128 латинских букв, цифр, точек, подчеркиваний или дефисов. Смена префикса создает новые группы, которые читают топик с самой ранней хранимой записи; маркеры дедупликации превращают уже примененные события в дубликаты. | | `CONSUMER_MAX_ATTEMPTS` | `5` | Попытки обработчика для одного события до перевода в dead letters, от 1 до 20. Сбои базы вне обработчика не считаются. Должно укладываться в бюджет ребалансировки ниже. | | `CONSUMER_BACKOFF_INITIAL` | `500ms` | Пауза после первой неудачной попытки; удваивается после каждой следующей неудачи. | @@ -347,6 +348,19 @@ make -C backend assessment-category-attest ARGS='attest --specialization backend - Триггер аттестации принимает политику вида `demo` с `real_mode = demo_basic`. При присвоении категории база сверяет порог результата с `basic_pass_mark_bp` версии политики, закрепленной за попыткой, поэтому порог 9000 в принятой политике работает так же, как 8000. Попытки, по которым решение принято до аттестации, категории не получают; категорию присваивает только результат, принятый после нее. - Без любого из шагов результат с пройденным порогом сохраняется как `not_eligible`: кандидат видит оценку, категории нет. `demo_express` категорию не создает ни при каких настройках. `make -C backend assessment-category-attest-build` собирает `backend/bin/assessment-category-attest`. +## Политика подбора на стенде + +Подбор ранжирует по разделу `matching` действующей политики `product` и без него отказывает закрыто: поиск отвечает 500 `internal`, в логе строка уровня error сообщает, что в действующей политике нет раздела подбора, и называет команду ниже, значения по умолчанию не используются. Стартовое заполнение публикует только первую демонстрационную версию, в которой такого раздела нет, поэтому при старте backend пишет предупреждение `the effective product policy has no matching section`, пока раздела нет. Опубликуйте его один раз на стенде как оператор: + +```sh +make -C backend policy-publish ARGS='matching --actor operator:' +``` + +- Команда берет последнюю версию политики product, которая должна быть демонстрационной (kind `demo`), и публикует следующую версию как ее копию с добавленным демонстрационным разделом подбора. Остальные значения не меняются. Если в последней версии раздел уже есть, ничего не меняется и печатается `already present`; если за это время другая публикация заняла следующий номер версии, команда ничего не сохраняет и просит запустить ее снова; последняя калиброванная версия или семейство без версий отклоняются. `make -C backend policy-publish-build` собирает `backend/bin/policy-publish`. +- Нужен только `DATABASE_URL`, dotenv-файл не читается, аргументы проверяются до подключения, печатается только номер версии. Автор версии - метка `operator:`: это метка аудита, а не аутентификация, границей оператора служит локальный доступ к базе. +- Новая версия действует для новых поисков сразу и не меняет сохраненных результатов. Это также новая версия всей политики product, поэтому открытие категории, привязанное к прежней версии, нужно открыть заново (и аттестовать заново на демонстрационном стенде, см. выше), прежде чем создавать новые попытки оценки. Публикуйте ее до начала попыток кандидатов либо повторите открытие и аттестацию после. +- Демонстрационные значения (коэффициенты PRD, предел 10 записей на группу и небольшая таксономия «специализация - технология») описаны в [архитектуре](ARCHITECTURE.md#версии-продуктовой-политики); они не калиброваны. Изолированный браузерный стенд публикует тот же раздел сам. + ## Отдельный ML Compose ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 866005a..8f7128e 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -53,7 +53,7 @@ Frontend зависимости выбираются из актуальных s - Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы продуктовых уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но отправка уведомлений еще не реализована. При `resend` backend запускает worker служебной почты identity: регистрация и повторная отправка создают письма подтверждения, привязанные к токенам; worker проверяет токен и аккаунт перед отправкой и использует шлюз квот и стабильный ключ идемпотентности. Сброс пароля пока не реализован. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). SPA использует generated API client; MSW handlers служат тестовыми данными. Реализованные формы перечислены ниже, остальные маршруты пока показывают заготовки. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). -- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает один продуктовый обработчик - обработчик доставки писем, а продуктовые сценарии пока не создают его событие; см. [Обработчики событий](#обработчики-событий). +- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает два продуктовых обработчика - доставки писем и inbox, а продуктовые сценарии пока не создают их события; см. [Обработчики событий](#обработчики-событий). - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. @@ -195,7 +195,7 @@ Backend, запущенный напрямую с `DATABASE_URL`, запуска Runtime обработчиков применяет события из Kafka к собственному состоянию сервиса, по одному разу на обработчик. Цикл находится в `backend/internal/worker/eventconsumer/`; он зависит от порта `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`) и портов `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` - участник группы на franz-go, который декодирует конверт и фиксирует offsets, а `postgres.EventConsumerStore` выполняет транзакцию дедупликации запросами из `backend/db/queries/event_consumer.sql`. Backoff общий с relay и находится в `backend/internal/worker/retry/`. -Зарегистрирован один продуктовый обработчик: `notification.DeliveryHandler` сохраняет доставки писем (см. [Доставки писем](#доставки-писем)). Чтобы добавить другой обработчик, реализуйте `inbound.EventHandler` в пакете usecase модуля: верните стабильное имя в snake_case из `ConsumerName()`, принимайте в `Handles` только применяемые типы событий и пишите эффект в `Handle` только через полученный `UnitOfWork`. Для события, которое нельзя применить никогда, например с неизвестной `schema_version`, верните ошибку, оборачивающую `inbound.ErrEventRejected`; любая другая ошибка повторяется. Затем добавьте обработчик в `eventHandlers()` в `backend/internal/bootstrap/consumers.go`. Bootstrap выдает ему consumer group, соединение из пула обработчиков и жизненный цикл рядом с HTTP-серверами. Проверяйте эффект на реальном PostgreSQL через хранилище, как это делает `TestEventConsumer`. +Зарегистрированы два продуктовых обработчика: `notification.DeliveryHandler` сохраняет доставки писем (см. [Доставки писем](#доставки-писем)), а `notification.InboxHandler` сохраняет ссылки inbox (см. [Внутренние уведомления](#внутренние-уведомления)). Чтобы добавить другой обработчик, реализуйте `inbound.EventHandler` в пакете usecase модуля: верните стабильное имя в snake_case из `ConsumerName()`, принимайте в `Handles` только применяемые типы событий и пишите эффект в `Handle` только через полученный `UnitOfWork`. Для события, которое нельзя применить никогда, например с неизвестной `schema_version`, верните ошибку, оборачивающую `inbound.ErrEventRejected`; любая другая ошибка повторяется. Затем добавьте обработчик в `eventHandlers()` в `backend/internal/bootstrap/consumers.go`. Bootstrap выдает ему consumer group, соединение из пула обработчиков и жизненный цикл рядом с HTTP-серверами. Проверяйте эффект на реальном PostgreSQL через хранилище, как это делает `TestEventConsumer`. Backend, запущенный напрямую с зарегистрированным обработчиком и `DATABASE_URL`, читает события из `KAFKA_BROKERS`; задайте `CONSUMER_ENABLED=false`, если это не нужно. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий); настройки, метрики и порядок работы с dead letters - в [DEPLOY.md](DEPLOY.md#обработчики-событий); тесты - в [TESTING.md](TESTING.md#тесты-обработчиков-событий). @@ -205,6 +205,10 @@ Backend, запущенный напрямую с зарегистрирован Каждая отправка обязана пройти `notification.QuotaGate`: соберите его с настроенными аккаунтом и лимитами и окном идемпотентности транспорта (`resend.IdempotencyWindow` или ноль для SMTP); вызовите `PrepareSend` в транзакции, которая захватывает доставку, и зафиксируйте ее до вызова `MailSender.Send`; затем вызовите `SettleSend` в транзакции, которая записывает попытку, и для отказа `quota_exhausted` используйте возвращенный момент как `next_attempt_at` попытки. Для отказа по квоте транспорт заполняет `SendResult.QuotaPeriod` по собственному имени ошибки провайдера. Никогда не вызывайте транспорт без разрешения и не переключайтесь на другой транспорт или аккаунт, когда квота исчерпана. Чтобы показать аккаунту статус его писем, вызывайте `notification.DeliveryStatusReader.LatestForUser` только с ID аутентифицированного аккаунта. Правила описаны в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты). +### Внутренние уведомления + +Чтобы положить уведомление в inbox получателя, добавьте событие через `unit.Outbox().Append` в собственной транзакции usecase. Тип должен быть разрешен (`domain.NotificationInboxSourceFor`), payload должен состоять ровно из `recipient_user_id` и `organization_id`, а агрегат - тот, который назван для типа (`invitation` для `invitation.delivered`). Никогда не кладите в payload текст или контакты. Обработчик `notification_inbox` сохраняет ссылку. Текст создается, когда получатель читает список, преобразователем, который вы регистрируете для своего типа источника в `notification.DefaultInboxSourceResolvers()`: `InboxSourceResolver` читает текущее состояние через `UnitOfWork`, применяет текущую видимость получателя и возвращает `ErrInboxContentUnavailable`, когда содержимое показывать нельзя. Для нового типа события добавьте пару в `domain.NotificationInboxSourceFor`, запись в `inboxProjections` в `usecase/notification/inbox_handler.go`, миграцию, расширяющую CHECK у `notification_inbox_events` (развернутую миграцию не правят), значение `NotificationKind` в контракт и отображение в `adapter/primary/http/v1/notifications.go`. Источнику письмо не нужно: почта запрашивается отдельно через `MailRequester`, а состояние inbox от нее не зависит. Путь можно проверить целиком синтетическим событием `notification.synthetic_delivered` (payload строит `notification.SyntheticNoticeEventPayload`); продуктового смысла у него нет, и обрабатывается он только при `NOTIFICATION_SYNTHETIC_ENABLED=true`. См. [Внутренние уведомления](ARCHITECTURE.md#внутренние-уведомления). + ### Задания по сроку Чтобы выполнить что-то в срок, например истечение или напоминание, запланируйте задание в собственной транзакции usecase: соберите его через `domain.NewScheduledJob` (вид, например `invitation.response_deadline`, ключ логического задания, например ID агрегата, срок по внедренным часам и payload только из идентификаторов) и вызовите `unit.ScheduledJobs().Schedule(ctx, job)`. Побеждает первое планирование вида и ключа, повтор игнорируется, поэтому для нового повторения используйте новый ключ, например `:`. Отменяйте через `unit.ScheduledJobs().Cancel(ctx, kind, key)` до блокировки продуктовых строк, которые трогает обработчик. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 1adb14b..3d64f86 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -174,7 +174,7 @@ Unit-тесты (`make -C backend test`) покрывают модель дос - `internal/usecase/notification/`: запрос сохраняет текст под ID агрегата события, а payload события содержит только `mail_request_id` и `kind`; некорректные запросы ничего не записывают; обработчик сохраняет одну доставку под ID запроса с исходным событием, адресом аккаунта, сформированным содержимым, настроенным аккаунтом провайдера и временем часов и удаляет запрос; то же событие повторно не находит запрос; существующая доставка под ID запроса принимается для того же получателя и вида и отклоняется в остальных случаях; сломанные события (другая версия схемы или агрегат, некорректный payload, данные после объекта, ID запроса, не равный ID агрегата, вид письма с токеном) и текст, который отклоняет шаблон, отклоняются без цитирования payload; исчезнувший запрос, исчезнувший аккаунт и неподтвержденный адрес пропускаются со строкой лога, которая называет только ID доставки и события; ошибки хранилища, включая аккаунт, удаленный между чтением и вставкой, остаются повторяемыми и сохраняют запрос; ни одна ошибка и строка лога не содержит адрес, тему или тело. - `internal/adapter/secondary/postgres/`: ошибки ограничений доставок и запросов писем переводятся в свои sentinel (`deliveries_content_immutable` и `delivery_attempts_immutable` - в `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` - в `ErrDeliveryProviderPinned`, внешние ключи на пользователей - в `ErrUserNotFound`), а любая другая ошибка PostgreSQL, например нарушение CHECK, сохраняет только SQLSTATE и имя ограничения без message и detail. - `internal/usecase/notification/mailtemplate/`: результат рендеринга переводится в сохраняемое содержимое с тем же видом, версией, частями и hash. -- `config/` и `internal/bootstrap/`: `EMAIL_ACCOUNT` по умолчанию равен `default`, принимает метки до 64 символов и отклоняет пустые, со смешанным регистром, похожие на ключ и слишком длинные значения, не повторяя их; bootstrap регистрирует ровно обработчик `notification_delivery` и отклоняет некорректную метку аккаунта. +- `config/` и `internal/bootstrap/`: `EMAIL_ACCOUNT` по умолчанию равен `default`, принимает метки до 64 символов и отклоняет пустые, со смешанным регистром, похожие на ключ и слишком длинные значения, не повторяя их; bootstrap регистрирует ровно обработчики `notification_delivery` и `notification_inbox` и отклоняет некорректную метку аккаунта. `TestMailDelivery` в `backend/integration_test/delivery_test.go` использует `bootstrap(t, postgresService, kafkaService)` и настоящие usecase запроса, обработчик, relay, runtime обработчиков и хранилища. Последовательные случаи: @@ -463,6 +463,22 @@ Unit-тесты (`make -C backend test`) проверяют правила жу Тесты доказывают сохраненные факты, закрепление политики, вычисление заданием и отсутствие полосы в контракте и в чтениях кандидата. Они не доказывают качество обнаружения: пороги не откалиброваны, измерение ложных срабатываний покрывает четыре написанных семейства, исследования на реальных кандидатах нет. Чтения работодателя покрыты обходом контракта, а не HTTP-вызовом каждой операции. +## Тесты внутренних уведомлений + +Модульные тесты (`make -C backend test`, `make -C frontend test`): + +- `domain/notification_inbox_test.go`: запись принимает только разрешенные пары типа события и типа источника (синтетическое событие с организацией, `invitation.delivered` с приглашением), новая запись непрочитана, а `MarkRead` сохраняет первое время. +- `usecase/notification/inbox_test.go` с памятью вместо репозитория и фальшивым unit of work: список вычисляет каждый элемент по текущему источнику и при отказе показывает его без содержимого; кабинет кандидата отказывает работодателю, кабинет организации отказывает кандидату, неизвестному или неподтвержденному аккаунту и отозванному членству (оно отвечает как неизвестная организация, и для списка, и для отметки); строка репозитория вне области получателя - внутренняя ошибка; владелец и рекрутер (и остальные роли) читают и отмечают только свои элементы организации, а членство блокируется на время чтения; работодатель с неподтвержденной почтой получает `ErrInboxEmailNotVerified`; отметка сохраняет первое время и не может задеть элемент другого получателя; ссылки содержимого отклоняют внешний URL, URL без схемы, query, fragment, обратную косую черту, escape, сегмент с точками и длинный путь; синтетический преобразователь следует положению получателя, а тип источника без преобразователя недоступен. +- `usecase/notification/inbox_handler_test.go`: повторное событие дает одну строку; неверная версия схемы, агрегат, неизвестное поле, отсутствие организации, payload не объектом, лишние данные и ID события, повторенный с другими метаданными, отклоняются окончательно; удаленный получатель пропускается; сбой хранилища остается повторяемым; неподтвержденный адрес все равно получает строку (inbox не читает состояние почты); получатель, исчезнувший между проверкой и вставкой, повторяется и затем пропускается, а не отклоняется; синтетическое событие игнорируется при выключенном флаге; событие `invitation.delivered` с тем же контрактом payload сохраняет приглашение как источник. +- `adapter/primary/http/v1/notifications_test.go` и `adapter/primary/http/notification_contract_test.go`: отображение содержимого и запасного варианта, курсор, привязанный к аккаунту и кабинету (чужой или перепутанный курсор дает 400), отказы, соглашения четырех операций и закрытые схемы. `bootstrap/consumers_test.go` фиксирует два зарегистрированных обработчика. +- Frontend: `features/notifications/` проверяет проверку ссылки, один повтор отметки после 403 (и отсутствие повтора после 401, 404 и 500), подписи, формулировку элемента без содержимого, ключи запросов и их удаление по аккаунту и отрисованный список (состояние прочтения словом, кнопка отметки только у непрочитанных, нет небезопасной ссылки, пустое состояние, отказ для чужого кабинета). + +Интеграционные тесты (`make -C backend test-int`; PostgreSQL и Redis, без Kafka): `TestNotificationInboxOverHTTP` пишет синтетическое событие через настоящий писатель outbox и доставляет его через хранилище обработчика с настоящим обработчиком. Одно событие, доставленное дважды и еще раз переименованным обработчиком, дает одну строку. Затем на том же роутере проверяются список кандидата, чужой кандидат, чужой кабинет, отсутствие CSRF-токена и чужой Origin, отметка и ее повтор (первое время сохраняется), сохранение состояния прочтения, потеря содержимого, когда кандидат скрывает организацию, страницы с курсором, привязанным к аккаунту, кабинет работодателя только с его элементами организации, рекрутер со своими элементами, не участник, элемент другой организации и 404 для списка и отметки после отзыва членства. `TestSyntheticNotificationMigrationAllowlistAndGuardedRollback` и `TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows` проверяют список разрешенных значений миграции 00036, отказ отката при синтетической строке и восстановленное ограничение. `TestNotificationInboxStoreNamesTheMissingReference` проверяет, что отсутствующий получатель и отсутствующая организация различаются. `TestPostgresMigrations` покрывает подъем и откат до нуля. + +Браузерный тест: `frontend/e2e/notifications.spec.ts` запускается в `make -C deploy test-e2e-registration`, overlay которого задает `NOTIFICATION_SYNTHETIC_ENABLED=true`. `company-fixture` (тег сборки Go `e2e`, bearer-токен, только синтетические получатели `@example.test`) добавляет синтетическое событие в настоящий outbox, поэтому relay, Kafka и обработчик `notification_inbox` доставляют его; тест ждет появления элемента. Затем он повторяет событие через fixture, который обязан сообщить, что настоящий обработчик уже применил его, и проверяет, что в списке по-прежнему один элемент. Кандидат открывает список, отмечает элемент с клавиатуры, перезагружает страницу и видит сохраненное состояние, а второй кандидат получает пустой список и 404 на тот же ID. После скрытия организации элемент остается без содержимого. Второй тест читает inbox организации как владелец, проверяет не участника, отзывает членство через fixture и проверяет, что тот же ID отклоняется, а страница не показывает содержимое. + +Чего эти тесты не показывают: настоящее приглашение (пока ни одно не создает событие), поведение inbox при сбое почтового провайдера (по построению обработчик не читает состояние почты, а модульный тест покрывает неподтвержденный адрес), задержку доставки и нагрузку, push и живые обновления, а также вёрстку и работу страницы со скринридером (автоматической проверки нет). + ## Будущая программная валидация Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером. diff --git a/frontend/README.en.md b/frontend/README.en.md index 26bb507..2607a57 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -124,6 +124,12 @@ The tests take their fixtures from the named contract examples in `api/core/open Candidates can use `/candidate/support/cases/manual-assessment` to submit a support request with a specialization, desired grade, and description. This does not run automatic assessment, create an attempt, change C3, or grant a confirmed grade. The hint under the specialization and grade selectors uses the published grades from the catalog but does not promise a rubric: the server pins the version on submission. The case page displays the status and rubric version returned by the server and, for `null`, says plainly that no published rubric existed when the request was made; the client does not create an outcome. After a page reload the form loses its idempotency key, and a repeated submission while a manual assessment of the same specialization is open receives 409; the page explains this and links to "My cases" without creating a second request. +## Notifications + +`features/notifications` shows the inbox of the signed-in account at `/candidate/notifications` and `/employer/notifications`, and each shell links to it. `NotificationInbox` takes a scope: the candidate cabinet, or one organization. `OrganizationNotificationInbox` chooses the organization from the active memberships of the account (the `organization_id` parameter keeps the choice across reloads) and renders the inbox. The list is read on every visit and window focus and is never kept (`gcTime: 0`); the cached pages are keyed by account and cabinet and dropped when the account or the session changes or when the server refuses access. + +The server resolves the text of every item from its current source. An item without content stays in the list with a generic line, and the client never shows an earlier copy. The read state is a word ("Не прочитано" or "Прочитано"), not only a style. "Отметить прочитанным" is a native button, sends the CSRF token of the session (read at call time; after a 403 it reads the session again and retries once, and only a 401 or 404 counts as lost access), and moves focus to the heading of the item after it succeeds, with a polite status message. A content link opens only if it is a same-origin path inside the cabinet that shows it. States: loading, empty, error with retry, forbidden (including a membership that ended), and "Показать еще" for the next page. Component tests render markup in Node; the keyboard path and the delivery of a real event are checked by `frontend/e2e/notifications.spec.ts`. + ## API client generation `make -C frontend generate` runs Orval with `codegen/orval.config.ts` and then `codegen/mock-patterns.ts`. For a string with a `pattern`, Orval 8.40 writes `faker.helpers.fromRegExp(pattern)` into the MSW mock: faker prints the `^` and `$` anchors and `(?:...)` groups as plain text, and Orval ignores `minLength` and `maxLength` when a `pattern` is present. The second step replaces such calls with `fakeFromPattern(pattern, {minLength, maxLength})` from `src/shared/api/mock-pattern.ts`. It takes the length bounds from the OpenAPI contract by the name of the property that holds the call and by the pattern. The step fails when a call has an unexpected form, when the contract has no such property with that pattern, or when the matching schemas disagree on the length bounds. It leaves its own output unchanged, so generation is reproducible and `make check-generated` stays stable. Enums in the mocks are written as literals (`enumGenerationType: "union"`): `Object.values` of a `zod.enum` returns Zod internals, not the values. diff --git a/frontend/README.md b/frontend/README.md index 52bacd3..2421dba 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -124,6 +124,12 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Кандидату доступен `/candidate/support/cases/manual-assessment`: форма отправляет специальность, желаемый грейд и описание как запрос поддержки. Это не запускает автоматическую оценку, не создает попытку, не меняет C3 и не присваивает подтвержденный грейд. Подсказка под выбором специальности и грейда учитывает опубликованные грейды каталога, но не обещает рубрику: версию фиксирует сервер при отправке. Страница обращения показывает статус и версию рубрики, возвращенные сервером, а при `null` прямо сообщает, что опубликованной рубрики на момент запроса не было; результат не создается на клиенте. После перезагрузки страницы форма теряет ключ идемпотентности, и повторная отправка при открытой ручной оценке той же специальности получает 409; страница объясняет это и ведет в "Мои обращения", не создавая второй запрос. +## Уведомления + +`features/notifications` показывает inbox текущего аккаунта на `/candidate/notifications` и `/employer/notifications`, а каждая оболочка ссылается на него. `NotificationInbox` принимает область: кабинет кандидата или одна организация. `OrganizationNotificationInbox` выбирает организацию из активных членств аккаунта (параметр `organization_id` сохраняет выбор при перезагрузке) и показывает inbox. Список читается при каждом заходе и при фокусе окна и не сохраняется (`gcTime: 0`); кэшированные страницы привязаны к аккаунту и кабинету и сбрасываются при смене аккаунта или сессии и когда сервер отказывает в доступе. + +Текст каждого элемента сервер вычисляет из его текущего источника. Элемент без содержимого остается в списке с общей строкой, а клиент никогда не показывает прежнюю копию. Состояние прочтения выражено словом ("Не прочитано" или "Прочитано"), а не только стилем. "Отметить прочитанным" - нативная кнопка, она отправляет CSRF-токен сессии (читается в момент запроса; после 403 сессия читается заново и запрос повторяется один раз, а потерей доступа считаются только 401 и 404) и после успеха переводит фокус на заголовок элемента, объявляя вежливое сообщение о статусе. Ссылка содержимого открывается, только если это путь того же origin внутри кабинета, который ее показывает. Состояния: загрузка, пусто, ошибка с повтором, нет доступа (в том числе при завершенном членстве) и "Показать еще" для следующей страницы. Компонентные тесты отрисовывают разметку в Node; путь с клавиатуры и доставку настоящего события проверяет `frontend/e2e/notifications.spec.ts`. + ## Генерация API-клиента `make -C frontend generate` запускает Orval с `codegen/orval.config.ts`, а затем `codegen/mock-patterns.ts`. Для строки с `pattern` Orval 8.40 пишет в MSW-мок `faker.helpers.fromRegExp(pattern)`: faker выводит якоря `^`, `$` и группы `(?:...)` как обычный текст, а `minLength` и `maxLength` при `pattern` Orval не учитывает. Второй шаг заменяет такие вызовы на `fakeFromPattern(pattern, {minLength, maxLength})` из `src/shared/api/mock-pattern.ts`. Границы длины он берет из OpenAPI-контракта по имени свойства, которое содержит вызов, и шаблону. Шаг завершается ошибкой, если вызов имеет неожиданный вид, в контракте нет такого свойства с этим шаблоном или схемы с ними расходятся в границах длины. На своем результате шаг ничего не меняет, поэтому генерация воспроизводима и `make check-generated` стабилен. Перечисления в моках записаны литералами (`enumGenerationType: "union"`): `Object.values` от `zod.enum` возвращает внутренние поля Zod, а не значения. diff --git a/frontend/e2e/notifications.spec.ts b/frontend/e2e/notifications.spec.ts new file mode 100644 index 0000000..91da9ad --- /dev/null +++ b/frontend/e2e/notifications.spec.ts @@ -0,0 +1,320 @@ +import { expect, test, type BrowserContext, type Page } from "@playwright/test"; + +type InboxMessage = { id?: string; text?: string; html?: string }; +type ApiResult = { status: number; body: unknown }; +type NotificationBody = { + id: string; + read_at: string | null; + content: { title: string; summary: string } | null; +}; +type NotificationPageBody = { items: NotificationBody[] }; + +const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; +const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1"; +const password = "correct horse battery staple 2026"; +const deliveryTimeoutMs = 60_000; + +test.use({ trace: "off", screenshot: "off", video: "off" }); +// Each test registers several accounts and waits for the event to travel +// through the relay and the bus, which a loaded stand makes slow. +test.setTimeout(120_000); + +function baseUrl(): string { + const value = process.env.E2E_BASE_URL; + if (!value) throw new Error("The local end-to-end base URL is not configured."); + return value; +} + +async function readInbox(email: string): Promise { + const inboxUrl = process.env.E2E_MAILBOX_URL; + const token = process.env.E2E_MAILBOX_TOKEN; + if (!inboxUrl || !token) throw new Error("The local registration mailbox is not configured."); + const url = new URL(inboxUrl); + url.searchParams.set("to", email); + const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); + if (!response.ok) throw new Error("Could not read the local registration mailbox."); + return ((await response.json()) as { messages: InboxMessage[] }).messages; +} + +async function verificationToken(email: string): Promise { + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + const message = (await readInbox(email)).at(-1); + if (message) { + const content = `${message.text ?? ""}\n${message.html ?? ""}`; + const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1]; + if (!token) throw new Error("The registration message had no verification link."); + return token; + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error("The local mailbox did not receive the verification message."); +} + +type Account = { email: string; userId: string }; + +// Registers, confirms, and signs in a synthetic account. Employer addresses +// follow the pattern that the company fixture accepts. +async function createAccount(page: Page, scenario: "candidate" | "employer"): Promise { + const suffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8); + const email = + scenario === "employer" ? `company-${suffix}@example.test` : `inbox-${suffix}@example.test`; + await page.goto("/register"); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + await page + .getByRole("radio", { name: scenario === "employer" ? /Работодатель/ : /Кандидат/ }) + .check(); + await page.getByRole("checkbox", { name: /принимаю его/ }).check(); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + + const verificationUrl = new URL("/verify-email", baseUrl()); + verificationUrl.hash = `token=${await verificationToken(email)}`; + await page.goto(verificationUrl.toString()); + await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + await page.getByRole("button", { name: "Подтвердить почту" }).click(); + await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); + + await page.goto(scenario === "employer" ? "/employer/company" : "/candidate"); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + const loginResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/sessions" && + response.status() === 201, + ); + await page.getByRole("button", { name: "Войти" }).click(); + const session = (await (await loginResponse).json()) as { account: { id: string } }; + return { email, userId: session.account.id }; +} + +// Calls the API from the page, so the cookie and the origin are the browser's. +async function api(page: Page, method: string, path: string, body?: unknown): Promise { + return page.evaluate( + async ({ method, path, body }) => { + const headers: Record = {}; + if (method !== "GET") { + const session = await fetch("/api/v1/identity/sessions/current", { + credentials: "include", + }); + headers["X-CSRF-Token"] = ((await session.json()) as { csrf_token: string }).csrf_token; + headers["Idempotency-Key"] = crypto.randomUUID(); + } + if (body !== undefined) headers["Content-Type"] = "application/json"; + const response = await fetch(path, { + method, + headers, + credentials: "include", + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + return { status: response.status, body: await response.json().catch(() => null) }; + }, + { method, path, body }, + ); +} + +async function createOrganization(page: Page, name: string): Promise { + const suffix = crypto.randomUUID().slice(0, 8); + const created = await api(page, "POST", "/api/v1/organizations", { + name, + contacts: { + website: `https://notice-${suffix}.example.test`, + email: `careers@notice-${suffix}.example.test`, + phone: "+12025550123", + telegram: "@noticeinbox", + }, + }); + expect(created.status).toBe(201); + return (created.body as { id: string }).id; +} + +async function fixture(path: string, body: unknown): Promise<{ status: number; body: unknown }> { + const origin = process.env.E2E_COMPANY_FIXTURE_URL; + const token = process.env.E2E_COMPANY_FIXTURE_TOKEN; + if (!origin || !token) throw new Error("The local company fixture is not configured."); + const response = await fetch(new URL(path, origin), { + method: "POST", + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + return { status: response.status, body: await response.json().catch(() => null) }; +} + +async function publishNotice(recipientUserId: string, organizationId: string): Promise { + const published = await fixture("/notifications/synthetic", { + recipient_user_id: recipientUserId, + organization_id: organizationId, + }); + expect(published.status).toBe(201); + return (published.body as { event_id: string }).event_id; +} + +// The event travels through the real outbox, relay, event bus, and consumer, +// so the item appears after a delay; the page is read again until it does. +async function waitForItems(page: Page, path: string, count: number): Promise { + await page.goto(path); + await expect(async () => { + await page.reload(); + await expect(page.getByRole("list", { name: "Уведомления" }).getByRole("listitem")).toHaveCount( + count, + { timeout: 2_000 }, + ); + }).toPass({ timeout: deliveryTimeoutMs, intervals: [500, 1_000, 2_000] }); +} + +async function newPage(context: BrowserContext): Promise { + return context.newPage(); +} + +test.describe("internal notifications", () => { + test.skip( + !mailFixtureEnabled || !companyFixtureEnabled, + "Requires the isolated mail and company fixtures.", + ); + + test("a candidate reads, marks, and loses the content of one delivered-twice event", async ({ + browser, + page, + }) => { + const context = (): Promise => + browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); + const senderContext = await context(); + const otherContext = await context(); + try { + const sender = await newPage(senderContext); + await createAccount(sender, "employer"); + const organizationName = `Север ${crypto.randomUUID().slice(0, 6)}`; + const organizationId = await createOrganization(sender, organizationName); + + const candidate = await createAccount(page, "candidate"); + await page.goto("/candidate/notifications"); + await expect(page.getByRole("heading", { name: "Уведомления", level: 1 })).toBeVisible(); + await expect(page.getByText("Уведомлений пока нет")).toBeVisible(); + + const eventId = await publishNotice(candidate.userId, organizationId); + await waitForItems(page, "/candidate/notifications", 1); + + // The real consumer already stored the event. A second delivery by the + // same consumer and a third by a renamed one still leave one item. + const replay = await fixture("/notifications/synthetic/replay", { event_id: eventId }); + expect(replay.status).toBe(200); + expect(replay.body).toEqual({ primary_applied: false, renamed_applied: true }); + await page.reload(); + const items = page.getByRole("list", { name: "Уведомления" }).getByRole("listitem"); + await expect(items).toHaveCount(1); + await expect(items.first()).toContainText(organizationName); + await expect(items.first()).toContainText("Не прочитано"); + + // The mark is reachable and operable from the keyboard. + const mark = items.first().getByRole("button", { name: /Отметить прочитанным/ }); + await mark.focus(); + await expect(mark).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(items.first()).toContainText("Прочитано"); + await expect(items.first()).not.toContainText("Не прочитано"); + await expect(items.first().getByRole("button")).toHaveCount(0); + await expect(items.first().getByRole("heading", { level: 2 })).toBeFocused(); + await expect( + page.getByRole("status").filter({ hasText: "отмечено прочитанным" }), + ).toBeAttached(); + + // The read state is stored on the server. + await page.reload(); + await expect(items).toHaveCount(1); + await expect(items.first()).toContainText("Прочитано"); + await expect(items.first().getByRole("button")).toHaveCount(0); + + // Another candidate neither lists nor marks the same ID. + const other = await newPage(otherContext); + await createAccount(other, "candidate"); + const otherList = await api(other, "GET", "/api/v1/me/notifications"); + expect(otherList.status).toBe(200); + expect((otherList.body as NotificationPageBody).items).toHaveLength(0); + const otherMark = await api(other, "POST", `/api/v1/me/notifications/${eventId}/read`); + expect(otherMark.status).toBe(404); + await other.goto("/candidate/notifications"); + await expect(other.getByText("Уведомлений пока нет")).toBeVisible(); + // An employer account gets no candidate inbox. + const employerRead = await api(sender, "GET", "/api/v1/me/notifications"); + expect(employerRead.status).toBe(403); + + // After the candidate hides the organization the item stays, but its + // text is gone from the next read and from the page. + const hidden = await fixture("/notifications/synthetic/hide-organization", { + recipient_user_id: candidate.userId, + organization_id: organizationId, + }); + expect(hidden.status).toBe(204); + await page.reload(); + await expect(items).toHaveCount(1); + await expect(items.first()).toContainText("Содержимое больше недоступно"); + await expect(items.first()).toContainText("Прочитано"); + await expect(page.getByText(organizationName)).toHaveCount(0); + const hiddenRead = await api(page, "GET", "/api/v1/me/notifications"); + expect((hiddenRead.body as NotificationPageBody).items[0]?.content).toBeNull(); + } finally { + await senderContext.close(); + await otherContext.close(); + } + }); + + test("an employer reads the organization inbox until the membership is revoked", async ({ + browser, + page, + }) => { + const successorContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); + try { + const owner = await createAccount(page, "employer"); + const organizationName = `Юг ${crypto.randomUUID().slice(0, 6)}`; + const organizationId = await createOrganization(page, organizationName); + const successorPage = await newPage(successorContext); + const successor = await createAccount(successorPage, "employer"); + + const eventId = await publishNotice(owner.userId, organizationId); + await waitForItems(page, "/employer/notifications", 1); + await expect(page.getByRole("heading", { name: "Уведомления", level: 1 })).toBeVisible(); + const items = page.getByRole("list", { name: "Уведомления" }).getByRole("listitem"); + await expect(items.first()).toContainText(organizationName); + + await items + .first() + .getByRole("button", { name: /Отметить прочитанным/ }) + .click(); + await expect(items.first()).toContainText("Прочитано"); + await page.reload(); + await expect(items.first()).toContainText("Прочитано"); + await expect(items.first().getByRole("button")).toHaveCount(0); + + // A non-member gets the same answer as for an unknown organization. + const listPath = `/api/v1/organizations/${organizationId}/notifications`; + expect((await api(successorPage, "GET", listPath)).status).toBe(404); + expect((await api(successorPage, "POST", `${listPath}/${eventId}/read`)).status).toBe(404); + + const revoked = await fixture("/company/memberships/revoke", { + organization_id: organizationId, + user_id: owner.userId, + successor_user_id: successor.userId, + }); + expect(revoked.status).toBe(204); + + // The same ID after the revocation: refusal, and no content in the page. + expect((await api(page, "GET", listPath)).status).toBe(404); + expect((await api(page, "POST", `${listPath}/${eventId}/read`)).status).toBe(404); + await page.goto(`/employer/notifications?organization_id=${organizationId}`); + await expect(page.getByText("Компаний пока нет")).toBeVisible(); + await expect(page.getByText(organizationName)).toHaveCount(0); + + // The new owner sees the organization inbox, not the item of the former + // owner, and cannot mark it. + const successorList = await api(successorPage, "GET", listPath); + expect(successorList.status).toBe(200); + expect((successorList.body as NotificationPageBody).items).toHaveLength(0); + expect((await api(successorPage, "POST", `${listPath}/${eventId}/read`)).status).toBe(404); + } finally { + await successorContext.close(); + } + }); +}); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx index 07a0524..b5ffcd1 100644 --- a/frontend/src/app/router/routes.tsx +++ b/frontend/src/app/router/routes.tsx @@ -9,6 +9,7 @@ import { SessionGate } from "../../entities/session"; import { NotFoundPage } from "../../pages/not-found"; import { NeedEditorPage } from "../../pages/need-editor"; import { NeedListPage } from "../../pages/needs"; +import { CandidateNotificationsPage, EmployerNotificationsPage } from "../../pages/notifications"; import { PlaceholderPage } from "../../pages/placeholder"; import { ProfilePage } from "../../pages/profile"; import { QuestionnairePage } from "../../pages/questionnaire"; @@ -81,6 +82,7 @@ export const routes: RouteObject[] = [ path: paths.candidate.invitations, element: , }, + { path: paths.candidate.notifications, element: }, { path: paths.candidate.privacy, element: , @@ -131,6 +133,7 @@ export const routes: RouteObject[] = [ path: paths.employer.invitations, element: , }, + { path: paths.employer.notifications, element: }, { path: "*", element: ( diff --git a/frontend/src/entities/match/model/adapter.test.ts b/frontend/src/entities/match/model/adapter.test.ts index ce599e6..d008049 100644 --- a/frontend/src/entities/match/model/adapter.test.ts +++ b/frontend/src/entities/match/model/adapter.test.ts @@ -111,6 +111,7 @@ function matchResponseFixture(): MatchSearchResponseOutput { }, ], }, + truncated: false, }); } @@ -195,6 +196,15 @@ describe("match response adapter", () => { expect(matchSearchFromTransport(roundTrip)).toEqual(model); }); + it("keeps the truncation flag, which carries no count", () => { + const response = { ...matchResponseFixture(), truncated: true }; + const model = matchSearchFromTransport(response); + + expect(model.truncated).toBe(true); + expect(matchSearchToTransport(model)).toEqual(response); + expect(() => matchSearchFromTransport({ ...response, truncated: undefined })).toThrow(); + }); + it("round-trips a need source using its requirements version", () => { const response = matchResponseFixture(); const needResponse = { diff --git a/frontend/src/entities/match/model/adapter.ts b/frontend/src/entities/match/model/adapter.ts index 10f210e..56153f3 100644 --- a/frontend/src/entities/match/model/adapter.ts +++ b/frontend/src/entities/match/model/adapter.ts @@ -84,6 +84,8 @@ export type MatchCardModel = MatchConfirmedCardModel | MatchUnconfirmedCardModel export type MatchSearchModel = { readonly source: MatchSearchSourceModel; readonly cards: readonly MatchCardModel[]; + /** True when the output is not the whole ranked result; it carries no count. */ + readonly truncated: boolean; }; function isRecord(value: unknown): value is Record { @@ -258,6 +260,7 @@ export function matchSearchFromTransport(value: unknown, status = 200): MatchSea ...response.groups.near.map((candidate) => confirmedFromTransport("near", candidate)), ...response.groups.unconfirmed.map(unconfirmedFromTransport), ], + truncated: response.truncated, }; } @@ -316,5 +319,6 @@ export function matchSearchToTransport(model: MatchSearchModel): MatchSearchResp return matchSearchResponseSchema.parse({ source: sourceToTransport(model.source), groups, + truncated: model.truncated, }); } diff --git a/frontend/src/features/notifications/index.ts b/frontend/src/features/notifications/index.ts new file mode 100644 index 0000000..30ae7ef --- /dev/null +++ b/frontend/src/features/notifications/index.ts @@ -0,0 +1,3 @@ +export { NotificationInbox } from "./ui/notification-inbox"; +export { OrganizationNotificationInbox } from "./ui/organization-notification-inbox"; +export type { NotificationScope } from "./model/scope"; diff --git a/frontend/src/features/notifications/model/mark-read.test.ts b/frontend/src/features/notifications/model/mark-read.test.ts new file mode 100644 index 0000000..9024a7b --- /dev/null +++ b/frontend/src/features/notifications/model/mark-read.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from "vitest"; +import { ApiRequestError } from "../../../shared/api"; +import { isMarkAccessLoss, markWithSessionRetry } from "./mark-read"; + +function failure( + status: number, + code: "csrf_check_failed" | "not_found" | "unauthenticated" | "internal", +) { + return new ApiRequestError({ status, code, title: "problem" }); +} + +describe("isMarkAccessLoss", () => { + it("counts only a lost session or a gone item, not a refusal", () => { + expect(isMarkAccessLoss(failure(401, "unauthenticated"))).toBe(true); + expect(isMarkAccessLoss(failure(404, "not_found"))).toBe(true); + expect(isMarkAccessLoss(failure(403, "csrf_check_failed"))).toBe(false); + expect(isMarkAccessLoss(failure(500, "internal"))).toBe(false); + expect(isMarkAccessLoss(new Error("network"))).toBe(false); + }); +}); + +describe("markWithSessionRetry", () => { + it("sends once when the first request succeeds", async () => { + const attempt = vi.fn().mockResolvedValue("ok"); + const refresh = vi.fn().mockResolvedValue(undefined); + await expect(markWithSessionRetry(attempt, refresh)).resolves.toBe("ok"); + expect(attempt).toHaveBeenCalledTimes(1); + expect(refresh).not.toHaveBeenCalled(); + }); + + it("reads the session again and retries once after a 403", async () => { + const attempt = vi + .fn() + .mockRejectedValueOnce(failure(403, "csrf_check_failed")) + .mockResolvedValueOnce("ok"); + const refresh = vi.fn().mockResolvedValue(undefined); + await expect(markWithSessionRetry(attempt, refresh)).resolves.toBe("ok"); + expect(refresh).toHaveBeenCalledTimes(1); + expect(attempt).toHaveBeenCalledTimes(2); + }); + + it("gives up after the second refusal and does not loop", async () => { + const refusal = failure(403, "csrf_check_failed"); + const attempt = vi.fn().mockRejectedValue(refusal); + const refresh = vi.fn().mockResolvedValue(undefined); + await expect(markWithSessionRetry(attempt, refresh)).rejects.toBe(refusal); + expect(attempt).toHaveBeenCalledTimes(2); + expect(refresh).toHaveBeenCalledTimes(1); + }); + + it.each([failure(401, "unauthenticated"), failure(404, "not_found"), failure(500, "internal")])( + "does not retry a $status", + async (error) => { + const attempt = vi.fn().mockRejectedValue(error); + const refresh = vi.fn().mockResolvedValue(undefined); + await expect(markWithSessionRetry(attempt, refresh)).rejects.toBe(error); + expect(attempt).toHaveBeenCalledTimes(1); + expect(refresh).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/frontend/src/features/notifications/model/mark-read.ts b/frontend/src/features/notifications/model/mark-read.ts new file mode 100644 index 0000000..f87fe87 --- /dev/null +++ b/frontend/src/features/notifications/model/mark-read.ts @@ -0,0 +1,35 @@ +import { ApiRequestError } from "../../../shared/api"; + +/** + * A mark loses access only when the session ended (401) or the item or the + * organization is gone for this account (404). A 403 is different: after a + * sign-in in another tab the CSRF token of this tab is stale, and that must + * not be reported as lost access. + */ +export function isMarkAccessLoss(error: unknown): error is ApiRequestError { + return error instanceof ApiRequestError && (error.status === 401 || error.status === 404); +} + +/** True for a refusal that a fresh session may fix, such as a stale CSRF token. */ +export function isRetryableMarkRefusal(error: unknown): error is ApiRequestError { + return error instanceof ApiRequestError && error.status === 403; +} + +/** + * Sends a mark and, after a 403, reads the session again and sends it once + * more with whatever the session now holds. `attempt` must take its CSRF + * token from the session at call time. A second refusal, or any other error, + * is returned to the caller as it is. + */ +export async function markWithSessionRetry( + attempt: () => Promise, + refreshSession: () => Promise, +): Promise { + try { + return await attempt(); + } catch (error: unknown) { + if (!isRetryableMarkRefusal(error)) throw error; + await refreshSession(); + return attempt(); + } +} diff --git a/frontend/src/features/notifications/model/presentation.test.ts b/frontend/src/features/notifications/model/presentation.test.ts new file mode 100644 index 0000000..dea9a2b --- /dev/null +++ b/frontend/src/features/notifications/model/presentation.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import { + formatDeliveredAt, + notificationKindLabel, + safeNotificationPath, + unavailableContentText, +} from "./presentation"; + +const candidate = { kind: "candidate" } as const; +const organization = { kind: "organization", organizationId: "org" } as const; + +describe("safeNotificationPath", () => { + it("opens only a same-origin path of the cabinet that shows it", () => { + expect(safeNotificationPath("/candidate/invitations", candidate)).toBe( + "/candidate/invitations", + ); + expect(safeNotificationPath("/employer/invitations", organization)).toBe( + "/employer/invitations", + ); + expect(safeNotificationPath("/employer/invitations", candidate)).toBeNull(); + expect(safeNotificationPath("/candidate/invitations", organization)).toBeNull(); + expect(safeNotificationPath("/candidatex", candidate)).toBeNull(); + }); + + it.each([ + "https://evil.example/candidate", + "//evil.example/candidate", + "/candidate/../employer", + "/candidate/a?token=1", + "/candidate/a#b", + "/candidate/%2e%2e", + "/candidate\\a", + "javascript:alert(1)", + "", + null, + undefined, + ])("refuses %s", (path) => { + expect(safeNotificationPath(path, candidate)).toBeNull(); + }); +}); + +describe("notification wording", () => { + it("labels known kinds and keeps an unknown kind generic", () => { + expect(notificationKindLabel("invitation_delivered")).toBe("Приглашение"); + expect(notificationKindLabel("synthetic")).toContain("Тестовое"); + expect(notificationKindLabel("something_new")).toBe("Уведомление"); + }); + + it("says plainly that the content is gone and shows no earlier copy", () => { + expect(unavailableContentText).toContain("больше недоступно"); + }); + + it("formats a delivery time in a given zone and ignores an invalid value", () => { + expect(formatDeliveredAt("2026-10-09T08:30:00Z", "UTC")).toMatch(/9 октября.*08:30/); + expect(formatDeliveredAt("not a date")).toBe(""); + }); +}); diff --git a/frontend/src/features/notifications/model/presentation.ts b/frontend/src/features/notifications/model/presentation.ts new file mode 100644 index 0000000..873cca0 --- /dev/null +++ b/frontend/src/features/notifications/model/presentation.ts @@ -0,0 +1,56 @@ +import type { Notification } from "../../../shared/api/schemas"; +import type { NotificationScope } from "./scope"; + +const kindLabels: Readonly> = { + invitation_delivered: "Приглашение", + synthetic: "Тестовое уведомление платформы", +}; + +/** Label of the event that produced a notification; unknown kinds stay generic. */ +export function notificationKindLabel(kind: string): string { + return (kindLabels as Readonly>)[kind] ?? "Уведомление"; +} + +/** + * Shown when the server returned no content: the source is gone or the + * recipient may not see it now. The client never keeps an earlier copy. + */ +export const unavailableContentText = + "Содержимое больше недоступно. Уведомление осталось в списке, но его текст не показывается."; + +const linkPathPattern = /^\/[A-Za-z0-9/_-]{0,255}$/; + +const cabinetRoots: Readonly> = { + candidate: "/candidate", + organization: "/employer", +}; + +/** + * A content link is opened only when it is a same-origin path of the cabinet + * that shows it. The server already restricts the shape; the client repeats + * the check so a malformed value can never become an external navigation. + */ +export function safeNotificationPath( + path: string | null | undefined, + scope: NotificationScope, +): string | null { + if (!path || path.startsWith("//") || !linkPathPattern.test(path)) return null; + const root = cabinetRoots[scope.kind]; + return path === root || path.startsWith(`${root}/`) ? path : null; +} + +function dateFormat(timeZone?: string): Intl.DateTimeFormat { + return new Intl.DateTimeFormat("ru-RU", { + day: "numeric", + month: "long", + hour: "2-digit", + minute: "2-digit", + ...(timeZone ? { timeZone } : {}), + }); +} + +/** Date and time of a delivery in the browser zone; empty for an invalid value. */ +export function formatDeliveredAt(value: string, timeZone?: string): string { + const date = new Date(value); + return Number.isNaN(date.getTime()) ? "" : dateFormat(timeZone).format(date); +} diff --git a/frontend/src/features/notifications/model/scope.test.ts b/frontend/src/features/notifications/model/scope.test.ts new file mode 100644 index 0000000..54a73f3 --- /dev/null +++ b/frontend/src/features/notifications/model/scope.test.ts @@ -0,0 +1,40 @@ +import { QueryClient } from "@tanstack/react-query"; +import { describe, expect, it } from "vitest"; +import { + notificationListQueryKey, + notificationOrganizationsQueryKey, + notificationScopeKey, + removeNotificationQueries, +} from "./scope"; + +describe("notification query keys", () => { + it("separate accounts and cabinets", () => { + const candidate = notificationListQueryKey("a", { kind: "candidate" }); + const first = notificationListQueryKey("a", { kind: "organization", organizationId: "o1" }); + const second = notificationListQueryKey("a", { kind: "organization", organizationId: "o2" }); + const other = notificationListQueryKey("b", { kind: "candidate" }); + expect(new Set([candidate, first, second, other].map((key) => key.join("/"))).size).toBe(4); + expect(notificationScopeKey({ kind: "organization", organizationId: "o1" })).toBe( + "organization:o1", + ); + }); + + it("drops the cached inbox of one account or of every account, and nothing else", () => { + const queryClient = new QueryClient(); + const a = notificationListQueryKey("a", { kind: "candidate" }); + const b = notificationListQueryKey("b", { kind: "candidate" }); + const directory = notificationOrganizationsQueryKey("a"); + const unrelated = ["account", "a", "support-cases", "list"] as const; + for (const key of [a, b, directory, unrelated]) queryClient.setQueryData(key, { value: 1 }); + + removeNotificationQueries(queryClient, "a"); + expect(queryClient.getQueryData(a)).toBeUndefined(); + expect(queryClient.getQueryData(directory)).toBeUndefined(); + expect(queryClient.getQueryData(b)).toBeDefined(); + expect(queryClient.getQueryData(unrelated)).toBeDefined(); + + removeNotificationQueries(queryClient); + expect(queryClient.getQueryData(b)).toBeUndefined(); + expect(queryClient.getQueryData(unrelated)).toBeDefined(); + }); +}); diff --git a/frontend/src/features/notifications/model/scope.ts b/frontend/src/features/notifications/model/scope.ts new file mode 100644 index 0000000..0d07314 --- /dev/null +++ b/frontend/src/features/notifications/model/scope.ts @@ -0,0 +1,40 @@ +import type { QueryClient } from "@tanstack/react-query"; + +/** + * Which inbox a screen reads. The candidate cabinet spans every organization + * that sent to the account; an employer cabinet is always one organization. + * The scope selects the operation only: the server derives the recipient from + * the session and re-checks the membership on every request. + */ +export type NotificationScope = + | { readonly kind: "candidate" } + | { readonly kind: "organization"; readonly organizationId: string }; + +export const notificationPageSize = 20; + +export function notificationScopeKey(scope: NotificationScope): string { + return scope.kind === "candidate" ? "candidate" : `organization:${scope.organizationId}`; +} + +/** + * Cached inbox pages belong to one account and one cabinet, so the account + * comes first and a query can be dropped by account or by cabinet. + */ +export function notificationListQueryKey(accountId: string, scope: NotificationScope) { + return ["account", accountId, "notifications", notificationScopeKey(scope), "list"] as const; +} + +/** The organizations of an employer account that the organization inbox can show. */ +export function notificationOrganizationsQueryKey(accountId: string) { + return ["account", accountId, "notifications", "organizations"] as const; +} + +/** Drops every cached inbox page of an account, or of all accounts. */ +export function removeNotificationQueries(queryClient: QueryClient, accountId?: string): void { + queryClient.removeQueries({ + predicate: (query) => + query.queryKey[0] === "account" && + query.queryKey[2] === "notifications" && + (accountId === undefined || query.queryKey[1] === accountId), + }); +} diff --git a/frontend/src/features/notifications/model/session.ts b/frontend/src/features/notifications/model/session.ts new file mode 100644 index 0000000..a76e8bc --- /dev/null +++ b/frontend/src/features/notifications/model/session.ts @@ -0,0 +1,19 @@ +import type { QueryClient } from "@tanstack/react-query"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { Session } from "../../../shared/api/schemas"; + +/** + * True while the cached session is the successful session of the same + * account and the same sign-in as the actor a request was made for, so a + * response is never applied to another account. + */ +export function isCurrentNotificationSession(queryClient: QueryClient, actor: Session): boolean { + const state = queryClient.getQueryState(getGetCurrentSessionQueryKey()); + return Boolean( + state && + state.status === "success" && + state.data && + state.data.account.id === actor.account.id && + state.data.csrf_token === actor.csrf_token, + ); +} diff --git a/frontend/src/features/notifications/ui/notification-inbox.module.css b/frontend/src/features/notifications/ui/notification-inbox.module.css new file mode 100644 index 0000000..ef9dd7c --- /dev/null +++ b/frontend/src/features/notifications/ui/notification-inbox.module.css @@ -0,0 +1,107 @@ +.root { + display: grid; + gap: var(--space-4); + min-width: 0; +} + +.live { + margin: 0; +} + +.list { + display: grid; + gap: var(--space-4); + margin: 0; + padding: 0; + list-style: none; +} + +.item { + min-width: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); + background: var(--color-surface); +} + +/* Unread is a heavier edge and the word "Не прочитано", never color alone. */ +.item[data-unread] { + border-color: var(--color-border-strong); + border-inline-start-width: var(--space-2); +} + +.item article { + display: grid; + gap: var(--space-3); +} + +.item p, +.item h2 { + margin: 0; + overflow-wrap: anywhere; +} + +.meta { + display: flex; + flex-wrap: wrap; + gap: var(--space-2) var(--space-4); + align-items: baseline; + color: var(--color-text-secondary); + font-size: var(--font-size-xs); +} + +.kind { + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; +} + +.unread { + color: var(--color-text); + font-weight: var(--font-weight-bold); +} + +.read { + font-weight: var(--font-weight-regular); +} + +.title { + font-size: var(--font-size-l); + line-height: var(--line-height-snug); +} + +.title:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.summary { + color: var(--color-text); +} + +.unavailable { + color: var(--color-text-secondary); + font-style: italic; +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3) var(--space-5); + align-items: center; +} + +.failure { + color: var(--color-danger); + font-weight: var(--font-weight-bold); +} + +.more { + display: flex; + justify-content: center; +} + +@media (width < 42rem) { + .item { + padding: var(--space-3); + } +} diff --git a/frontend/src/features/notifications/ui/notification-inbox.test.tsx b/frontend/src/features/notifications/ui/notification-inbox.test.tsx new file mode 100644 index 0000000..e954f01 --- /dev/null +++ b/frontend/src/features/notifications/ui/notification-inbox.test.tsx @@ -0,0 +1,130 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { renderToString } from "react-dom/server"; +import { MemoryRouter } from "react-router-dom"; +import { describe, expect, it } from "vitest"; +import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity"; +import type { NotificationList, Session } from "../../../shared/api/schemas"; +import { notificationListQueryKey, type NotificationScope } from "../model/scope"; +import { NotificationInbox } from "./notification-inbox"; + +const accountId = "11111111-1111-4111-8111-111111111111"; +const organizationId = "22222222-2222-4222-8222-222222222222"; + +function session(scenario: "candidate" | "employer"): Session { + return { + account: { + id: accountId, + email: "person@example.test", + email_verified: true, + scenario, + onboarding_step: "completed", + created_at: "2026-10-07T12:00:00Z", + }, + csrf_token: "A".repeat(43), + }; +} + +const page: NotificationList = { + items: [ + { + id: "33333333-3333-4333-8333-333333333333", + kind: "synthetic", + organization_id: organizationId, + delivered_at: "2026-10-09T08:30:00Z", + read_at: null, + content: { + title: "Тестовое уведомление", + summary: "Организация «Север» отправила проверочное уведомление.", + link_path: "/candidate/invitations", + }, + }, + { + id: "44444444-4444-4444-8444-444444444444", + kind: "synthetic", + organization_id: organizationId, + delivered_at: "2026-10-08T17:05:00Z", + read_at: "2026-10-08T17:10:00Z", + content: null, + }, + { + id: "55555555-5555-4555-8555-555555555555", + kind: "invitation_delivered", + organization_id: organizationId, + delivered_at: "2026-10-07T10:00:00Z", + read_at: null, + content: { + title: "Внешняя ссылка", + summary: "Ссылка не должна открываться.", + link_path: "//evil.example/x", + }, + }, + ], + page: { has_more: true, next_cursor: "cursor" }, +}; + +function render(options: { + scope?: NotificationScope; + scenario?: "candidate" | "employer"; + data?: NotificationList | null; +}): string { + const scope = options.scope ?? { kind: "candidate" }; + const queryClient = new QueryClient(); + queryClient.setQueryData( + getGetCurrentSessionQueryKey(), + session(options.scenario ?? "candidate"), + ); + if (options.data !== null) { + queryClient.setQueryData(notificationListQueryKey(accountId, scope), { + pages: [options.data ?? page], + pageParams: [undefined], + }); + } + return renderToString( + + + + + , + ); +} + +describe("NotificationInbox", () => { + it("lists items with a visible read state and a mark button only for unread ones", () => { + const html = render({}); + expect(html).toContain("Тестовое уведомление"); + expect(html).toContain("Не прочитано"); + expect(html).toContain("Прочитано"); + expect(html.match(/Отметить прочитанным/g)).toHaveLength(2); + expect(html).toContain('