From 676b3c6e24f9b1ea88d28566a6da703fb1f00a83 Mon Sep 17 00:00:00 2001 From: shira Date: Fri, 9 Oct 2026 18:03:35 +0300 Subject: [PATCH] feat(invitations): accept invitations with C4 consent and contact grants; share the E0 quota across holdings --- api/README.en.md | 7 +- api/README.md | 7 +- backend/README.en.md | 6 +- backend/README.md | 6 +- .../migrations/00040_accept_invitations.sql | 347 +++++++++++ .../db/migrations/00041_create_holdings.sql | 134 ++++ backend/db/queries/company_quota.sql | 60 +- backend/db/queries/contact_grants.sql | 45 ++ backend/db/queries/holdings.sql | 20 + backend/db/queries/invitation_answers.sql | 39 ++ backend/db/queries/organizations.sql | 12 +- .../candidate_card_access_migration_test.go | 6 +- .../candidate_privacy_test.go | 18 +- .../integration_test/company_quota_test.go | 33 +- .../holding_migration_test.go | 193 ++++++ backend/integration_test/holding_test.go | 418 +++++++++++++ .../invitation_accept_http_test.go | 579 ++++++++++++++++++ .../invitation_answer_http_test.go | 19 +- .../integration_test/invitation_http_test.go | 3 +- .../match_search_http_test.go | 22 +- backend/integration_test/needs_test.go | 12 +- .../notification_inbox_migration_test.go | 6 +- .../integration_test/organizations_test.go | 20 +- backend/integration_test/policy_test.go | 2 +- .../skill_evidence_http_test.go | 12 + .../adapter/primary/http/v1/invitation.go | 1 + .../primary/http/v1/invitation_candidate.go | 113 +++- .../http/v1/invitation_candidate_test.go | 25 + .../secondary/postgres/company_quota.go | 181 +++++- .../secondary/postgres/invitation_accept.go | 209 +++++++ .../secondary/postgres/organizations.go | 39 +- .../postgres/sqlc/company_quota.sql.go | 120 +++- .../postgres/sqlc/contact_grants.sql.go | 111 ++++ .../secondary/postgres/sqlc/holdings.sql.go | 53 ++ .../postgres/sqlc/invitation_answers.sql.go | 88 +++ .../adapter/secondary/postgres/sqlc/models.go | 27 + .../postgres/sqlc/organizations.sql.go | 35 +- .../secondary/postgres/sqlc/querier.go | 57 +- backend/internal/bootstrap/invitation.go | 3 +- backend/internal/domain/company_quota.go | 13 +- backend/internal/domain/contact_grant.go | 339 ++++++++++ backend/internal/domain/contact_grant_test.go | 242 ++++++++ backend/internal/domain/holding.go | 49 ++ backend/internal/domain/invitation_answer.go | 59 +- .../internal/port/outbound/company_quota.go | 46 +- .../internal/port/outbound/contact_grants.go | 29 + backend/internal/port/outbound/invitations.go | 41 ++ .../internal/port/outbound/organizations.go | 13 +- .../internal/usecase/companyquota/service.go | 12 +- backend/internal/usecase/invitation/accept.go | 413 +++++++++++++ .../usecase/invitation/accept_test.go | 467 ++++++++++++++ .../internal/usecase/invitation/decline.go | 14 +- .../internal/usecase/invitation/service.go | 27 +- .../usecase/invitation/service_test.go | 36 ++ backend/internal/usecase/invitation/view.go | 116 +++- docs/en/ARCHITECTURE.md | 38 +- docs/en/COMPANY_QUOTAS.md | 20 +- docs/ru/ARCHITECTURE.md | 38 +- docs/ru/COMPANY_QUOTAS.md | 20 +- 59 files changed, 4926 insertions(+), 194 deletions(-) create mode 100644 backend/db/migrations/00040_accept_invitations.sql create mode 100644 backend/db/migrations/00041_create_holdings.sql create mode 100644 backend/db/queries/contact_grants.sql create mode 100644 backend/db/queries/holdings.sql create mode 100644 backend/integration_test/holding_migration_test.go create mode 100644 backend/integration_test/holding_test.go create mode 100644 backend/integration_test/invitation_accept_http_test.go create mode 100644 backend/internal/adapter/secondary/postgres/invitation_accept.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/contact_grants.sql.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/holdings.sql.go create mode 100644 backend/internal/domain/contact_grant.go create mode 100644 backend/internal/domain/contact_grant_test.go create mode 100644 backend/internal/domain/holding.go create mode 100644 backend/internal/port/outbound/contact_grants.go create mode 100644 backend/internal/usecase/invitation/accept.go create mode 100644 backend/internal/usecase/invitation/accept_test.go diff --git a/api/README.en.md b/api/README.en.md index 53739cd..33b07d6 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -459,7 +459,7 @@ Planned contract changes (new enum values; like the catalog codes, generated cli ### Invitations and contact grants -The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). `SendOrganizationInvitation` and `ListMyInvitations` are implemented as well: the send checks the owner, the key, the version, the state, and the current visibility of the candidate and charges the weekly organization quota, while the pending limit of a need and the 30-day pause are not checked yet; a success means the invitation is already in `ListMyInvitations`, and the notification and the email follow through the outbox ([architecture](../docs/en/ARCHITECTURE.md#sending-invitations)). `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` are implemented as described below, with two limits until the related operations exist: no read or command applies the due expiry, so a view at the deadline or later changes nothing and a late decline answers 409 `state_conflict` while the state stays `delivered` or `viewed`; and `contact_consent` and `contact_grant` are always null, because an acceptance is impossible before `AcceptMyInvitation` is implemented ([architecture](../docs/en/ARCHITECTURE.md#candidate-view-and-decline)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. +The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). `SendOrganizationInvitation` and `ListMyInvitations` are implemented as well: the send checks the owner, the key, the version, the state, and the current visibility of the candidate and charges the weekly organization quota, while the pending limit of a need and the 30-day pause are not checked yet; a success means the invitation is already in `ListMyInvitations`, and the notification and the email follow through the outbox ([architecture](../docs/en/ARCHITECTURE.md#sending-invitations)). `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` are implemented as described below, with two limits until the related operations exist: no read or command applies the due expiry, so a view at the deadline or later changes nothing and a late decline answers 409 `state_conflict` while the state stays `delivered` or `viewed`; a declined invitation has `contact_consent` and `contact_grant` null. `AcceptMyInvitation` is implemented as the rules below describe, but the contact read and the revocation of a grant are not implemented yet ([architecture](../docs/en/ARCHITECTURE.md#candidate-acceptance)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -623,11 +623,12 @@ Foreign keys to organizations: `memberships` and `organization_representatives` Open questions for the product owner: - Representatives: may the card show their names to every candidate before an invitation is accepted, and who answers for the right to publish an employee's name (152-FZ)? The alternative is to show representatives only in an invitation sent by their organization. -- Organizations per account (blocking for organization creation and quota enforcement): the PRD sets no limit, and FR07 says that quotas belong to the organization as a whole and never grow on their own, but nothing stops one account from creating many organizations, each at `e0` with its own quota, which multiplies the quotas. This contract invents no number. The mechanism is ready: a cap would answer 409 `state_conflict` on `CreateOrganization` without a change of the schema, and the anti-abuse signals belong to organization risk assessment. The owner must decide the limit, or accept the risk explicitly, before the organization quotas are enforced and before `CreateOrganization` is opened to users. - Sphere: free text now; a taxonomy for the sphere, matching the domains of needs, is a decision for the search filters. - Contacts: whether the card needs a fifth kind, such as a careers page, and whether the email must share the domain of the website. -Planned, additive: member invitations, listing, role changes, and removal, the full role matrix, the verification processes and their history, the quotas by level, the card in the candidate's invitation, the number-of-organizations cap, and a sphere code. +Decided by the product owner: organizations per account are not limited. The organizations of one account form a holding, and the E0 quotas (in the demo policy 10 invitations per 7 days and 50 distinct card views per 24 hours) are shared by the E0 organizations of that holding; an organization at E1 and above counts its own quotas. The contract does not change: the holding is internal and no operation exposes it. + +Planned, additive: member invitations, listing, role changes, and removal, the full role matrix, the verification processes and their history, the quotas by level, the card in the candidate's invitation, and a sphere code. No new problem code is added: the contract reuses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused`, and `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`, and `TestOrganizationContractFollowsThePRD` pin the generated server and the bundle, and `frontend/src/shared/api/organization-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of role, owner, member, and verification fields in the requests. diff --git a/api/README.md b/api/README.md index f0e316c..f5e88dd 100644 --- a/api/README.md +++ b/api/README.md @@ -459,7 +459,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Приглашения и контактные разрешения -Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Сторона организации в черновике реализована: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` следуют правилам ниже, но `salary_fit` всегда равен `not_available`, а лимит вилки и счетчик `withheld` пока не применяются ([backend](../backend/README.md#черновики-приглашений)). Реализованы также `SendOrganizationInvitation` и `ListMyInvitations`: отправка проверяет владельца, ключ, версию, состояние и текущую видимость кандидата и списывает недельную квоту организации, а предел ожидающих на потребность и 30-дневная пауза пока не проверяются; успех означает, что приглашение уже есть в `ListMyInvitations`, а уведомление и письмо идут следом через outbox ([архитектура](../docs/ru/ARCHITECTURE.md#отправка-приглашений)). `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` реализованы, как описано ниже, с двумя ограничениями до появления связанных операций: ни чтение, ни команда не применяют наступившее истечение, поэтому просмотр в момент срока и позже ничего не меняет, а опоздавший отказ отвечает 409 `state_conflict`, пока состояние остается `delivered` или `viewed`; `contact_consent` и `contact_grant` всегда null, потому что принять приглашение до реализации `AcceptMyInvitation` нельзя ([архитектура](../docs/ru/ARCHITECTURE.md#просмотр-и-отказ-кандидата)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. +Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Сторона организации в черновике реализована: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` следуют правилам ниже, но `salary_fit` всегда равен `not_available`, а лимит вилки и счетчик `withheld` пока не применяются ([backend](../backend/README.md#черновики-приглашений)). Реализованы также `SendOrganizationInvitation` и `ListMyInvitations`: отправка проверяет владельца, ключ, версию, состояние и текущую видимость кандидата и списывает недельную квоту организации, а предел ожидающих на потребность и 30-дневная пауза пока не проверяются; успех означает, что приглашение уже есть в `ListMyInvitations`, а уведомление и письмо идут следом через outbox ([архитектура](../docs/ru/ARCHITECTURE.md#отправка-приглашений)). `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` реализованы, как описано ниже, с двумя ограничениями до появления связанных операций: ни чтение, ни команда не применяют наступившее истечение, поэтому просмотр в момент срока и позже ничего не меняет, а опоздавший отказ отвечает 409 `state_conflict`, пока состояние остается `delivered` или `viewed`; у отказанного приглашения `contact_consent` и `contact_grant` равны null. `AcceptMyInvitation` реализован, как описывают правила ниже, но чтение контактов и отзыв разрешения еще не реализованы ([архитектура](../docs/ru/ARCHITECTURE.md#принятие-кандидатом)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -623,11 +623,12 @@ ML-сервис отвечает на ошибки той же схемой `Pro Открытые вопросы к владельцу продукта: - Представители: может ли карточка показывать их имена любому кандидату до принятия приглашения и кто отвечает за право публиковать имя сотрудника (152-ФЗ)? Альтернатива - показывать представителей только в приглашении, отправленном их организацией. -- Организаций на аккаунт (блокирует создание организаций и применение квот): в PRD лимита нет, а FR07 говорит, что квоты принадлежат организации целиком и сами не растут, но ничто не мешает одному аккаунту создать много организаций, каждая из которых начинает с `e0` со своей квотой, что умножает квоты. Этот контракт не придумывает число. Механизм готов: ограничение отвечало бы 409 `state_conflict` на `CreateOrganization` без изменения схемы, а сигналы против злоупотреблений относятся к оценке риска организации. Владелец продукта должен решить лимит или явно принять риск до того, как квоты организации начнут применяться и до того, как `CreateOrganization` откроют пользователям. - Сфера: пока свободный текст; таксономия сферы, согласованная с доменами потребностей, - решение для поисковых фильтров. - Контакты: нужен ли в карточке пятый вид, например страница вакансий, и должна ли почта совпадать с доменом сайта. -Запланировано, аддитивно: приглашения участников, список, смена ролей и удаление, полная матрица ролей, процессы проверки и их история, квоты по уровню, карточка в приглашении кандидата, ограничение числа организаций и код сферы. +Решение владельца продукта: число организаций на аккаунт не ограничено. Организации одного аккаунта образуют холдинг, а E0-квоты (в демо-политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа) общие для E0-организаций этого холдинга; организация на E1 и выше считает свои квоты отдельно. Контракт не меняется: холдинг внутренний, и ни одна операция его не показывает. + +Запланировано, аддитивно: приглашения участников, список, смена ролей и удаление, полная матрица ролей, процессы проверки и их история, квоты по уровню, карточка в приглашении кандидата, и код сферы. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused` и `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart` и `TestOrganizationContractFollowsThePRD` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/organization-contract.test.ts` - сгенерированные правила Zod и, на уровне типов, отсутствие полей роли, владельца, участников и уровня проверки в запросах. diff --git a/backend/README.en.md b/backend/README.en.md index e4d3993..fa544a0 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -38,6 +38,8 @@ The same `Idempotency-Key` and body replay the original `201` snapshot within 24 `TestOrganizationCreationAndOwnerEditingOverHTTP` checks concurrent replay, rollback on owner insertion failure, cross-account denial, persisted reads after rebuilding the API, and reuse of an expired key against PostgreSQL. +The organization joins the holding of the owner account: `CreateWithOwner` creates the holding (table `holdings`, migration `00041_create_holdings.sql`) in the same transaction when the account creates its first organization. The E0 invitation and card-view limits are shared by all E0 organizations of the holding; the pool and lock rules are described in [Company quotas](../docs/en/COMPANY_QUOTAS.md#holding-pool). `TestHoldings` covers the shared pool, account isolation, concurrent reservations, and concurrent creation, and `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` covers the backfill and the guarded rollback. + `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` covers company isolation, candidate denial even with a manually inserted membership, denial for other roles, pagination, and owner revocation with the same cookie. A company in the active-membership directory does not grant owner authority; the server checks the role on every request. ## Organization needs @@ -66,7 +68,9 @@ The integration tests `TestOrganizationInvitationDraftsOverHTTP` (the router, se Sending is implemented: `POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send` (`usecase/invitation/send.go`) and the candidate's list `GET /api/v1/me/invitations` (`usecase/invitation/candidate_inbox.go`). One transaction takes the organization lock, the owner membership, the key, and the invitation row, checks the version and the state, resolves the stored candidate through the card visibility barrier again (409 when hidden, C2 revoked, or suppressed), charges the organization quota through `companyquota.Service.ReserveInvitation` (429 with `Retry-After`), moves the draft to `delivered` with `response_deadline_at = delivered_at + response_period_days`, appends the `delivered` audit event, and writes the outbox events `invitation.delivered` and `notification.mail_requested` (`usecase/notification/invitation.go`). A success therefore means the invitation is already in the candidate's list; the notification and the email follow through the consumers, and neither they nor their retries change the deadline. A repeat with the same key replays the stored outcome, and a send of a delivered invitation answers 200 with its current state without a second charge. Migration `00038_send_invitations.sql` adds the `delivered` event kind, `invitation_send_results` (the 200, 404, or 409 kept under the key), and the foreign key from `company_invitation_quota_usage` to `invitations`; its rollback refuses while a delivery event or a stored outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#sending-invitations). `TestOrganizationInvitationSendOverHTTP` and `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage` cover it against a real PostgreSQL. -The candidate's read, view, and decline are implemented: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view`, and `POST .../decline` (`usecase/invitation/view.go` and `decline.go`). The read records nothing; the view moves `delivered` to `viewed` before the deadline, keeps the deadline, and otherwise answers with the invitation as it is; the decline moves `delivered`, `viewed`, or the planned `counter` to `declined` before the deadline with a reason and an optional comment and creates no consent or grant. Both commands lock only the invitation row, never the organization, and append the audit events `viewed` and `declined`. A late decline answers 409, since the expiry is not implemented yet, and `contact_consent` and `contact_grant` stay null until the acceptance exists. Migration `00039_answer_invitations.sql` adds the event kinds, the state rules of the view and the answer, `invitation_declines` (the reason and the comment, which the organization never reads), and `invitation_decline_results` (the outcome under the key); its rollback refuses while a view, a decline, or an outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#candidate-view-and-decline). `TestCandidateInvitationViewAndDeclineOverHTTP` and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` cover it against a real PostgreSQL. +The candidate's read, view, decline, and acceptance are implemented: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view`, and `POST .../decline` (`usecase/invitation/view.go` and `decline.go`). The read records nothing; the view moves `delivered` to `viewed` before the deadline, keeps the deadline, and otherwise answers with the invitation as it is; the decline moves `delivered`, `viewed`, or the planned `counter` to `declined` before the deadline with a reason and an optional comment and creates no consent or grant. Both commands lock only the invitation row, never the organization, and append the audit events `viewed` and `declined`. A late decline answers 409, since the expiry is not implemented yet, and a declined invitation has `contact_consent` and `contact_grant` null. Migration `00039_answer_invitations.sql` adds the event kinds, the state rules of the view and the answer, `invitation_declines` (the reason and the comment, which the organization never reads), and `invitation_decline_results` (the outcome under the key); its rollback refuses while a view, a decline, or an outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#candidate-view-and-decline). `TestCandidateInvitationViewAndDeclineOverHTTP` and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` cover it against a real PostgreSQL. + +The candidate's acceptance is implemented: `POST /api/v1/me/invitations/{invitation_id}/accept` (`usecase/invitation/accept.go`). One transaction locks the invitation row, moves a delivered or viewed invitation before its deadline to `accepted` at the invitation version and the terms version that the candidate read, records the consent C4 through `consent.Service.GrantContact` (the published text and the selected fields), stores the contact grant of exactly the selected fields in `contact_grants`, and appends the audit event `accepted`. A stale version answers 412 and is not stored; the consent rules answer 400 with a pointer under `/consent_c4`; a repeat answers the stored acceptance, and another field set answers 409 `state_conflict`. Acceptance never publishes the profile or lifts a hiding: the grant is readable only while the organization may read the profile. Migration `00040_accept_invitations.sql` adds the event kind, the grant table with composite keys that tie it to the invitation, the candidate, and the C4 record, the outcome table, and a refusal of rollback while an acceptance exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#candidate-acceptance). `TestCandidateInvitationAcceptOverHTTP` and `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` cover it against a real PostgreSQL. ## Support cases diff --git a/backend/README.md b/backend/README.md index 77518f1..9f8f9c0 100644 --- a/backend/README.md +++ b/backend/README.md @@ -38,6 +38,8 @@ `TestOrganizationCreationAndOwnerEditingOverHTTP` проверяет в PostgreSQL параллельный повтор, откат при ошибке вставки владельца, запрет чужого доступа, сохранение данных после пересоздания API и повторное использование истекшего ключа. +Организация сохраняется в холдинге аккаунта-владельца: `CreateWithOwner` создает холдинг (таблица `holdings`, миграция `00041_create_holdings.sql`) в той же транзакции при первой организации аккаунта. E0-лимиты приглашений и просмотров карточек общие для всех E0-организаций холдинга; правила пула и блокировок описаны в [квотах компании](../docs/ru/COMPANY_QUOTAS.md#пул-холдинга). `TestHoldings` проверяет общий пул, изоляцию аккаунтов, конкурентные резервирования и параллельное создание, а `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` - заполнение миграции и защищенный откат. + `TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` проверяет изоляцию компаний, отказ кандидату даже с вручную добавленным членством, отказ другим ролям, пагинацию и отзыв доступа владельца с той же cookie. Компания в справочнике активных членств не дает права владельца; сервер проверяет роль на каждом запросе. ## Потребности организаций @@ -66,7 +68,9 @@ Реализована отправка: `POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send` (`usecase/invitation/send.go`) и список кандидата `GET /api/v1/me/invitations` (`usecase/invitation/candidate_inbox.go`). Одна транзакция берет блокировку организации, членство владельца, ключ и строку приглашения, проверяет версию и состояние, снова разрешает сохраненного кандидата через барьер видимости карточки (409 при скрытии, отзыве C2 или подавлении), списывает квоту организации через `companyquota.Service.ReserveInvitation` (429 с `Retry-After`), переводит черновик в `delivered` с `response_deadline_at = delivered_at + response_period_days`, добавляет событие аудита `delivered` и пишет события outbox `invitation.delivered` и `notification.mail_requested` (`usecase/notification/invitation.go`). Поэтому успех означает, что приглашение уже в списке кандидата; уведомление и письмо идут следом через обработчики, и ни они, ни их повторы срок не меняют. Повтор с тем же ключом возвращает сохраненный исход, а отправка доставленного приглашения отвечает 200 с текущим состоянием без второго списания. Миграция `00038_send_invitations.sql` добавляет вид события `delivered`, `invitation_send_results` (200, 404 или 409 под ключом) и внешний ключ из `company_invitation_quota_usage` на `invitations`; ее откат отказывает, пока есть событие доставки или сохраненный исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#отправка-приглашений). `TestOrganizationInvitationSendOverHTTP` и `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage` проверяют это на настоящем PostgreSQL. -Реализованы чтение, просмотр и отказ кандидата: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view` и `POST .../decline` (`usecase/invitation/view.go` и `decline.go`). Чтение ничего не записывает; просмотр переводит `delivered` в `viewed` до срока, сохраняет срок, а иначе отвечает приглашением как есть; отказ переводит `delivered`, `viewed` или запланированное `counter` в `declined` до срока с причиной и необязательным комментарием и не создает ни согласия, ни разрешения. Обе команды блокируют только строку приглашения, но не организацию, и добавляют события аудита `viewed` и `declined`. Опоздавший отказ отвечает 409, потому что истечение еще не реализовано, а `contact_consent` и `contact_grant` остаются null, пока нет принятия. Миграция `00039_answer_invitations.sql` добавляет виды событий, правила состояния для просмотра и ответа, `invitation_declines` (причина и комментарий, которые организация никогда не читает) и `invitation_decline_results` (исход под ключом); ее откат отказывает, пока есть просмотр, отказ или исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#просмотр-и-отказ-кандидата). `TestCandidateInvitationViewAndDeclineOverHTTP` и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` проверяют это на настоящем PostgreSQL. +Реализованы чтение, просмотр, отказ и принятие кандидата: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view` и `POST .../decline` (`usecase/invitation/view.go` и `decline.go`). Чтение ничего не записывает; просмотр переводит `delivered` в `viewed` до срока, сохраняет срок, а иначе отвечает приглашением как есть; отказ переводит `delivered`, `viewed` или запланированное `counter` в `declined` до срока с причиной и необязательным комментарием и не создает ни согласия, ни разрешения. Обе команды блокируют только строку приглашения, но не организацию, и добавляют события аудита `viewed` и `declined`. Опоздавший отказ отвечает 409, потому что истечение еще не реализовано, а у отказанного приглашения `contact_consent` и `contact_grant` равны null. Миграция `00039_answer_invitations.sql` добавляет виды событий, правила состояния для просмотра и ответа, `invitation_declines` (причина и комментарий, которые организация никогда не читает) и `invitation_decline_results` (исход под ключом); ее откат отказывает, пока есть просмотр, отказ или исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#просмотр-и-отказ-кандидата). `TestCandidateInvitationViewAndDeclineOverHTTP` и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` проверяют это на настоящем PostgreSQL. + +Принятие кандидатом реализовано: `POST /api/v1/me/invitations/{invitation_id}/accept` (`usecase/invitation/accept.go`). Одна транзакция блокирует строку приглашения, переводит доставленное или просмотренное приглашение до срока в `accepted` при версии приглашения и версии условий, которые прочитал кандидат, записывает согласие C4 через `consent.Service.GrantContact` (опубликованный текст и выбранные поля), сохраняет разрешение ровно на выбранные поля в `contact_grants` и добавляет событие аудита `accepted`. Устаревшая версия отвечает 412 и не сохраняется; правила согласия отвечают 400 с указателем под `/consent_c4`; повтор отвечает сохраненным принятием, другой набор полей отвечает 409 `state_conflict`. Принятие никогда не публикует профиль и не снимает скрытие: разрешение читается только пока организация может читать профиль. Миграция `00040_accept_invitations.sql` добавляет вид события, таблицу разрешений с составными ключами на приглашение, кандидата и запись C4, таблицу исходов и отказ отката, пока принятие существует. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#принятие-кандидатом). `TestCandidateInvitationAcceptOverHTTP` и `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` проверяют это на настоящем PostgreSQL. ## Обращения в поддержку diff --git a/backend/db/migrations/00040_accept_invitations.sql b/backend/db/migrations/00040_accept_invitations.sql new file mode 100644 index 0000000..b76f397 --- /dev/null +++ b/backend/db/migrations/00040_accept_invitations.sql @@ -0,0 +1,347 @@ +-- +goose Up +-- The candidate's acceptance of the current terms with the consent C4. One +-- transaction moves a delivered or viewed invitation to `accepted` before its +-- deadline, records the consent C4 in the consent ledger, stores the contact +-- grant that covers exactly the selected fields, and appends the audit event. +-- The acceptance never changes the publication (C2) and never lifts a hiding: +-- a grant alone does not make the contacts readable, and the read model shows +-- whether the organization may read them now. +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ( + 'draft_created', 'draft_updated', 'delivered', 'viewed', 'declined', + 'accepted' + ) +); + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_answer_changes_no_field; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_answer_changes_no_field CHECK ( + kind NOT IN ('viewed', 'declined', 'accepted') OR cardinality(changed_fields) = 0 +); + +-- An accepted invitation records its answer, as a declined one does. The +-- acceptance from `delivered` leaves the view empty. +ALTER TABLE invitations +DROP CONSTRAINT invitations_answer_matches_state; + +ALTER TABLE invitations +ADD CONSTRAINT invitations_answer_matches_state CHECK ( + (state <> 'delivered' OR (viewed_at IS NULL AND responded_at IS NULL)) + AND (state <> 'viewed' OR (viewed_at IS NOT NULL AND responded_at IS NULL)) + AND (state NOT IN ('declined', 'accepted') OR responded_at IS NOT NULL) + AND (viewed_at IS NULL OR (delivered_at IS NOT NULL AND viewed_at >= delivered_at)) + AND ( + responded_at IS NULL + OR (delivered_at IS NOT NULL AND responded_at >= delivered_at) + ) +); + +-- The contact grant names the invitation together with its candidate, so the +-- grant can only belong to the candidate the invitation was addressed to. +ALTER TABLE invitations +ADD CONSTRAINT invitations_organization_id_id_candidate_id_key UNIQUE ( + organization_id, id, candidate_id +); + +-- A grant names exactly the C4 record of its acceptance: the same subject, +-- organization, invitation, and terms version. The record stays a ledger row +-- of its own and does not reference the invitation tables, which the ledger +-- migration leaves to a later change. +ALTER TABLE consent_records +ADD CONSTRAINT consent_records_contact_scope_key UNIQUE ( + id, subject_id, organization_id, invitation_id, invitation_terms_version +); + +-- The contact grant of one accepted invitation. It holds kinds only, never +-- contact values. The grant is created by the acceptance next to its C4 record +-- and the accepted state. Its revocation stamp is reserved for the revocation +-- procedure of a later change, and this migration never sets it. +CREATE TABLE contact_grants ( + id uuid NOT NULL, + organization_id uuid NOT NULL, + candidate_id uuid NOT NULL, + source_invitation_id uuid NOT NULL, + consent_record_id uuid NOT NULL, + terms_version bigint NOT NULL, + fields text [] NOT NULL, + consent_text_version text NOT NULL, + granted_at timestamptz NOT NULL, + revoked_at timestamptz, + revocation_reason text, + CONSTRAINT contact_grants_pkey PRIMARY KEY (id), + -- One grant per accepted invitation, and one per consent record. + CONSTRAINT contact_grants_source_invitation_key UNIQUE (source_invitation_id), + CONSTRAINT contact_grants_consent_record_key UNIQUE (consent_record_id), + CONSTRAINT contact_grants_candidate_fkey FOREIGN KEY (candidate_id) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT contact_grants_invitation_fkey FOREIGN KEY ( + organization_id, source_invitation_id, candidate_id + ) REFERENCES invitations (organization_id, id, candidate_id) ON DELETE RESTRICT, + CONSTRAINT contact_grants_terms_fkey FOREIGN KEY ( + source_invitation_id, terms_version + ) REFERENCES invitation_terms_versions (invitation_id, version) ON DELETE RESTRICT, + CONSTRAINT contact_grants_consent_fkey FOREIGN KEY ( + consent_record_id, + candidate_id, + organization_id, + source_invitation_id, + terms_version + ) REFERENCES consent_records ( + id, + subject_id, + organization_id, + invitation_id, + invitation_terms_version + ) ON DELETE RESTRICT, + CONSTRAINT contact_grants_terms_version_positive CHECK (terms_version > 0), + CONSTRAINT contact_grants_fields_canonical CHECK ( + consent_field_set_is_canonical(fields) + ), + CONSTRAINT contact_grants_consent_text_version_format CHECK ( + consent_text_version ~ '^[A-Za-z0-9._-]{1,64}$' + ), + CONSTRAINT contact_grants_revocation_stamp CHECK ( + (revoked_at IS NULL) = (revocation_reason IS NULL) + AND ( + revocation_reason IS NULL + OR revocation_reason IN ( + 'consent_revoked', 'participation_cancelled', 'visibility_closed' + ) + ) + AND (revoked_at IS NULL OR revoked_at >= granted_at) + ) +); + +-- The grant of an organization's invitations is read for one candidate while +-- the grant is active. +CREATE INDEX contact_grants_organization_candidate_active_idx +ON contact_grants (organization_id, candidate_id) +WHERE revoked_at IS NULL; + +-- Outcome of an idempotent acceptance, kept beside the generic idempotency +-- record and removed with it after the 24-hour replay window. An accepted +-- invitation keeps its answer and its grant, so a replay rebuilds the response +-- from them and the outcome holds only the invitation and the result. +CREATE TABLE invitation_accept_results ( + scope_hash bytea NOT NULL, + invitation_id uuid NOT NULL, + outcome text NOT NULL, + CONSTRAINT invitation_accept_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT invitation_accept_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT invitation_accept_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT invitation_accept_results_outcome CHECK ( + outcome IN ('accepted', 'not_found', 'state_conflict') + ) +); + +-- A view, an answer, and an acceptance are never undone, and a declined or +-- accepted invitation never returns to an earlier state. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION invitations_guard_answer() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (OLD.viewed_at IS NOT NULL AND NEW.viewed_at IS DISTINCT FROM OLD.viewed_at) + OR (OLD.responded_at IS NOT NULL AND NEW.responded_at IS DISTINCT FROM OLD.responded_at) + OR (OLD.state = 'declined' AND NEW.state <> 'declined') + OR (OLD.state = 'accepted' AND NEW.state IN ('draft', 'delivered', 'viewed', 'counter', 'declined')) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_answer_immutable', + TABLE = 'invitations', + MESSAGE = 'a view, an answer, a decline, and an acceptance are never undone'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +-- The grant must agree with its C4 record: the fields, the text version, and +-- the grant time are the record's own, so a grant cannot cover a field its +-- consent did not name. +-- +goose StatementBegin +CREATE FUNCTION contact_grants_match_consent() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM consent_records AS record + WHERE + record.id = NEW.consent_record_id + AND record.purpose = 'c4' + AND record.field_set = NEW.fields + AND record.text_version = NEW.consent_text_version + AND record.granted_at = NEW.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'contact_grants_match_consent', + TABLE = 'contact_grants', + MESSAGE = 'a contact grant agrees with its consent C4 record'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER contact_grants_match_consent +BEFORE INSERT ON contact_grants +FOR EACH ROW EXECUTE FUNCTION contact_grants_match_consent(); + +-- A grant changes only by its one revocation stamp, which is set once. Every +-- other change, and every delete, is refused. +-- +goose StatementBegin +CREATE FUNCTION contact_grants_guard_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.revoked_at IS NOT NULL + OR NEW.revoked_at IS NULL + OR ( + NEW.id, NEW.organization_id, NEW.candidate_id, NEW.source_invitation_id, + NEW.consent_record_id, NEW.terms_version, NEW.fields, + NEW.consent_text_version, NEW.granted_at + ) IS DISTINCT FROM ( + OLD.id, OLD.organization_id, OLD.candidate_id, OLD.source_invitation_id, + OLD.consent_record_id, OLD.terms_version, OLD.fields, + OLD.consent_text_version, OLD.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'contact_grants_immutable', + TABLE = 'contact_grants', + MESSAGE = 'contact grants are append-only: only an active grant can be revoked, once'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER contact_grants_guard_change +BEFORE UPDATE ON contact_grants +FOR EACH ROW EXECUTE FUNCTION contact_grants_guard_change(); + +CREATE TRIGGER contact_grants_refuse_delete +BEFORE DELETE ON contact_grants +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +-- An accepted invitation has its contact grant by the end of the transaction +-- that accepted it. +-- +goose StatementBegin +CREATE FUNCTION invitations_require_contact_grant() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM contact_grants + WHERE + contact_grants.organization_id = NEW.organization_id + AND contact_grants.source_invitation_id = NEW.id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_acceptance_recorded', + TABLE = 'invitations', + MESSAGE = 'an accepted invitation records its contact grant'; + END IF; + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +CREATE CONSTRAINT TRIGGER invitations_require_contact_grant +AFTER UPDATE ON invitations +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW +WHEN (new.state = 'accepted' AND old.state <> 'accepted') +EXECUTE FUNCTION invitations_require_contact_grant(); + +-- +goose Down +-- A rollback must not silently remove an acceptance, its consent, or its grant. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitation_events WHERE kind = 'accepted') + OR EXISTS (SELECT 1 FROM invitations WHERE state = 'accepted') + OR EXISTS (SELECT 1 FROM contact_grants) + OR EXISTS (SELECT 1 FROM consent_records WHERE purpose = 'c4') + OR EXISTS (SELECT 1 FROM invitation_accept_results) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_acceptances_retained', + TABLE = 'invitation_events', + MESSAGE = 'accepted invitations and their consents must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER invitations_require_contact_grant ON invitations; +DROP FUNCTION invitations_require_contact_grant(); +DROP TABLE invitation_accept_results; +DROP TABLE contact_grants; +DROP FUNCTION contact_grants_guard_change(); +DROP FUNCTION contact_grants_match_consent(); + +ALTER TABLE consent_records +DROP CONSTRAINT consent_records_contact_scope_key; + +ALTER TABLE invitations +DROP CONSTRAINT invitations_organization_id_id_candidate_id_key; + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION invitations_guard_answer() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (OLD.viewed_at IS NOT NULL AND NEW.viewed_at IS DISTINCT FROM OLD.viewed_at) + OR (OLD.responded_at IS NOT NULL AND NEW.responded_at IS DISTINCT FROM OLD.responded_at) + OR (OLD.state = 'declined' AND NEW.state <> 'declined') THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_answer_immutable', + TABLE = 'invitations', + MESSAGE = 'a view, an answer, and a decline are never undone'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE invitations +DROP CONSTRAINT invitations_answer_matches_state; + +ALTER TABLE invitations +ADD CONSTRAINT invitations_answer_matches_state CHECK ( + (state <> 'delivered' OR (viewed_at IS NULL AND responded_at IS NULL)) + AND (state <> 'viewed' OR (viewed_at IS NOT NULL AND responded_at IS NULL)) + AND (state <> 'declined' OR responded_at IS NOT NULL) + AND (viewed_at IS NULL OR (delivered_at IS NOT NULL AND viewed_at >= delivered_at)) + AND ( + responded_at IS NULL + OR (delivered_at IS NOT NULL AND responded_at >= delivered_at) + ) +); + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_answer_changes_no_field; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_answer_changes_no_field CHECK ( + kind NOT IN ('viewed', 'declined') OR cardinality(changed_fields) = 0 +); + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ('draft_created', 'draft_updated', 'delivered', 'viewed', 'declined') +); diff --git a/backend/db/migrations/00041_create_holdings.sql b/backend/db/migrations/00041_create_holdings.sql new file mode 100644 index 0000000..99aee4a --- /dev/null +++ b/backend/db/migrations/00041_create_holdings.sql @@ -0,0 +1,134 @@ +-- +goose Up +-- Holdings group the organizations that one account founded, the way the +-- divisions of one company belong to one parent. A holding has no profile and +-- grants no right. It only names the scope of the E0 quota pool: the E0 +-- organizations of one holding share one pool, so creating more organizations +-- does not multiply the unverified allowance. An organization at E1 or above +-- keeps its own pool and does not use its holding for quotas. +-- +-- A holding belongs to its founder account, the account that created its first +-- organization. Every organization belongs to exactly one holding. Holdings of +-- different founders are never merged. +CREATE TABLE holdings ( + -- Internal identifier, never shown by the API. The application creates it + -- as UUIDv7; the backfill below uses a random UUID. + id uuid NOT NULL, + founder_account_id uuid NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT holdings_pkey PRIMARY KEY (id), + -- One holding per founder. A second creation of the same account that + -- races the first waits on this key and then reads the stored holding. + CONSTRAINT holdings_founder_account_id_key UNIQUE (founder_account_id), + CONSTRAINT holdings_founder_account_id_fkey FOREIGN KEY ( + founder_account_id + ) REFERENCES users (id) ON DELETE RESTRICT +); + +-- The backfill and the NOT NULL constraint must see every organization and +-- membership. Writers of both tables wait until this migration commits. +LOCK TABLE organizations, memberships IN SHARE ROW EXCLUSIVE MODE; + +-- Refuses an organization without any membership, because its founder cannot +-- be found. Creation stores the owner membership in the same transaction as +-- the organization, and no statement deletes memberships, so an existing +-- database should never reach this check. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM organizations AS organization + WHERE NOT EXISTS ( + SELECT 1 + FROM memberships AS membership + WHERE membership.organization_id = organization.id + ) + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'organizations_founder_required', + TABLE = 'organizations', + MESSAGE = 'an organization without a membership has no founder for its holding'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE organizations ADD COLUMN holding_id uuid; + +-- The founder of an organization is the account of its earliest membership. +-- Creation inserts the organization and its owner membership in one +-- transaction, and a membership cannot exist before its organization, so the +-- earliest membership is the creator's. Ties are broken by identifier. A holding +-- is dated by the earliest creation of its founder. +WITH founders AS ( + SELECT DISTINCT ON (membership.organization_id) + membership.organization_id, + membership.user_id + FROM memberships AS membership + ORDER BY membership.organization_id, membership.created_at, membership.id +) + +INSERT INTO holdings (id, founder_account_id, created_at) +SELECT + gen_random_uuid(), + founders.user_id, + min(organization.created_at) +FROM founders +INNER JOIN organizations AS organization ON organization.id = founders.organization_id +GROUP BY founders.user_id; + +WITH founders AS ( + SELECT DISTINCT ON (membership.organization_id) + membership.organization_id, + membership.user_id + FROM memberships AS membership + ORDER BY membership.organization_id, membership.created_at, membership.id +) + +UPDATE organizations AS organization +SET holding_id = holding.id +FROM founders +INNER JOIN holdings AS holding ON holding.founder_account_id = founders.user_id +WHERE founders.organization_id = organization.id; + +ALTER TABLE organizations ALTER COLUMN holding_id SET NOT NULL; + +ALTER TABLE organizations +ADD CONSTRAINT organizations_holding_id_fkey FOREIGN KEY (holding_id) +REFERENCES holdings (id) ON DELETE RESTRICT; + +-- Serves the pool of an E0 organization, which reads the organizations of its +-- holding, and the foreign key. +CREATE INDEX organizations_holding_id_idx ON organizations (holding_id); + +-- +goose Down +-- A rollback removes the grouping of organizations into holdings. It refuses +-- while a holding groups several organizations, because the schema without +-- holdings would count their E0 quotas separately and could not keep the pool +-- they share. The lock stops a concurrent creation from joining a holding +-- between the check and the removal. +LOCK TABLE organizations IN SHARE ROW EXCLUSIVE MODE; + +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM organizations + GROUP BY holding_id + HAVING count(*) > 1 + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'organizations_holding_grouped', + TABLE = 'organizations', + MESSAGE = 'holdings with several organizations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE organizations DROP COLUMN holding_id; + +DROP TABLE holdings; diff --git a/backend/db/queries/company_quota.sql b/backend/db/queries/company_quota.sql index 3b45536..e2578e2 100644 --- a/backend/db/queries/company_quota.sql +++ b/backend/db/queries/company_quota.sql @@ -1,6 +1,8 @@ --- 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. +-- Writers lock the organization first, then, for an E0 organization, the holding +-- whose pool it shares, then invitation/card-view state, and finally usage rows. +-- The organization lock serializes quota decisions for the tenant, the holding +-- lock serializes the E0 pool across the organizations of one holding, and +-- together they make 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 @@ -9,9 +11,13 @@ -- 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. +-- transaction. The result carries the holding, whose pool an E0 organization +-- shares; the caller locks that holding right after this lock. -- name: LockCompanyQuotaOrganizationFirst :one -SELECT id +SELECT + id, + verification_level, + holding_id FROM organizations WHERE id = sqlc.arg(organization_id) FOR NO KEY UPDATE; @@ -21,11 +27,24 @@ SELECT id, verification_level, verification_basis, - verification_changed_at + verification_changed_at, + holding_id FROM organizations WHERE id = sqlc.arg(organization_id) FOR UPDATE; +-- Takes the pool lock of an E0 holding. It follows the organization lock, so +-- every writer locks an organization first and its holding second. Two +-- reservations of one holding queue here, and the second one counts the +-- usage that the first one committed. The lock does not conflict with the +-- FOR KEY SHARE that organizations.holding_id takes when an organization joins +-- the holding. +-- name: LockCompanyQuotaHolding :one +SELECT id +FROM holdings +WHERE id = sqlc.arg(holding_id) +FOR NO KEY UPDATE; + -- name: FindCompanyInvitationQuotaUsage :one SELECT invitation_id FROM company_invitation_quota_usage @@ -43,6 +62,20 @@ WHERE organization_id = sqlc.arg(organization_id) AND reserved_at > sqlc.arg(window_start); +-- Counts the invitation usage of the E0 pool of a holding: the usage of every +-- organization of the holding whose trust level is E0 when the count runs. Each +-- row stays attributed to the organization that consumed it. +-- name: CountCompanyInvitationQuotaHoldingWindow :one +SELECT + count(*)::bigint AS usage_count, + min(usage.reserved_at) AS earliest_at +FROM company_invitation_quota_usage AS usage +INNER JOIN organizations AS organization ON organization.id = usage.organization_id +WHERE + organization.holding_id = sqlc.arg(holding_id) + AND organization.verification_level = 'e0' + AND usage.reserved_at > sqlc.arg(window_start); + -- name: InsertCompanyInvitationQuotaUsage :exec INSERT INTO company_invitation_quota_usage ( organization_id, @@ -95,6 +128,21 @@ WHERE organization_id = sqlc.arg(organization_id) AND last_seen_at > sqlc.arg(window_start); +-- Counts the distinct-card usage of the E0 pool of a holding, with the same +-- rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted +-- per organization: the same candidate seen by two organizations of one +-- holding is two charges. +-- name: CountCompanyCardViewQuotaHoldingWindow :one +SELECT + count(*)::bigint AS usage_count, + min(usage.last_seen_at) AS earliest_at +FROM company_card_view_quota_usage AS usage +INNER JOIN organizations AS organization ON organization.id = usage.organization_id +WHERE + organization.holding_id = sqlc.arg(holding_id) + AND organization.verification_level = 'e0' + AND usage.last_seen_at > sqlc.arg(window_start); + -- name: SaveCompanyCardViewQuotaUsage :exec INSERT INTO company_card_view_quota_usage ( organization_id, diff --git a/backend/db/queries/contact_grants.sql b/backend/db/queries/contact_grants.sql new file mode 100644 index 0000000..2482439 --- /dev/null +++ b/backend/db/queries/contact_grants.sql @@ -0,0 +1,45 @@ +-- Store the contact grant of an acceptance. The row is inserted in the same +-- transaction as its C4 consent record and the accepted state; the database +-- checks that the record, the invitation, and the candidate agree. +-- name: InsertContactGrant :exec +INSERT INTO contact_grants ( + id, + organization_id, + candidate_id, + source_invitation_id, + consent_record_id, + terms_version, + fields, + consent_text_version, + granted_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(organization_id), + sqlc.arg(candidate_id), + sqlc.arg(source_invitation_id), + sqlc.arg(consent_record_id), + sqlc.arg(terms_version), + sqlc.arg(fields)::text [], + sqlc.arg(consent_text_version), + sqlc.arg(granted_at) +); + +-- Read the grant of one invitation of one organization. An invitation of +-- another organization finds nothing. +-- name: GetContactGrantByInvitation :one +SELECT + id, + organization_id, + candidate_id, + source_invitation_id, + consent_record_id, + terms_version, + fields, + consent_text_version, + granted_at, + revoked_at, + revocation_reason +FROM contact_grants +WHERE + organization_id = sqlc.arg(organization_id) + AND source_invitation_id = sqlc.arg(invitation_id); diff --git a/backend/db/queries/holdings.sql b/backend/db/queries/holdings.sql new file mode 100644 index 0000000..ad0e9aa --- /dev/null +++ b/backend/db/queries/holdings.sql @@ -0,0 +1,20 @@ +-- Stores the holding of a founder account unless the account already has one. +-- A concurrent creation of the same account waits on the founder key until the +-- other transaction ends; then this insert does nothing, and the caller reads +-- the stored holding with GetHoldingIDByFounder. +-- name: InsertHoldingIfAbsent :exec +INSERT INTO holdings ( + id, + founder_account_id, + created_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(founder_account_id), + sqlc.arg(created_at) +) +ON CONFLICT (founder_account_id) DO NOTHING; + +-- name: GetHoldingIDByFounder :one +SELECT id +FROM holdings +WHERE founder_account_id = sqlc.arg(founder_account_id); diff --git a/backend/db/queries/invitation_answers.sql b/backend/db/queries/invitation_answers.sql index 30468bc..4334e59 100644 --- a/backend/db/queries/invitation_answers.sql +++ b/backend/db/queries/invitation_answers.sql @@ -127,3 +127,42 @@ SELECT outcome FROM invitation_decline_results WHERE scope_hash = sqlc.arg(scope_hash); + +-- The compare-and-swap of an acceptance: it applies only to a delivered or +-- viewed invitation at the version and the terms version that the candidate +-- read, and before its deadline. The answer is the acceptance time, and the +-- deadline is kept. +-- name: AcceptInvitation :one +UPDATE invitations +SET + state = 'accepted', + version = sqlc.arg(next_version), + responded_at = sqlc.arg(accepted_at), + updated_at = sqlc.arg(accepted_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state IN ('delivered', 'viewed') + AND version = sqlc.arg(expected_version) + AND terms_version = sqlc.arg(terms_version) + AND response_deadline_at > sqlc.arg(accepted_at) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- name: InsertInvitationAcceptResult :exec +INSERT INTO invitation_accept_results ( + scope_hash, + invitation_id, + outcome +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(invitation_id), + sqlc.arg(outcome) +); + +-- name: GetInvitationAcceptResult :one +SELECT + invitation_id, + outcome +FROM invitation_accept_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/organizations.sql b/backend/db/queries/organizations.sql index e57d365..c79b699 100644 --- a/backend/db/queries/organizations.sql +++ b/backend/db/queries/organizations.sql @@ -1,7 +1,7 @@ -- Stores a new organization with the verification level that the domain --- gave it. The deferred constraint organizations_owner_required fails the --- transaction at commit unless an active owner membership was inserted in --- it too. +-- gave it and the holding of its creator. The deferred constraint +-- organizations_owner_required fails the transaction at commit unless an +-- active owner membership was inserted in it too. -- name: InsertOrganization :exec INSERT INTO organizations ( id, @@ -17,7 +17,8 @@ INSERT INTO organizations ( verification_changed_at, version, created_at, - updated_at + updated_at, + holding_id ) VALUES ( sqlc.arg(id), sqlc.arg(name), @@ -32,7 +33,8 @@ INSERT INTO organizations ( sqlc.arg(verification_changed_at), sqlc.arg(version), sqlc.arg(created_at), - sqlc.arg(updated_at) + sqlc.arg(updated_at), + sqlc.arg(holding_id) ); -- Stores one representative at its position in the list. The adapter calls it diff --git a/backend/integration_test/candidate_card_access_migration_test.go b/backend/integration_test/candidate_card_access_migration_test.go index 3efd9b2..209f2b5 100644 --- a/backend/integration_test/candidate_card_access_migration_test.go +++ b/backend/integration_test/candidate_card_access_migration_test.go @@ -25,8 +25,8 @@ func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) { if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() error = %v", err) } - rollBackToCandidateCardAccessVersion(ctx, t, migrator) - + // The organization is created while the latest schema is in place: its creation + // needs the holdings table, which the rollback below removes. now := time.Now().UTC().Truncate(time.Microsecond) identity := identityFixture{ ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now, @@ -38,6 +38,8 @@ func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) { } owner := organizationFixture.employer(t, "owner@example.com") organization := organizationFixture.create(t, owner, organizationFixture.completeProfile(t, "Example Company"), now) + rollBackToCandidateCardAccessVersion(ctx, t, migrator) + if _, err := pool.Exec(ctx, `INSERT INTO candidate_card_access_events ( id, candidate_id, organization_id, actor_id, kind, field_codes, occurred_at ) VALUES ($1, $2, $3, $4, 'card_viewed', ARRAY['stack']::text[], $5)`, diff --git a/backend/integration_test/candidate_privacy_test.go b/backend/integration_test/candidate_privacy_test.go index c9e2cd4..6abe38e 100644 --- a/backend/integration_test/candidate_privacy_test.go +++ b/backend/integration_test/candidate_privacy_test.go @@ -416,8 +416,13 @@ func TestCandidatePrivacyStorage(t *testing.T) { } defer func() { _ = tx.Rollback(ctx) }() if _, err := tx.Exec(ctx, ` - INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at) - SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1 FROM generate_series(1, $2::int) AS n`, now, limit+1); err != nil { + INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, $2)`, employer.ID, now); err != nil { + t.Fatalf("create holding: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id) + SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1, (SELECT id FROM holdings WHERE founder_account_id = $3) + FROM generate_series(1, $2::int) AS n`, now, limit+1, employer.ID); err != nil { t.Fatalf("create organizations: %v", err) } if _, err := tx.Exec(ctx, ` @@ -696,8 +701,13 @@ func TestCandidatePrivacyStorage(t *testing.T) { t.Fatalf("begin: %v", err) } if _, err := tx.Exec(ctx, ` - INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at) - SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1 FROM generate_series(1, $2::int) AS n`, now, limit-1+parallel); err != nil { + INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, $2)`, employer.ID, now); err != nil { + t.Fatalf("create holding: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id) + SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1, (SELECT id FROM holdings WHERE founder_account_id = $3) + FROM generate_series(1, $2::int) AS n`, now, limit-1+parallel, employer.ID); err != nil { t.Fatalf("create organizations: %v", err) } if _, err := tx.Exec(ctx, ` diff --git a/backend/integration_test/company_quota_test.go b/backend/integration_test/company_quota_test.go index 889a5fe..0339f83 100644 --- a/backend/integration_test/company_quota_test.go +++ b/backend/integration_test/company_quota_test.go @@ -38,11 +38,10 @@ type companyQuotaFixture struct { invitationCandidate uuid.UUID } -func TestCompanyQuota(t *testing.T) { - env := bootstrap(t, postgresService) - ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout) - defer cancel() - databaseURL := env.createIsolatedDatabase(ctx, t) +// newCompanyQuotaFixture migrates the isolated database, publishes the demo +// product policy, and returns the fixture the quota tests share. +func newCompanyQuotaFixture(ctx context.Context, t *testing.T, databaseURL string) companyQuotaFixture { + t.Helper() applyMigrations(ctx, t, databaseURL) pool := newPoolFor(ctx, t, databaseURL) @@ -60,13 +59,20 @@ func TestCompanyQuota(t *testing.T) { if err != nil { t.Fatalf("GetEffective(product) error = %v", err) } - fixture := companyQuotaFixture{ + return companyQuotaFixture{ ctx: ctx, pool: pool, clock: clock, transactor: transactor, service: companyquota.NewService(clock.Now), organizations: organizationFixture, policies: policyStore.Policies(), version: version, invitationAuthor: organizationFixture.employer(t, "quota-invitation-author@example.test").ID, invitationCandidate: identity.createUser(t, "quota-invitation-candidate@example.test", domain.ScenarioCandidate, clock.Now().Add(-time.Hour)).ID, } +} + +func TestCompanyQuota(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout) + defer cancel() + fixture := newCompanyQuotaFixture(ctx, t, env.createIsolatedDatabase(ctx, t)) t.Run("E0 shares limits across requests and concurrent final reservations", func(t *testing.T) { organization, _ := fixture.newOrganization(t, "e0-boundary", domain.OrganizationVerificationE0) @@ -381,6 +387,19 @@ func (fixture companyQuotaFixture) newOrganization( ) (domain.Organization, domain.User) { t.Helper() owner := fixture.organizations.employer(t, fmt.Sprintf("quota-%s-%s@example.test", name, uuid.NewString())) + return fixture.organizationOf(t, owner, name, level), owner +} + +// organizationOf stores an organization of owner at the given verification +// level and returns it as read back from storage. Several organizations of one +// owner belong to one holding. +func (fixture companyQuotaFixture) organizationOf( + t *testing.T, + owner domain.User, + name string, + level domain.OrganizationVerificationLevel, +) domain.Organization { + t.Helper() organization := fixture.organizations.create(t, owner, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Quota " + name}), fixture.clock.Now().Add(-time.Minute)) if level != domain.OrganizationVerificationE0 { basis := domain.OrganizationBasisCorporateDomain @@ -401,7 +420,7 @@ func (fixture companyQuotaFixture) newOrganization( if err != nil { t.Fatalf("read %s organization: %v", level, err) } - return stored, owner + return stored } // newInvitationID stores a draft of the organization and returns its diff --git a/backend/integration_test/holding_migration_test.go b/backend/integration_test/holding_migration_test.go new file mode 100644 index 0000000..dcd25ad --- /dev/null +++ b/backend/integration_test/holding_migration_test.go @@ -0,0 +1,193 @@ +//go:build integration + +package integration_test + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" +) + +// holdingsMigrationVersion creates the holdings table and organizations.holding_id. +const holdingsMigrationVersion = 41 + +// legacyMembership is a membership row written without the application. +type legacyMembership struct { + userID uuid.UUID + role string + createdAt time.Time +} + +// TestHoldingsMigrationBackfillsFoundersAndGuardsRollback runs the migration on +// organizations that were created before holdings existed. The backfill must +// give one holding per founder, and the rollback must refuse while a holding +// groups several organizations. +func TestHoldingsMigrationBackfillsFoundersAndGuardsRollback(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) + } + // The schema before holdings: the organizations are written without them. + rollBackAboveMigration(ctx, t, migrator, holdingsMigrationVersion-1) + + now := time.Now().UTC().Truncate(time.Microsecond).Add(-24 * time.Hour) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + founderA := identity.createUser(t, "holding-backfill-first@example.test", domain.ScenarioEmployer, now.Add(-time.Hour)) + founderB := identity.createUser(t, "holding-backfill-other@example.test", domain.ScenarioEmployer, now.Add(-time.Hour)) + cofounder := identity.createUser(t, "holding-backfill-cofounder@example.test", domain.ScenarioEmployer, now.Add(-time.Hour)) + + first := insertLegacyOrganization(ctx, t, pool, "Legacy first", now, + legacyMembership{userID: founderA.ID, role: "owner", createdAt: now}) + second := insertLegacyOrganization(ctx, t, pool, "Legacy second", now.Add(time.Hour), + legacyMembership{userID: founderA.ID, role: "owner", createdAt: now.Add(time.Hour)}, + // A later owner does not change the founder: the earliest membership does. + legacyMembership{userID: cofounder.ID, role: "owner", createdAt: now.Add(2 * time.Hour)}) + other := insertLegacyOrganization(ctx, t, pool, "Legacy other", now.Add(30*time.Minute), + legacyMembership{userID: founderB.ID, role: "owner", createdAt: now.Add(30 * time.Minute)}) + + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() with the holdings migration error = %v", err) + } + + t.Run("backfill gives each founder one holding dated by its first organization", func(t *testing.T) { + firstHolding := legacyHolding(ctx, t, pool, first) + if got := legacyHolding(ctx, t, pool, second); got != firstHolding { + t.Fatalf("holding of the second organization = %s, want the founder's holding %s", got, firstHolding) + } + if got := legacyHolding(ctx, t, pool, other); got == firstHolding { + t.Fatal("two founders share one holding") + } + assertLegacyHoldingFounder(ctx, t, pool, firstHolding, founderA.ID, now) + assertLegacyHoldingFounder(ctx, t, pool, legacyHolding(ctx, t, pool, other), founderB.ID, now.Add(30*time.Minute)) + var count int64 + if err := pool.QueryRow(ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil { + t.Fatalf("count holdings: %v", err) + } + if count != 2 { + t.Fatalf("holdings = %d, want one per founder (2)", count) + } + }) + + t.Run("rollback refuses while a holding groups several organizations", func(t *testing.T) { + _, err := migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a grouped holding", err, privacyIntegrityViolation, "organizations_holding_grouped") + if got := legacyHolding(ctx, t, pool, first); got != legacyHolding(ctx, t, pool, second) { + t.Fatal("refused rollback changed the grouping") + } + }) + + t.Run("rollback succeeds once every holding has one organization", func(t *testing.T) { + split := uuid.Must(uuid.NewV7()) + if _, err := pool.Exec(ctx, ` + INSERT INTO holdings (id, founder_account_id, created_at) VALUES ($1, $2, $3)`, + split, cofounder.ID, now); err != nil { + t.Fatalf("insert the holding of the split organization: %v", err) + } + if _, err := pool.Exec(ctx, `UPDATE organizations SET holding_id = $2 WHERE id = $1`, second, split); err != nil { + t.Fatalf("move the second organization to its own holding: %v", err) + } + if _, err := migrator.DownOne(ctx); err != nil { + t.Fatalf("DownOne() with single-organization holdings error = %v", err) + } + var holdingsGone, columnGone bool + var organizations int64 + if err := pool.QueryRow(ctx, ` + SELECT + to_regclass('public.holdings') IS NULL, + NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'organizations' AND column_name = 'holding_id'), + (SELECT count(*) FROM organizations)`).Scan(&holdingsGone, &columnGone, &organizations); err != nil { + t.Fatalf("read the rolled-back schema: %v", err) + } + if !holdingsGone || !columnGone { + t.Fatalf("rollback left holdings table gone = %t, holding_id column gone = %t", holdingsGone, columnGone) + } + if organizations != 3 { + t.Fatalf("organizations after rollback = %d, want the 3 that were created", organizations) + } + + // Applying the migration again backfills the same grouping from the + // memberships, so the founders get one holding each. + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } + if got := legacyHolding(ctx, t, pool, second); got != legacyHolding(ctx, t, pool, first) { + t.Fatal("reapplied backfill does not group the founder's organizations") + } + }) +} + +// insertLegacyOrganization stores an organization and its memberships in one +// transaction, as creation did before holdings. The owner membership keeps the +// deferred constraint satisfied at commit. +func insertLegacyOrganization( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + name string, + createdAt time.Time, + memberships ...legacyMembership, +) uuid.UUID { + t.Helper() + organizationID := uuid.Must(uuid.NewV7()) + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin legacy organization transaction: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, ` + INSERT INTO organizations ( + id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at + ) VALUES ($1, $2, 'e0', 'confirmed_email', $3, 1, $3, $3)`, organizationID, name, createdAt); err != nil { + t.Fatalf("insert legacy organization: %v", err) + } + for _, membership := range memberships { + if _, err := tx.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + VALUES ($1, $2, $3, $4, 'active', $5, $5)`, + uuid.Must(uuid.NewV7()), organizationID, membership.userID, membership.role, membership.createdAt); err != nil { + t.Fatalf("insert legacy membership: %v", err) + } + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit legacy organization: %v", err) + } + return organizationID +} + +func legacyHolding(ctx context.Context, t *testing.T, pool *pgxpool.Pool, organizationID uuid.UUID) uuid.UUID { + t.Helper() + var holdingID uuid.UUID + if err := pool.QueryRow(ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil { + t.Fatalf("read holding of organization: %v", err) + } + return holdingID +} + +func assertLegacyHoldingFounder(ctx context.Context, t *testing.T, pool *pgxpool.Pool, holdingID, founderID uuid.UUID, createdAt time.Time) { + t.Helper() + var gotFounder uuid.UUID + var gotCreatedAt time.Time + if err := pool.QueryRow(ctx, ` + SELECT founder_account_id, created_at FROM holdings WHERE id = $1`, holdingID).Scan(&gotFounder, &gotCreatedAt); err != nil { + t.Fatalf("read holding: %v", err) + } + if gotFounder != founderID { + t.Fatalf("holding founder = %s, want %s", gotFounder, founderID) + } + if !gotCreatedAt.Equal(createdAt) { + t.Fatalf("holding created_at = %s, want %s", gotCreatedAt, createdAt) + } +} diff --git a/backend/integration_test/holding_test.go b/backend/integration_test/holding_test.go new file mode 100644 index 0000000..9fc989f --- /dev/null +++ b/backend/integration_test/holding_test.go @@ -0,0 +1,418 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// holdingConcurrentConns sizes the pool of the concurrency subtests, so that +// every goroutine of one subtest holds a connection at the same time. +const holdingConcurrentConns = 8 + +// TestHoldings covers the E0 quota pools that the organizations of one holding +// share, the isolation of accounts, and the creation of holdings. +func TestHoldings(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + fixture := newCompanyQuotaFixture(ctx, t, databaseURL) + + t.Run("organizations of one account share the E0 pools and keep the E1 pools apart", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("shared-owner")) + first := fixture.organizationOf(t, owner, "shared-first", domain.OrganizationVerificationE0) + second := fixture.organizationOf(t, owner, "shared-second", domain.OrganizationVerificationE0) + verified := fixture.organizationOf(t, owner, "shared-verified", domain.OrganizationVerificationE1) + fixture.assertSameHolding(t, owner.ID, first.ID(), second.ID(), verified.ID()) + + // The verified organization draws on its own pool, and its usage does + // not count toward the E0 pool that follows. + for range 3 { + fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified)) + fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t)) + } + for range 6 { + fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first)) + } + for range 4 { + fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second)) + } + fixture.assertInvitationDenied(t, first, fixture.clock.Now().Add(7*24*time.Hour)) + fixture.assertInvitationDenied(t, second, fixture.clock.Now().Add(7*24*time.Hour)) + fixture.assertQuotaRowCounts(t, first.ID(), 6, 0) + fixture.assertQuotaRowCounts(t, second.ID(), 4, 0) + fixture.assertQuotaRowCounts(t, verified.ID(), 3, 3) + + for range 30 { + fixture.reserveCardViewAllowed(t, first, fixture.newCandidateID(t)) + } + for range 20 { + fixture.reserveCardViewAllowed(t, second, fixture.newCandidateID(t)) + } + fixture.assertCardViewDenied(t, first, fixture.clock.Now().Add(24*time.Hour)) + fixture.assertCardViewDenied(t, second, fixture.clock.Now().Add(24*time.Hour)) + fixture.assertQuotaRowCounts(t, first.ID(), 6, 30) + fixture.assertQuotaRowCounts(t, second.ID(), 4, 20) + + // The verified organization keeps its own pool: it still has room. + fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified)) + fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t)) + }) + + t.Run("a second account forms its own holding and pool", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("other-owner")) + other := fixture.organizationOf(t, owner, "other-first", domain.OrganizationVerificationE0) + for range 10 { + fixture.reserveInvitationAllowed(t, other, fixture.newInvitationID(t, other)) + } + fixture.assertInvitationDenied(t, other, fixture.clock.Now().Add(7*24*time.Hour)) + + neighbour := fixture.organizations.employer(t, uniqueHoldingEmail("neighbour-owner")) + separate := fixture.organizationOf(t, neighbour, "neighbour-first", domain.OrganizationVerificationE0) + if fixture.holdingOf(t, separate.ID()) == fixture.holdingOf(t, other.ID()) { + t.Fatal("organizations of two accounts share one holding") + } + fixture.reserveInvitationAllowed(t, separate, fixture.newInvitationID(t, separate)) + fixture.reserveCardViewAllowed(t, separate, fixture.newCandidateID(t)) + }) + + t.Run("usage leaves the E0 pool with its organization", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("leave-owner")) + raised := fixture.organizationOf(t, owner, "leave-raised", domain.OrganizationVerificationE0) + sibling := fixture.organizationOf(t, owner, "leave-sibling", domain.OrganizationVerificationE0) + for range 6 { + fixture.reserveInvitationAllowed(t, raised, fixture.newInvitationID(t, raised)) + } + + if _, err := fixture.pool.Exec(fixture.ctx, ` + UPDATE organizations + SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2 + WHERE id = $1`, raised.ID(), fixture.clock.Now().Add(-30*time.Second)); err != nil { + t.Fatalf("raise organization to E1: %v", err) + } + raisedNow, _, err := fixture.organizations.read(owner.ID, raised.ID()) + if err != nil { + t.Fatalf("read raised organization: %v", err) + } + // The six invitations stay stored, but they no longer count toward the + // E0 pool, which the sibling can use in full. + for range 10 { + fixture.reserveInvitationAllowed(t, sibling, fixture.newInvitationID(t, sibling)) + } + fixture.assertInvitationDenied(t, sibling, fixture.clock.Now().Add(7*24*time.Hour)) + fixture.assertQuotaRowCounts(t, raised.ID(), 6, 0) + fixture.reserveInvitationAllowed(t, raisedNow, fixture.newInvitationID(t, raisedNow)) + }) + + t.Run("concurrent reservations of one E0 pool never exceed its limits", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("race-owner")) + first := fixture.organizationOf(t, owner, "race-first", domain.OrganizationVerificationE0) + second := fixture.organizationOf(t, owner, "race-second", domain.OrganizationVerificationE0) + concurrent := newConcurrentTransactor(ctx, t, databaseURL) + + for range 5 { + fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first)) + } + for range 4 { + fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second)) + } + // Nine of the ten invitations are used. Four reservations race for the + // last place, two from each organization. + racers := []domain.Organization{first, second, first, second} + invitationIDs := make([]uuid.UUID, len(racers)) + for index, organization := range racers { + invitationIDs[index] = fixture.newInvitationID(t, organization) + } + decisions := make([]outbound.CompanyQuotaDecision, len(racers)) + runConcurrently(t, len(racers), func(index int) error { + decision, err := fixture.reserveInvitationLocked(concurrent, racers[index], invitationIDs[index]) + decisions[index] = decision + return err + }) + fixture.assertOneAllowed(t, decisions, fixture.clock.Now().Add(7*24*time.Hour)) + fixture.assertInvitationRowsOf(t, 10, first.ID(), second.ID()) + + viewCandidates := make([]uuid.UUID, 0, 49) + for range 49 { + viewCandidates = append(viewCandidates, fixture.newCandidateID(t)) + } + for index, candidateID := range viewCandidates { + organization := first + if index%2 == 1 { + organization = second + } + fixture.reserveCardViewAllowed(t, organization, candidateID) + } + viewRacers := make([]uuid.UUID, len(racers)) + for index := range racers { + viewRacers[index] = fixture.newCandidateID(t) + } + viewDecisions := make([]outbound.CompanyQuotaDecision, len(racers)) + runConcurrently(t, len(racers), func(index int) error { + decision, err := fixture.reserveCardViewLocked(concurrent, racers[index], viewRacers[index]) + viewDecisions[index] = decision + return err + }) + fixture.assertOneAllowed(t, viewDecisions, fixture.clock.Now().Add(24*time.Hour)) + fixture.assertCardViewRowsOf(t, 50, first.ID(), second.ID()) + }) + + t.Run("concurrent creations by one account end in one holding", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("create-owner")) + concurrent := newConcurrentTransactor(ctx, t, databaseURL) + const creations = holdingConcurrentConns + at := fixture.clock.Now().Add(-time.Minute) + organizationIDs := make([]uuid.UUID, creations) + runConcurrently(t, creations, func(index int) error { + profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{Name: fmt.Sprintf("Concurrent company %d", index)}) + if err != nil { + return fmt.Errorf("profile: %w", err) + } + company, err := domain.NewOrganization(profile, at) + if err != nil { + return fmt.Errorf("organization: %w", err) + } + membership, err := domain.NewOwnerMembership(company.ID(), owner.ID, at) + if err != nil { + return fmt.Errorf("owner membership: %w", err) + } + organizationIDs[index] = company.ID() + return concurrent.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Organizations().CreateWithOwner(ctx, company, membership) + }) + }) + fixture.assertSameHolding(t, owner.ID, organizationIDs...) + if got := fixture.holdingCount(t, owner.ID); got != 1 { + t.Fatalf("holdings of the founder = %d, want 1", got) + } + }) + + t.Run("an unknown founder stores no holding", func(t *testing.T) { + before := fixture.totalHoldings(t) + unknown := uuid.New() + profile := mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Orphan company"}) + company, err := domain.NewOrganization(profile, fixture.clock.Now().Add(-time.Minute)) + if err != nil { + t.Fatalf("NewOrganization() error = %v", err) + } + membership, err := domain.NewOwnerMembership(company.ID(), unknown, company.CreatedAt()) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Organizations().CreateWithOwner(ctx, company, membership) + }) + if !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("CreateWithOwner(unknown founder) error = %v, want ErrUserNotFound", err) + } + if after := fixture.totalHoldings(t); after != before { + t.Fatalf("holdings = %d after the refused creation, want %d", after, before) + } + }) +} + +// uniqueHoldingEmail returns a fresh address so that every subtest creates its +// own account and therefore its own holding. +func uniqueHoldingEmail(prefix string) string { + return fmt.Sprintf("holding-%s-%s@example.test", prefix, uuid.NewString()) +} + +// newConcurrentTransactor opens a pool of the isolated database that lets every +// goroutine of a subtest run its transaction at the same time. +func newConcurrentTransactor(ctx context.Context, t *testing.T, databaseURL string) *postgresadapter.Transactor { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(databaseURL) + if err != nil { + t.Fatalf("parse isolated database URL: %v", err) + } + poolConfig.MaxConns = holdingConcurrentConns + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create concurrent PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return postgresadapter.NewTransactor(pool) +} + +// runConcurrently calls work for every index at once, after all goroutines +// have started, and fails the test on the first error. work must not call +// testing methods that stop the test goroutine. +func runConcurrently(t *testing.T, count int, work func(index int) error) { + t.Helper() + errs := make([]error, count) + start := make(chan struct{}) + done := make(chan struct{}, count) + for index := range count { + go func() { + defer func() { done <- struct{}{} }() + <-start + errs[index] = work(index) + }() + } + close(start) + for range count { + <-done + } + for index, err := range errs { + if err != nil { + t.Fatalf("concurrent call %d error = %v", index, err) + } + } +} + +// reserveInvitationLocked reserves one invitation the way the production +// callers do: the organization lock first, then the reservation, in one +// transaction. +func (fixture companyQuotaFixture) reserveInvitationLocked( + transactor *postgresadapter.Transactor, + organization domain.Organization, + invitationID uuid.UUID, +) (outbound.CompanyQuotaDecision, error) { + var decision outbound.CompanyQuotaDecision + err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil { + return err + } + var err error + decision, err = fixture.service.ReserveInvitation(ctx, unit, organization, invitationID) + return err + }) + return decision, err +} + +// reserveCardViewLocked is reserveInvitationLocked for a distinct card view. +func (fixture companyQuotaFixture) reserveCardViewLocked( + transactor *postgresadapter.Transactor, + organization domain.Organization, + candidateID uuid.UUID, +) (outbound.CompanyQuotaDecision, error) { + var decision outbound.CompanyQuotaDecision + err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil { + return err + } + var err error + decision, err = fixture.service.ReserveCardView(ctx, unit, organization, candidateID) + return err + }) + return decision, err +} + +// assertSameHolding checks that every organization is in the holding of the +// owner and that the owner has exactly one holding. +func (fixture companyQuotaFixture) assertSameHolding(t *testing.T, founderID uuid.UUID, organizationIDs ...uuid.UUID) { + t.Helper() + if got := fixture.holdingCount(t, founderID); got != 1 { + t.Fatalf("holdings of the founder = %d, want 1", got) + } + want := fixture.holdingOf(t, organizationIDs[0]) + for _, organizationID := range organizationIDs { + if got := fixture.holdingOf(t, organizationID); got != want { + t.Fatalf("organization %s is in holding %s, want %s", organizationID, got, want) + } + } +} + +func (fixture companyQuotaFixture) holdingOf(t *testing.T, organizationID uuid.UUID) uuid.UUID { + t.Helper() + var holdingID uuid.UUID + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil { + t.Fatalf("read holding of organization: %v", err) + } + return holdingID +} + +func (fixture companyQuotaFixture) holdingCount(t *testing.T, founderID uuid.UUID) int64 { + t.Helper() + var count int64 + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings WHERE founder_account_id = $1`, founderID).Scan(&count); err != nil { + t.Fatalf("count holdings of founder: %v", err) + } + return count +} + +func (fixture companyQuotaFixture) totalHoldings(t *testing.T) int64 { + t.Helper() + var count int64 + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil { + t.Fatalf("count holdings: %v", err) + } + return count +} + +// assertInvitationDenied checks that the organization cannot reserve a new +// invitation and that the denial retries at retryAt. +func (fixture companyQuotaFixture) assertInvitationDenied(t *testing.T, organization domain.Organization, retryAt time.Time) { + t.Helper() + decision, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization)) + if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) { + t.Fatalf("ReserveInvitation() = %+v, %v; want a denial that retries at %s", decision, err, retryAt) + } +} + +// assertCardViewDenied is assertInvitationDenied for a distinct card view. +func (fixture companyQuotaFixture) assertCardViewDenied(t *testing.T, organization domain.Organization, retryAt time.Time) { + t.Helper() + decision, err := fixture.reserveCardView(organization, fixture.newCandidateID(t)) + if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) { + t.Fatalf("ReserveCardView() = %+v, %v; want a denial that retries at %s", decision, err, retryAt) + } +} + +// assertOneAllowed checks that exactly one of the decisions was allowed and +// that the others were denied with the given retry time. +func (fixture companyQuotaFixture) assertOneAllowed(t *testing.T, decisions []outbound.CompanyQuotaDecision, retryAt time.Time) { + t.Helper() + allowed := 0 + for _, decision := range decisions { + switch { + case decision.Allowed && decision.RetryAt.IsZero() && !decision.Reused: + allowed++ + case !decision.Allowed && decision.RetryAt.Equal(retryAt): + default: + t.Fatalf("unexpected concurrent decision %+v, want retry at %s", decision, retryAt) + } + } + if allowed != 1 { + t.Fatalf("allowed concurrent reservations = %d, want exactly 1 of %d", allowed, len(decisions)) + } +} + +// assertInvitationRowsOf checks the invitation usage stored for the given +// organizations together, which is the count of the shared pool. +func (fixture companyQuotaFixture) assertInvitationRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) { + t.Helper() + var got int64 + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil { + t.Fatalf("count invitation usage rows: %v", err) + } + if got != want { + t.Fatalf("invitation usage rows of the pool = %d, want %d", got, want) + } +} + +// assertCardViewRowsOf is assertInvitationRowsOf for distinct card views. +func (fixture companyQuotaFixture) assertCardViewRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) { + t.Helper() + var got int64 + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil { + t.Fatalf("count card-view usage rows: %v", err) + } + if got != want { + t.Fatalf("card-view usage rows of the pool = %d, want %d", got, want) + } +} diff --git a/backend/integration_test/invitation_accept_http_test.go b/backend/integration_test/invitation_accept_http_test.go new file mode 100644 index 0000000..a0fab53 --- /dev/null +++ b/backend/integration_test/invitation_accept_http_test.go @@ -0,0 +1,579 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + 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/consent" + "lincodex/backend/internal/usecase/policy" +) + +const ( + // invitationAcceptMigrationVersion adds the acceptance: its audit event, the + // contact grant, and the outcomes kept under the keys. + invitationAcceptMigrationVersion = 40 + invitationAcceptancesRetained = "invitation_acceptances_retained" + acceptTextVersion = "c4-2026-10-01" +) + +// candidateContactGrantHTTP is the contact grant as the candidate reads it. +type candidateContactGrantHTTP struct { + ID uuid.UUID `json:"id"` + Fields []string `json:"fields"` + Status string `json:"status"` + Readable bool `json:"readable"` + BlockedBy *string `json:"blocked_by"` + TermsVersion int64 `json:"terms_version"` + ConsentTextVersion string `json:"consent_text_version"` + GrantedAt string `json:"granted_at"` + RevokedAt *string `json:"revoked_at"` + RevocationReason *string `json:"revocation_reason"` +} + +func decodeContactGrantHTTP(t *testing.T, body candidateInvitationHTTPBody) candidateContactGrantHTTP { + t.Helper() + var grant candidateContactGrantHTTP + if err := json.Unmarshal(body.ContactGrant, &grant); err != nil { + t.Fatalf("decode contact grant %s: %v", body.ContactGrant, err) + } + return grant +} + +// invitationAcceptCounts are the rows that acceptances write for one +// invitation, the C4 consents of its candidate, and the outcomes kept under +// the keys. +type invitationAcceptCounts struct { + acceptedEvents, grants, c4Consents, outcomes int +} + +func readInvitationAcceptCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationAcceptCounts { + t.Helper() + var counts invitationAcceptCounts + if err := harness.pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'accepted'), + (SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1), + (SELECT count(*) FROM consent_records WHERE subject_id = $2 AND purpose = 'c4'), + (SELECT count(*) FROM invitation_accept_results WHERE invitation_id = $1)`, + invitationID, candidateID).Scan(&counts.acceptedEvents, &counts.grants, &counts.c4Consents, &counts.outcomes); err != nil { + t.Fatalf("count the rows of an acceptance: %v", err) + } + return counts +} + +// parallelAcceptRequests sends every acceptance at once, each under its own +// key, and returns the responses in the order of the bodies. +func parallelAcceptRequests( + t *testing.T, + harness *invitationHTTPHarness, + path, origin string, + session organizationHTTPSession, + bodies, keys []string, +) []*httptest.ResponseRecorder { + t.Helper() + responses := make([]*httptest.ResponseRecorder, len(bodies)) + var group sync.WaitGroup + start := make(chan struct{}) + for index := range bodies { + group.Go(func() { + <-start + responses[index] = organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, path, bodies[index], origin, session, keys[index]) + }) + } + close(start) + group.Wait() + return responses +} + +// firstAcceptance is the acceptance that later cases of the test repeat. +type firstAcceptance struct { + candidate domain.User + invitation invitationHTTPBody + key string + body string +} + +func TestCandidateInvitationAcceptOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolated := *env + isolated.Config.DatabaseURL = databaseURL + setupPool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + harness := newInvitationHTTPHarness(ctx, t, &isolated) + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) + origin := env.Config.AppPublicURL + now := harness.clock.Now() + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + account := func(email string, scenario domain.Scenario) domain.User { + return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) + } + owner := account("accept-owner@example.test", domain.ScenarioEmployer) + sessionOwner := loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwner, "accept-company") + var nameA string + if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, orgA).Scan(&nameA); err != nil { + t.Fatalf("read organization name: %v", err) + } + + identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, + organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now}, + ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now} + // Every candidate publishes the card and holds a name, an email, and a phone + // number. Telegram is held by none of them. + publishCandidate := func(candidate domain.User) { + consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now) + privacy.publish(t, candidate.ID, consent.ID(), 0, + domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, + domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility) + profiles.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision(invitationCandidateName), Email: confirmedDecision(invitationCandidateContact), + Phone: confirmedDecision("+70000000000"), + Stack: privacyCohortConfirmedItems("go"), + Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}), + Experience: privacyCohortConfirmedItems(domain.ProfileExperience{ + EmployerName: invitationCandidateMarker, Specialization: domain.SpecializationBackend, + StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private summary", + }), + SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 777_000, TaxBasis: domain.ProfileTaxNet}), + }, 0) + if _, err := privacy.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{ + UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now), + }); err != nil { + t.Fatalf("InsertCandidateQuestionnaire() error = %v", err) + } + } + // Seven published candidates form the visible cohort. Each case uses its own + // candidate, so the cases do not share the state of an invitation. + var candidates []domain.User + for index := range 7 { + candidate := account(fmt.Sprintf("accept-candidate-%d@example.test", index), domain.ScenarioCandidate) + candidates = append(candidates, candidate) + publishCandidate(candidate) + } + login := func(candidate domain.User) organizationHTTPSession { + return loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) + } + request := func(method, path, body string, session organizationHTTPSession, key string) *httptest.ResponseRecorder { + t.Helper() + return organizationHTTPRequest(t, harness.sessionHTTPHarness, method, path, body, origin, session, key) + } + var keySequence int + nextKey := func() string { + keySequence++ + return fmt.Sprintf("invitation-accept-key-%d", keySequence) + } + deliver := func(candidate domain.User) invitationHTTPBody { + t.Helper() + handle, err := harness.key.ForOrganization(orgA, candidate.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + draft := decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", orgA), + invitationCreateJSON(t, handle, nil), sessionOwner, nextKey()), http.StatusCreated) + return decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/send", orgA, draft.ID), + fmt.Sprintf(`{"expected_version":%d}`, draft.Version), sessionOwner, nextKey()), http.StatusOK) + } + myPath := func(invitationID uuid.UUID) string { return "/api/v1/me/invitations/" + invitationID.String() } + acceptBody := func(version, terms int64, text string, fields ...string) string { + encoded, err := json.Marshal(map[string]any{ + "expected_version": version, "terms_version": terms, + "consent_c4": map[string]any{"text_version": text, "accepted": true, "fields": fields}, + }) + if err != nil { + t.Fatalf("marshal acceptance: %v", err) + } + return string(encoded) + } + accept := func(candidate domain.User, invitationID uuid.UUID, body, key string) *httptest.ResponseRecorder { + t.Helper() + return request(http.MethodPost, myPath(invitationID)+"/accept", body, login(candidate), key) + } + // raiseTerms stores the next terms version the way a later raise does, with + // a higher salary, and advances the invitation version by one. + raiseTerms := func(invitationID uuid.UUID) int64 { + t.Helper() + if _, err := harness.pool.Exec(ctx, ` + INSERT INTO invitation_terms_versions (invitation_id, organization_id, version, terms, salary_from, salary_to, + salary_currency, salary_period, salary_tax_basis, created_at) + SELECT invitation_id, organization_id, 2, + jsonb_set(jsonb_set(terms, '{salary,salary_from}', '120000'::jsonb), '{salary,salary_to}', '160000'::jsonb), + 120000, 160000, salary_currency, salary_period, salary_tax_basis, $2 + FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, invitationID, harness.clock.Now()); err != nil { + t.Fatalf("store the raised terms: %v", err) + } + var version int64 + if err := harness.pool.QueryRow(ctx, ` + UPDATE invitations SET terms_version = 2, version = version + 1, updated_at = $2 + WHERE id = $1 RETURNING version`, invitationID, harness.clock.Now()).Scan(&version); err != nil { + t.Fatalf("raise the invitation: %v", err) + } + return version + } + candidateMarkers := []string{invitationCandidateName, invitationCandidateContact, invitationCandidateMarker} + for _, candidate := range candidates { + candidateMarkers = append(candidateMarkers, candidate.ID.String(), candidate.Email.Address()) + } + requireNoCandidateData := func(label, text string) { + t.Helper() + for _, marker := range candidateMarkers { + if strings.Contains(text, marker) { + t.Errorf("%s contains the private marker %q: %s", label, marker, text) + } + } + for _, field := range []string{"candidate_id", "candidate_handle", "salary_fit", "salary_minimum", "full_name", "telegram", "email", "phone"} { + if strings.Contains(text, `"`+field+`":`) { + t.Errorf("%s contains the key %q: %s", label, field, text) + } + } + } + + var first firstAcceptance + t.Run("an email-only acceptance stores one grant of that field and one consent", func(t *testing.T) { + candidate := candidates[0] + sent := deliver(candidate) + key := nextKey() + body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email") + response := accept(candidate, sent.ID, body, key) + accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + requireNoCandidateData("accept response", response.Body.String()) + grant := decodeContactGrantHTTP(t, accepted) + if accepted.State != "accepted" || accepted.Version != sent.Version+1 || accepted.TermsVersion != sent.TermsVersion || + accepted.RespondedAt == nil || accepted.Decline != nil || string(accepted.ContactConsent) != "null" || + accepted.ResponseDeadlineAt != *sent.ResponseDeadlineAt || accepted.Organization.Name != nameA { + t.Fatalf("accepted = %+v, want the accepted invitation with its deadline and no offer", accepted) + } + if !slices.Equal(grant.Fields, []string{"email"}) || grant.Status != "active" || grant.ConsentTextVersion != acceptTextVersion || + grant.TermsVersion != sent.TermsVersion || grant.RevokedAt != nil || grant.RevocationReason != nil { + t.Fatalf("grant = %+v, want the email only, active, under the current text", grant) + } + // The published profile is not hidden, so the grant is readable now. + if !grant.Readable || grant.BlockedBy != nil { + t.Fatalf("grant = %+v, want readable while the organization may read the profile", grant) + } + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 1}) { + t.Fatalf("acceptance stored %+v, want one event, one grant, one C4 consent, and one outcome", counts) + } + // The grant names the one selected kind, although the profile holds the + // phone number too, and the consent names the same kind. + var fields, consentFields []string + if err := harness.pool.QueryRow(ctx, ` + SELECT grant_row.fields, record.field_set + FROM contact_grants AS grant_row + JOIN consent_records AS record ON record.id = grant_row.consent_record_id + WHERE grant_row.source_invitation_id = $1`, sent.ID).Scan(&fields, &consentFields); err != nil { + t.Fatalf("read the grant and its consent: %v", err) + } + if !slices.Equal(fields, []string{"email"}) || !slices.Equal(consentFields, []string{"email"}) { + t.Fatalf("stored grant fields = %v and consent fields = %v, want the email only", fields, consentFields) + } + reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) + if decodeContactGrantHTTP(t, reread).ID != grant.ID || reread.Version != accepted.Version { + t.Fatalf("reread = %+v, want the same grant and version", reread) + } + first = firstAcceptance{candidate: candidate, invitation: sent, key: key, body: body} + }) + + t.Run("repeats replay the answer and a different choice is a state conflict", func(t *testing.T) { + if first.invitation.ID == uuid.Nil { + t.Fatal("the first acceptance did not run") + } + original := accept(first.candidate, first.invitation.ID, first.body, first.key) + if original.Code != http.StatusOK { + t.Fatalf("replay = %d %s, want the original 200", original.Code, original.Body.String()) + } + // The same request under a new key, with the older expected version, + // answers the accepted invitation without a second grant or event. + again := accept(first.candidate, first.invitation.ID, first.body, nextKey()) + if again.Code != http.StatusOK || again.Body.String() != original.Body.String() { + t.Fatalf("repeat = %d %s, want the same answer %s", again.Code, again.Body.String(), original.Body.String()) + } + // Another field set is a different acceptance that the grant refuses. + requireSessionProblem(t, accept(first.candidate, first.invitation.ID, + acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "email", "phone"), nextKey()), + http.StatusConflict, "state_conflict") + // A reused key with another body is refused and stores nothing. + requireSessionProblem(t, accept(first.candidate, first.invitation.ID, + acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "phone"), first.key), + http.StatusUnprocessableEntity, "idempotency_key_reused") + // Three outcomes: the first acceptance, the repeat, and the refused field set. + if counts := readInvitationAcceptCounts(ctx, t, harness, first.invitation.ID, first.candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) { + t.Fatalf("repeats stored %+v, want the first acceptance, its repeat, and the refusal", counts) + } + }) + + t.Run("a stale terms version is refused and nothing is stored, and the raised terms are accepted", func(t *testing.T) { + candidate := candidates[1] + sent := deliver(candidate) + raisedVersion := raiseTerms(sent.ID) + // The candidate read the terms of version 1: 412, nothing stored. + requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()), + http.StatusPreconditionFailed, "version_conflict") + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) { + t.Fatalf("a stale terms version stored %+v", counts) + } + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) + if read.TermsVersion != 2 || read.Version != raisedVersion || read.State != "delivered" { + t.Fatalf("read after the raise = %+v, want the new terms and the delivered state", read) + } + accepted := decodeCandidateInvitationHTTP(t, accept(candidate, sent.ID, acceptBody(raisedVersion, 2, acceptTextVersion, "email"), nextKey()), http.StatusOK) + if accepted.State != "accepted" || accepted.TermsVersion != 2 || decodeContactGrantHTTP(t, accepted).TermsVersion != 2 { + t.Fatalf("accepted = %+v, want the raised terms version accepted", accepted) + } + // The old terms version is a different acceptance once the grant exists. + requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()), + http.StatusConflict, "state_conflict") + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 2}) { + t.Fatalf("raised acceptance stored %+v, want one acceptance, one grant, one consent, and the refusal", counts) + } + }) + + t.Run("concurrent acceptances make one transition and one grant", func(t *testing.T) { + candidate := candidates[2] + sent := deliver(candidate) + session := login(candidate) + path := myPath(sent.ID) + "/accept" + body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email") + responses := parallelAcceptRequests(t, harness, path, origin, session, + []string{body, body, body}, []string{nextKey(), nextKey(), nextKey()}) + var answers []string + for _, response := range responses { + accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + if accepted.State != "accepted" { + t.Fatalf("concurrent answer = %+v, want accepted", accepted) + } + answers = append(answers, response.Body.String()) + } + if !slices.Equal(answers[1:], answers[:len(answers)-1]) { + t.Fatalf("concurrent answers differ: %v", answers) + } + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) { + t.Fatalf("concurrent acceptances stored %+v, want one transition, one grant, one consent", counts) + } + + // Two different field sets race: one transition, the other a conflict. + other := candidates[3] + raced := deliver(other) + responses = parallelAcceptRequests(t, harness, myPath(raced.ID)+"/accept", origin, login(other), + []string{ + acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "email"), + acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "phone"), + }, []string{nextKey(), nextKey()}) + statuses := []int{responses[0].Code, responses[1].Code} + slices.Sort(statuses) + if !slices.Equal(statuses, []int{http.StatusOK, http.StatusConflict}) { + t.Fatalf("raced acceptances = %v, want one 200 and one 409 state_conflict", statuses) + } + if counts := readInvitationAcceptCounts(ctx, t, harness, raced.ID, other.ID); counts.acceptedEvents != 1 || counts.grants != 1 || counts.c4Consents != 1 { + t.Fatalf("raced acceptances stored %+v, want one transition, one grant, one consent", counts) + } + }) + + t.Run("a hidden organization accepts without changing the publication or the hiding", func(t *testing.T) { + candidate := candidates[4] + sent := deliver(candidate) + privacy.hide(t, candidate.ID, orgA, harness.clock.Now()) + publication := privacy.rawPublication(t, candidate.ID) + hidden := privacy.rawHidden(t, candidate.ID) + response := accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email"), nextKey()) + accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + grant := decodeContactGrantHTTP(t, accepted) + if grant.Readable || grant.BlockedBy == nil || *grant.BlockedBy != "visibility" || len(grant.Fields) != 1 { + t.Fatalf("grant while hidden = %+v, want stored and blocked by visibility", grant) + } + if after := privacy.rawPublication(t, candidate.ID); after != publication { + t.Fatalf("the acceptance changed the publication: %s became %s", publication, after) + } + if after := privacy.rawHidden(t, candidate.ID); after != hidden { + t.Fatalf("the acceptance changed the hiding: %s became %s", hidden, after) + } + // The candidate removes the hiding; the same grant becomes readable. + if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1 AND organization_id = $2`, + candidate.ID, orgA); err != nil { + t.Fatalf("unhide the organization: %v", err) + } + reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) + if grantRead := decodeContactGrantHTTP(t, reread); grantRead.ID != grant.ID || !grantRead.Readable || grantRead.BlockedBy != nil { + t.Fatalf("grant after unhiding = %+v, want the same grant readable", grantRead) + } + }) + + t.Run("a late acceptance is refused under its key whatever the version", func(t *testing.T) { + candidate := candidates[5] + sent := deliver(candidate) + var deadline time.Time + if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, sent.ID).Scan(&deadline); err != nil { + t.Fatalf("read the deadline: %v", err) + } + harness.clock.Set(deadline.UTC()) + key := nextKey() + for range 2 { + requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(sent.Version+5, sent.TermsVersion, acceptTextVersion, "email"), key), + http.StatusConflict, "state_conflict") + } + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{outcomes: 1}) { + t.Fatalf("late acceptances stored %+v, want one state_conflict outcome and nothing else", counts) + } + }) + + t.Run("the consent text and the held kinds are checked before anything is stored", func(t *testing.T) { + // The late case moved the clock to a deadline, which ends the owner session. + sessionOwner = loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address()) + candidate := candidates[6] + sent := deliver(candidate) + requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, "c4-2025-01-01", "email"), nextKey()), + "/consent_c4/text_version", "") + requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email", "telegram"), nextKey()), + "/consent_c4/fields/1", "") + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) { + t.Fatalf("refused consent stored %+v", counts) + } + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) + if read.State != "delivered" || string(read.ContactGrant) != "null" { + t.Fatalf("read after the refusals = %+v, want the delivered invitation without a grant", read) + } + }) + + t.Run("the acceptance answers stay out of the server log", func(t *testing.T) { + requireNoCandidateData("server log", harness.logs.String()) + }) +} + +func TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback(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) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + // The fixture creates an organization with the schema of the current head. + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + // Migrations added after this one are not part of this guard: the test + // rolls them back, so that this migration is the one rolled back below. + rollBackAboveVersion(ctx, t, migrator, invitationAcceptMigrationVersion) + store := func(t *testing.T, work func(context.Context, outbound.UnitOfWork) error) error { + t.Helper() + return fixture.transactor.WithinTransaction(ctx, work) + } + deliverDraft := func(t *testing.T) domain.Invitation { + t.Helper() + draft := fixture.draft(t) + delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + event, err := delivered.DeliveryEvent(fixture.owner.ID) + if err != nil { + t.Fatalf("DeliveryEvent() error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) + }); err != nil { + t.Fatalf("Deliver() through the repository error = %v", err) + } + return delivered + } + + delivered := deliverDraft(t) + acceptedAt := delivered.UpdatedAt().Add(time.Minute) + accepted, err := delivered.Accept(delivered.TermsVersion(), acceptedAt) + if err != nil { + t.Fatalf("Accept() error = %v", err) + } + acceptEvent, err := accepted.AnswerEvent(fixture.candidate.ID) + if err != nil { + t.Fatalf("AnswerEvent() error = %v", err) + } + fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + consents := consent.NewService(fixture.transactor, func() time.Time { return acceptedAt }) + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Invitations().Accept(ctx, delivered.Version(), accepted, acceptEvent); err != nil { + return err + } + granted, err := consents.GrantContact(ctx, unit, consent.ContactGrantInput{ + SubjectID: fixture.candidate.ID, OrganizationID: fixture.organization.ID(), OrganizationName: fixture.organization.Profile().Name(), + Fields: fields, InvitationID: delivered.ID(), InvitationTermsVersion: delivered.TermsVersion(), TextVersion: acceptTextVersion, + }) + if err != nil { + return err + } + grant, err := domain.NewContactGrant(granted.Record, accepted) + if err != nil { + return err + } + return unit.ContactGrants().Create(ctx, grant) + }); err != nil { + t.Fatalf("accept through the repositories error = %v", err) + } + + // The database guards the acceptance and its grant against other writers. + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'delivered', responded_at = NULL, version = version + 1 WHERE id = $1`, delivered.ID()) + assertPgError(t, "leave the acceptance", err, privacyIntegrityViolation, "invitations_answer_immutable") + _, err = pool.Exec(ctx, `UPDATE contact_grants SET fields = '{phone}' WHERE source_invitation_id = $1`, delivered.ID()) + assertPgError(t, "change the grant", err, privacyIntegrityViolation, "contact_grants_immutable") + _, err = pool.Exec(ctx, `DELETE FROM contact_grants WHERE source_invitation_id = $1`, delivered.ID()) + assertPgError(t, "delete the grant", err, privacyIntegrityViolation, "contact_grants_immutable") + _, err = pool.Exec(ctx, `INSERT INTO invitation_events (id, invitation_id, organization_id, version, terms_version, kind, actor_id, changed_fields, occurred_at) + SELECT $1, id, organization_id, version + 1, terms_version, 'accepted', created_by, ARRAY['terms'], now() FROM invitations WHERE id = $2`, uuid.New(), delivered.ID()) + assertPgError(t, "accepted event with a field", err, privacyCheckViolation, "invitation_events_answer_changes_no_field") + + // An acceptance without its grant cannot commit. + other := deliverDraft(t) + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'accepted', responded_at = delivered_at + interval '1 minute', + updated_at = delivered_at + interval '1 minute', version = version + 1 WHERE id = $1`, other.ID()) + assertPgError(t, "accepted without a grant", err, privacyIntegrityViolation, "invitations_acceptance_recorded") + + _, err = migrator.DownOne(ctx) + assertPgError(t, "DownOne() with an accepted invitation", err, privacyIntegrityViolation, invitationAcceptancesRetained) + // The database is isolated to this test: CASCADE also clears the tables that + // refer to the consent ledger, such as the publication history of C2. + if _, err := pool.Exec(ctx, `TRUNCATE consent_records, invitations, invitation_accept_results, invitation_decline_results, + invitation_send_results, invitation_creation_results CASCADE`); err != nil { + t.Fatalf("clear the invitation tables: %v", err) + } + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != invitationAcceptMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationAcceptMigrationVersion) + } + var remaining int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name IN ('contact_grants', 'invitation_accept_results')`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("acceptance tables left after the rollback: %d, %v", remaining, err) + } + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } +} diff --git a/backend/integration_test/invitation_answer_http_test.go b/backend/integration_test/invitation_answer_http_test.go index 7ac8dbc..7c404da 100644 --- a/backend/integration_test/invitation_answer_http_test.go +++ b/backend/integration_test/invitation_answer_http_test.go @@ -9,6 +9,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "slices" "strings" "testing" "time" @@ -254,9 +255,25 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) { read := request(http.MethodGet, myPath(sent.ID), "", sessionTarget, "") opened := decodeCandidateInvitationHTTP(t, read, http.StatusOK) requireNoCandidateData("candidate read", read.Body.String()) + // While an acceptance is possible the read offers the consent C4 with + // the kinds that the profile holds, and no grant exists yet. + var offer struct { + Text struct { + TextVersion string `json:"text_version"` + Text string `json:"text"` + } `json:"text"` + AvailableFields []string `json:"available_fields"` + } + if err := json.Unmarshal(opened.ContactConsent, &offer); err != nil { + t.Fatalf("decode contact consent %s: %v", opened.ContactConsent, err) + } + if strings.Contains(offer.Text.Text, "{organization}") || !strings.Contains(offer.Text.Text, nameA) || + offer.Text.TextVersion != "c4-2026-10-01" || !slices.Equal(offer.AvailableFields, []string{"full_name", "email"}) { + t.Fatalf("contact consent = %+v, want the C4 text for the organization and the held kinds", offer) + } if opened.State != "delivered" || opened.Version != sent.Version || opened.ViewedAt != nil || opened.Organization.ID != orgA || opened.Organization.Name != nameA || opened.ResponseDeadlineAt != *sent.ResponseDeadlineAt || opened.Decline != nil || - string(opened.ContactConsent) != "null" || string(opened.ContactGrant) != "null" || len(opened.Terms) == 0 { + string(opened.ContactGrant) != "null" || len(opened.Terms) == 0 { t.Fatalf("read = %+v, want the delivered invitation with its terms and no side effect", opened) } // A read records nothing: it is free of side effects by contract. diff --git a/backend/integration_test/invitation_http_test.go b/backend/integration_test/invitation_http_test.go index 0260578..bc8d194 100644 --- a/backend/integration_test/invitation_http_test.go +++ b/backend/integration_test/invitation_http_test.go @@ -30,6 +30,7 @@ import ( "lincodex/backend/internal/usecase/anonymousprofile" "lincodex/backend/internal/usecase/candidateview" "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/consent" "lincodex/backend/internal/usecase/health" "lincodex/backend/internal/usecase/identity" invitationusecase "lincodex/backend/internal/usecase/invitation" @@ -119,7 +120,7 @@ func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnviro Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { return quota.ReserveInvitation(ctx, unit, organization, invitationID) }, - Notifier: notifier, Clock: clock.Now, + Notifier: notifier, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now, }) if err != nil { t.Fatalf("invitation.NewService() error = %v", err) diff --git a/backend/integration_test/match_search_http_test.go b/backend/integration_test/match_search_http_test.go index 2ffbeb5..f3b7346 100644 --- a/backend/integration_test/match_search_http_test.go +++ b/backend/integration_test/match_search_http_test.go @@ -1078,13 +1078,15 @@ func TestMatchSearchOverHTTP(t *testing.T) { }) 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) + // Organizations of one owner share the E0 pool, so this one gets an owner of its own. + ownerC := client.employer(t, "match-employer-c@example.test") + orgC := organizations.create(t, domain.User{ID: ownerC.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":{}}`) + result, response := search(ownerC, orgC.ID(), `{"filters":{}}`) if response.Code != http.StatusOK { t.Fatalf("search of organization C = %d %s", response.Code, response.Body.String()) } @@ -1119,7 +1121,7 @@ func TestMatchSearchOverHTTP(t *testing.T) { 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 || + if got := harness.request(t, http.MethodGet, cardPath(first.Groups.Main[0].CandidateHandle), "", "", ownerC.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())) } @@ -1131,7 +1133,7 @@ func TestMatchSearchOverHTTP(t *testing.T) { } } } - if got := harness.request(t, http.MethodGet, cardPath(unpaid), "", "", employer.cookie, "", client.remote()); got.Code != http.StatusTooManyRequests { + if got := harness.request(t, http.MethodGet, cardPath(unpaid), "", "", ownerC.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. @@ -1176,7 +1178,8 @@ func TestMatchSearchOverHTTP(t *testing.T) { }) 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) + ownerD := client.employer(t, "match-employer-d@example.test") + orgD := organizations.create(t, domain.User{ID: ownerD.id}, organizations.completeProfile(t, "Match organization D"), now) publishPolicy(func(product *domain.ProductPolicy) { product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8 }) type outcome struct { status int @@ -1193,7 +1196,7 @@ func TestMatchSearchOverHTTP(t *testing.T) { group.Add(1) go func() { defer group.Done() - response := harness.request(t, http.MethodPost, searchPath(orgD.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, employer.cookie, employer.csrf, remote) + response := harness.request(t, http.MethodPost, searchPath(orgD.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerD.cookie, ownerD.csrf, remote) outcomes <- outcome{status: response.Code, body: response.Body.String()} }() } @@ -1238,7 +1241,8 @@ func TestMatchSearchOverHTTP(t *testing.T) { }) 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) + ownerF := client.employer(t, "match-employer-f@example.test") + orgF := organizations.create(t, domain.User{ID: ownerF.id}, organizations.completeProfile(t, "Match organization F"), now) visible := make([]categoryHTTPCandidate, 0, 17) for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} { visible = append(visible, group...) @@ -1269,14 +1273,14 @@ func TestMatchSearchOverHTTP(t *testing.T) { 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) + response := harness.request(t, http.MethodGet, path, "", "", ownerF.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) + response := harness.request(t, http.MethodPost, searchPath(orgF.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerF.cookie, ownerF.csrf, remote) return outcome{what: "search", status: response.Code} } } diff --git a/backend/integration_test/needs_test.go b/backend/integration_test/needs_test.go index 75a86a0..922b9e6 100644 --- a/backend/integration_test/needs_test.go +++ b/backend/integration_test/needs_test.go @@ -367,9 +367,8 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) { t.Fatalf("apply migrations to rollback test database: %v", err) } // The preflight belongs to the migration that created the replay table, so - // the migrations added after it are rolled back first. The database holds - // no data yet, which keeps their own guarded rollbacks out of this test. - rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion) + // the migrations added after it are rolled back first. The one organization + // below has its own holding, so their guarded rollbacks do not refuse. pool := newPoolFor(ctx, t, databaseURL) now := time.Now().UTC().Truncate(time.Microsecond) fixture := organizationFixture{ @@ -377,6 +376,11 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) { identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}, transactor: postgresadapter.NewTransactor(pool), now: now, } + // The organization is created while the latest schema is in place: its + // creation needs the holdings table, which the rollback below removes. + owner := fixture.employer(t, "need-migration-owner@example.test") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now) + rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion) scope := []byte(strings.Repeat("s", outbound.IdempotencyDigestSize)) fingerprint := []byte(strings.Repeat("f", outbound.IdempotencyDigestSize)) if _, err := pool.Exec(ctx, ` @@ -400,8 +404,6 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) { now.Add(-outbound.IdempotencyRetention-time.Second), now.Add(-time.Second), scope); err != nil { t.Fatalf("expire idempotency replay before checking historical bounds: %v", err) } - owner := fixture.employer(t, "need-migration-owner@example.test") - organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now) need := newIntegrationNeed(t, organization.ID(), "Bounded rollback fixture", now.Add(time.Minute)) encoded, err := json.Marshal(need.Snapshot()) if err != nil { diff --git a/backend/integration_test/notification_inbox_migration_test.go b/backend/integration_test/notification_inbox_migration_test.go index f89d527..d056835 100644 --- a/backend/integration_test/notification_inbox_migration_test.go +++ b/backend/integration_test/notification_inbox_migration_test.go @@ -31,8 +31,8 @@ func TestSyntheticNotificationMigrationAllowlistAndGuardedRollback(t *testing.T) if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() error = %v", err) } - rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion) - + // The candidate and the organization are created while the latest schema is in + // place: their creation needs the holdings table, which the rollback removes. 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)) @@ -42,6 +42,8 @@ func TestSyntheticNotificationMigrationAllowlistAndGuardedRollback(t *testing.T) owner := organizations.employer(t, "inbox-migration-owner@example.com") organization := organizations.create(t, owner, organizations.completeProfile(t, "Example Company"), now) + rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion) + 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 diff --git a/backend/integration_test/organizations_test.go b/backend/integration_test/organizations_test.go index e5deefe..4fc0806 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -41,11 +41,13 @@ var ( organizationTables = []pgx.Identifier{ {"candidate_card_access_events"}, {"invitation_creation_results"}, {"invitation_send_results"}, {"invitation_decline_results"}, {"invitation_declines"}, - {"invitation_events"}, {"invitation_terms_versions"}, {"invitations"}, + {"invitation_events"}, {"invitation_terms_versions"}, {"invitation_accept_results"}, {"contact_grants"}, {"invitations"}, {"organization_need_versions"}, {"organization_needs"}, {"organization_need_creation_results"}, {"company_invitation_quota_usage"}, {"company_card_view_quota_usage"}, organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable, + // holdings reference users and are referenced by organizations. + {"holdings"}, } candidateQuestionnaireTables = []pgx.Identifier{ {"candidate_questionnaire_specializations"}, {"candidate_questionnaires"}, @@ -260,10 +262,16 @@ func TestOrganizationsAndMemberships(t *testing.T) { reset(t) member := fixture.employer(t, "member@example.com") insertOrganization := func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error { + if _, err := tx.Exec(ctx, ` + INSERT INTO holdings (id, founder_account_id, created_at) VALUES ($1, $2, $3) + ON CONFLICT (founder_account_id) DO NOTHING`, uuid.New(), member.ID, now); err != nil { + return err + } _, err := tx.Exec(ctx, ` INSERT INTO organizations ( - id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at - ) VALUES ($1, 'ООО Без владельца', 'e0', 'confirmed_email', $2, 1, $2, $2)`, id, now) + id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id + ) VALUES ($1, 'ООО Без владельца', 'e0', 'confirmed_email', $2, 1, $2, $2, + (SELECT id FROM holdings WHERE founder_account_id = $3))`, id, now, member.ID) return err } insertMember := func(ctx context.Context, tx pgx.Tx, organizationID uuid.UUID, role, state string) error { @@ -692,10 +700,12 @@ func TestOrganizationsAndMemberships(t *testing.T) { user := fixture.employer(t, "owner@example.com") organization := fixture.create(t, user, fixture.completeProfile(t, "ООО Пример"), now) insertOrganization := func(name, verificationLevel, basis string, version int) error { + // The holding of the owner exists, so only the checked columns can fail. _, err := pool.Exec(ctx, ` INSERT INTO organizations ( - id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at - ) VALUES ($1, $2, $3, $4, $5, $6, $5, $5)`, uuid.New(), name, verificationLevel, basis, now, version) + id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id + ) VALUES ($1, $2, $3, $4, $5, $6, $5, $5, + (SELECT id FROM holdings WHERE founder_account_id = $7))`, uuid.New(), name, verificationLevel, basis, now, version, user.ID) return err } for _, test := range []struct { diff --git a/backend/integration_test/policy_test.go b/backend/integration_test/policy_test.go index 278c772..9fd599a 100644 --- a/backend/integration_test/policy_test.go +++ b/backend/integration_test/policy_test.go @@ -252,7 +252,7 @@ func TestPolicyVersions(t *testing.T) { assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks, assessment_synthetic_category_reviews, candidate_assessment_categories, skill_evidence_facts, skill_evidence_skills, - invitations, invitation_terms_versions, invitation_events, invitation_declines`}, + invitations, invitation_terms_versions, invitation_events, invitation_declines, contact_grants`}, } for _, statement := range statements { _, err := fixture.pool.Exec(ctx, statement.sql, statement.args...) diff --git a/backend/integration_test/skill_evidence_http_test.go b/backend/integration_test/skill_evidence_http_test.go index 0e7ceac..4cfaccf 100644 --- a/backend/integration_test/skill_evidence_http_test.go +++ b/backend/integration_test/skill_evidence_http_test.go @@ -807,6 +807,18 @@ 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) } + // The rollback of the holdings migration refuses a holding that groups several + // organizations. The second organization moves to a holding of its own first; + // the evidence rollback under test does not depend on the grouping. + split := client.employer(t, "evidence-holding-split@example.test") + if _, err := harness.pool.Exec(ctx, ` + INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, now())`, split.id); err != nil { + t.Fatalf("create the holding of the split organization: %v", err) + } + if _, err := harness.pool.Exec(ctx, ` + UPDATE organizations SET holding_id = (SELECT id FROM holdings WHERE founder_account_id = $1) WHERE id = $2`, split.id, organizationB.ID()); err != nil { + t.Fatalf("move the second organization to its own holding: %v", err) + } // Later migrations may exist; the rollback under test is the evidence one. rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion) _, err = migrator.DownOne(ctx) diff --git a/backend/internal/adapter/primary/http/v1/invitation.go b/backend/internal/adapter/primary/http/v1/invitation.go index ce04b3e..8268a46 100644 --- a/backend/internal/adapter/primary/http/v1/invitation.go +++ b/backend/internal/adapter/primary/http/v1/invitation.go @@ -30,6 +30,7 @@ type InvitationOperations interface { GetMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) ViewMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) DeclineMine(ctx context.Context, command invitationusecase.DeclineCommand) (domain.CandidateInvitationView, error) + AcceptMine(ctx context.Context, command invitationusecase.AcceptCommand) (domain.CandidateInvitationView, error) } // InvitationHandler serves the organization side of invitation drafts and diff --git a/backend/internal/adapter/primary/http/v1/invitation_candidate.go b/backend/internal/adapter/primary/http/v1/invitation_candidate.go index 6664075..62a069c 100644 --- a/backend/internal/adapter/primary/http/v1/invitation_candidate.go +++ b/backend/internal/adapter/primary/http/v1/invitation_candidate.go @@ -31,6 +31,66 @@ func (handler *Handler) DeclineMyInvitation(ctx context.Context, request *api.In return handler.invitation.DeclineMyInvitation(ctx, request, params) } +func (handler *Handler) AcceptMyInvitation(ctx context.Context, request *api.InvitationAcceptance, params api.AcceptMyInvitationParams) (api.AcceptMyInvitationRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.AcceptMyInvitation(ctx, request, params) + } + return handler.invitation.AcceptMyInvitation(ctx, request, params) +} + +// AcceptMyInvitation accepts the current terms of an invitation with the consent +// C4. The fields come from the body as kinds only; the server takes the values +// from the profile, and the request never carries them. +func (handler *InvitationHandler) AcceptMyInvitation( + ctx context.Context, + request *api.InvitationAcceptance, + params api.AcceptMyInvitationParams, +) (api.AcceptMyInvitationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.AcceptMyInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if request == nil { + return (*api.AcceptMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil + } + fields := make([]domain.ContactField, 0, len(request.ConsentC4.Fields)) + for _, field := range request.ConsentC4.Fields { + fields = append(fields, domain.ContactField(field)) + } + view, err := handler.operations.AcceptMine(ctx, invitationusecase.AcceptCommand{ + ActorID: principal.UserID, InvitationID: params.InvitationID, IdempotencyKey: params.IdempotencyKey, + ExpectedVersion: int64(request.ExpectedVersion), TermsVersion: int64(request.TermsVersion), + TextVersion: string(request.ConsentC4.TextVersion), Fields: fields, + }) + if err != nil { + return invitationAcceptFailure(ctx, err) + } + return &api.CandidateInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: candidateInvitationResponse(view)}, nil +} + +func invitationAcceptFailure(ctx context.Context, err error) (api.AcceptMyInvitationRes, error) { + if errors.Is(err, invitationusecase.ErrAnswerBlocked) { + return (*api.AcceptMyInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil + } + switch classifyInvitationError(err) { + case invitationFailureForbidden: + return (*api.AcceptMyInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case invitationFailureNotFound: + return (*api.AcceptMyInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case invitationFailureKeyReused: + return (*api.AcceptMyInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil + case invitationFailureBadKey: + return (*api.AcceptMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil + case invitationFailureInvalid: + return (*api.AcceptMyInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil + case invitationFailureVersionConflict: + return (*api.AcceptMyInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil + case invitationFailureStateConflict, invitationFailureOther: + return nil, err + } + return nil, err +} + func (handler *InvitationHandler) GetMyInvitation(ctx context.Context, params api.GetMyInvitationParams) (api.GetMyInvitationRes, error) { principal, ok := PrincipalFromContext(ctx) if !ok { @@ -123,10 +183,9 @@ func invitationDeclineFailure(ctx context.Context, err error) (api.DeclineMyInvi return nil, err } -// candidateInvitationResponse maps the candidate's view. The consent offer -// and the contact grant belong to the acceptance, which is not served yet, -// so an acceptance is impossible now and both are null, as the contract -// requires when no acceptance can be made. +// candidateInvitationResponse maps the candidate's view. The consent offer is +// set only while an acceptance is possible, and the contact grant only after +// the acceptance; otherwise both are null, as the contract requires. func candidateInvitationResponse(view domain.CandidateInvitationView) api.CandidateInvitation { response := api.CandidateInvitation{ ID: view.ID, @@ -138,7 +197,13 @@ func candidateInvitationResponse(view domain.CandidateInvitationView) api.Candid RespondedAt: nullableTimestamp(view.RespondedAt), UpdatedAt: api.Timestamp(view.UpdatedAt), } response.ContactConsent.SetToNull() + if view.ContactConsent != nil { + response.ContactConsent.SetTo(contactConsentOfferResponse(*view.ContactConsent)) + } response.ContactGrant.SetToNull() + if view.ContactGrant != nil { + response.ContactGrant.SetTo(contactGrantResponse(*view.ContactGrant)) + } if view.Decline == nil { response.Decline.SetToNull() return response @@ -154,3 +219,43 @@ func candidateInvitationResponse(view domain.CandidateInvitationView) api.Candid response.Decline.SetTo(record) return response } + +func contactConsentOfferResponse(offer domain.ContactConsentOffer) api.ContactConsentOffer { + fields := make([]api.ContactFieldKind, 0, len(offer.AvailableFields)) + for _, field := range offer.AvailableFields { + fields = append(fields, api.ContactFieldKind(field)) + } + return api.ContactConsentOffer{ + Text: api.ContactConsentText{ + TextVersion: api.ConsentTextVersion(offer.Text.TextVersion), Text: offer.Text.Text, + }, + AvailableFields: fields, + } +} + +// contactGrantResponse maps the grant as the candidate reads it: the kinds, the +// status, and whether the organization can read them now, never a value. +func contactGrantResponse(view domain.ContactGrantView) api.ContactGrant { + fields := make([]api.ContactFieldKind, 0, len(view.Fields)) + for _, field := range view.Fields { + fields = append(fields, api.ContactFieldKind(field)) + } + response := api.ContactGrant{ + ID: view.ID, Fields: fields, Status: api.ContactGrantState(view.Status), Readable: view.Readable, + TermsVersion: api.InvitationTermsVersion(view.TermsVersion), + ConsentTextVersion: api.ConsentTextVersion(view.ConsentTextVersion), + GrantedAt: api.Timestamp(view.GrantedAt), + } + if view.BlockedBy == nil { + response.BlockedBy.SetToNull() + } else { + response.BlockedBy.SetTo(api.ContactAccessBlock(*view.BlockedBy)) + } + response.RevokedAt = nullableTimestamp(view.RevokedAt) + if view.RevocationReason == nil { + response.RevocationReason.SetToNull() + } else { + response.RevocationReason.SetTo(api.ContactRevocationReason(*view.RevocationReason)) + } + return response +} diff --git a/backend/internal/adapter/primary/http/v1/invitation_candidate_test.go b/backend/internal/adapter/primary/http/v1/invitation_candidate_test.go index 9a08d83..eab50a6 100644 --- a/backend/internal/adapter/primary/http/v1/invitation_candidate_test.go +++ b/backend/internal/adapter/primary/http/v1/invitation_candidate_test.go @@ -94,3 +94,28 @@ func TestCandidateInvitationResponseCarriesTheDeclineAndNoCandidateData(t *testi } } } + +func TestInvitationAcceptFailuresMapToTheContractStatuses(t *testing.T) { + ctx := context.Background() + text := &domain.InvitationFieldError{Pointer: "/consent_c4/text_version", Reason: "x"} + for name, test := range map[string]struct { + err error + want string + }{ + "employer": {invitationusecase.ErrForbidden, "*api.AcceptMyInvitationForbidden"}, + "unknown": {fmt.Errorf("wrapped: %w", outbound.ErrInvitationNotFound), "*api.AcceptMyInvitationNotFound"}, + "reused key": {invitationusecase.ErrIdempotencyKeyReused, "*api.AcceptMyInvitationUnprocessableEntity"}, + "bad key": {invitationusecase.ErrInvalidIdempotencyKey, "*api.AcceptMyInvitationBadRequest"}, + "consent text": {fmt.Errorf("wrapped: %w", text), "*api.AcceptMyInvitationBadRequest"}, + "stale version": {fmt.Errorf("wrapped: %w", domain.ErrInvitationVersionConflict), "*api.AcceptMyInvitationPreconditionFailed"}, + "terminal or late": {fmt.Errorf("wrapped: %w", invitationusecase.ErrAnswerBlocked), "*api.AcceptMyInvitationConflict"}, + } { + response, unexpected := invitationAcceptFailure(ctx, test.err) + if unexpected != nil || fmt.Sprintf("%T", response) != test.want { + t.Errorf("%s: failure = %T, %v; want %s", name, response, unexpected, test.want) + } + } + if _, unexpected := invitationAcceptFailure(ctx, errors.New("storage failed")); unexpected == nil { + t.Error("an unknown failure produced a public response instead of reaching the responder") + } +} diff --git a/backend/internal/adapter/secondary/postgres/company_quota.go b/backend/internal/adapter/secondary/postgres/company_quota.go index 4717397..c00f5c6 100644 --- a/backend/internal/adapter/secondary/postgres/company_quota.go +++ b/backend/internal/adapter/secondary/postgres/company_quota.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" @@ -26,6 +27,20 @@ type companyQuotaRepository struct { var _ outbound.CompanyQuotaRepository = companyQuotaRepository{} +// quotaScope names the usage rows that one reservation counts. An organization +// at a tier that shares its holding pool counts the usage of every E0 +// organization of the holding; any other tier counts its own usage only. +type quotaScope struct { + organizationID uuid.UUID + // holdingID is the holding of the shared pool, and uuid.Nil when the + // organization keeps its own pool. + holdingID uuid.UUID +} + +func (scope quotaScope) sharesHoldingPool() bool { + return scope.holdingID != uuid.Nil +} + func (repository companyQuotaRepository) ReserveInvitation( ctx context.Context, quota domain.CompanyQuota, @@ -38,7 +53,8 @@ func (repository companyQuotaRepository) ReserveInvitation( if invitationID == uuid.Nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota) } - if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil { + scope, err := repository.lockAndCheckSnapshot(ctx, location, quota) + if err != nil { return outbound.CompanyQuotaDecision{}, err } @@ -57,18 +73,15 @@ func (repository companyQuotaRepository) ReserveInvitation( return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read invitation usage: %w", location, mapOrganizationError(err)) } - usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{ - OrganizationID: organizationID, - WindowStart: pgTime(quota.InvitationWindowStart()), - }) + count, earliestAt, err := repository.countInvitationUsage(ctx, location, scope, quota.InvitationWindowStart()) if err != nil { - return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err)) + return outbound.CompanyQuotaDecision{}, err } - if usage.UsageCount < 0 { + if count < 0 { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation usage count is negative", location) } - if usage.UsageCount >= quota.InvitationLimit() { - earliest, err := quotaWindowEarliest(usage.EarliestAt) + if count >= quota.InvitationLimit() { + earliest, err := quotaWindowEarliest(earliestAt) if err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest invitation expiry: %w", location, err) } @@ -92,7 +105,8 @@ func (repository companyQuotaRepository) ReserveCardView( if candidateID == uuid.Nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota) } - if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil { + scope, err := repository.lockAndCheckSnapshot(ctx, location, quota) + if err != nil { return outbound.CompanyQuotaDecision{}, err } @@ -101,7 +115,7 @@ func (repository companyQuotaRepository) ReserveCardView( if err != nil || handled { return decision, err } - return repository.reserveNewCardView(ctx, location, quota, candidateID, organizationID) + return repository.reserveNewCardView(ctx, location, quota, candidateID, scope) } func (repository companyQuotaRepository) reserveExistingCardView( @@ -166,20 +180,17 @@ func (repository companyQuotaRepository) reserveNewCardView( location string, quota domain.CompanyQuota, candidateID uuid.UUID, - organizationID uuid.UUID, + scope quotaScope, ) (outbound.CompanyQuotaDecision, error) { - usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{ - OrganizationID: pgUUID(organizationID), - WindowStart: pgTime(quota.CardViewWindowStart()), - }) + count, earliestAt, err := repository.countCardViewUsage(ctx, location, scope, quota.CardViewWindowStart()) if err != nil { - return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err)) + return outbound.CompanyQuotaDecision{}, err } - if usage.UsageCount < 0 { + if count < 0 { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - card-view usage count is negative", location) } - if usage.UsageCount >= quota.CardViewLimit() { - earliest, err := quotaWindowEarliest(usage.EarliestAt) + if count >= quota.CardViewLimit() { + earliest, err := quotaWindowEarliest(earliestAt) if err != nil { return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest card-view expiry: %w", location, err) } @@ -194,30 +205,119 @@ func (repository companyQuotaRepository) reserveNewCardView( return outbound.CompanyQuotaDecision{Allowed: true}, nil } +// countInvitationUsage returns the invitation usage in the window of scope and +// the earliest counted reservation, which sets the retry time of a denial. +func (repository companyQuotaRepository) countInvitationUsage( + ctx context.Context, + location string, + scope quotaScope, + windowStart time.Time, +) (int64, any, error) { + if scope.sharesHoldingPool() { + usage, err := repository.queries.CountCompanyInvitationQuotaHoldingWindow(ctx, sqlc.CountCompanyInvitationQuotaHoldingWindowParams{ + HoldingID: pgUUID(scope.holdingID), + WindowStart: pgTime(windowStart), + }) + if err != nil { + return 0, nil, fmt.Errorf("%s - count invitation usage of the holding pool: %w", location, mapOrganizationError(err)) + } + return usage.UsageCount, usage.EarliestAt, nil + } + usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{ + OrganizationID: pgUUID(scope.organizationID), + WindowStart: pgTime(windowStart), + }) + if err != nil { + return 0, nil, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err)) + } + return usage.UsageCount, usage.EarliestAt, nil +} + +// countCardViewUsage is countInvitationUsage for distinct card views. +func (repository companyQuotaRepository) countCardViewUsage( + ctx context.Context, + location string, + scope quotaScope, + windowStart time.Time, +) (int64, any, error) { + if scope.sharesHoldingPool() { + usage, err := repository.queries.CountCompanyCardViewQuotaHoldingWindow(ctx, sqlc.CountCompanyCardViewQuotaHoldingWindowParams{ + HoldingID: pgUUID(scope.holdingID), + WindowStart: pgTime(windowStart), + }) + if err != nil { + return 0, nil, fmt.Errorf("%s - count card-view usage of the holding pool: %w", location, mapOrganizationError(err)) + } + return usage.UsageCount, usage.EarliestAt, nil + } + usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{ + OrganizationID: pgUUID(scope.organizationID), + WindowStart: pgTime(windowStart), + }) + if err != nil { + return 0, nil, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err)) + } + return usage.UsageCount, usage.EarliestAt, nil +} + +// LockOrganization takes the organization lock and, for an E0 organization, +// the lock of its holding, in that order. Every caller that reserves usage +// later takes it first, so the pool is serialized before any other lock. 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 { + organization, err := repository.queries.LockCompanyQuotaOrganizationFirst(ctx, pgUUID(organizationID)) + if 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)) } + // The level is read under the organization lock, which a trust change + // must also take, so the tier cannot change before the holding is locked. + if tier, ok := domain.OrganizationVerificationLevel(organization.VerificationLevel).QuotaTier(); ok && tier.SharesHoldingPool() { + if _, err := lockQuotaHolding(ctx, repository.queries, location, organization.HoldingID); err != nil { + return err + } + } return nil } +// lockAndCheckSnapshot takes the organization lock for the reservation, checks +// the stored trust and effective policy against the snapshot, and returns the +// usage scope. The holding of an E0 organization is locked after the +// organization and before the usage is counted. func (repository companyQuotaRepository) lockAndCheckSnapshot( ctx context.Context, location string, quota domain.CompanyQuota, -) error { - organizationID := pgUUID(quota.OrganizationID()) - organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, organizationID) +) (quotaScope, error) { + organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, pgUUID(quota.OrganizationID())) if errors.Is(err, pgx.ErrNoRows) { - return fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) + return quotaScope{}, fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) } if err != nil { - return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err)) + return quotaScope{}, fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err)) } + if err := checkStoredTrust(location, quota, organization); err != nil { + return quotaScope{}, err + } + + scope := quotaScope{organizationID: quota.OrganizationID()} + if quota.Tier().SharesHoldingPool() { + scope.holdingID, err = lockQuotaHolding(ctx, repository.queries, location, organization.HoldingID) + if err != nil { + return quotaScope{}, err + } + } + if err := repository.checkEffectivePolicy(ctx, location, quota); err != nil { + return quotaScope{}, err + } + return scope, nil +} + +// checkStoredTrust refuses a reservation whose snapshot no longer matches the +// verification of the locked organization. +func checkStoredTrust(location string, quota domain.CompanyQuota, organization sqlc.LockCompanyQuotaOrganizationRow) error { if !organization.ID.Valid || organization.ID.Bytes != quota.OrganizationID() || !organization.VerificationChangedAt.Valid || organization.VerificationLevel != string(quota.VerificationLevel()) || @@ -225,7 +325,12 @@ func (repository companyQuotaRepository) lockAndCheckSnapshot( !organization.VerificationChangedAt.Time.Equal(quota.VerificationChangedAt()) { return fmt.Errorf("%s - stored organization trust changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) } + return nil +} +// checkEffectivePolicy refuses a reservation whose policy version is no longer +// the effective product policy at the application clock snapshot. +func (repository companyQuotaRepository) checkEffectivePolicy(ctx context.Context, location string, quota domain.CompanyQuota) error { policy, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{ PolicyKey: string(domain.ProductPolicyKey), At: pgTime(quota.At()), @@ -242,6 +347,30 @@ func (repository companyQuotaRepository) lockAndCheckSnapshot( return nil } +// lockQuotaHolding takes the pool lock of an E0 holding. The caller must hold +// the lock of the organization that names the holding. +func lockQuotaHolding( + ctx context.Context, + queries *sqlc.Queries, + location string, + holdingID pgtype.UUID, +) (uuid.UUID, error) { + if !holdingID.Valid { + return uuid.Nil, fmt.Errorf("%s - organization has no holding", location) + } + locked, err := queries.LockCompanyQuotaHolding(ctx, holdingID) + if errors.Is(err, pgx.ErrNoRows) { + return uuid.Nil, fmt.Errorf("%s - holding was removed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged) + } + if err != nil { + return uuid.Nil, fmt.Errorf("%s - lock holding: %w", location, mapOrganizationError(err)) + } + if !locked.Valid { + return uuid.Nil, fmt.Errorf("%s - locked holding has no identifier", location) + } + return uuid.UUID(locked.Bytes), nil +} + func (repository companyQuotaRepository) cleanupExpiredCardViews( ctx context.Context, location string, diff --git a/backend/internal/adapter/secondary/postgres/invitation_accept.go b/backend/internal/adapter/secondary/postgres/invitation_accept.go new file mode 100644 index 0000000..75beea1 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/invitation_accept.go @@ -0,0 +1,209 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ( + _ outbound.InvitationAcceptResultRepository = invitationRepository{} + _ outbound.ContactGrantRepository = contactGrantRepository{} +) + +func (unit *UnitOfWork) InvitationAcceptResults() outbound.InvitationAcceptResultRepository { + return invitationRepository{queries: unit.queries} +} + +func (unit *UnitOfWork) ContactGrants() outbound.ContactGrantRepository { + return contactGrantRepository{queries: unit.queries} +} + +type contactGrantRepository struct { + queries *sqlc.Queries +} + +// Accept stores the acceptance of an invitation. The compare-and-swap applies +// only to a delivered or viewed invitation at the expected version and terms +// version, before its deadline, so a stale writer loses without changing it. +func (repository invitationRepository) Accept( + ctx context.Context, + expectedVersion int64, + next domain.Invitation, + event domain.InvitationEvent, +) error { + const location = "invitationRepository.Accept" + stored := next.Stored() + if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationAccepted) || + stored.RespondedAt == nil || event.Kind != domain.InvitationEventAccepted { + return fmt.Errorf("%s - the next version must be the acceptance that follows the expected one: %w", location, domain.ErrInvalidInvitation) + } + if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil { + return err + } + _, err := repository.queries.AcceptInvitation(ctx, sqlc.AcceptInvitationParams{ + NextVersion: stored.Version, AcceptedAt: pgTime(*stored.RespondedAt), OrganizationID: pgUUID(stored.OrganizationID), + InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, TermsVersion: stored.TermsVersion, + }) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - accept invitation: %w", location, outbound.ErrInvitationVersionConflict) + } + if err != nil { + return fmt.Errorf("%s - accept invitation: %w", location, mapInvitationError(err)) + } + return repository.insertEvent(ctx, location, event) +} + +func (repository invitationRepository) SaveAcceptResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, + result outbound.InvitationAcceptResult, +) error { + const location = "invitationRepository.SaveAcceptResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) { + return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) + } + if err := validateInvitationAcceptResult(result); err != nil { + return fmt.Errorf("%s - validate outcome: %w", location, err) + } + if err := repository.queries.InsertInvitationAcceptResult(ctx, sqlc.InsertInvitationAcceptResultParams{ + ScopeHash: scope[:], InvitationID: pgUUID(result.InvitationID), Outcome: string(result.Outcome), + }); err != nil { + return fmt.Errorf("%s - store outcome: %w", location, mapInvitationAcceptResultError(err)) + } + return nil +} + +func (repository invitationRepository) GetAcceptResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, +) (outbound.InvitationAcceptResult, error) { + const location = "invitationRepository.GetAcceptResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) { + return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) + } + row, err := repository.queries.GetInvitationAcceptResult(ctx, scope[:]) + if errors.Is(err, pgx.ErrNoRows) { + return outbound.InvitationAcceptResult{}, outbound.ErrInvitationAcceptResultNotFound + } + if err != nil { + return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err)) + } + if !row.InvitationID.Valid { + return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - stored outcome has no invitation: %w", location, domain.ErrInvalidInvitation) + } + result := outbound.InvitationAcceptResult{ + InvitationID: uuid.UUID(row.InvitationID.Bytes), Outcome: outbound.InvitationAcceptOutcome(row.Outcome), + } + if err := validateInvitationAcceptResult(result); err != nil { + return outbound.InvitationAcceptResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err) + } + return result, nil +} + +func validateInvitationAcceptResult(result outbound.InvitationAcceptResult) error { + const location = "postgres.validateInvitationAcceptResult" + switch result.Outcome { + case outbound.InvitationAcceptAccepted: + if result.InvitationID == uuid.Nil { + return fmt.Errorf("%s - an accepted outcome names the invitation: %w", location, domain.ErrInvalidInvitation) + } + case outbound.InvitationAcceptNotFound, outbound.InvitationAcceptStateConflict: + // A refusal names the identifier of the path, which may name nothing. + default: + return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation) + } + return nil +} + +func mapInvitationAcceptResultError(err error) error { + var pgError *pgconn.PgError + if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_accept_results_idempotency_fkey" { + return fmt.Errorf("postgres.mapInvitationAcceptResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound) + } + return mapInvitationError(err) +} + +// Create stores a grant of an accepted invitation. The row can only be created +// active: a revoked grant is never stored by a new acceptance. +func (repository contactGrantRepository) Create(ctx context.Context, grant domain.ContactGrant) error { + const location = "contactGrantRepository.Create" + if grant.IsZero() || grant.Status() != domain.ContactGrantActive { + return fmt.Errorf("%s - the grant must be built by the domain and active: %w", location, domain.ErrInvalidContactGrant) + } + stored := grant.Stored() + if err := repository.queries.InsertContactGrant(ctx, sqlc.InsertContactGrantParams{ + ID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), CandidateID: pgUUID(stored.CandidateID), + SourceInvitationID: pgUUID(stored.InvitationID), ConsentRecordID: pgUUID(stored.ConsentRecordID), + TermsVersion: stored.TermsVersion, Fields: stored.Fields, ConsentTextVersion: stored.ConsentTextVersion, + GrantedAt: pgTime(stored.GrantedAt), + }); err != nil { + return fmt.Errorf("%s - insert contact grant: %w", location, mapInvitationError(err)) + } + return nil +} + +// GetByInvitation reads the grant of one invitation of one organization. The +// read rebuilds the grant through the domain, so a stored row that breaks a +// rule fails instead of being served. +func (repository contactGrantRepository) GetByInvitation( + ctx context.Context, + organizationID, invitationID uuid.UUID, +) (domain.ContactGrant, error) { + const location = "contactGrantRepository.GetByInvitation" + if organizationID == uuid.Nil || invitationID == uuid.Nil { + return domain.ContactGrant{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidContactGrant) + } + row, err := repository.queries.GetContactGrantByInvitation(ctx, sqlc.GetContactGrantByInvitationParams{ + OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, outbound.ErrContactGrantNotFound) + } + if err != nil { + return domain.ContactGrant{}, fmt.Errorf("%s - select contact grant: %w", location, mapInvitationError(err)) + } + stored, err := storedContactGrantRow(row) + if err != nil { + return domain.ContactGrant{}, fmt.Errorf("%s - read stored grant: %w", location, err) + } + grant, err := domain.RestoreContactGrant(stored) + if err != nil { + return domain.ContactGrant{}, fmt.Errorf("%s - restore contact grant: %w", location, err) + } + if stored.OrganizationID != organizationID || stored.InvitationID != invitationID { + return domain.ContactGrant{}, fmt.Errorf("%s - stored grant has another scope: %w", location, domain.ErrInvalidContactGrant) + } + return grant, nil +} + +// storedContactGrantRow maps a grant row to its stored form. A row without an +// identifier or a time is refused before the domain rebuilds the grant. +func storedContactGrantRow(row sqlc.ContactGrant) (domain.StoredContactGrant, error) { + if !row.ID.Valid || !row.OrganizationID.Valid || !row.CandidateID.Valid || !row.SourceInvitationID.Valid || + !row.ConsentRecordID.Valid || !row.GrantedAt.Valid { + return domain.StoredContactGrant{}, fmt.Errorf("stored grant has missing identifiers: %w", domain.ErrInvalidContactGrant) + } + stored := domain.StoredContactGrant{ + ID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes), + CandidateID: uuid.UUID(row.CandidateID.Bytes), InvitationID: uuid.UUID(row.SourceInvitationID.Bytes), + ConsentRecordID: uuid.UUID(row.ConsentRecordID.Bytes), TermsVersion: row.TermsVersion, Fields: row.Fields, + ConsentTextVersion: row.ConsentTextVersion, GrantedAt: row.GrantedAt.Time.UTC(), + } + if row.RevokedAt.Valid { + revokedAt := row.RevokedAt.Time.UTC() + stored.RevokedAt = &revokedAt + } + if row.RevocationReason.Valid { + stored.RevocationReason = row.RevocationReason.String + } + return stored, nil +} diff --git a/backend/internal/adapter/secondary/postgres/organizations.go b/backend/internal/adapter/secondary/postgres/organizations.go index 1a14d29..f662051 100644 --- a/backend/internal/adapter/secondary/postgres/organizations.go +++ b/backend/internal/adapter/secondary/postgres/organizations.go @@ -24,6 +24,7 @@ var organizationConstraintErrors = map[constraintViolation]error{ {uniqueViolationCode, "memberships_user_id_organization_id_key"}: outbound.ErrMembershipExists, {foreignKeyViolationCode, "memberships_organization_id_fkey"}: outbound.ErrOrganizationNotFound, {foreignKeyViolationCode, "memberships_user_id_fkey"}: outbound.ErrUserNotFound, + {foreignKeyViolationCode, "holdings_founder_account_id_fkey"}: outbound.ErrUserNotFound, {foreignKeyViolationCode, "organization_representatives_organization_id_fkey"}: outbound.ErrOrganizationNotFound, } @@ -72,10 +73,14 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or case owner.OrganizationID() != organization.ID() || owner.Role() != domain.OrganizationRoleOwner || !owner.GrantsAccess(): return fmt.Errorf("%s - owner must be the active owner membership of the organization: %w", location, domain.ErrInvalidMembership) } + holdingID, err := repository.ensureFounderHolding(ctx, owner.UserID(), organization.CreatedAt()) + if err != nil { + return fmt.Errorf("%s - join founder holding: %w", location, err) + } profile := organization.Profile() contacts := profile.Contacts() verification := organization.Verification() - err := repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{ + err = repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{ ID: pgUUID(organization.ID()), Name: profile.Name(), Description: pgOptionalText(profile.Description()), @@ -90,6 +95,7 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or Version: organization.Version(), CreatedAt: pgTime(organization.CreatedAt()), UpdatedAt: pgTime(organization.UpdatedAt()), + HoldingID: pgUUID(holdingID), }) if err != nil { return fmt.Errorf("%s - insert organization: %w", location, mapOrganizationError(err)) @@ -103,6 +109,37 @@ func (repository organizationRepository) CreateWithOwner(ctx context.Context, or return nil } +// ensureFounderHolding returns the holding of the founder account and creates +// it in the caller's transaction when the account has none. The insert ignores +// an existing holding, so a concurrent creation of the same account waits for +// the other transaction and then reads the holding that was stored. +func (repository organizationRepository) ensureFounderHolding( + ctx context.Context, + founderID uuid.UUID, + createdAt time.Time, +) (uuid.UUID, error) { + const location = "organizationRepository.ensureFounderHolding" + holding, err := domain.NewHolding(founderID, createdAt) + if err != nil { + return uuid.Nil, fmt.Errorf("%s - build holding: %w", location, err) + } + if err := repository.queries.InsertHoldingIfAbsent(ctx, sqlc.InsertHoldingIfAbsentParams{ + ID: pgUUID(holding.ID()), + FounderAccountID: pgUUID(holding.FounderAccountID()), + CreatedAt: pgTime(holding.CreatedAt()), + }); err != nil { + return uuid.Nil, fmt.Errorf("%s - insert holding: %w", location, mapOrganizationError(err)) + } + stored, err := repository.queries.GetHoldingIDByFounder(ctx, pgUUID(founderID)) + if err != nil { + return uuid.Nil, fmt.Errorf("%s - read stored holding: %w", location, mapOrganizationError(err)) + } + if !stored.Valid { + return uuid.Nil, fmt.Errorf("%s - stored holding has no identifier", location) + } + return uuid.UUID(stored.Bytes), nil +} + func (repository organizationRepository) SaveCreationResult( ctx context.Context, scope [outbound.IdempotencyDigestSize]byte, 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 3d3ee16..e77b7b5 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/company_quota.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/company_quota.sql.go @@ -11,6 +11,39 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const countCompanyCardViewQuotaHoldingWindow = `-- name: CountCompanyCardViewQuotaHoldingWindow :one +SELECT + count(*)::bigint AS usage_count, + min(usage.last_seen_at) AS earliest_at +FROM company_card_view_quota_usage AS usage +INNER JOIN organizations AS organization ON organization.id = usage.organization_id +WHERE + organization.holding_id = $1 + AND organization.verification_level = 'e0' + AND usage.last_seen_at > $2 +` + +type CountCompanyCardViewQuotaHoldingWindowParams struct { + HoldingID pgtype.UUID + WindowStart pgtype.Timestamptz +} + +type CountCompanyCardViewQuotaHoldingWindowRow struct { + UsageCount int64 + EarliestAt interface{} +} + +// Counts the distinct-card usage of the E0 pool of a holding, with the same +// rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted +// per organization: the same candidate seen by two organizations of one +// holding is two charges. +func (q *Queries) CountCompanyCardViewQuotaHoldingWindow(ctx context.Context, arg CountCompanyCardViewQuotaHoldingWindowParams) (CountCompanyCardViewQuotaHoldingWindowRow, error) { + row := q.db.QueryRow(ctx, countCompanyCardViewQuotaHoldingWindow, arg.HoldingID, arg.WindowStart) + var i CountCompanyCardViewQuotaHoldingWindowRow + err := row.Scan(&i.UsageCount, &i.EarliestAt) + return i, err +} + const countCompanyCardViewQuotaWindow = `-- name: CountCompanyCardViewQuotaWindow :one SELECT count(*)::bigint AS usage_count, @@ -38,6 +71,38 @@ func (q *Queries) CountCompanyCardViewQuotaWindow(ctx context.Context, arg Count return i, err } +const countCompanyInvitationQuotaHoldingWindow = `-- name: CountCompanyInvitationQuotaHoldingWindow :one +SELECT + count(*)::bigint AS usage_count, + min(usage.reserved_at) AS earliest_at +FROM company_invitation_quota_usage AS usage +INNER JOIN organizations AS organization ON organization.id = usage.organization_id +WHERE + organization.holding_id = $1 + AND organization.verification_level = 'e0' + AND usage.reserved_at > $2 +` + +type CountCompanyInvitationQuotaHoldingWindowParams struct { + HoldingID pgtype.UUID + WindowStart pgtype.Timestamptz +} + +type CountCompanyInvitationQuotaHoldingWindowRow struct { + UsageCount int64 + EarliestAt interface{} +} + +// Counts the invitation usage of the E0 pool of a holding: the usage of every +// organization of the holding whose trust level is E0 when the count runs. Each +// row stays attributed to the organization that consumed it. +func (q *Queries) CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error) { + row := q.db.QueryRow(ctx, countCompanyInvitationQuotaHoldingWindow, arg.HoldingID, arg.WindowStart) + var i CountCompanyInvitationQuotaHoldingWindowRow + err := row.Scan(&i.UsageCount, &i.EarliestAt) + return i, err +} + const countCompanyInvitationQuotaWindow = `-- name: CountCompanyInvitationQuotaWindow :one SELECT count(*)::bigint AS usage_count, @@ -185,12 +250,33 @@ func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg Ins return err } +const lockCompanyQuotaHolding = `-- name: LockCompanyQuotaHolding :one +SELECT id +FROM holdings +WHERE id = $1 +FOR NO KEY UPDATE +` + +// Takes the pool lock of an E0 holding. It follows the organization lock, so +// every writer locks an organization first and its holding second. Two +// reservations of one holding queue here, and the second one counts the +// usage that the first one committed. The lock does not conflict with the +// FOR KEY SHARE that organizations.holding_id takes when an organization joins +// the holding. +func (q *Queries) LockCompanyQuotaHolding(ctx context.Context, holdingID pgtype.UUID) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, lockCompanyQuotaHolding, holdingID) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one SELECT id, verification_level, verification_basis, - verification_changed_at + verification_changed_at, + holding_id FROM organizations WHERE id = $1 FOR UPDATE @@ -201,6 +287,7 @@ type LockCompanyQuotaOrganizationRow struct { VerificationLevel string VerificationBasis string VerificationChangedAt pgtype.Timestamptz + HoldingID pgtype.UUID } func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) { @@ -211,21 +298,33 @@ func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organization &i.VerificationLevel, &i.VerificationBasis, &i.VerificationChangedAt, + &i.HoldingID, ) return i, err } const lockCompanyQuotaOrganizationFirst = `-- name: LockCompanyQuotaOrganizationFirst :one -SELECT id +SELECT + id, + verification_level, + holding_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. +type LockCompanyQuotaOrganizationFirstRow struct { + ID pgtype.UUID + VerificationLevel string + HoldingID pgtype.UUID +} + +// Writers lock the organization first, then, for an E0 organization, the holding +// whose pool it shares, then invitation/card-view state, and finally usage rows. +// The organization lock serializes quota decisions for the tenant, the holding +// lock serializes the E0 pool across the organizations of one holding, and +// together they make 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 @@ -233,12 +332,13 @@ FOR NO KEY UPDATE // 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) { +// transaction. The result carries the holding, whose pool an E0 organization +// shares; the caller locks that holding right after this lock. +func (q *Queries) LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationFirstRow, error) { row := q.db.QueryRow(ctx, lockCompanyQuotaOrganizationFirst, organizationID) - var id pgtype.UUID - err := row.Scan(&id) - return id, err + var i LockCompanyQuotaOrganizationFirstRow + err := row.Scan(&i.ID, &i.VerificationLevel, &i.HoldingID) + return i, err } const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows diff --git a/backend/internal/adapter/secondary/postgres/sqlc/contact_grants.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/contact_grants.sql.go new file mode 100644 index 0000000..04299be --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/contact_grants.sql.go @@ -0,0 +1,111 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: contact_grants.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const getContactGrantByInvitation = `-- name: GetContactGrantByInvitation :one +SELECT + id, + organization_id, + candidate_id, + source_invitation_id, + consent_record_id, + terms_version, + fields, + consent_text_version, + granted_at, + revoked_at, + revocation_reason +FROM contact_grants +WHERE + organization_id = $1 + AND source_invitation_id = $2 +` + +type GetContactGrantByInvitationParams struct { + OrganizationID pgtype.UUID + InvitationID pgtype.UUID +} + +// Read the grant of one invitation of one organization. An invitation of +// another organization finds nothing. +func (q *Queries) GetContactGrantByInvitation(ctx context.Context, arg GetContactGrantByInvitationParams) (ContactGrant, error) { + row := q.db.QueryRow(ctx, getContactGrantByInvitation, arg.OrganizationID, arg.InvitationID) + var i ContactGrant + err := row.Scan( + &i.ID, + &i.OrganizationID, + &i.CandidateID, + &i.SourceInvitationID, + &i.ConsentRecordID, + &i.TermsVersion, + &i.Fields, + &i.ConsentTextVersion, + &i.GrantedAt, + &i.RevokedAt, + &i.RevocationReason, + ) + return i, err +} + +const insertContactGrant = `-- name: InsertContactGrant :exec +INSERT INTO contact_grants ( + id, + organization_id, + candidate_id, + source_invitation_id, + consent_record_id, + terms_version, + fields, + consent_text_version, + granted_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7::text [], + $8, + $9 +) +` + +type InsertContactGrantParams struct { + ID pgtype.UUID + OrganizationID pgtype.UUID + CandidateID pgtype.UUID + SourceInvitationID pgtype.UUID + ConsentRecordID pgtype.UUID + TermsVersion int64 + Fields []string + ConsentTextVersion string + GrantedAt pgtype.Timestamptz +} + +// Store the contact grant of an acceptance. The row is inserted in the same +// transaction as its C4 consent record and the accepted state; the database +// checks that the record, the invitation, and the candidate agree. +func (q *Queries) InsertContactGrant(ctx context.Context, arg InsertContactGrantParams) error { + _, err := q.db.Exec(ctx, insertContactGrant, + arg.ID, + arg.OrganizationID, + arg.CandidateID, + arg.SourceInvitationID, + arg.ConsentRecordID, + arg.TermsVersion, + arg.Fields, + arg.ConsentTextVersion, + arg.GrantedAt, + ) + return err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/holdings.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/holdings.sql.go new file mode 100644 index 0000000..7a5ca1c --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/holdings.sql.go @@ -0,0 +1,53 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: holdings.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const getHoldingIDByFounder = `-- name: GetHoldingIDByFounder :one +SELECT id +FROM holdings +WHERE founder_account_id = $1 +` + +func (q *Queries) GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, getHoldingIDByFounder, founderAccountID) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + +const insertHoldingIfAbsent = `-- name: InsertHoldingIfAbsent :exec +INSERT INTO holdings ( + id, + founder_account_id, + created_at +) VALUES ( + $1, + $2, + $3 +) +ON CONFLICT (founder_account_id) DO NOTHING +` + +type InsertHoldingIfAbsentParams struct { + ID pgtype.UUID + FounderAccountID pgtype.UUID + CreatedAt pgtype.Timestamptz +} + +// Stores the holding of a founder account unless the account already has one. +// A concurrent creation of the same account waits on the founder key until the +// other transaction ends; then this insert does nothing, and the caller reads +// the stored holding with GetHoldingIDByFounder. +func (q *Queries) InsertHoldingIfAbsent(ctx context.Context, arg InsertHoldingIfAbsentParams) error { + _, err := q.db.Exec(ctx, insertHoldingIfAbsent, arg.ID, arg.FounderAccountID, arg.CreatedAt) + return err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/invitation_answers.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/invitation_answers.sql.go index 352b9a7..17ddc11 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/invitation_answers.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/invitation_answers.sql.go @@ -11,6 +11,51 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const acceptInvitation = `-- name: AcceptInvitation :one +UPDATE invitations +SET + state = 'accepted', + version = $1, + responded_at = $2, + updated_at = $2 +WHERE + organization_id = $3 + AND id = $4 + AND state IN ('delivered', 'viewed') + AND version = $5 + AND terms_version = $6 + AND response_deadline_at > $2 + AND $1::bigint = $5::bigint + 1 +RETURNING id +` + +type AcceptInvitationParams struct { + NextVersion int64 + AcceptedAt pgtype.Timestamptz + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + ExpectedVersion int64 + TermsVersion int64 +} + +// The compare-and-swap of an acceptance: it applies only to a delivered or +// viewed invitation at the version and the terms version that the candidate +// read, and before its deadline. The answer is the acceptance time, and the +// deadline is kept. +func (q *Queries) AcceptInvitation(ctx context.Context, arg AcceptInvitationParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, acceptInvitation, + arg.NextVersion, + arg.AcceptedAt, + arg.OrganizationID, + arg.InvitationID, + arg.ExpectedVersion, + arg.TermsVersion, + ) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + const declineInvitation = `-- name: DeclineInvitation :one UPDATE invitations SET @@ -51,6 +96,26 @@ func (q *Queries) DeclineInvitation(ctx context.Context, arg DeclineInvitationPa return id, err } +const getInvitationAcceptResult = `-- name: GetInvitationAcceptResult :one +SELECT + invitation_id, + outcome +FROM invitation_accept_results +WHERE scope_hash = $1 +` + +type GetInvitationAcceptResultRow struct { + InvitationID pgtype.UUID + Outcome string +} + +func (q *Queries) GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error) { + row := q.db.QueryRow(ctx, getInvitationAcceptResult, scopeHash) + var i GetInvitationAcceptResultRow + err := row.Scan(&i.InvitationID, &i.Outcome) + return i, err +} + const getInvitationDeclineResult = `-- name: GetInvitationDeclineResult :one SELECT invitation_id, @@ -71,6 +136,29 @@ func (q *Queries) GetInvitationDeclineResult(ctx context.Context, scopeHash []by return i, err } +const insertInvitationAcceptResult = `-- name: InsertInvitationAcceptResult :exec +INSERT INTO invitation_accept_results ( + scope_hash, + invitation_id, + outcome +) VALUES ( + $1, + $2, + $3 +) +` + +type InsertInvitationAcceptResultParams struct { + ScopeHash []byte + InvitationID pgtype.UUID + Outcome string +} + +func (q *Queries) InsertInvitationAcceptResult(ctx context.Context, arg InsertInvitationAcceptResultParams) error { + _, err := q.db.Exec(ctx, insertInvitationAcceptResult, arg.ScopeHash, arg.InvitationID, arg.Outcome) + return err +} + const insertInvitationDecline = `-- name: InsertInvitationDecline :exec INSERT INTO invitation_declines ( invitation_id, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 0eae178..cb5bff9 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -476,6 +476,20 @@ type ConsumerProcessedEvent struct { ProcessedAt pgtype.Timestamptz } +type ContactGrant struct { + ID pgtype.UUID + OrganizationID pgtype.UUID + CandidateID pgtype.UUID + SourceInvitationID pgtype.UUID + ConsentRecordID pgtype.UUID + TermsVersion int64 + Fields []string + ConsentTextVersion string + GrantedAt pgtype.Timestamptz + RevokedAt pgtype.Timestamptz + RevocationReason pgtype.Text +} + type Delivery struct { ID pgtype.UUID SourceEventID pgtype.UUID @@ -563,6 +577,12 @@ type EmailToken struct { PendingOnboardingStep pgtype.Text } +type Holding struct { + ID pgtype.UUID + FounderAccountID pgtype.UUID + CreatedAt pgtype.Timestamptz +} + type IdempotencyRecord struct { ScopeHash []byte Fingerprint []byte @@ -592,6 +612,12 @@ type Invitation struct { RespondedAt pgtype.Timestamptz } +type InvitationAcceptResult struct { + ScopeHash []byte + InvitationID pgtype.UUID + Outcome string +} + type InvitationCreationResult struct { ScopeHash []byte Snapshot []byte @@ -715,6 +741,7 @@ type Organization struct { Version int64 CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz + HoldingID pgtype.UUID } type OrganizationCreationResult struct { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go index a9936c9..c52103b 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/organizations.sql.go @@ -229,7 +229,8 @@ INSERT INTO organizations ( verification_changed_at, version, created_at, - updated_at + updated_at, + holding_id ) VALUES ( $1, $2, @@ -244,7 +245,8 @@ INSERT INTO organizations ( $11, $12, $13, - $14 + $14, + $15 ) ` @@ -263,12 +265,13 @@ type InsertOrganizationParams struct { Version int64 CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz + HoldingID pgtype.UUID } // Stores a new organization with the verification level that the domain -// gave it. The deferred constraint organizations_owner_required fails the -// transaction at commit unless an active owner membership was inserted in -// it too. +// gave it and the holding of its creator. The deferred constraint +// organizations_owner_required fails the transaction at commit unless an +// active owner membership was inserted in it too. func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error { _, err := q.db.Exec(ctx, insertOrganization, arg.ID, @@ -285,6 +288,7 @@ func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganization arg.Version, arg.CreatedAt, arg.UpdatedAt, + arg.HoldingID, ) return err } @@ -549,6 +553,23 @@ type UpdateOrganizationProfileParams struct { ManagerRoles []string } +type UpdateOrganizationProfileRow struct { + ID pgtype.UUID + Name string + Description pgtype.Text + Sphere pgtype.Text + ContactWebsite pgtype.Text + ContactEmail pgtype.Text + ContactPhone pgtype.Text + ContactTelegram pgtype.Text + VerificationLevel string + VerificationBasis string + VerificationChangedAt pgtype.Timestamptz + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + // Changes the profile of an organization over the version the caller read // and advances the version in the same statement. It names no verification // column, so a profile update cannot move the trust level. The change @@ -562,7 +583,7 @@ type UpdateOrganizationProfileParams struct { // follow it). No row returns for a stale version, an account that is no // active manager, or an unknown organization; the adapter reads the // membership to tell them apart. -func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error) { +func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (UpdateOrganizationProfileRow, error) { row := q.db.QueryRow(ctx, updateOrganizationProfile, arg.Name, arg.Description, @@ -577,7 +598,7 @@ func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrgan arg.ActorID, arg.ManagerRoles, ) - var i Organization + var i UpdateOrganizationProfileRow err := row.Scan( &i.ID, &i.Name, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 77c493b..cd47447 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -11,6 +11,11 @@ import ( ) type Querier interface { + // The compare-and-swap of an acceptance: it applies only to a delivered or + // viewed invitation at the version and the terms version that the candidate + // read, and before its deadline. The answer is the acceptance time, and the + // deadline is kept. + AcceptInvitation(ctx context.Context, arg AcceptInvitationParams) (pgtype.UUID, error) // Adds recipients to the day and the month row. The caller holds their // locks from LockMailQuotaRows and has checked both limits. AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error) @@ -131,7 +136,16 @@ type Querier interface { CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error) // Counts the hiding records of one candidate for the settings read. CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error) + // Counts the distinct-card usage of the E0 pool of a holding, with the same + // rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted + // per organization: the same candidate seen by two organizations of one + // holding is two charges. + CountCompanyCardViewQuotaHoldingWindow(ctx context.Context, arg CountCompanyCardViewQuotaHoldingWindowParams) (CountCompanyCardViewQuotaHoldingWindowRow, error) CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error) + // Counts the invitation usage of the E0 pool of a holding: the usage of every + // organization of the holding whose trust level is E0 when the count runs. Each + // row stays attributed to the organization that consumed it. + CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error) CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error) // Counts the families of a category that have at least one published // version, however many versions each has. @@ -275,6 +289,9 @@ type Querier interface { GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error) GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error) GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error) + // Read the grant of one invitation of one organization. An invitation of + // another organization finds nothing. + GetContactGrantByInvitation(ctx context.Context, arg GetContactGrantByInvitationParams) (ContactGrant, error) GetCurrentAssessmentCategoryOpening(ctx context.Context, category string) (AssessmentCategoryOpening, error) // The newest unrevoked record of a purpose other than C4. GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error) @@ -304,6 +321,8 @@ type Querier interface { GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error) // Explains why ConsumeEmailToken matched no row. GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) + GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error) + GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error) GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error) GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, error) GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error) @@ -470,6 +489,10 @@ type Querier interface { // when no row returns; the insert then changes nothing and does not abort // the transaction. InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error) + // Store the contact grant of an acceptance. The row is inserted in the same + // transaction as its C4 consent record and the accepted state; the database + // checks that the record, the invitation, and the candidate agree. + InsertContactGrant(ctx context.Context, arg InsertContactGrantParams) error // Stores a new delivery. A delivery with the same ID already exists when the // same request is handled again; the statement then inserts nothing and // returns 0 rows, and the stored content stays as it was. While another @@ -477,10 +500,16 @@ type Querier interface { // for it. InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error + // Stores the holding of a founder account unless the account already has one. + // A concurrent creation of the same account waits on the founder key until the + // other transaction ends; then this insert does nothing, and the caller reads + // the stored holding with GetHoldingIDByFounder. + InsertHoldingIfAbsent(ctx context.Context, arg InsertHoldingIfAbsentParams) error // The invitation row, its first terms version, and its first audit event are // inserted in one caller-owned transaction. The deferred reference to the // current terms version is checked when the transaction commits. InsertInvitation(ctx context.Context, arg InsertInvitationParams) error + InsertInvitationAcceptResult(ctx context.Context, arg InsertInvitationAcceptResultParams) error InsertInvitationDecline(ctx context.Context, arg InsertInvitationDeclineParams) error InsertInvitationDeclineResult(ctx context.Context, arg InsertInvitationDeclineResultParams) error InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error @@ -493,9 +522,9 @@ type Querier interface { // unique key absorbs at-least-once redelivery without copying event content. InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error) // Stores a new organization with the verification level that the domain - // gave it. The deferred constraint organizations_owner_required fails the - // transaction at commit unless an active owner membership was inserted in - // it too. + // gave it and the holding of its creator. The deferred constraint + // organizations_owner_required fails the transaction at commit unless an + // active owner membership was inserted in it too. InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error // The parent and first immutable snapshot are inserted in one caller-owned // transaction. Deferred version references are checked when it commits. @@ -741,10 +770,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) + // Takes the pool lock of an E0 holding. It follows the organization lock, so + // every writer locks an organization first and its holding second. Two + // reservations of one holding queue here, and the second one counts the + // usage that the first one committed. The lock does not conflict with the + // FOR KEY SHARE that organizations.holding_id takes when an organization joins + // the holding. + LockCompanyQuotaHolding(ctx context.Context, holdingID pgtype.UUID) (pgtype.UUID, 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. + // Writers lock the organization first, then, for an E0 organization, the holding + // whose pool it shares, then invitation/card-view state, and finally usage rows. + // The organization lock serializes quota decisions for the tenant, the holding + // lock serializes the E0 pool across the organizations of one holding, and + // together they make 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 @@ -752,8 +790,9 @@ type Querier interface { // 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) + // transaction. The result carries the holding, whose pool an E0 organization + // shares; the caller locks that holding right after this lock. + LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationFirstRow, 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. @@ -1086,7 +1125,7 @@ type Querier interface { // follow it). No row returns for a stale version, an account that is no // active manager, or an unknown organization; the adapter reads the // membership to tell them apart. - UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error) + UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (UpdateOrganizationProfileRow, error) // Replaces the registration of an unverified account and advances the // registration version in the same statement, so no caller can choose it. // The version check rejects a writer that read an older row; a verified diff --git a/backend/internal/bootstrap/invitation.go b/backend/internal/bootstrap/invitation.go index 98f43c5..9f94592 100644 --- a/backend/internal/bootstrap/invitation.go +++ b/backend/internal/bootstrap/invitation.go @@ -14,6 +14,7 @@ import ( "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/consent" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/invitation" "lincodex/backend/internal/usecase/notification" @@ -70,7 +71,7 @@ func newInvitationHandler( Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { return quota.ReserveInvitation(ctx, unit, organization, invitationID) }, - Notifier: notifier, Clock: time.Now, + Notifier: notifier, Consents: consent.NewService(transactor, time.Now), Clock: time.Now, }) if err != nil { pool.Close() diff --git a/backend/internal/domain/company_quota.go b/backend/internal/domain/company_quota.go index 99c3541..6dda6eb 100644 --- a/backend/internal/domain/company_quota.go +++ b/backend/internal/domain/company_quota.go @@ -18,10 +18,21 @@ var ( ErrCompanyQuotaDenied = errors.New("company quota denied") ) +// SharesHoldingPool reports whether the usage of an organization at this tier +// is counted in the pool of its holding instead of its own. Only the +// unverified tier E0 shares a pool: the organizations of one holding at E0 +// draw on one allowance, so creating more of them does not multiply it. A +// verified tier keeps its own pool, and usage of any organization that is no +// longer E0 leaves the shared pool. +func (tier OrganizationTier) SharesHoldingPool() bool { + return tier == OrganizationTierE0 +} + // CompanyQuota is an immutable snapshot of the limits that apply to one // organization at one instant. It carries the stored verification and // effective policy identities so the transactional repository can verify -// that neither changed before it reserves usage. +// that neither changed before it reserves usage. Its usage scope is the +// organization, or the holding pool for a tier that SharesHoldingPool. type CompanyQuota struct { organizationID uuid.UUID policyVersionID PolicyVersionID diff --git a/backend/internal/domain/contact_grant.go b/backend/internal/domain/contact_grant.go new file mode 100644 index 0000000..a69c0f6 --- /dev/null +++ b/backend/internal/domain/contact_grant.go @@ -0,0 +1,339 @@ +package domain + +import ( + "errors" + "fmt" + "log/slog" + "slices" + "time" + + "github.com/google/uuid" +) + +var ( + // ErrInvalidContactGrant reports a grant that breaks a rule of the contact + // grant or does not agree with the accepted invitation and its C4 record. + ErrInvalidContactGrant = errors.New("invalid contact grant") +) + +// ContactRevocationReason says why a contact grant was revoked. It is shown +// only to the candidate. The revocation itself belongs to a later operation. +type ContactRevocationReason string + +const ( + // ContactRevocationConsentRevoked closes every grant under a revoked C4. + ContactRevocationConsentRevoked ContactRevocationReason = "consent_revoked" + // ContactRevocationParticipationCancelled closes the grant of one + // invitation that the candidate cancelled. + ContactRevocationParticipationCancelled ContactRevocationReason = "participation_cancelled" + // ContactRevocationVisibilityClosed closes a grant after the publication + // was closed or the organization was hidden. + ContactRevocationVisibilityClosed ContactRevocationReason = "visibility_closed" +) + +func (reason ContactRevocationReason) known() bool { + switch reason { + case ContactRevocationConsentRevoked, ContactRevocationParticipationCancelled, ContactRevocationVisibilityClosed: + return true + default: + return false + } +} + +// ContactAccessBlock says why an active grant does not allow a read now. +type ContactAccessBlock string + +// ContactAccessBlockVisibility means the profile is not published (C2) or is +// hidden from the organization. The acceptance never publishes the profile or +// lifts the hiding, so the grant becomes readable only when the candidate does. +const ContactAccessBlockVisibility ContactAccessBlock = "visibility" + +// ContactGrantStatus is the state of a contact grant. +type ContactGrantStatus string + +const ( + ContactGrantActive ContactGrantStatus = "active" + ContactGrantRevoked ContactGrantStatus = "revoked" +) + +const redactedContactGrant = "[redacted contact grant]" + +// ContactGrant is the permission of one organization to read the selected +// contact kinds of one candidate, created by the acceptance of one invitation. +// It names the C4 consent record that gave it, so the grant and its consent +// always agree. The candidate identifier is internal and never logged. +type ContactGrant struct { + id uuid.UUID + organizationID uuid.UUID + candidateID uuid.UUID + invitationID uuid.UUID + consentRecordID uuid.UUID + fields ContactFieldSet + termsVersion int64 + consentTextVersion ConsentTextVersion + grantedAt time.Time + revokedAt time.Time + revocationReason ContactRevocationReason +} + +// StoredContactGrant carries the columns of a stored grant. A nil RevokedAt +// marks an active grant, and an empty RevocationReason goes with it. +type StoredContactGrant struct { + ID uuid.UUID + OrganizationID uuid.UUID + CandidateID uuid.UUID + InvitationID uuid.UUID + ConsentRecordID uuid.UUID + TermsVersion int64 + Fields []string + ConsentTextVersion string + GrantedAt time.Time + RevokedAt *time.Time + RevocationReason string +} + +// NewContactGrant builds the grant of an accepted invitation from its C4 +// consent record. The record and the invitation must name the same subject, +// organization, invitation, and terms version, and the invitation must be +// accepted. The grant takes the fields, the text version, and the grant time +// of the record, so it covers exactly what the candidate consented to. +func NewContactGrant(record ConsentRecord, invitation Invitation) (ContactGrant, error) { + const location = "domain.NewContactGrant" + if record.Purpose() != ConsentPurposeContactDisclosure || record.Source() != ConsentSourceInvitationAcceptance { + return ContactGrant{}, fmt.Errorf("%s - the grant needs the C4 record of an acceptance: %w", location, ErrInvalidContactGrant) + } + if _, revoked := record.RevokedAt(); revoked { + return ContactGrant{}, fmt.Errorf("%s - a revoked C4 record gives no grant: %w", location, ErrInvalidContactGrant) + } + if invitation.State() != InvitationAccepted { + return ContactGrant{}, fmt.Errorf("%s - only an accepted invitation has a grant: %w", location, ErrInvalidContactGrant) + } + switch { + case record.OrganizationID() != invitation.OrganizationID(), + record.InvitationID() != invitation.ID(), + record.SubjectID() != invitation.CandidateID(), + record.InvitationTermsVersion() != invitation.TermsVersion(): + return ContactGrant{}, fmt.Errorf("%s - the C4 record must name the accepted invitation: %w", location, ErrInvalidContactGrant) + case record.Fields().IsZero(): + return ContactGrant{}, fmt.Errorf("%s - the C4 record must name its fields: %w", location, ErrInvalidContactGrant) + } + id, err := uuid.NewV7() + if err != nil { + return ContactGrant{}, fmt.Errorf("%s - generate grant ID: %w", location, err) + } + return ContactGrant{ + id: id, + organizationID: invitation.OrganizationID(), + candidateID: invitation.CandidateID(), + invitationID: invitation.ID(), + consentRecordID: record.ID(), + fields: record.Fields(), + termsVersion: invitation.TermsVersion(), + consentTextVersion: record.TextVersion(), + grantedAt: record.GrantedAt(), + }, nil +} + +// RestoreContactGrant validates a stored grant, so a row changed outside the +// application is not served. +func RestoreContactGrant(stored StoredContactGrant) (ContactGrant, error) { + const location = "domain.RestoreContactGrant" + switch { + case stored.ID == uuid.Nil, stored.OrganizationID == uuid.Nil, stored.CandidateID == uuid.Nil, + stored.InvitationID == uuid.Nil, stored.ConsentRecordID == uuid.Nil: + return ContactGrant{}, fmt.Errorf("%s - identifiers must be set: %w", location, ErrInvalidContactGrant) + case stored.TermsVersion < 1, stored.GrantedAt.IsZero(): + return ContactGrant{}, fmt.Errorf("%s - terms version and grant time must be set: %w", location, ErrInvalidContactGrant) + } + fields, err := restoreGrantFields(stored.Fields) + if err != nil { + return ContactGrant{}, fmt.Errorf("%s - validate fields: %w", location, err) + } + version, err := ParseConsentTextVersion(stored.ConsentTextVersion) + if err != nil { + return ContactGrant{}, fmt.Errorf("%s - validate consent text version: %w", location, err) + } + grant := ContactGrant{ + id: stored.ID, organizationID: stored.OrganizationID, candidateID: stored.CandidateID, + invitationID: stored.InvitationID, consentRecordID: stored.ConsentRecordID, fields: fields, + termsVersion: stored.TermsVersion, consentTextVersion: version, grantedAt: stored.GrantedAt, + } + switch { + case stored.RevokedAt == nil && stored.RevocationReason == "": + case stored.RevokedAt != nil && ContactRevocationReason(stored.RevocationReason).known() && + !stored.RevokedAt.Before(stored.GrantedAt): + grant.revokedAt = *stored.RevokedAt + grant.revocationReason = ContactRevocationReason(stored.RevocationReason) + default: + return ContactGrant{}, fmt.Errorf("%s - the revocation stamp is inconsistent: %w", location, ErrInvalidContactGrant) + } + return grant, nil +} + +// restoreGrantFields accepts the stored kinds only in the canonical form the +// database stores: distinct, known, and ascending. +func restoreGrantFields(stored []string) (ContactFieldSet, error) { + fields := make([]ContactField, 0, len(stored)) + for _, value := range stored { + field, err := ParseContactField(value) + if err != nil { + return ContactFieldSet{}, err + } + fields = append(fields, field) + } + set, err := NewContactFieldSet(fields...) + if err != nil { + return ContactFieldSet{}, err + } + if !slices.Equal(contactFieldCodes(set), stored) { + return ContactFieldSet{}, fmt.Errorf("stored fields are not in canonical order: %w", ErrInvalidContactGrant) + } + return set, nil +} + +func (grant ContactGrant) ID() uuid.UUID { return grant.id } +func (grant ContactGrant) OrganizationID() uuid.UUID { return grant.organizationID } +func (grant ContactGrant) CandidateID() uuid.UUID { return grant.candidateID } +func (grant ContactGrant) InvitationID() uuid.UUID { return grant.invitationID } +func (grant ContactGrant) ConsentRecordID() uuid.UUID { return grant.consentRecordID } +func (grant ContactGrant) Fields() ContactFieldSet { return grant.fields } +func (grant ContactGrant) TermsVersion() int64 { return grant.termsVersion } +func (grant ContactGrant) ConsentTextVersion() ConsentTextVersion { return grant.consentTextVersion } +func (grant ContactGrant) GrantedAt() time.Time { return grant.grantedAt } + +// RevokedAt returns the revocation time, and false while the grant is active. +func (grant ContactGrant) RevokedAt() (time.Time, bool) { + return grant.revokedAt, !grant.revokedAt.IsZero() +} + +// RevocationReason is empty while the grant is active. +func (grant ContactGrant) RevocationReason() ContactRevocationReason { return grant.revocationReason } + +// Status is revoked once a revocation stamp is set; a grant never becomes +// active again. +func (grant ContactGrant) Status() ContactGrantStatus { + if grant.revokedAt.IsZero() { + return ContactGrantActive + } + return ContactGrantRevoked +} + +// IsZero reports a grant not built by NewContactGrant or RestoreContactGrant. +func (grant ContactGrant) IsZero() bool { return grant.id == uuid.Nil } + +// Stored returns the persisted form of the grant. +func (grant ContactGrant) Stored() StoredContactGrant { + stored := StoredContactGrant{ + ID: grant.id, OrganizationID: grant.organizationID, CandidateID: grant.candidateID, + InvitationID: grant.invitationID, ConsentRecordID: grant.consentRecordID, + TermsVersion: grant.termsVersion, Fields: contactFieldCodes(grant.fields), + ConsentTextVersion: string(grant.consentTextVersion), GrantedAt: grant.grantedAt, + RevocationReason: string(grant.revocationReason), + } + if !grant.revokedAt.IsZero() { + revokedAt := grant.revokedAt + stored.RevokedAt = &revokedAt + } + return stored +} + +// ContactGrantView is the grant as the candidate reads it. It holds kinds +// only, never contact values, and it names no organization identifier. The +// organization reads it through its own view. +type ContactGrantView struct { + ID uuid.UUID + Fields []ContactField + Status ContactGrantStatus + Readable bool + BlockedBy *ContactAccessBlock + TermsVersion int64 + ConsentTextVersion ConsentTextVersion + GrantedAt time.Time + RevokedAt *time.Time + RevocationReason *ContactRevocationReason +} + +// CandidateView returns the grant for the candidate. visible reports whether +// the organization may read the profile now, which is the publication and the +// hiding of the organization. An active grant is readable only when it is +// visible; a revoked grant is never readable and shows its reason instead. +func (grant ContactGrant) CandidateView(visible bool) ContactGrantView { + view := ContactGrantView{ + ID: grant.id, Fields: grant.fields.Fields(), Status: grant.Status(), + TermsVersion: grant.termsVersion, ConsentTextVersion: grant.consentTextVersion, GrantedAt: grant.grantedAt, + } + if view.Status == ContactGrantRevoked { + revokedAt, reason := grant.revokedAt, grant.revocationReason + view.RevokedAt, view.RevocationReason = &revokedAt, &reason + return view + } + if visible { + view.Readable = true + return view + } + block := ContactAccessBlockVisibility + view.BlockedBy = &block + return view +} + +func (grant ContactGrant) String() string { return redactedContactGrant } +func (grant ContactGrant) GoString() string { return redactedContactGrant } +func (grant ContactGrant) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedContactGrant) +} + +// LogValue carries the grant identifier and its status only. +func (grant ContactGrant) LogValue() slog.Value { + return slog.GroupValue(slog.String("grant_id", grant.id.String()), slog.String("status", string(grant.Status()))) +} + +// ContactConsentText is the published C4 text that the candidate sees, with +// the organization name in it. +type ContactConsentText struct { + TextVersion ConsentTextVersion + Text string +} + +// ContactConsentOffer is what the candidate can consent to while an +// acceptance is possible: the rendered text and the kinds the profile holds. +// Nothing is preselected, and no contact value is part of it. +type ContactConsentOffer struct { + Text ContactConsentText + AvailableFields []ContactField +} + +// NewContactConsentOffer renders the C4 text for the organization name and +// lists the kinds that the profile holds, in the order given. It needs at least +// one kind, because a grant covers at least one field. +func NewContactConsentOffer(text ConsentText, organizationName string, available []ContactField) (ContactConsentOffer, error) { + const location = "domain.NewContactConsentOffer" + if len(available) == 0 || len(available) > maxContactFields { + return ContactConsentOffer{}, fmt.Errorf("%s - the offer needs 1 to %d kinds: %w", location, maxContactFields, ErrInvalidContactGrant) + } + for index, field := range available { + if _, err := ParseContactField(string(field)); err != nil { + return ContactConsentOffer{}, fmt.Errorf("%s - validate kind: %w", location, err) + } + if slices.Contains(available[:index], field) { + return ContactConsentOffer{}, fmt.Errorf("%s - kinds must be distinct: %w", location, ErrInvalidContactGrant) + } + } + rendered, err := text.RenderForOrganization(organizationName) + if err != nil { + return ContactConsentOffer{}, fmt.Errorf("%s - render consent text: %w", location, err) + } + return ContactConsentOffer{ + Text: ContactConsentText{TextVersion: text.Version(), Text: rendered}, + AvailableFields: slices.Clone(available), + }, nil +} + +// contactFieldCodes returns the kinds of a set as the stored strings, in the +// set's canonical order. +func contactFieldCodes(set ContactFieldSet) []string { + codes := make([]string, 0, len(set.Fields())) + for _, field := range set.Fields() { + codes = append(codes, string(field)) + } + return codes +} diff --git a/backend/internal/domain/contact_grant_test.go b/backend/internal/domain/contact_grant_test.go new file mode 100644 index 0000000..33b8d12 --- /dev/null +++ b/backend/internal/domain/contact_grant_test.go @@ -0,0 +1,242 @@ +package domain + +import ( + "errors" + "fmt" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +const testContactTextBody = "I consent to the transfer of the contact data I select to {organization} for this invitation." + +// testContactText is the published C4 text of the domain tests. +func testContactText(t *testing.T) ConsentText { + t.Helper() + hash := HashConsentText(testContactTextBody) + text, err := RestoreConsentText(StoredConsentText{ + Purpose: string(ConsentPurposeContactDisclosure), Version: "c4-2026-10-01", Body: testContactTextBody, + Hash: hash[:], Kind: string(ConsentTextKindDemo), PublishedAt: time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC), + }) + if err != nil { + t.Fatalf("RestoreConsentText() error = %v", err) + } + return text +} + +// acceptedTestInvitation accepts the delivered test invitation an hour after +// its delivery, from its delivered state and at its current terms version. +func acceptedTestInvitation(t *testing.T) (Invitation, time.Time) { + t.Helper() + delivered, _ := deliveredTestInvitation(t) + at := delivered.UpdatedAt().Add(time.Hour) + accepted, err := delivered.Accept(delivered.TermsVersion(), at) + if err != nil { + t.Fatalf("Accept() error = %v", err) + } + return accepted, at +} + +// testConsentRecordFor stores the C4 record of an acceptance the way the ledger +// does: the hash of the text with the organization name filled in. +func testStoredConsentRecord(t *testing.T, invitation Invitation, granted time.Time, fields ...string) StoredConsentRecord { + t.Helper() + shown, err := testContactText(t).RenderForOrganization("Acme") + if err != nil { + t.Fatalf("RenderForOrganization() error = %v", err) + } + hash := HashConsentText(shown) + return StoredConsentRecord{ + ID: uuid.Must(uuid.NewV7()), SubjectID: invitation.CandidateID(), Purpose: string(ConsentPurposeContactDisclosure), + TextVersion: "c4-2026-10-01", TextHash: hash[:], Source: string(ConsentSourceInvitationAcceptance), + State: string(ConsentStateActive), GrantedAt: granted, OrganizationID: invitation.OrganizationID(), + OrganizationName: "Acme", FieldSet: fields, InvitationID: invitation.ID(), InvitationTermsVersion: invitation.TermsVersion(), + } +} + +// testConsentRecordFor restores the stored C4 record of an acceptance. +func testConsentRecordFor(t *testing.T, invitation Invitation, granted time.Time, fields ...string) ConsentRecord { + t.Helper() + record, err := RestoreConsentRecord(testStoredConsentRecord(t, invitation, granted, fields...)) + if err != nil { + t.Fatalf("RestoreConsentRecord() error = %v", err) + } + return record +} + +func TestNewContactGrantCoversExactlyTheRecordedFields(t *testing.T) { + accepted, at := acceptedTestInvitation(t) + record := testConsentRecordFor(t, accepted, at, "email") + grant, err := NewContactGrant(record, accepted) + if err != nil { + t.Fatalf("NewContactGrant() error = %v", err) + } + if grant.OrganizationID() != accepted.OrganizationID() || grant.InvitationID() != accepted.ID() || + grant.CandidateID() != accepted.CandidateID() || grant.ConsentRecordID() != record.ID() || + grant.TermsVersion() != accepted.TermsVersion() || grant.ConsentTextVersion() != "c4-2026-10-01" || + !grant.GrantedAt().Equal(at) || grant.Status() != ContactGrantActive { + t.Fatalf("grant = %+v, want the scope of the accepted invitation and its record", grant.Stored()) + } + if fields := grant.Fields().Fields(); len(fields) != 1 || fields[0] != ContactFieldEmail { + t.Fatalf("fields = %v, want the email only", fields) + } + if _, revoked := grant.RevokedAt(); revoked { + t.Fatal("a new grant is revoked") + } + restored, err := RestoreContactGrant(grant.Stored()) + if err != nil || restored.ID() != grant.ID() || !restored.Fields().Equal(grant.Fields()) { + t.Fatalf("RestoreContactGrant(stored) = %+v, %v; want the same grant", restored.Stored(), err) + } +} + +func TestNewContactGrantNeedsAnAcceptedInvitationAndItsOwnRecord(t *testing.T) { + accepted, at := acceptedTestInvitation(t) + delivered, _ := deliveredTestInvitation(t) + + if _, err := NewContactGrant(testConsentRecordFor(t, delivered, at, "email"), delivered); !errors.Is(err, ErrInvalidContactGrant) { + t.Fatalf("grant of a delivered invitation error = %v, want ErrInvalidContactGrant", err) + } + otherInvitation := testConsentRecordFor(t, delivered, at, "email") + if _, err := NewContactGrant(otherInvitation, accepted); !errors.Is(err, ErrInvalidContactGrant) { + t.Fatalf("grant with another invitation's record error = %v, want ErrInvalidContactGrant", err) + } + stored := testStoredConsentRecord(t, accepted, at, "email") + stored.RevokedAt = &at + stored.RevocationSource = string(ConsentRevocationSourceConsentSettings) + stored.State = string(ConsentStateRevoked) + revoked, err := RestoreConsentRecord(stored) + if err != nil { + t.Fatalf("RestoreConsentRecord(revoked) error = %v", err) + } + if _, err := NewContactGrant(revoked, accepted); !errors.Is(err, ErrInvalidContactGrant) { + t.Fatalf("grant of a revoked record error = %v, want ErrInvalidContactGrant", err) + } +} + +func TestContactGrantShowsWhetherTheOrganizationCanReadItNow(t *testing.T) { + accepted, at := acceptedTestInvitation(t) + grant, err := NewContactGrant(testConsentRecordFor(t, accepted, at, "email"), accepted) + if err != nil { + t.Fatalf("NewContactGrant() error = %v", err) + } + if view := grant.CandidateView(true); !view.Readable || view.BlockedBy != nil || view.Status != ContactGrantActive { + t.Fatalf("visible view = %+v, want readable and not blocked", view) + } + view := grant.CandidateView(false) + if view.Readable || view.BlockedBy == nil || *view.BlockedBy != ContactAccessBlockVisibility { + t.Fatalf("hidden view = %+v, want blocked by visibility", view) + } + + revokedAt := at.Add(time.Hour) + revoked, err := RestoreContactGrant(StoredContactGrant{ + ID: grant.ID(), OrganizationID: grant.OrganizationID(), CandidateID: grant.CandidateID(), InvitationID: grant.InvitationID(), + ConsentRecordID: grant.ConsentRecordID(), TermsVersion: grant.TermsVersion(), Fields: []string{"email"}, + ConsentTextVersion: "c4-2026-10-01", GrantedAt: at, RevokedAt: &revokedAt, RevocationReason: string(ContactRevocationConsentRevoked), + }) + if err != nil { + t.Fatalf("RestoreContactGrant(revoked) error = %v", err) + } + closed := revoked.CandidateView(true) + if closed.Readable || closed.BlockedBy != nil || closed.Status != ContactGrantRevoked || closed.RevokedAt == nil || + !closed.RevokedAt.Equal(revokedAt) || closed.RevocationReason == nil || *closed.RevocationReason != ContactRevocationConsentRevoked { + t.Fatalf("revoked view = %+v, want closed with its reason and no read", closed) + } +} + +func TestRestoreContactGrantRefusesNonCanonicalFieldsAndBrokenRevocation(t *testing.T) { + accepted, at := acceptedTestInvitation(t) + valid := StoredContactGrant{ + ID: uuid.Must(uuid.NewV7()), OrganizationID: accepted.OrganizationID(), CandidateID: accepted.CandidateID(), + InvitationID: accepted.ID(), ConsentRecordID: uuid.Must(uuid.NewV7()), TermsVersion: accepted.TermsVersion(), + Fields: []string{"email", "phone"}, ConsentTextVersion: "c4-2026-10-01", GrantedAt: at, + } + if _, err := RestoreContactGrant(valid); err != nil { + t.Fatalf("RestoreContactGrant(valid) error = %v", err) + } + reversed := valid + reversed.Fields = []string{"phone", "email"} + beforeGrant := valid + beforeGrant.RevokedAt = ptrTime(at.Add(-time.Minute)) + beforeGrant.RevocationReason = string(ContactRevocationVisibilityClosed) + noReason := valid + noReason.RevokedAt = ptrTime(at.Add(time.Minute)) + unknownKind := valid + unknownKind.Fields = []string{"address"} + for name, stored := range map[string]StoredContactGrant{ + "reversed fields": reversed, + "unknown kind": unknownKind, + "revocation before grant": beforeGrant, + "revocation without a reason": noReason, + } { + if _, err := RestoreContactGrant(stored); !errors.Is(err, ErrInvalidContactGrant) && !errors.Is(err, ErrInvalidConsent) { + t.Errorf("%s: RestoreContactGrant() error = %v, want a refusal", name, err) + } + } +} + +func ptrTime(value time.Time) *time.Time { return &value } + +func TestInvitationAcceptsOnlyTheCurrentTermsFromAnAnswerableState(t *testing.T) { + delivered, _ := deliveredTestInvitation(t) + at := delivered.UpdatedAt().Add(time.Hour) + if _, err := delivered.Accept(delivered.TermsVersion()+1, at); !errors.Is(err, ErrInvitationVersionConflict) { + t.Fatalf("stale terms error = %v, want ErrInvitationVersionConflict", err) + } + counter := withState(t, delivered, InvitationCounter, nil) + if _, err := counter.Accept(counter.TermsVersion(), at); !errors.Is(err, ErrInvitationNotAnswerable) { + t.Fatalf("counter error = %v, want ErrInvitationNotAnswerable", err) + } + if _, err := delivered.Accept(delivered.TermsVersion(), *delivered.Snapshot().ResponseDeadlineAt); !errors.Is(err, ErrInvitationNotAnswerable) { + t.Fatalf("accept at the deadline error = %v, want ErrInvitationNotAnswerable", err) + } + viewed, _, err := delivered.RecordView(at) + if err != nil { + t.Fatalf("RecordView() error = %v", err) + } + accepted, err := viewed.Accept(viewed.TermsVersion(), at.Add(time.Minute)) + if err != nil { + t.Fatalf("Accept(viewed) error = %v", err) + } + snapshot := accepted.Snapshot() + if snapshot.State != InvitationAccepted || snapshot.Version != viewed.Version()+1 || snapshot.RespondedAt == nil || + !snapshot.ResponseDeadlineAt.Equal(*delivered.Snapshot().ResponseDeadlineAt) { + t.Fatalf("accepted = %+v, want the next version accepted with the deadline kept", snapshot) + } + event, err := accepted.AnswerEvent(delivered.CandidateID()) + if err != nil || event.Kind != InvitationEventAccepted || len(event.ChangedFields) != 0 { + t.Fatalf("AnswerEvent() = %+v, %v; want an accepted event naming no field", event, err) + } +} + +func TestNewContactConsentOfferRendersTheTextAndListsTheHeldKinds(t *testing.T) { + offer, err := NewContactConsentOffer(testContactText(t), "Acme", []ContactField{ContactFieldFullName, ContactFieldEmail}) + if err != nil { + t.Fatalf("NewContactConsentOffer() error = %v", err) + } + if !strings.Contains(offer.Text.Text, "Acme") || strings.Contains(offer.Text.Text, ConsentTextOrganizationPlaceholder) || + offer.Text.TextVersion != "c4-2026-10-01" || !slices.Equal(offer.AvailableFields, []ContactField{ContactFieldFullName, ContactFieldEmail}) { + t.Fatalf("offer = %+v, want the rendered text and the kinds in the given order", offer) + } + if _, err := NewContactConsentOffer(testContactText(t), "Acme", nil); !errors.Is(err, ErrInvalidContactGrant) { + t.Fatalf("empty offer error = %v, want ErrInvalidContactGrant", err) + } + if _, err := NewContactConsentOffer(testContactText(t), "Acme", []ContactField{ContactFieldEmail, ContactFieldEmail}); !errors.Is(err, ErrInvalidContactGrant) { + t.Fatalf("repeated kind error = %v, want ErrInvalidContactGrant", err) + } +} + +func TestContactGrantValuesAreRedacted(t *testing.T) { + accepted, at := acceptedTestInvitation(t) + grant, err := NewContactGrant(testConsentRecordFor(t, accepted, at, "email"), accepted) + if err != nil { + t.Fatalf("NewContactGrant() error = %v", err) + } + for _, rendered := range []string{fmt.Sprint(grant), fmt.Sprintf("%+v", grant), fmt.Sprintf("%#v", grant)} { + if strings.Contains(rendered, accepted.CandidateID().String()) || strings.Contains(rendered, "email") { + t.Fatalf("rendered grant = %q, want the identifier and the kinds hidden", rendered) + } + } +} diff --git a/backend/internal/domain/holding.go b/backend/internal/domain/holding.go new file mode 100644 index 0000000..a7eed23 --- /dev/null +++ b/backend/internal/domain/holding.go @@ -0,0 +1,49 @@ +package domain + +import ( + "errors" + "fmt" + "time" + + "github.com/google/uuid" +) + +// ErrInvalidHolding reports a holding that was not built with a founder +// account and a creation time. +var ErrInvalidHolding = errors.New("invalid holding") + +// Holding groups the organizations that one founder account created, as the +// divisions of one company belong to one parent. It carries no profile and no +// right: its only effect is the E0 quota pool that its organizations share. +// Organizations of one account are grouped; cross-owner merges are not +// modelled. +type Holding struct { + id uuid.UUID + founderAccountID uuid.UUID + createdAt time.Time +} + +// NewHolding creates the holding of a founder account with a time-ordered +// UUIDv7 identifier. The storage keeps one holding per founder and returns the +// stored one when the account already has it, so the identifier of this value +// is only used when the holding is new. +func NewHolding(founderAccountID uuid.UUID, createdAt time.Time) (Holding, error) { + const location = "domain.NewHolding" + if founderAccountID == uuid.Nil { + return Holding{}, fmt.Errorf("%s - founder account must be set: %w", location, ErrInvalidHolding) + } + if createdAt.IsZero() { + return Holding{}, fmt.Errorf("%s - creation time must be set: %w", location, ErrInvalidHolding) + } + id, err := uuid.NewV7() + if err != nil { + return Holding{}, fmt.Errorf("%s - generate holding ID: %w", location, err) + } + return Holding{id: id, founderAccountID: founderAccountID, createdAt: createdAt.UTC()}, nil +} + +func (holding Holding) ID() uuid.UUID { return holding.id } + +func (holding Holding) FounderAccountID() uuid.UUID { return holding.founderAccountID } + +func (holding Holding) CreatedAt() time.Time { return holding.createdAt } diff --git a/backend/internal/domain/invitation_answer.go b/backend/internal/domain/invitation_answer.go index d913621..026a02b 100644 --- a/backend/internal/domain/invitation_answer.go +++ b/backend/internal/domain/invitation_answer.go @@ -27,6 +27,9 @@ const ( // candidate's answer for the responsiveness metrics, never a consent or // a hire, and it holds neither the reason nor the comment. InvitationEventDeclined InvitationEventKind = "declined" + // InvitationEventAccepted is the audit event of an acceptance. It names no + // field: the consent C4 and the grant are stored in their own records. + InvitationEventAccepted InvitationEventKind = "accepted" ) const ( @@ -46,6 +49,7 @@ var ( // answerEventKinds name the audit event of each answer state. answerEventKinds = map[InvitationState]InvitationEventKind{ InvitationViewed: InvitationEventViewed, InvitationDeclined: InvitationEventDeclined, + InvitationAccepted: InvitationEventAccepted, } ) @@ -234,8 +238,44 @@ func (invitation Invitation) Decline(choice InvitationDeclineChoice, at time.Tim return declined, decline, nil } -// AnswerEvent builds the audit event of the version that a view or a -// decline by actor has just produced. It names no field and holds neither +// Accept returns the next version in the state accepted. The candidate may +// accept a delivered or viewed invitation before its deadline and only at the +// terms version that the candidate read; any other state, a late command, and +// a stale terms version are refused. The deadline and the terms are kept. The +// consent C4, the contact grant, and the audit event belong to the same +// transaction and are built by the caller. +func (invitation Invitation) Accept(termsVersion int64, at time.Time) (Invitation, error) { + const location = "Invitation.Accept" + if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) { + return Invitation{}, fmt.Errorf("%s - accept time must be set and not before the last change: %w", location, ErrInvalidInvitation) + } + if !invitation.acceptable() || !invitation.IsDelivered() || invitation.ResponseDeadlinePassed(at) { + return Invitation{}, fmt.Errorf("%s - %w", location, ErrInvitationNotAnswerable) + } + if termsVersion != invitation.record.TermsVersion { + return Invitation{}, fmt.Errorf("%s - the candidate read another terms version: %w", location, ErrInvitationVersionConflict) + } + at = at.UTC() + next := invitation.Stored() + next.State = string(InvitationAccepted) + next.Version++ + next.UpdatedAt = at + next.RespondedAt = &at + accepted, err := RestoreInvitation(next) + if err != nil { + return Invitation{}, fmt.Errorf("%s - restore accepted invitation: %w", location, err) + } + return accepted, nil +} + +// acceptable reports the states from which the candidate may accept: the +// delivered and viewed invitation. The planned counter offer is not one. +func (invitation Invitation) acceptable() bool { + return invitation.State() == InvitationDelivered || invitation.State() == InvitationViewed +} + +// AnswerEvent builds the audit event of the version that a view, a decline, +// or an acceptance by actor has just produced. It names no field and holds neither // the reason nor the comment of a decline. func (invitation Invitation) AnswerEvent(actorID uuid.UUID) (InvitationEvent, error) { const location = "Invitation.AnswerEvent" @@ -257,6 +297,12 @@ func (invitation Invitation) AnswerEvent(actorID uuid.UUID) (InvitationEvent, er }, nil } +// answeredInvitationState reports the states that record the candidate's answer: +// a declined or an accepted invitation has its answer time. +func answeredInvitationState(state InvitationState) bool { + return state == InvitationDeclined || state == InvitationAccepted +} + // storedInvitationAnswerDefect checks the view and the answer against the // state: a delivered invitation has neither, a viewed one has its view, a // declined one has its answer, and neither precedes the delivery. @@ -267,8 +313,8 @@ func storedInvitationAnswerDefect(stored StoredInvitation) string { return "a delivered invitation has no view or answer" case state == InvitationViewed && (stored.ViewedAt == nil || stored.RespondedAt != nil): return "a viewed invitation has a view and no answer" - case state == InvitationDeclined && stored.RespondedAt == nil: - return "a declined invitation has an answer" + case answeredInvitationState(state) && stored.RespondedAt == nil: + return "a declined or accepted invitation has an answer" case stored.ViewedAt != nil && (stored.DeliveredAt == nil || stored.ViewedAt.Before(*stored.DeliveredAt)): return "a view follows the delivery" case stored.RespondedAt != nil && (stored.DeliveredAt == nil || stored.RespondedAt.Before(*stored.DeliveredAt)): @@ -305,6 +351,11 @@ type CandidateInvitationView struct { RespondedAt *time.Time UpdatedAt time.Time Decline *InvitationDeclineView + // ContactConsent is set while an acceptance is possible, and ContactGrant + // once the invitation was accepted. The usecase fills both: they need the + // profile, the consent texts, and the visibility, which the view does not. + ContactConsent *ContactConsentOffer + ContactGrant *ContactGrantView } // CandidateView returns the invitation for the candidate it is addressed to. diff --git a/backend/internal/port/outbound/company_quota.go b/backend/internal/port/outbound/company_quota.go index 89a64a6..cdc1cde 100644 --- a/backend/internal/port/outbound/company_quota.go +++ b/backend/internal/port/outbound/company_quota.go @@ -28,12 +28,18 @@ type CompanyQuotaDecision struct { // creates the invitation or applies the visibility change in the same // transaction, so a failed business operation cannot leave quota charged. // -// Writers lock rows in this order: organization, active membership, -// invitation or visibility record, then quota usage. A repository may take an -// organization lock again inside the same transaction, but must not invert -// this order. Each method rechecks the organization's stored verification -// level, basis, and changed_at against the snapshot in CompanyQuota before it -// writes; a caller cannot grant itself a tier by supplying a different level. +// Writers lock rows in this order: organization, then for an E0 organization +// its holding, then active membership, invitation or visibility record, and +// last quota usage. A repository may take an organization lock again inside +// the same transaction, but must not invert this order. Each method rechecks +// the organization's stored verification level, basis, and changed_at against +// the snapshot in CompanyQuota before it writes; a caller cannot grant itself +// a tier by supplying a different level. +// +// The E0 limits are pooled per holding: the usage of every E0 organization of +// one holding counts toward the same window. Usage rows stay attributed to the +// organization that consumed them, and idempotency stays per organization. +// Organizations at E1 and above count only their own usage. // // Invitation usage is keyed by organization and invitation ID and remains // until the organization is deleted. The unique key makes retries idempotent @@ -49,24 +55,28 @@ 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 + // 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. For an E0 organization it also takes the lock of its holding, + // which serializes the shared E0 pool; the holding is locked right after + // the organization, before any other lock of the caller, so the callers of + // one holding cannot deadlock on it. 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 - // denied new invitation writes no usage and reports RetryAt after the - // earliest currently counted invitation expires. + // limit of the organization's usage scope. An existing invitation ID is + // returned as allowed and reused without a second charge, regardless of + // its age or the request key. A denied new invitation writes no usage and + // reports RetryAt after the earliest currently counted invitation expires. ReserveInvitation(ctx context.Context, quota domain.CompanyQuota, invitationID uuid.UUID) (CompanyQuotaDecision, error) // ReserveCardView counts a distinct candidate within the rolling card-view - // window. A repeat while the prior view is active is allowed and reused, - // and refreshes last_seen with a monotonic update. A denied new view writes - // no usage and reports RetryAt after the earliest active view expires. + // window of the organization's usage scope. A repeat while the prior view + // of the same organization is active is allowed and reused, and refreshes + // last_seen with a monotonic update. A denied new view writes no usage and + // reports RetryAt after the earliest active view expires. ReserveCardView(ctx context.Context, quota domain.CompanyQuota, candidateID uuid.UUID) (CompanyQuotaDecision, error) } diff --git a/backend/internal/port/outbound/contact_grants.go b/backend/internal/port/outbound/contact_grants.go new file mode 100644 index 0000000..33ff843 --- /dev/null +++ b/backend/internal/port/outbound/contact_grants.go @@ -0,0 +1,29 @@ +package outbound + +import ( + "context" + "errors" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +// ErrContactGrantNotFound reports that the invitation has no contact grant of +// the organization. An accepted invitation always has one, so a missing grant +// of an accepted invitation is a storage defect. +var ErrContactGrantNotFound = errors.New("contact grant not found") + +// ContactGrantRepository stores the contact grants of accepted invitations. A +// grant is created in the acceptance transaction next to its consent C4 +// record; it is never updated here, and a read is always scoped by the +// organization. +type ContactGrantRepository interface { + // Create inserts the grant in the surrounding transaction. The database + // checks that the grant agrees with its consent record and invitation. + Create(ctx context.Context, grant domain.ContactGrant) error + + // GetByInvitation returns the grant of one invitation of one organization, + // or ErrContactGrantNotFound. + GetByInvitation(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.ContactGrant, error) +} diff --git a/backend/internal/port/outbound/invitations.go b/backend/internal/port/outbound/invitations.go index 982fb12..71d1ad0 100644 --- a/backend/internal/port/outbound/invitations.go +++ b/backend/internal/port/outbound/invitations.go @@ -36,6 +36,10 @@ var ( // ErrInvitationDeclineResultNotFound reports a missing outcome of a // decline for a live idempotency record. ErrInvitationDeclineResultNotFound = errors.New("invitation decline result not found") + + // ErrInvitationAcceptResultNotFound reports a missing outcome of an + // acceptance for a live idempotency record. + ErrInvitationAcceptResultNotFound = errors.New("invitation accept result not found") ) // MaxInvitationPageSize is the largest organization-scoped or candidate page @@ -49,6 +53,8 @@ type InvitationRepositories interface { InvitationCreationResults() InvitationCreationResultRepository InvitationSendResults() InvitationSendResultRepository InvitationDeclineResults() InvitationDeclineResultRepository + InvitationAcceptResults() InvitationAcceptResultRepository + ContactGrants() ContactGrantRepository } // InvitationRepository stores invitations, their immutable terms versions, and @@ -130,6 +136,14 @@ type InvitationRepository interface { // GetDecline returns the stored decline of the invitation or // ErrInvitationDeclineNotFound. GetDecline(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.InvitationDecline, error) + + // Accept moves a delivered or viewed invitation from expectedVersion to the + // accepted version of next before its deadline, keeps the deadline and the + // terms, and records the audit event. It returns + // ErrInvitationVersionConflict when the stored row is not answerable at + // expectedVersion, at its terms version, or before its deadline. The consent + // C4 and the contact grant are stored by the caller in the same transaction. + Accept(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error } // InvitationCreationResultRepository stores the original response of a @@ -246,3 +260,30 @@ type InvitationDeclineResultRepository interface { SaveDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationDeclineResult) error GetDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationDeclineResult, error) } + +// InvitationAcceptOutcome is the stored result of an acceptance under an +// Idempotency-Key. The contract stores a success, a missing invitation, and a +// state conflict; a stale version and a consent refusal are not stored. +type InvitationAcceptOutcome string + +const ( + InvitationAcceptAccepted InvitationAcceptOutcome = "accepted" + InvitationAcceptNotFound InvitationAcceptOutcome = "not_found" + InvitationAcceptStateConflict InvitationAcceptOutcome = "state_conflict" +) + +// InvitationAcceptResult is the outcome of one acceptance. It keeps no copy of +// the response: an accepted invitation keeps its answer and its grant, so a +// replay rebuilds the response from them. +type InvitationAcceptResult struct { + InvitationID uuid.UUID + Outcome InvitationAcceptOutcome +} + +// InvitationAcceptResultRepository stores the outcome of an idempotent +// acceptance. The scope references the generic idempotency record, so the +// outcome is removed when that record is purged. +type InvitationAcceptResultRepository interface { + SaveAcceptResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationAcceptResult) error + GetAcceptResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationAcceptResult, error) +} diff --git a/backend/internal/port/outbound/organizations.go b/backend/internal/port/outbound/organizations.go index ca140cb..f9142b5 100644 --- a/backend/internal/port/outbound/organizations.go +++ b/backend/internal/port/outbound/organizations.go @@ -61,11 +61,14 @@ type OrganizationRepositories interface { type OrganizationRepository interface { // CreateWithOwner stores a new organization and the active owner // membership of its creator. The two inserts run in the surrounding - // transaction, so a failure between them leaves neither. The database also - // refuses to commit an organization that has no active owner (constraint - // organizations_owner_required, SQLSTATE 23514, raised by the commit of - // the transaction), whatever code inserted it. owner must be an active - // owner membership of organization; an unknown account fails with + // transaction, so a failure between them leaves neither. The organization + // joins the holding of the owner account: the holding is created in the + // same transaction when that account has none, and an existing one is + // reused, so concurrent creations of one account end in one holding. The + // database also refuses to commit an organization that has no active owner + // (constraint organizations_owner_required, SQLSTATE 23514, raised by the + // commit of the transaction), whatever code inserted it. owner must be an + // active owner membership of organization; an unknown account fails with // ErrUserNotFound, and the caller's transaction is aborted. CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error diff --git a/backend/internal/usecase/companyquota/service.go b/backend/internal/usecase/companyquota/service.go index cd3d16e..eaa729c 100644 --- a/backend/internal/usecase/companyquota/service.go +++ b/backend/internal/usecase/companyquota/service.go @@ -43,8 +43,9 @@ func NewService(clock func() time.Time) *Service { } // ReserveInvitation atomically records a new invitation against the policy -// effective at the operation's clock snapshot. Repeating invitationID is -// idempotent even when the caller uses a different request key. +// effective at the operation's clock snapshot. The limit applies to the usage +// scope of the organization: its own usage, or the holding pool at E0. Repeating +// invitationID is idempotent even when the caller uses a different request key. func (service *Service) ReserveInvitation( ctx context.Context, repositories Repositories, @@ -72,9 +73,10 @@ func (service *Service) ReserveInvitation( return decision, nil } -// ReserveCardView atomically counts a distinct candidate in the organization's -// rolling view window. A repeat within the window refreshes the stored time -// without charging another distinct view. +// ReserveCardView atomically counts a distinct candidate in the rolling view +// window of the organization's usage scope. A repeat within the window by the +// same organization refreshes the stored time without charging another distinct +// view. func (service *Service) ReserveCardView( ctx context.Context, repositories Repositories, diff --git a/backend/internal/usecase/invitation/accept.go b/backend/internal/usecase/invitation/accept.go new file mode 100644 index 0000000..f8548f4 --- /dev/null +++ b/backend/internal/usecase/invitation/accept.go @@ -0,0 +1,413 @@ +package invitation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/consent" +) + +const ( + acceptOperation = "candidate_invitation.accept" + acceptLocation = "invitation.Service.AcceptMine" + // consentTextPointer and consentFieldsPointer name the consent rules of + // the body in the problem response. + consentTextPointer = "/consent_c4/text_version" + consentFieldsPointer = "/consent_c4/fields" +) + +// AcceptCommand binds the session candidate and the path to one acceptance: +// the invitation version and the terms version that the candidate read, the +// consent text version that the candidate saw, and the contact kinds that the +// candidate selected, in the order sent. +type AcceptCommand struct { + ActorID uuid.UUID + InvitationID uuid.UUID + IdempotencyKey string + ExpectedVersion int64 + TermsVersion int64 + TextVersion string + Fields []domain.ContactField +} + +type acceptRequest struct { + fingerprint [outbound.IdempotencyDigestSize]byte + scope [outbound.IdempotencyDigestSize]byte + record outbound.IdempotencyRecord + now time.Time + textVersion domain.ConsentTextVersion + fields domain.ContactFieldSet +} + +// acceptFingerprint is the canonical request of an acceptance. The fields keep +// their order, so a reordered choice is a different request under one key. +type acceptFingerprint struct { + InvitationID uuid.UUID `json:"invitation_id"` + ExpectedVersion int64 `json:"expected_version"` + TermsVersion int64 `json:"terms_version"` + TextVersion string `json:"text_version"` + Fields []domain.ContactField `json:"fields"` +} + +// acceptOutcome is what a committed acceptance transaction decided: the +// invitation, or a refusal that the contract stores under the key and that the +// caller returns after the commit. +type acceptOutcome struct { + view domain.CandidateInvitationView + refusal error +} + +// AcceptMine accepts the current terms of an invitation of the session +// candidate with the consent C4. In one transaction it checks the candidate, +// the key, the invitation, a repeat of the acceptance, a terminal state or a +// passed deadline, the versions, the state, and the consent rules; then it +// moves the invitation to accepted, records the consent C4 in the consent +// ledger, stores the contact grant of exactly the selected fields, and appends +// the audit event. The acceptance never publishes the profile and never lifts +// a hiding: the grant is readable only while the organization may read the +// profile. +// +// Locks: the idempotency record of the candidate's own key and then only the +// invitation row, never the organization, as for the other candidate commands. +func (service *Service) AcceptMine(ctx context.Context, command AcceptCommand) (domain.CandidateInvitationView, error) { + request, err := service.prepareAccept(command) + if err != nil { + return domain.CandidateInvitationView{}, err + } + var outcome acceptOutcome + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + outcome, err = service.acceptInTransaction(ctx, unit, command, request) + return err + }) + if err != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", acceptLocation, err) + } + if outcome.refusal != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - %w", acceptLocation, outcome.refusal) + } + return outcome.view, nil +} + +// prepareAccept validates the request before any storage is read, in the order +// of the contract: the request is validated before the account. +func (service *Service) prepareAccept(command AcceptCommand) (acceptRequest, error) { + const location = "invitation.Service.prepareAccept" + switch { + case command.ActorID == uuid.Nil: + return acceptRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden) + case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize: + return acceptRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey) + case command.ExpectedVersion < 1: + return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"}) + case command.TermsVersion < 1: + return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/terms_version", Reason: "must be positive"}) + } + textVersion, err := domain.ParseConsentTextVersion(command.TextVersion) + if err != nil { + return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: consentTextPointer, Reason: "must be a consent text version"}) + } + fields, err := domain.NewContactFieldSet(command.Fields...) + if err != nil { + return acceptRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: consentFieldsPointer, Reason: "must name one to four distinct kinds"}) + } + now, err := service.now(location) + if err != nil { + return acceptRequest{}, err + } + canonical, err := json.Marshal(acceptFingerprint{ + InvitationID: command.InvitationID, ExpectedVersion: command.ExpectedVersion, TermsVersion: command.TermsVersion, + TextVersion: command.TextVersion, Fields: command.Fields, + }) + if err != nil { + return acceptRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, err) + } + fingerprint := service.keyring.Fingerprint(canonical) + scope := service.keyring.IdempotencyScope(acceptOperation, command.IdempotencyKey, command.ActorID.String()) + return acceptRequest{ + fingerprint: fingerprint, scope: scope, now: now, textVersion: textVersion, fields: fields, + record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)}, + }, nil +} + +// acceptInTransaction follows the order of checks of the contract after the +// HTTP boundary: the account (403), the key (422 or a replay), the invitation +// (404, stored), the repeat of an accepted invitation (200), a terminal state +// or a passed deadline (409, stored), the versions (412, not stored), any other +// state that does not allow an acceptance (409, stored), and the consent rules +// (400, not stored). +func (service *Service) acceptInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command AcceptCommand, + request acceptRequest, +) (acceptOutcome, error) { + if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil { + return acceptOutcome{}, err + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return acceptOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", acceptLocation, err) + } + if !created { + return service.replayAccept(ctx, unit, request, command, stored) + } + entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true) + if errors.Is(err, outbound.ErrInvitationNotFound) { + return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptNotFound) + } + if err != nil { + return acceptOutcome{}, err + } + return service.acceptFound(ctx, unit, command, request, entry) +} + +// acceptFound applies the checks that follow a found invitation and, when they +// pass, stores the acceptance with its consent and grant. +func (service *Service) acceptFound( + ctx context.Context, + unit outbound.UnitOfWork, + command AcceptCommand, + request acceptRequest, + entry outbound.CandidateInvitationEntry, +) (acceptOutcome, error) { + current := entry.Invitation + at := notBefore(request.now, current.UpdatedAt()) + switch { + case current.State() == domain.InvitationAccepted: + return service.repeatAccept(ctx, unit, command, request, entry) + case current.IsTerminal() || current.ResponseDeadlinePassed(at): + return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict) + } + if command.ExpectedVersion != current.Version() || command.TermsVersion != current.TermsVersion() { + return acceptOutcome{}, fmt.Errorf("%s - compare versions: %w", acceptLocation, domain.ErrInvitationVersionConflict) + } + accepted, err := current.Accept(command.TermsVersion, at) + if errors.Is(err, domain.ErrInvitationNotAnswerable) { + return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict) + } + if err != nil { + return acceptOutcome{}, fmt.Errorf("%s - accept invitation: %w", acceptLocation, err) + } + if err := service.checkAcceptConsent(ctx, unit, command, request); err != nil { + return acceptOutcome{}, err + } + if err := service.storeAcceptance(ctx, unit, command, request, entry, accepted); err != nil { + return acceptOutcome{}, err + } + entry.Invitation = accepted + return service.completeAccept(ctx, unit, request, entry) +} + +// checkAcceptConsent refuses a consent text that is not the published one and a +// kind that the profile does not hold. It stores nothing: the caller returns the +// error, and the transaction rolls back. +func (service *Service) checkAcceptConsent( + ctx context.Context, + unit outbound.UnitOfWork, + command AcceptCommand, + request acceptRequest, +) error { + if _, err := service.consents.CheckTextVersion(ctx, unit, domain.ConsentPurposeContactDisclosure, request.textVersion); err != nil { + if errors.Is(err, consent.ErrStaleConsentText) { + return fmt.Errorf("%s - %w", acceptLocation, &domain.InvitationFieldError{Pointer: consentTextPointer, Reason: "must be the published consent text"}) + } + return fmt.Errorf("%s - check consent text: %w", acceptLocation, err) + } + profile, err := unit.CandidateProfiles().Get(ctx, command.ActorID) + if err != nil { + return fmt.Errorf("%s - read candidate profile: %w", acceptLocation, err) + } + held := heldContactFields(profile) + for index, field := range command.Fields { + if !slices.Contains(held, field) { + return fmt.Errorf("%s - %w", acceptLocation, &domain.InvitationFieldError{ + Pointer: fmt.Sprintf("%s/%d", consentFieldsPointer, index), Reason: "the profile holds no such contact", + }) + } + } + return nil +} + +// storeAcceptance writes the acceptance in the transaction: the invitation moves +// to accepted with its audit event, the consent C4 is recorded in the ledger, and +// the grant of the selected fields is stored next to them. +func (service *Service) storeAcceptance( + ctx context.Context, + unit outbound.UnitOfWork, + command AcceptCommand, + request acceptRequest, + entry outbound.CandidateInvitationEntry, + accepted domain.Invitation, +) error { + current := entry.Invitation + event, err := accepted.AnswerEvent(command.ActorID) + if err != nil { + return fmt.Errorf("%s - build audit event: %w", acceptLocation, err) + } + if err := unit.Invitations().Accept(ctx, current.Version(), accepted, event); err != nil { + if errors.Is(err, outbound.ErrInvitationVersionConflict) { + return fmt.Errorf("%s - store acceptance: %w", acceptLocation, domain.ErrInvitationVersionConflict) + } + return fmt.Errorf("%s - store acceptance: %w", acceptLocation, err) + } + granted, err := service.consents.GrantContact(ctx, unit, consent.ContactGrantInput{ + SubjectID: command.ActorID, OrganizationID: current.OrganizationID(), OrganizationName: entry.OrganizationName, + Fields: request.fields, InvitationID: current.ID(), InvitationTermsVersion: command.TermsVersion, + TextVersion: request.textVersion, + }) + if err != nil { + return fmt.Errorf("%s - grant consent C4: %w", acceptLocation, err) + } + if !granted.Created { + return fmt.Errorf("%s - the invitation already has a consent C4 record: %w", acceptLocation, domain.ErrInvalidContactGrant) + } + grant, err := domain.NewContactGrant(granted.Record, accepted) + if err != nil { + return fmt.Errorf("%s - build contact grant: %w", acceptLocation, err) + } + if err := unit.ContactGrants().Create(ctx, grant); err != nil { + return fmt.Errorf("%s - store contact grant: %w", acceptLocation, err) + } + return nil +} + +// repeatAccept answers an acceptance of an invitation that is already accepted. +// The same terms version and the same fields answer 200 with the invitation, +// even under a new key or an older expected version, and record nothing. Any +// other terms version or field set is a conflict with the accepted answer. +func (service *Service) repeatAccept( + ctx context.Context, + unit outbound.UnitOfWork, + command AcceptCommand, + request acceptRequest, + entry outbound.CandidateInvitationEntry, +) (acceptOutcome, error) { + grant, err := unit.ContactGrants().GetByInvitation(ctx, entry.Invitation.OrganizationID(), entry.Invitation.ID()) + if err != nil { + return acceptOutcome{}, fmt.Errorf("%s - read contact grant: %w", acceptLocation, err) + } + if grant.TermsVersion() == command.TermsVersion && grant.Fields().Equal(request.fields) { + return service.completeAccept(ctx, unit, request, entry) + } + return service.refuseAccept(ctx, unit, command, request, outbound.InvitationAcceptStateConflict) +} + +// completeAccept stores the successful outcome under the key and builds the +// response with the contact grant. +func (service *Service) completeAccept( + ctx context.Context, + unit outbound.UnitOfWork, + request acceptRequest, + entry outbound.CandidateInvitationEntry, +) (acceptOutcome, error) { + view, err := service.candidateView(ctx, unit, entry, request.now) + if err != nil { + return acceptOutcome{}, err + } + result := outbound.InvitationAcceptResult{InvitationID: entry.Invitation.ID(), Outcome: outbound.InvitationAcceptAccepted} + if err := finishAccept(ctx, unit, request, result); err != nil { + return acceptOutcome{}, err + } + return acceptOutcome{view: view}, nil +} + +// refuseAccept stores a refusal that the contract keeps under the key and lets +// the transaction commit, since nothing else was written. +func (service *Service) refuseAccept( + ctx context.Context, + unit outbound.UnitOfWork, + command AcceptCommand, + request acceptRequest, + outcome outbound.InvitationAcceptOutcome, +) (acceptOutcome, error) { + result := outbound.InvitationAcceptResult{InvitationID: command.InvitationID, Outcome: outcome} + if err := finishAccept(ctx, unit, request, result); err != nil { + return acceptOutcome{}, err + } + return acceptOutcome{refusal: acceptRefusal(outcome)}, nil +} + +func finishAccept(ctx context.Context, unit outbound.UnitOfWork, request acceptRequest, result outbound.InvitationAcceptResult) error { + if err := unit.InvitationAcceptResults().SaveAcceptResult(ctx, request.scope, result); err != nil { + return fmt.Errorf("%s - store outcome: %w", acceptLocation, err) + } + if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { + return fmt.Errorf("%s - purge expired idempotency records: %w", acceptLocation, err) + } + return nil +} + +func acceptRefusal(outcome outbound.InvitationAcceptOutcome) error { + if outcome == outbound.InvitationAcceptNotFound { + return outbound.ErrInvitationNotFound + } + return ErrAnswerBlocked +} + +// replayAccept returns the stored outcome of the same request, or refuses a key +// used with another request. A stored acceptance is rebuilt from the invitation +// and its grant, which the acceptance keeps. +func (service *Service) replayAccept( + ctx context.Context, + unit outbound.UnitOfWork, + request acceptRequest, + command AcceptCommand, + stored outbound.IdempotencyRecord, +) (acceptOutcome, error) { + if stored.Fingerprint != request.fingerprint { + return acceptOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", acceptLocation, ErrIdempotencyKeyReused) + } + original, err := unit.InvitationAcceptResults().GetAcceptResult(ctx, request.scope) + if err != nil { + return acceptOutcome{}, fmt.Errorf("%s - read original outcome: %w", acceptLocation, err) + } + if original.InvitationID != command.InvitationID { + return acceptOutcome{}, fmt.Errorf("%s - validate original outcome: %w", acceptLocation, domain.ErrInvalidInvitation) + } + if original.Outcome != outbound.InvitationAcceptAccepted { + return acceptOutcome{refusal: acceptRefusal(original.Outcome)}, nil + } + entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, false) + if err != nil { + return acceptOutcome{}, err + } + view, err := service.candidateView(ctx, unit, entry, request.now) + if err != nil { + return acceptOutcome{}, err + } + return acceptOutcome{view: view}, nil +} + +// heldContactFields lists the kinds that the profile holds as confirmed claims, +// in the order of ContactFieldKind. A suggestion that nobody confirmed is not +// held, so it can never be disclosed. +func heldContactFields(profile domain.CandidateProfile) []domain.ContactField { + content := profile.Content() + held := make([]domain.ContactField, 0, 4) + if claim, ok := content.FullName(); confirmedClaim(claim.Status(), ok) { + held = append(held, domain.ContactFieldFullName) + } + if claim, ok := content.Email(); confirmedClaim(claim.Status(), ok) { + held = append(held, domain.ContactFieldEmail) + } + if claim, ok := content.Phone(); confirmedClaim(claim.Status(), ok) { + held = append(held, domain.ContactFieldPhone) + } + if claim, ok := content.Telegram(); confirmedClaim(claim.Status(), ok) { + held = append(held, domain.ContactFieldTelegram) + } + return held +} + +func confirmedClaim(status domain.ProfileClaimStatus, present bool) bool { + return present && status == domain.ProfileClaimConfirmed +} diff --git a/backend/internal/usecase/invitation/accept_test.go b/backend/internal/usecase/invitation/accept_test.go new file mode 100644 index 0000000..9659979 --- /dev/null +++ b/backend/internal/usecase/invitation/accept_test.go @@ -0,0 +1,467 @@ +package invitation + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// testC4Version is the published C4 text of the fakes. +const testC4Version = domain.ConsentTextVersion("c4-2026-10-01") + +func (unit *testUnit) ContactGrants() outbound.ContactGrantRepository { + return testContactGrants{state: unit.state} +} + +func (unit *testUnit) InvitationAcceptResults() outbound.InvitationAcceptResultRepository { + return testInvitations{state: unit.state} +} + +func (unit *testUnit) CandidateProfiles() outbound.CandidateProfileRepository { + return testProfiles{state: unit.state} +} + +func (unit *testUnit) ConsentTexts() outbound.ConsentTextRepository { + return testConsentTexts{} +} + +func (unit *testUnit) ConsentLedger() outbound.ConsentLedger { + return testConsentLedger{state: unit.state} +} + +func (unit *testUnit) PrivacySettings() outbound.PrivacySettingsRepository { + return testPrivacySettings{state: unit.state} +} + +// Accept applies the compare-and-swap of the acceptance like the database does: +// the stored invitation must be answerable at the expected version. +func (repository testInvitations) Accept(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error { + current, ok := repository.state.invitations[next.ID()] + answerable := current.State() == domain.InvitationDelivered || current.State() == domain.InvitationViewed + if !ok || current.Version() != expectedVersion || !answerable { + return outbound.ErrInvitationVersionConflict + } + repository.state.invitations[next.ID()] = next + repository.state.events = append(repository.state.events, event) + return nil +} + +func (repository testInvitations) SaveAcceptResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationAcceptResult) error { + repository.state.acceptResults[scope] = result + return nil +} + +func (repository testInvitations) GetAcceptResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationAcceptResult, error) { + result, ok := repository.state.acceptResults[scope] + if !ok { + return outbound.InvitationAcceptResult{}, outbound.ErrInvitationAcceptResultNotFound + } + return result, nil +} + +type testContactGrants struct { + state *testState +} + +func (repository testContactGrants) Create(_ context.Context, grant domain.ContactGrant) error { + if _, exists := repository.state.grants[grant.InvitationID()]; exists { + return errors.New("contact grant already exists") + } + repository.state.grants[grant.InvitationID()] = grant + return nil +} + +func (repository testContactGrants) GetByInvitation(_ context.Context, organizationID, invitationID uuid.UUID) (domain.ContactGrant, error) { + grant, ok := repository.state.grants[invitationID] + if !ok || grant.OrganizationID() != organizationID { + return domain.ContactGrant{}, outbound.ErrContactGrantNotFound + } + return grant, nil +} + +type testProfiles struct { + outbound.CandidateProfileRepository + + state *testState +} + +func (repository testProfiles) Get(_ context.Context, userID uuid.UUID) (domain.CandidateProfile, error) { + if profile, ok := repository.state.profiles[userID]; ok { + return profile, nil + } + return domain.EmptyCandidateProfile(userID) +} + +// testConsentTexts publishes one C4 text that names the organization. +type testConsentTexts struct { + outbound.ConsentTextRepository +} + +func (testConsentTexts) Current(_ context.Context, purpose domain.ConsentPurpose, _ time.Time) (domain.ConsentText, error) { + if purpose != domain.ConsentPurposeContactDisclosure { + return domain.ConsentText{}, outbound.ErrConsentTextNotFound + } + body := "I consent to the transfer of the contact data I select to {organization} for this invitation." + hash := domain.HashConsentText(body) + text, err := domain.RestoreConsentText(domain.StoredConsentText{ + Purpose: string(purpose), Version: string(testC4Version), Body: body, Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), + PublishedAt: time.Date(2026, time.October, 1, 0, 0, 0, 0, time.UTC), + }) + if err != nil { + return domain.ConsentText{}, err + } + return text, nil +} + +// testConsentLedger stores the C4 record of an acceptance once per invitation, +// as the ledger does. +type testConsentLedger struct { + outbound.ConsentLedger + + state *testState +} + +func (ledger testConsentLedger) GrantContact(_ context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) { + if existing, ok := ledger.state.consentRecords[grant.InvitationID()]; ok { + return existing, false, nil + } + hash := grant.TextHash() + fields := make([]string, 0, 4) + for _, field := range grant.Fields().Fields() { + fields = append(fields, string(field)) + } + record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{ + ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(domain.ConsentPurposeContactDisclosure), + TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance), + State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(), OrganizationID: grant.OrganizationID(), + OrganizationName: grant.OrganizationName(), FieldSet: fields, InvitationID: grant.InvitationID(), + InvitationTermsVersion: grant.InvitationTermsVersion(), + }) + if err != nil { + return domain.ConsentRecord{}, false, err + } + ledger.state.consentRecords[grant.InvitationID()] = record + return record, true, nil +} + +// testPrivacySettings reads the publication and the hidings of the fakes. A +// candidate who never published has the closed publication. +type testPrivacySettings struct { + outbound.PrivacySettingsRepository + + state *testState +} + +func (repository testPrivacySettings) ReadSettings(_ context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) { + publication, ok := repository.state.publications[userID] + if !ok { + closed, err := domain.NewPublication(userID) + if err != nil { + return outbound.CandidatePrivacySettings{}, err + } + publication = closed + } + return outbound.CandidatePrivacySettings{Publication: publication}, nil +} + +func (repository testPrivacySettings) GetHiddenOrganization(_ context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error) { + if !repository.state.hidden[[2]uuid.UUID{userID, organizationID}] { + return outbound.HiddenOrganizationRecord{}, outbound.ErrCandidatePrivacySettingsNotFound + } + return outbound.HiddenOrganizationRecord{OrganizationID: organizationID, OrganizationName: "Test organization"}, nil +} + +// testProfile builds a candidate profile whose confirmed claims are the held +// kinds, the way the profile service stores them. +func testProfile(t *testing.T, candidateID uuid.UUID, held ...domain.ContactField) domain.CandidateProfile { + t.Helper() + confirmed := func(value string) *domain.ProfileClaimInput[string] { + return &domain.ProfileClaimInput[string]{Value: value, Status: domain.ProfileClaimConfirmed} + } + var input domain.CandidateProfileInput + for _, field := range held { + switch field { + case domain.ContactFieldFullName: + input.FullName = confirmed("Test Candidate") + case domain.ContactFieldEmail: + input.Email = confirmed("candidate@example.test") + case domain.ContactFieldPhone: + input.Phone = confirmed("+70000000000") + case domain.ContactFieldTelegram: + input.Telegram = confirmed("@candidate_test") + } + } + empty, err := domain.EmptyCandidateProfile(candidateID) + if err != nil { + t.Fatalf("EmptyCandidateProfile() error = %v", err) + } + profile, _, err := empty.Replace(input, 0, time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC)) + if err != nil { + t.Fatalf("Replace() error = %v", err) + } + return profile +} + +// setState changes the committed state of the fakes between commands. +func (test *harness) setState(change func(state *testState)) { + test.transactor.mu.Lock() + defer test.transactor.mu.Unlock() + change(&test.transactor.state) +} + +func (test *harness) setProfile(t *testing.T, candidateID uuid.UUID, held ...domain.ContactField) { + t.Helper() + profile := testProfile(t, candidateID, held...) + test.setState(func(state *testState) { state.profiles[candidateID] = profile }) +} + +func (test *harness) publish(candidateID uuid.UUID, at time.Time) { + publication, err := domain.RestorePublication(domain.StoredPublication{ + UserID: candidateID, State: string(domain.PublicationPublished), Fields: []string{string(domain.CardFieldCategories)}, + ConsentRecordID: uuid.Must(uuid.NewV7()), PublishedAt: at, Version: 1, + }) + if err != nil { + panic(err) + } + test.setState(func(state *testState) { state.publications[candidateID] = publication }) +} + +func acceptCommand(actorID, invitationID uuid.UUID, version, terms int64, key string, fields ...domain.ContactField) AcceptCommand { + return AcceptCommand{ + ActorID: actorID, InvitationID: invitationID, IdempotencyKey: key, ExpectedVersion: version, + TermsVersion: terms, TextVersion: string(testC4Version), Fields: fields, + } +} + +func TestAcceptMineStoresTheAcceptanceAndTheGrantOfTheSelectedFieldsOnly(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + test.setProfile(t, candidateID, domain.ContactFieldEmail) + test.setTime(sent.DeliveredAt.Add(time.Hour)) + + // The profile holds only the email, so a phone request is refused by its + // pointer, and nothing is stored. + _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-phone", + domain.ContactFieldPhone)) + if got := fieldPointer(t, err); got != "/consent_c4/fields/0" { + t.Fatalf("pointer = %s, want /consent_c4/fields/0", got) + } + if state := test.transactor.snapshot(); len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.acceptResults) != 0 { + t.Fatalf("a refused acceptance stored grants %d, consents %d, outcomes %d", len(state.grants), len(state.consentRecords), len(state.acceptResults)) + } + + view, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-email", + domain.ContactFieldEmail)) + if err != nil { + t.Fatalf("AcceptMine() error = %v", err) + } + if view.State != domain.InvitationAccepted || view.Version != sent.Version+1 || view.TermsVersion != sent.TermsVersion || + view.RespondedAt == nil || view.ContactConsent != nil || view.ContactGrant == nil { + t.Fatalf("accepted = %+v, want the accepted invitation with its grant and no offer", view) + } + grant := view.ContactGrant + if len(grant.Fields) != 1 || grant.Fields[0] != domain.ContactFieldEmail || grant.Status != domain.ContactGrantActive || + grant.Readable || grant.BlockedBy == nil || *grant.BlockedBy != domain.ContactAccessBlockVisibility || + grant.TermsVersion != sent.TermsVersion || grant.ConsentTextVersion != testC4Version { + t.Fatalf("grant = %+v, want the email only, active, blocked by visibility while the profile is not published", grant) + } + state := test.transactor.snapshot() + invitation := state.invitations[sent.ID] + last := state.events[len(state.events)-1] + if invitation.State() != domain.InvitationAccepted || len(state.grants) != 1 || len(state.consentRecords) != 1 || + last.Kind != domain.InvitationEventAccepted || last.ActorID != candidateID || len(last.ChangedFields) != 0 { + t.Fatalf("stored state = %s grants %d consents %d last event %s, want one acceptance, grant, and consent", + invitation.State(), len(state.grants), len(state.consentRecords), last.Kind) + } + record := state.consentRecords[sent.ID] + if record.InvitationTermsVersion() != sent.TermsVersion || record.OrganizationName() != "Test organization" || + len(record.Fields().Fields()) != 1 || record.Fields().Fields()[0] != domain.ContactFieldEmail { + t.Fatalf("C4 record = %s, want the organization, the terms version, and the email only", record) + } +} + +func TestAcceptMineRepeatsWithoutRecordingAgainAndRefusesAnotherChoice(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + test.setProfile(t, candidateID, domain.ContactFieldEmail, domain.ContactFieldPhone) + test.setTime(sent.DeliveredAt.Add(time.Hour)) + first, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first", + domain.ContactFieldEmail)) + if err != nil { + t.Fatalf("AcceptMine() error = %v", err) + } + before := test.transactor.snapshot() + + test.setTime(sent.DeliveredAt.Add(2 * time.Hour)) + // A new key with the older expected version and the same terms and fields + // answers the accepted invitation without a second grant or event. + again, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-again", + domain.ContactFieldEmail)) + if err != nil || again.Version != first.Version || again.ContactGrant == nil || again.ContactGrant.ID != first.ContactGrant.ID { + t.Fatalf("repeat = %+v, %v; want the first acceptance", again, err) + } + replay, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first", + domain.ContactFieldEmail)) + if err != nil || replay.ContactGrant == nil || replay.ContactGrant.ID != first.ContactGrant.ID { + t.Fatalf("replay = %+v, %v; want the stored response", replay, err) + } + after := test.transactor.snapshot() + if len(after.events) != len(before.events) || len(after.grants) != 1 || len(after.consentRecords) != 1 { + t.Fatalf("repeats stored events %d to %d, grants %d, consents %d", len(before.events), len(after.events), len(after.grants), len(after.consentRecords)) + } + + // Another field set or a reused key with another body is refused, and the + // refusal is stored under its key. + if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-more", + domain.ContactFieldEmail, domain.ContactFieldPhone)); !errors.Is(err, ErrAnswerBlocked) { + t.Fatalf("another field set error = %v, want ErrAnswerBlocked", err) + } + if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "accept-first", + domain.ContactFieldPhone)); !errors.Is(err, ErrIdempotencyKeyReused) { + t.Fatalf("reused key error = %v, want ErrIdempotencyKeyReused", err) + } + if got := test.transactor.snapshot().acceptResults; len(got) != 3 { + t.Fatalf("stored outcomes = %d, want accepted, accepted again, and the refused field set", len(got)) + } +} + +func TestAcceptMineRefusesAStaleTermsVersionWithoutStoringAnything(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + test.setProfile(t, candidateID, domain.ContactFieldEmail) + before := test.transactor.snapshot() + + // The terms the candidate read are not the current ones: 412, nothing + // recorded, and no outcome under the key. + for name, command := range map[string]AcceptCommand{ + "stale terms": acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion+1, "stale-terms", domain.ContactFieldEmail), + "stale version": acceptCommand(candidateID, sent.ID, sent.Version+1, sent.TermsVersion, "stale-version", domain.ContactFieldEmail), + } { + if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, domain.ErrInvitationVersionConflict) { + t.Fatalf("%s error = %v, want ErrInvitationVersionConflict", name, err) + } + } + after := test.transactor.snapshot() + if len(after.grants) != 0 || len(after.consentRecords) != 0 || len(after.acceptResults) != 0 || len(after.events) != len(before.events) { + t.Fatalf("a stale acceptance stored grants %d, consents %d, outcomes %d", len(after.grants), len(after.consentRecords), len(after.acceptResults)) + } + if after.invitations[sent.ID].State() != domain.InvitationDelivered { + t.Fatalf("state = %s, want delivered", after.invitations[sent.ID].State()) + } +} + +func TestAcceptMineAtTheDeadlineStoresTheConflictAndGrantsNothing(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + test.setProfile(t, candidateID, domain.ContactFieldEmail) + test.setTime(*sent.ResponseDeadlineAt) + + _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version+5, sent.TermsVersion, "late", + domain.ContactFieldEmail)) + if !errors.Is(err, ErrAnswerBlocked) { + t.Fatalf("late acceptance error = %v, want ErrAnswerBlocked whatever the version", err) + } + state := test.transactor.snapshot() + if result := state.acceptResults[testKeyring{}.IdempotencyScope(acceptOperation, "late", candidateID.String())]; result.Outcome != outbound.InvitationAcceptStateConflict { + t.Fatalf("stored outcome = %+v, want state_conflict under the key", result) + } + if len(state.grants) != 0 || len(state.consentRecords) != 0 || state.invitations[sent.ID].State() != domain.InvitationDelivered { + t.Fatalf("a late acceptance changed the invitation: grants %d, consents %d", len(state.grants), len(state.consentRecords)) + } +} + +func TestAcceptMineChecksTheConsentTextAndTheHeldKinds(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + test.setProfile(t, candidateID, domain.ContactFieldFullName) + test.setTime(sent.DeliveredAt.Add(time.Hour)) + + outdated := acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "outdated", domain.ContactFieldFullName) + outdated.TextVersion = "c4-2025-01-01" + if got := fieldPointer(t, mustFail(t, test, outdated)); got != "/consent_c4/text_version" { + t.Fatalf("outdated text pointer = %s, want /consent_c4/text_version", got) + } + if got := fieldPointer(t, mustFail(t, test, acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "email", + domain.ContactFieldFullName, domain.ContactFieldEmail))); got != "/consent_c4/fields/1" { + t.Fatalf("unheld kind pointer = %s, want /consent_c4/fields/1", got) + } + if state := test.transactor.snapshot(); len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.acceptResults) != 0 { + t.Fatalf("refused consent stored grants %d, consents %d, outcomes %d", len(state.grants), len(state.consentRecords), len(state.acceptResults)) + } + + // The offer lists the held kinds in the order of the contract and shows the + // text with the organization name. A profile without a kind has no offer. + offered := decodeOffer(t, test, candidateID, sent.ID) + if offered.Text.TextVersion != testC4Version || !strings.Contains(offered.Text.Text, "Test organization") || + strings.Contains(offered.Text.Text, "{organization}") || len(offered.AvailableFields) != 1 || offered.AvailableFields[0] != domain.ContactFieldFullName { + t.Fatalf("offer = %+v, want the rendered text and the held kind", offered) + } + test.setProfile(t, candidateID) + read, err := test.service.GetMine(t.Context(), candidateID, sent.ID) + if err != nil || read.ContactConsent != nil { + t.Fatalf("GetMine without a held kind = %+v, %v; want no offer", read.ContactConsent, err) + } +} + +func TestAcceptedInvitationReadsTheGrantAndKeepsThePublicationAndTheHiding(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + test.setProfile(t, candidateID, domain.ContactFieldEmail) + test.setTime(sent.DeliveredAt.Add(time.Hour)) + test.publish(candidateID, *sent.DeliveredAt) + test.setState(func(state *testState) { state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] = true }) + publications := test.transactor.snapshot().publications + + accepted, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion, "hidden", + domain.ContactFieldEmail)) + if err != nil { + t.Fatalf("AcceptMine() while hidden error = %v", err) + } + if accepted.ContactGrant == nil || accepted.ContactGrant.Readable || accepted.ContactGrant.BlockedBy == nil { + t.Fatalf("grant while hidden = %+v, want stored and blocked by visibility", accepted.ContactGrant) + } + state := test.transactor.snapshot() + if len(state.publications) != len(publications) || state.publications[candidateID].State() != domain.PublicationPublished || + !state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] { + t.Fatal("the acceptance changed the publication or lifted the hiding") + } + + // Unhiding the organization makes the same grant readable; the grant + // itself never changes. + test.setState(func(state *testState) { delete(state.hidden, [2]uuid.UUID{candidateID, test.organizationID}) }) + read, err := test.service.GetMine(t.Context(), candidateID, sent.ID) + if err != nil || read.ContactGrant == nil || !read.ContactGrant.Readable || read.ContactGrant.BlockedBy != nil || + read.ContactGrant.ID != accepted.ContactGrant.ID { + t.Fatalf("read after unhiding = %+v, %v; want the same grant readable", read.ContactGrant, err) + } +} + +// decodeOffer reads the invitation of the candidate and returns its consent offer. +func decodeOffer(t *testing.T, test *harness, candidateID, invitationID uuid.UUID) domain.ContactConsentOffer { + t.Helper() + read, err := test.service.GetMine(t.Context(), candidateID, invitationID) + if err != nil { + t.Fatalf("GetMine() error = %v", err) + } + if read.ContactConsent == nil { + t.Fatal("GetMine() = no contact consent offer, want one") + } + return *read.ContactConsent +} + +// mustFail returns the error of an acceptance that must be refused. +func mustFail(t *testing.T, test *harness, command AcceptCommand) error { + t.Helper() + _, err := test.service.AcceptMine(t.Context(), command) + if err == nil { + t.Fatalf("AcceptMine(%s) succeeded, want a refusal", command.IdempotencyKey) + } + return err +} diff --git a/backend/internal/usecase/invitation/decline.go b/backend/internal/usecase/invitation/decline.go index 6c30a9e..8b315f5 100644 --- a/backend/internal/usecase/invitation/decline.go +++ b/backend/internal/usecase/invitation/decline.go @@ -144,7 +144,7 @@ func (service *Service) declineInTransaction( return declineOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", declineLocation, err) } if !created { - return replayDecline(ctx, unit, request, command, stored) + return service.replayDecline(ctx, unit, request, command, stored) } entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true) if errors.Is(err, outbound.ErrInvitationNotFound) { @@ -176,7 +176,7 @@ func (service *Service) declineFound( if previous.Choice.Equal(command.Choice) { // The same decline answers with the invitation as it is, whatever // the key or the version, and records nothing again. - return completeDecline(ctx, unit, request, entry) + return service.completeDecline(ctx, unit, request, entry) } return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict) } @@ -204,18 +204,18 @@ func (service *Service) declineFound( return declineOutcome{}, fmt.Errorf("%s - store decline: %w", declineLocation, err) } entry.Invitation = declined - return completeDecline(ctx, unit, request, entry) + return service.completeDecline(ctx, unit, request, entry) } // completeDecline stores the successful outcome under the key and builds the // response with the stored decline. -func completeDecline( +func (service *Service) completeDecline( ctx context.Context, unit outbound.UnitOfWork, request declineRequest, entry outbound.CandidateInvitationEntry, ) (declineOutcome, error) { - view, err := candidateView(ctx, unit, entry) + view, err := service.candidateView(ctx, unit, entry, request.now) if err != nil { return declineOutcome{}, err } @@ -263,7 +263,7 @@ func declineRefusal(outcome outbound.InvitationDeclineOutcome) error { // key used with another request. A stored success is rebuilt from the // declined invitation and its decline: both are final, so the replay shows // the same answer without a second copy of the comment. -func replayDecline( +func (service *Service) replayDecline( ctx context.Context, unit outbound.UnitOfWork, request declineRequest, @@ -290,7 +290,7 @@ func replayDecline( if entry.Invitation.State() != domain.InvitationDeclined { return declineOutcome{}, fmt.Errorf("%s - validate original response: %w", declineLocation, domain.ErrInvalidInvitation) } - view, err := candidateView(ctx, unit, entry) + view, err := service.candidateView(ctx, unit, entry, request.now) if err != nil { return declineOutcome{}, err } diff --git a/backend/internal/usecase/invitation/service.go b/backend/internal/usecase/invitation/service.go index 7697e77..192e102 100644 --- a/backend/internal/usecase/invitation/service.go +++ b/backend/internal/usecase/invitation/service.go @@ -3,9 +3,9 @@ // candidate card of the organization, the idempotent creation, and the // idempotent send that delivers a draft to the candidate's inbox. On the // candidate's side it lists that inbox, reads one invitation, records the -// view, and records a structured decline. The acceptance, the cancellation, -// and the contact grant belong to later operations that build on the same -// records. +// view, records a structured decline, and accepts the current terms with the +// consent C4 and its contact grant in one transaction. The cancellation and +// the revocation of a grant belong to later operations. package invitation import ( @@ -18,6 +18,7 @@ import ( "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/consent" ) var ( @@ -70,6 +71,14 @@ type CandidateResolver func(ctx context.Context, unit outbound.UnitOfWork, actor // invitation that is already charged is allowed without a second charge. type InvitationQuota func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) +// ContactConsents is the consent ledger of the acceptance. It reads the +// published C4 text, checks the version that the candidate saw, and records +// the C4 grant inside the caller's transaction. consent.Service implements it. +type ContactConsents interface { + CheckTextVersion(ctx context.Context, repositories outbound.ConsentRepositories, purpose domain.ConsentPurpose, version domain.ConsentTextVersion) (domain.ConsentText, error) + GrantContact(ctx context.Context, repositories outbound.ConsentRepositories, input consent.ContactGrantInput) (consent.GrantResult, error) +} + // DeliveryNotifier records, inside the caller's transaction, the outbox // events that tell the candidate about a delivered invitation: the in-platform // notification and the email. Neither blocks the delivery: the invitation is @@ -90,11 +99,13 @@ type Dependencies struct { Candidates CandidateResolver Quota InvitationQuota Notifier DeliveryNotifier - Clock func() time.Time + // Consents records the consent C4 of an acceptance in its transaction. + Consents ContactConsents + Clock func() time.Time } // Service applies organization-scoped invitation commands and reads, and the -// candidate's reads, view, and decline of the own invitations. +// candidate's reads, view, decline, and acceptance of the own invitations. type Service struct { transactor outbound.Transactor keyring Keyring @@ -102,13 +113,14 @@ type Service struct { candidates CandidateResolver quota InvitationQuota notifier DeliveryNotifier + consents ContactConsents clock func() time.Time } // NewService fails at startup when a required dependency is missing. func NewService(deps Dependencies) (*Service, error) { if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Quota == nil || - deps.Notifier == nil || deps.Clock == nil { + deps.Notifier == nil || deps.Consents == nil || deps.Clock == nil { return nil, errors.New("invitation.NewService - every dependency must be set") } if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil { @@ -116,7 +128,8 @@ func NewService(deps Dependencies) (*Service, error) { } return &Service{ transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey, - candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, clock: deps.Clock, + candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, consents: deps.Consents, + clock: deps.Clock, }, nil } diff --git a/backend/internal/usecase/invitation/service_test.go b/backend/internal/usecase/invitation/service_test.go index 6757718..ef283d7 100644 --- a/backend/internal/usecase/invitation/service_test.go +++ b/backend/internal/usecase/invitation/service_test.go @@ -16,6 +16,7 @@ import ( "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/consent" ) type testKeyring struct{} @@ -47,6 +48,16 @@ type testState struct { // the decline outcomes kept under a key. declines map[uuid.UUID]domain.InvitationDecline declineResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult + // grants holds the contact grants by invitation, acceptResults the + // acceptance outcomes by key, and consentRecords the C4 records by + // invitation. profiles and publications are the candidates' profiles and + // publication settings, and hidden the hidden organizations by candidate. + grants map[uuid.UUID]domain.ContactGrant + acceptResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationAcceptResult + consentRecords map[uuid.UUID]domain.ConsentRecord + profiles map[uuid.UUID]domain.CandidateProfile + publications map[uuid.UUID]domain.Publication + hidden map[[2]uuid.UUID]bool // charged lists the invitations charged against the organization quota, // and notified the delivered invitations that were notified. charged []uuid.UUID @@ -63,6 +74,12 @@ func newTestState() testState { needVersions: map[[3]string]bool{}, declines: map[uuid.UUID]domain.InvitationDecline{}, declineResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult{}, + grants: map[uuid.UUID]domain.ContactGrant{}, + acceptResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationAcceptResult{}, + consentRecords: map[uuid.UUID]domain.ConsentRecord{}, + profiles: map[uuid.UUID]domain.CandidateProfile{}, + publications: map[uuid.UUID]domain.Publication{}, + hidden: map[[2]uuid.UUID]bool{}, } } @@ -99,6 +116,24 @@ func (state testState) clone() testState { for scope, result := range state.declineResults { cloned.declineResults[scope] = result } + for id, grant := range state.grants { + cloned.grants[id] = grant + } + for scope, result := range state.acceptResults { + cloned.acceptResults[scope] = result + } + for id, record := range state.consentRecords { + cloned.consentRecords[id] = record + } + for id, profile := range state.profiles { + cloned.profiles[id] = profile + } + for id, publication := range state.publications { + cloned.publications[id] = publication + } + for key, hidden := range state.hidden { + cloned.hidden[key] = hidden + } cloned.charged = slices.Clone(state.charged) cloned.notified = slices.Clone(state.notified) return cloned @@ -417,6 +452,7 @@ func newHarness(t *testing.T) *harness { return outbound.CompanyQuotaDecision{Allowed: true}, nil }, Notifier: testNotifier{}, + Consents: consent.NewService(test.transactor, func() time.Time { return current }), }) if err != nil { t.Fatalf("NewService() error = %v", err) diff --git a/backend/internal/usecase/invitation/view.go b/backend/internal/usecase/invitation/view.go index 270aab1..7b37018 100644 --- a/backend/internal/usecase/invitation/view.go +++ b/backend/internal/usecase/invitation/view.go @@ -2,6 +2,7 @@ package invitation import ( "context" + "errors" "fmt" "time" @@ -25,8 +26,12 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid. if actorID == uuid.Nil { return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", getMineLocation, ErrForbidden) } + now, err := service.now(getMineLocation) + if err != nil { + return domain.CandidateInvitationView{}, err + } var view domain.CandidateInvitationView - err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := authorizeCandidate(ctx, unit, actorID); err != nil { return err } @@ -34,7 +39,7 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid. if err != nil { return err } - view, err = candidateView(ctx, unit, entry) + view, err = service.candidateView(ctx, unit, entry, now) return err }) if err != nil { @@ -85,7 +90,7 @@ func (service *Service) ViewMine(ctx context.Context, actorID, invitationID uuid } entry.Invitation = viewed } - view, err = candidateView(ctx, unit, entry) + view, err = service.candidateView(ctx, unit, entry, now) return err }) if err != nil { @@ -123,25 +128,118 @@ func readCandidateEntry( // organization from seeing the candidate, while the candidate needs to know // who sent the offer to answer it. Pushed content, such as the inbox // notification, follows the hiding instead. -func candidateView(ctx context.Context, unit outbound.UnitOfWork, entry outbound.CandidateInvitationEntry) (domain.CandidateInvitationView, error) { - const location = "invitation.candidateView" +// +// The consent offer is set while an acceptance is possible, and the contact +// grant once the invitation is accepted. The grant is readable only while the +// organization may read the profile, so a hidden profile shows the grant as +// blocked by visibility. at is the time of the command that builds the view. +func (service *Service) candidateView( + ctx context.Context, + unit outbound.UnitOfWork, + entry outbound.CandidateInvitationEntry, + at time.Time, +) (domain.CandidateInvitationView, error) { + const location = "invitation.Service.candidateView" + current := entry.Invitation var decline *domain.InvitationDecline - if entry.Invitation.State() == domain.InvitationDeclined { - stored, err := unit.Invitations().GetDecline(ctx, entry.Invitation.OrganizationID(), entry.Invitation.ID()) + if current.State() == domain.InvitationDeclined { + stored, err := unit.Invitations().GetDecline(ctx, current.OrganizationID(), current.ID()) if err != nil { return domain.CandidateInvitationView{}, fmt.Errorf("%s - read decline: %w", location, err) } decline = &stored } - view, err := entry.Invitation.CandidateView(domain.InvitationOrganizationRef{ - ID: entry.Invitation.OrganizationID(), Name: entry.OrganizationName, + view, err := current.CandidateView(domain.InvitationOrganizationRef{ + ID: current.OrganizationID(), Name: entry.OrganizationName, }, decline) if err != nil { return domain.CandidateInvitationView{}, fmt.Errorf("%s - build view: %w", location, err) } + switch { + case current.State() == domain.InvitationAccepted: + grant, err := unit.ContactGrants().GetByInvitation(ctx, current.OrganizationID(), current.ID()) + if err != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - read contact grant: %w", location, err) + } + visible, err := candidateVisibleTo(ctx, unit, current.CandidateID(), current.OrganizationID()) + if err != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - read visibility: %w", location, err) + } + grantView := grant.CandidateView(visible) + view.ContactGrant = &grantView + case acceptancePossible(current, at): + offer, offered, err := contactConsentOffer(ctx, unit, current, entry.OrganizationName, at) + if err != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - build consent offer: %w", location, err) + } + if offered { + view.ContactConsent = &offer + } + } return view, nil } +// acceptancePossible reports the states and the time in which the candidate +// may accept: a delivered or viewed invitation before its deadline. +func acceptancePossible(invitation domain.Invitation, at time.Time) bool { + state := invitation.State() + return (state == domain.InvitationDelivered || state == domain.InvitationViewed) && + invitation.IsDelivered() && !invitation.ResponseDeadlinePassed(at) +} + +// candidateVisibleTo reports whether the organization may read the profile of +// the candidate now: the publication is effective, and the candidate has not +// hidden the organization. The read model of the profile applies C2 and the +// revocation of C2; the hiding is a record of its own. +func candidateVisibleTo(ctx context.Context, unit outbound.UnitOfWork, candidateID, organizationID uuid.UUID) (bool, error) { + const location = "invitation.candidateVisibleTo" + settings, err := unit.PrivacySettings().ReadSettings(ctx, candidateID) + if err != nil { + return false, fmt.Errorf("%s - read privacy settings: %w", location, err) + } + if settings.Publication.State() != domain.PublicationPublished { + return false, nil + } + _, err = unit.PrivacySettings().GetHiddenOrganization(ctx, candidateID, organizationID) + switch { + case err == nil: + return false, nil + case errors.Is(err, outbound.ErrCandidatePrivacySettingsNotFound): + return true, nil + default: + return false, fmt.Errorf("%s - read hidden organization: %w", location, err) + } +} + +// contactConsentOffer builds the consent offer of an invitation: the rendered +// C4 text and the kinds that the profile holds. It reports false when the +// profile holds no kind, because a grant must cover at least one field. +func contactConsentOffer( + ctx context.Context, + unit outbound.UnitOfWork, + invitation domain.Invitation, + organizationName string, + at time.Time, +) (domain.ContactConsentOffer, bool, error) { + profile, err := unit.CandidateProfiles().Get(ctx, invitation.CandidateID()) + if err != nil { + return domain.ContactConsentOffer{}, false, fmt.Errorf("read candidate profile: %w", err) + } + held := heldContactFields(profile) + if len(held) == 0 { + return domain.ContactConsentOffer{}, false, nil + } + text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposeContactDisclosure, at) + if err != nil { + return domain.ContactConsentOffer{}, false, fmt.Errorf("read consent C4 text: %w", err) + } + offer, err := domain.NewContactConsentOffer(text, organizationName, held) + if err != nil { + return domain.ContactConsentOffer{}, false, fmt.Errorf("build offer: %w", err) + } + return offer, true, nil +} + // notBefore keeps a clock that stepped back from recording a change before // the last one. func notBefore(now, last time.Time) time.Time { diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 408264c..d6f209a 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -467,7 +467,7 @@ Demo and calibrated policy: `domain.DemoProductPolicyV1()` is the accepted initi | Section | Values | | --- | --- | | `invitations` | response deadline options 3, 7, and 14 days, default 7; at most 20 pending invitations per need; repeat after a decline in 30 days; interview proposal within 5 business days; 30-day pause after no deal | -| `organization_quotas` | rolling windows of 7 days for invitations and 24 hours for distinct card views; E0 10 invitations and 50 views, E1 40 and 150, E2 100 and 400; E2 is inactive until the organization verification that grants it exists | +| `organization_quotas` | rolling windows of 7 days for invitations and 24 hours for distinct card views; E0 10 invitations and 50 views, E1 40 and 150, E2 100 and 400; E2 is inactive until the organization verification that grants it exists; the E0 companies of one holding share one pool, and E1 and above count separately (see [Company quotas](COMPANY_QUOTAS.md#holding-pool)) | | `assessment`, uncalibrated initial | same-grade retry after 30 days; at most 3 attempts per 180 days; at most one promotion per 90 days; confirmation at P_G >= 0.80, high strength from 0.90; after at least 8 scored items stop at P_G >= 0.90 or <= 0.10 or SE <= 0.25; at most 23 scored items plus 2 seed items; practice is mandatory | | `identity` | verification token 24 hours; unverified account deleted 7 days after the latest registration; session idle timeout 24 hours, absolute lifetime 7 days | | `search_status` | the "searching" status is confirmed every 30 days | @@ -695,7 +695,7 @@ Implemented as a deterministic search without ML: `POST /api/v1/organizations/{o - 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. +- 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). For an E0 company, `LockOrganization` takes the lock of its holding right after the organization row (the shared E0 pool is described in [Company quotas](COMPANY_QUOTAS.md#holding-pool)), so the order stays the same: the organization, then the holding, and no holding is taken before its organization. `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. @@ -861,20 +861,22 @@ Tables: - `organizations`: UUIDv7 `id` (the `org_id` of every organization path), `name` (1-200 characters, the bound of the consent snapshot), `description`, `sphere` (free text; the PRD has no taxonomy), four public contact columns (`contact_website`, `contact_email`, `contact_phone`, `contact_telegram`), the verification columns `verification_level`, `verification_basis`, and `verification_changed_at`, the profile `version`, and the times. Every text column has a CHECK for the same format and bounds as the contract (no surrounding whitespace, no control characters, `https` website without credentials). - `organization_representatives`: `organization_id`, `ordinal` (0 to 9, so at most ten), `name`, and `job_title`; deleted with the organization row. The list is replaced as a whole with a profile update. - `memberships`: UUIDv7 `id`, `organization_id`, `user_id`, `role`, `state`, and the times. `UNIQUE (user_id, organization_id)` allows one membership per pair in any state, and `UNIQUE (organization_id, id)` is the target of the composite foreign keys that later tables (the assignments of needs) use to bind a membership to its organization. Both foreign keys are `ON DELETE RESTRICT`. +- `holdings`: UUIDv7 `id` (internal; the API never shows it), `founder_account_id`, the account that created the first organization of the holding, with `UNIQUE` and a foreign key to `users` with `ON DELETE RESTRICT`, and `created_at`. The column `organizations.holding_id` is required, references the holding with `ON DELETE RESTRICT`, and has an index; migration `00041_create_holdings.sql` fills it from the account of the earliest membership of each organization. Decisions: - Active context. It is not a server-side session attribute. The organization is the `org_id` in the path, and the server derives the right from the active membership on every request, so a removal, a suspension, or a leave closes the next read with nothing to invalidate. `ListMyOrganizations` is the directory a client picks from; remembering the last choice is a browser convenience. The context comes only from the caller's active memberships, and a terminated membership closes reads at once. A switch clears the client's tenant queries. - Role and state in the membership only. `OrganizationRole` is `owner`, `recruiter`, `hiring_manager`, or `technical_expert` (PRD 2.2, Q3, and the FR07 matrix), and `MembershipState` is `active`, `suspended`, `removed`, or `left`, each a CHECK constraint, not a PostgreSQL enum, so a later value is a constraint change in a migration. There is no `invited` state: PRD 6.4 lists `MemberInvite` as its own entity, an invitation to an email address that may have no account yet, and a membership row appears when its owner accepts it. `organizations` has no role, owner, or member column (an integration test reads the catalog to prove it), and `Organization`, `OrganizationCreate`, and `OrganizationUpdate` have no such field. Only the owner manages the company (`OrganizationRole.CanManageOrganization`); the rest of the matrix is applied by the operations it governs, and in the MVP the other roles grant nothing. - Verification level. `verification_level` is `e0` to `e3` with `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), and one CHECK ties each level to its own bases. The columns are separate from the profile: `UpdateOrganizationProfile` never names them, `domain.NewOrganization` cannot choose a level and starts every organization at `e0` on `confirmed_email`, `Organization.ApplyProfile` keeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; the planned verification flow adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process. `OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the quota tiers of the product policy and has none for `e3`, which the PRD gives a separate policy (quota enforcement reads the tier and must fail closed on an `e3` organization: no quota granted, the action refused, never a fallback to another tier). +- Holding. The organizations of one founder account form a holding. `CreateWithOwner` stores the organization in the holding of its owner account in the same transaction, and creates the holding with the first organization of the account (`INSERT ... ON CONFLICT (founder_account_id) DO NOTHING`, then a read), so concurrent creations of one account end in one holding. A holding carries no profile and no right: it only defines the scope of the shared E0 quota pool (invitations and card views). The number of organizations per account is not limited; merging holdings of different owners is not modelled. The pool and lock rules are in [Company quotas](COMPANY_QUOTAS.md#holding-pool). - An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management, not of this constraint, which would otherwise block a platform decision about an abusive organization. - Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management, which changes a membership and the organization together, and the tenant repository must take the locks in that order, or two transactions can deadlock. - Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the consent ledger tests to create real organizations, and the `invitation_id` key needs real invitations; both arrive with the acceptance of an invitation, the first writer of C4 rows that name a real invitation. The invitation tables (migration 00037) and the needs reference organizations, accounts, and policy versions with `ON DELETE RESTRICT`, so an organization with needs or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3). -- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and remove it through bounded opportunistic cleanup after the replay window; physical deletion may happen later when create traffic resumes; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (organization creation and quota enforcement need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations). +- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and remove it through bounded opportunistic cleanup after the replay window; physical deletion may happen later when create traffic resumes; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the owner's decision on the number of organizations per account (no limit; the E0 quotas of a holding are shared) are in [api/README.en.md](../../api/README.en.md#organizations). What the ports guarantee (`outbound.OrganizationRepositories`, available on `UnitOfWork` only, because a write needs the transaction): -- `Organizations().CreateWithOwner` stores the organization and its owner membership and validates that the owner is the active owner membership of that organization. An unknown account returns `ErrUserNotFound` and aborts the surrounding transaction. +- `Organizations().CreateWithOwner` stores the organization and its owner membership and validates that the owner is the active owner membership of that organization. The organization joins the holding of the owner account, and the holding is created in the same transaction when none exists yet. An unknown account returns `ErrUserNotFound` and aborts the surrounding transaction. - `GetForMember` reads the organization, its representatives (aggregated as JSON in the same statement), and the caller's active membership from one snapshot, and returns them or `ErrOrganizationNotFound` for an unknown organization, an account without a membership, and a `suspended`, `removed`, or `left` member alike. `ListForUser` pages the active organizations of one account, newest membership first, with the organization identifier as the tie-breaker. `UpdateProfile` is described above. - `Memberships().Insert` returns `ErrMembershipExists` for a repeated pair in any state, `ErrOrganizationNotFound` for an unknown organization, and `ErrUserNotFound` for an unknown account; `Get` returns the membership in any state or `ErrMembershipNotFound`, and the caller checks `GrantsAccess`. There is no method that changes a role or a state yet. @@ -941,13 +943,13 @@ The anonymous card for organizations is not built here: `AnonymousCardContent` i ### Invitation drafts -Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in [Sending invitations](#sending-invitations). Withdrawal, the salary raise, the contact read, the acceptance, and the cancellation still answer 501 after the common checks; the candidate's read, view, and decline are described in [Candidate view and decline](#candidate-view-and-decline). Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`. +Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in [Sending invitations](#sending-invitations). Withdrawal, the salary raise, the contact read, and the cancellation still answer 501 after the common checks; the candidate's read, view, decline, and acceptance are described in [Candidate view and decline](#candidate-view-and-decline) and [Candidate acceptance](#candidate-acceptance). Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`. Tables: - `invitations`: UUIDv7 `id`, `organization_id`, the internal `candidate_id` (never serialized, logged, or printed), the optional need link (`need_id` with `need_requirements_version`, bound by composite foreign keys to a stored version of a need of the same organization), `state` (all fourteen states of the contract, so the later operations need no constraint change), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7, or 14), `policy_version_id` (the product policy version that allowed the period), `response_deadline_at`, `salary_raise_used`, `created_by`, and `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. CHECK constraints tie the deadline to the delivery (both set or both null), keep a draft free of delivery, view, answer, and raise, and tie the expiry reason to the state. A trigger keeps the identity columns, makes every UPDATE advance `version` by exactly one and `terms_version` by at most one, and refuses to undo a raise or to move the delivery, the deadline, or the period after a delivery. A second trigger refuses DELETE. The foreign keys to organizations, accounts, and policy versions are `ON DELETE RESTRICT`, so an account with invitations is undeletable until a deletion procedure settles them. - `invitation_terms_versions`: `(invitation_id, version)`, the terms as a JSONB snapshot, and the salary again in typed columns (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Constraints repeat the money rules in integers: both bounds from 1000 to 100 000 000 rubles in steps of 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B` (a width of 10% to 40% of the midpoint), RUB, month, and `net` or `gross`. The snapshot must hold all twelve terms and its salary must equal the typed columns. A trigger refuses UPDATE and DELETE: a version of the terms is immutable, and a change appends the next version. The invitation points at its current version by a deferred composite foreign key, so the first version is inserted in the same transaction. -- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created`, `draft_updated`, since migration 00038 `delivered`, and since migration 00039 `viewed` and `declined`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only. +- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created`, `draft_updated`, since migration 00038 `delivered`, and since migration 00039 `viewed` and `declined`, and since migration 00040 `accepted`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only. - `invitation_creation_results`: the original response of an idempotent create, bound to the generic idempotency record and removed with it. It holds the terms, the alias, and no candidate identifier. Decisions: @@ -962,7 +964,7 @@ Decisions: - Locks. A create and an update both take the exclusive organization lock first (`CompanyQuotaRepository.LockOrganization`), like a card read and a search, and only then the share lock of the membership check, the cohort locks of a create, or the invitation row lock of an update, so commands of one organization queue instead of deadlocking on a lock upgrade, and a later command that also charges the organization, such as sending, keeps the same order. An update locks the invitation row with a statement of its own (`LockInvitation`) and reads it afterwards: a locking read joined to the terms table would, after waiting for a concurrent commit, pair the new `terms_version` with the terms row it fetched before the wait and find nothing. A create repeats a bounded number of times when the visible cohort changed while it was locked. - The indicator. `salary_fit` is always `not_available` and `contact_access` is `not_granted` with no fields. The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet. -How the later operations plug in: the pair rules read the index on the organization and the candidate. The contact grant, the C4 key to `invitations`, and the keys of the consent ledger to `organizations` and `invitations` arrive with the acceptance, the first writer of C4 rows that name a real invitation. +How the later operations plug in: the pair rules read the index on the organization and the candidate. The contact grant arrives with the acceptance ([Candidate acceptance](#candidate-acceptance)). The C4 columns of the consent ledger still have no foreign keys to `organizations` and `invitations`; that is a follow-up. Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the limit of pending invitations per need, the raise, the withdrawal, the candidate side beyond the list of invitations, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned. @@ -997,16 +999,34 @@ Implemented: `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` ([ - Privacy of the decline. The organization reads only `declined` and `responded_at`: none of its operations reads `invitation_declines`, and the audit event names no reason. The comment is never logged, notified, or copied into the stored outcome; the candidate reads both back in `decline`. - Order of checks after the boundary: the candidate (403), the key (422 or a replay), the invitation (404, stored), the same decline of a declined invitation (200 with a new key or an older version), another reason or comment on a declined invitation, any other terminal state, or a passed deadline (409 whatever the version, stored), the version (412, not stored), then a state without an open answer (409, stored). `invitation_decline_results` keeps only the outcome and the invitation: a declined invitation and its decline never change, so a replay rebuilds the same answer and the comment is stored once. - Deadline. Expiry is not implemented yet, so no read or command applies the transition to `expired`. A view at the deadline or later changes nothing, and a decline at the deadline or later answers 409 `state_conflict`, as the contract requires for a late command; the invitation stays `delivered` or `viewed` with its passed deadline until the expiry arrives. The conditional UPDATEs repeat the deadline, so a command cannot cross it between the check and the write. -- Consent and grant. Acceptance is not implemented, so an acceptance is impossible now and `contact_consent` and `contact_grant` are always null, as the contract requires when no acceptance can be made. Both arrive with `AcceptMyInvitation`. +- Consent and grant. A decline creates neither a consent nor a grant, so `contact_consent` and `contact_grant` are null after it. The acceptance is described in [Candidate acceptance](#candidate-acceptance). - Hiding. The candidate's read shows the sending organization even after the candidate hid the profile from it: the hiding keeps the organization from seeing the candidate, while the candidate must know who sent the offer to answer it. The pushed content follows the hiding instead: the inbox notice of the invitation loses its content (`ResolveInvitationNotice`). - Locks. A candidate command locks only the invitation row (`LockCandidateInvitation`) after the candidate's own idempotency record, never the organization. An organization command takes the organization lock first and the invitation row afterwards, so the two orders never cross: a candidate command does not wait for an organization lock while it holds the row. - Database rules of migration 00039: the event kinds `viewed` and `declined` without changed fields; `invitations_answer_matches_state` (a delivered invitation has no view or answer, a viewed one has its view, a declined one its answer, and neither precedes the delivery); the trigger `invitations_guard_answer`, which refuses to move or undo a view or an answer and to leave `declined`; `invitation_declines` with the known reasons, the comment bound, a trigger that ties the row to a declined invitation answered at the same moment, and a refusal of UPDATE and DELETE; and the deferred constraint trigger `invitations_require_decline`, so a declined invitation without its decline cannot commit. The down migration refuses while a view, a decline, or a stored outcome exists. - Notification. The contract has no notification kind for an answer, so the organization gets no inbox entry for a view or a decline yet; it sees the state in its invitation list. A notice of the answer is planned as a contract change. -Not implemented: the expiry at the deadline and its application on a read, the acceptance with C4 and the contact grant, the cancellation, the counter offer that would produce `counter`, the decline aggregates with a minimum group size, the responsiveness metrics, the 30-day pause after a decline, and a notification of the organization about an answer. +Not implemented: the expiry at the deadline and its application on a read, the cancellation, the counter offer that would produce `counter`, the decline aggregates with a minimum group size, the responsiveness metrics, the 30-day pause after a decline, and a notification of the organization about an answer. Tests: `domain/invitation_answer_test.go` (the view only from `delivered` before the deadline, the decline from `delivered`, `viewed`, and `counter`, the refusal of terminal and late invitations, the comment rules, the stored answer rules, redaction), `usecase/invitation/answer_test.go` (no side effect of a read, the deadline kept, repeats, order of checks, foreign callers, invalid comments), `adapter/primary/http/v1/invitation_candidate_test.go` (statuses and a response without candidate data), and the integration tests `TestCandidateInvitationViewAndDeclineOverHTTP` (the read and the view with the same deadline, concurrent views with one event, a decline with `other` and no comment without a C4 consent, the stored answer event, replays and conflicts, the comment kept from the organization and the audit, foreign candidates and employers, CSRF and Origin, the hiding, a stale version, a late command) and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`. +### Candidate acceptance + +Implemented: `AcceptMyInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_answer.go` (`Accept`), `domain/contact_grant.go`, `usecase/invitation/accept.go` and `view.go` (the candidate's view with the consent offer and the grant), `usecase/consent` (`GrantContact`, the C4 record), the HTTP handler `adapter/primary/http/v1/invitation_candidate.go`, the adapter `adapter/secondary/postgres/invitation_accept.go` with `db/queries/invitation_answers.sql` and `db/queries/contact_grants.sql`, and migration `00040_accept_invitations.sql`. + +- One transaction. The candidate accepts the current terms with the consent C4 from `delivered` or `viewed`, before the deadline, at the invitation version and the terms version that the candidate read. The transaction takes its own idempotency record, then only the invitation row (`LockCandidateInvitation`), and then, in order: it moves the invitation to `accepted` with one conditional UPDATE (`responded_at` is the answer time, `version` plus one; the deadline and the terms stay), records the consent C4 in the consent ledger through `consent.Service.GrantContact` (the published text, the organization name as it was shown, the selected fields, the invitation, and its terms version), stores the contact grant of exactly those fields, and appends the audit event `accepted`, which names no field. A failure of any step rolls the whole transaction back. +- Order of checks. The contract order: the candidate (403), the key (422 or a replay), the invitation (404, stored), a repeat of an accepted invitation (200), a terminal state or a passed deadline (409 `state_conflict`, stored), the versions (412 `version_conflict`, not stored), any state other than `delivered` or `viewed` (409, stored), and the consent rules (400 at `/consent_c4/text_version` for a text that is not the published one, and at `/consent_c4/fields/N` for a kind that the profile does not hold). A kind is held when the profile has it as a confirmed claim; a suggestion that nobody confirmed is never disclosed. +- Repeats. An accepted invitation whose grant has the same terms version and the same set of fields answers 200 with the same invitation, under the same key or a new one and with an older `expected_version`, and records nothing. Another terms version or set of fields answers 409 `state_conflict`, stored under the key. The outcomes under a key are `accepted`, `not_found`, and `state_conflict`; a stale version and a consent refusal are not stored. +- The grant. `contact_grants` holds the organization, the candidate, the source invitation (one grant per invitation), the consent record (one per grant), the canonical field set, the terms version, the consent text version, the grant time, and the revocation stamp (`revoked_at` and `revocation_reason`). This change never sets the stamp; the revocation is a later operation. Composite foreign keys tie the grant to its invitation of the same organization and candidate, and to its C4 record of the same subject, organization, invitation, and terms version. A trigger checks that the fields, the text version, and the grant time equal those of the record; a second trigger refuses DELETE and every change other than the one stamp. A deferred constraint trigger refuses to commit an accepted invitation without its grant. The grant holds kinds only, never contact values. +- The candidate's view. While an acceptance is possible, `contact_consent` holds the rendered C4 text and the kinds that the profile holds, in the order of the contract, with nothing preselected; it is null when the profile holds no confirmed kind. After the acceptance, `contact_grant` holds the selected kinds, the status, the terms version, the consent text version, and `readable`. `readable` is true only while the organization may read the profile: the publication is effective and the candidate has not hidden the organization. Otherwise `blocked_by` is `visibility`. A declined invitation keeps both fields null. +- Visibility decision. The acceptance is allowed while the profile is hidden from the organization or not published, as the contract's example of a blocked grant shows. It never publishes the profile, never changes the publication, and never lifts or adds a hiding. The grant stays stored and becomes readable when the candidate publishes the profile or unhides the organization; `readable` is recomputed on every read, so the grant itself never changes. The contact read through the grant is a later operation, so the organization still sees `contact_access` as not granted. +- Concurrency. The candidate command never takes the organization lock. Two concurrent acceptances of one version make one transition: the second waits for the row and then answers as a repeat, which is 200 with the same answer for identical terms and fields and 409 for another field set. +- Clocks. The answer time comes from the invitation service and the grant time from the consent service. In production both read the process clock, so they can differ by microseconds; the grant keeps the consent time. A replay of a stored acceptance rebuilds the response from the invitation and the grant. The outcome table keeps no copy of the response, so a later state change would show in a replay, as it would for a decline. +- Ledger keys. The C4 columns of the consent ledger still have no foreign keys to `organizations` and `invitations`: the ledger tests write C4 records with synthetic identifiers. The composite keys of the grant keep an acceptance consistent without that change; the ledger keys need fixtures with real invitations and are a follow-up. + +Not implemented: the contact read through a grant, the revocation of a grant (after the publication is closed, after the hiding, after the consent is revoked, or after the participation is cancelled), the counter offer, the expiry at the deadline, and the cancellation. + +Tests: `domain/contact_grant_test.go` (the grant from its record, the scope and revocation rules, the visibility view, the offer rendering, and `Accept`), `usecase/invitation/accept_test.go` (the order of checks, repeats, stale terms, late commands, consent pointers, visibility without a change of the publication), `adapter/primary/http/v1/invitation_candidate_test.go` (failure statuses), and the integration tests `TestCandidateInvitationAcceptOverHTTP` (an email-only grant, repeats and conflicts, a stale terms version and the raised terms, concurrent acceptances, a hidden profile, a late acceptance, consent and kind checks, the server log) and `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` against a real PostgreSQL. + ## Frontend The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. diff --git a/docs/en/COMPANY_QUOTAS.md b/docs/en/COMPANY_QUOTAS.md index 1cdb26a..a330bf8 100644 --- a/docs/en/COMPANY_QUOTAS.md +++ b/docs/en/COMPANY_QUOTAS.md @@ -14,9 +14,9 @@ The quota snapshot captures the policy version and the stored organization verif Call `companyquota.Service.ReserveInvitation` or `ReserveCardView` with repositories from the current `outbound.UnitOfWork`. The repository returned by `UnitOfWork.CompanyQuotas()` is transaction-scoped and must not be retained. Make the quota reservation and its eventual business change in the same transaction so rollback removes both. The service is constructed with the application clock and reads the effective policy once per operation. -Tenant authorization remains the caller's responsibility. Recheck active membership and owner permission inside the same transaction. Writers follow this order: organization, active membership, invitation or visibility record, then quota usage. The quota adapter locks the organization row first; a caller that already holds that row may lock it again in the same transaction. Do not reverse this order. +Tenant authorization remains the caller's responsibility. Recheck active membership and owner permission inside the same transaction. Writers follow this order: organization, then for an E0 organization its holding (see [Holding pool](#holding-pool)), active membership, invitation or visibility record, then quota usage. The quota adapter locks the organization row first and, for an E0 organization, the holding row right after it; a caller that already holds those rows may lock them again in the same transaction. Do not reverse this order. -The organization lock serializes concurrent reservations. The adapter checks existing usage, counts the active window, and inserts or refreshes usage while that lock is held. A decision is either allowed or denied; reuse implies allowed. A denied reservation writes no usage and includes `RetryAt`, the earliest active usage expiry that can free capacity. +The organization lock serializes concurrent reservations of one organization, and the holding lock serializes the shared E0 pool. The adapter checks existing usage, counts the active window, and inserts or refreshes usage while those locks are held. A decision is either allowed or denied; reuse implies allowed. A denied reservation writes no usage and includes `RetryAt`, the earliest active usage expiry that can free capacity. ## Windows and retries @@ -24,10 +24,24 @@ An invitation is keyed by `(organization_id, invitation_id)`. Repeating the same A card view is keyed by `(organization_id, candidate_id)`, so viewing the same candidate again during the active window does not consume another distinct-view slot. The repeat refreshes `last_seen_at` monotonically: a backdated application clock cannot move the stored time backward. -The active-window query uses a strict comparison with the cutoff. A row exactly at `now - window` has expired. Invitation usage is counted over seven rolling days; card views are counted over 24 rolling hours. The limits apply across requests and users in the organization. +The active-window query uses a strict comparison with the cutoff. A row exactly at `now - window` has expired. Invitation usage is counted over seven rolling days; card views are counted over 24 rolling hours. The limits apply across requests and users of the organization, except that an E0 organization shares its limits with the other E0 organizations of its holding (see [Holding pool](#holding-pool)). Expired card-view rows are deleted in batches of at most 100 after a successful allowed reservation. Window expiry is logical; this cleanup does not promise deletion at an exact time. Deleting a candidate account cascades its card-view usage row. Deleting an organization cascades both quota tables. Invitation usage has no invitation foreign key, so future invitation withdrawal cannot erase its idempotency evidence. +## Holding pool + +A holding groups the organizations that one founder account created; the `holdings` table and the migration `00041_create_holdings.sql` store it. `CreateWithOwner` stores each new organization in the holding of its owner account in the same transaction. The holding of an account is created with its first organization, and concurrent creations of one account end in one holding, because the insert ignores an existing founder key and the transaction then reads the stored holding. A holding carries no profile and no right; its only effect is the shared E0 pool. + +The E0 limits (10 invitations per 7 days and 50 distinct card views per 24 hours in the bundled demo policy) are shared by the E0 organizations of a holding. An E0 reservation counts the usage rows of every organization of its holding whose trust level is E0 when the count runs. Each usage row stays attributed to the organization that consumed it, and usage of an organization that is no longer E0 leaves the shared pool. An organization at E1 or above counts only its own usage and keeps its own pool, so its usage does not count toward the E0 pool. + +Idempotency stays per organization. The same invitation ID, or a repeated view of one candidate by the same organization inside the window, is not charged twice. The same candidate viewed by two organizations of one holding is two charges of the shared pool. + +Locks: for an E0 organization, `CompanyQuotaRepository.LockOrganization` and each reservation take the holding row with `FOR NO KEY UPDATE` right after the organization row. Reservations of one pool therefore run one after another, and the second one counts the usage that the first one committed, because it counts only after the holding lock. Every writer takes the organization lock before the holding lock, and no code takes an organization lock while it holds a holding lock, so the holding lock adds no cycle to the documented order. The cost is that E0 searches, card reads, and invitation drafts or sends of one holding wait for one another while their transactions are open; a search holds the lock for its whole ranking transaction. + +The migration gives each founder one holding: the founder of an organization is the account of its earliest membership, which is the creator's owner membership, and the holding is dated by its first organization. The rollback refuses while a holding groups several organizations, because the schema without holdings could not keep their E0 pool together. Merging holdings of different owners is out of scope. + ## Verification +`TestHoldings` in `backend/integration_test/holding_test.go` covers the shared E0 pool of two organizations of one account with a verified organization apart, a second account's own holding, usage leaving the pool when its organization is raised, concurrent reservations from two organizations that never exceed the shared limits, concurrent creations ending in one holding, and a refused creation of an unknown founder. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` in `backend/integration_test/holding_migration_test.go` covers the backfill and the guarded rollback. + `TestCompanyQuota` in `backend/integration_test/company_quota_test.go` exercises the real PostgreSQL adapter in an isolated database. It checks concurrent E0 reservations, E0/E1 boundaries, exact window cutoffs and `RetryAt`, same-ID invitation reuse, cross-request card-view reuse, monotonic refresh, rollback, policy or organization snapshot changes, an allowed reservation with an active E2 policy and stored E2 verification, rejection of a forged E2 snapshot for a stored E0 company, inactive E2 and E3 denial, and candidate-deletion cleanup. It does not test a delivered invitation because that workflow is not implemented. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index f3e6653..7749868 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -467,7 +467,7 @@ Offsets и партиции. Каждый обработчик - один уча | Раздел | Значения | | --- | --- | | `invitations` | варианты срока ответа 3, 7 и 14 дней, по умолчанию 7; не более 20 ожидающих приглашений на одну потребность; повтор после отказа через 30 дней; предложение интервью в течение 5 рабочих дней; пауза 30 дней после контакта без сделки | -| `organization_quotas` | скользящие окна 7 дней для приглашений и 24 часа для просмотров разных карточек; E0 10 приглашений и 50 просмотров, E1 40 и 150, E2 100 и 400; E2 неактивен, пока нет верификации организаций, которая его дает | +| `organization_quotas` | скользящие окна 7 дней для приглашений и 24 часа для просмотров разных карточек; E0 10 приглашений и 50 просмотров, E1 40 и 150, E2 100 и 400; E2 неактивен, пока нет верификации организаций, которая его дает; E0-компании одного холдинга делят общий пул, E1 и выше считают отдельно (см. [Квоты компании](COMPANY_QUOTAS.md#пул-холдинга)) | | `assessment`, начальные некалиброванные значения | повтор того же грейда через 30 дней; не более 3 попыток за 180 дней; повышение не чаще одного раза в 90 дней; подтверждение при P_G >= 0.80, высокая уверенность от 0.90; после не менее 8 оцениваемых заданий остановка при P_G >= 0.90 или <= 0.10 или SE <= 0.25; не более 23 оцениваемых заданий плюс 2 seed-задания; практика обязательна | | `identity` | токен подтверждения 24 часа; неподтвержденный аккаунт удаляется через 7 дней после последней регистрации; сессия без активности 24 часа, абсолютный срок 7 дней | | `search_status` | статус "ищу работу" подтверждается каждые 30 дней | @@ -695,7 +695,7 @@ contact_grant относится к паре кандидат-компания - Порядок и округление. Баллы - целые числа в микроединицах (шесть знаков), доли - базисные пункты, произведения точные целые, поэтому одни и те же данные и политика дают один порядок на любой платформе. `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` запускает одновременные чтения карточек, чтения доказательств и поиски одной организации и проверяет отсутствие взаимной блокировки и одну строку квоты на кандидата. +- Параллельность. Резервирования берут исключительную блокировку организации порта квоты компании. Проверка членства до них держит на той же строке только разделяемую блокировку, и два поиска одной организации взаимно блокировались бы при ее повышении, поэтому поиск сначала берет блокировку организации (`CompanyQuotaRepository.LockOrganization`, документированный порядок; это FOR NO KEY UPDATE, поэтому читатели встают в очередь друг за другом, но блокировка внешнего ключа при собственном скрытии кандидата, которое держит строку кандидата и затем требует строку организации, не блокируется, а само резервирование по-прежнему берет FOR UPDATE в той же транзакции), а оплата одной организации сериализуется. Изменение видимой когорты во время ее блокировки (`ErrConcurrentVisibilityChange`) повторяет весь поиск до трех раз, а записи неудачной попытки откатываются вместе с ней. Чтение карточки (`GetOrganizationCard`) и раздел доказательств (`AuthorizeCategoriesSection`) по той же причине берут эту исключительную блокировку первой, до любой разделяемой: до такого порядка два одновременных чтения карточек одной организации взаимно блокировались (SQLSTATE 40P01). Для компании на E0 `LockOrganization` сразу после строки организации берет блокировку ее холдинга (общий пул E0 описан в [Квотах компании](COMPANY_QUOTAS.md#пул-холдинга)), поэтому порядок остается прежним: организация, затем холдинг, и холдинг нигде не берется раньше организации. `TestMatchSearchOverHTTP` запускает одновременные чтения карточек, чтения доказательств и поиски одной организации и проверяет отсутствие взаимной блокировки и одну строку квоты на кандидата. - Принятые остаточные риски. `truncated` - один бит о размере видимого банка (он говорит, что существует больше, чем предел или лимит), а время ответа растет с банком, поэтому оба раскрывают владельцу грубый размер. Бит ограничен пределом группы, число не возвращается; риск принят для демонстрации и внесен в вопросы владельцу. - Проверки. Модульные тесты `internal/usecase/matching` (формулы с рассчитанными вручную значениями, равенства и порядок, фильтры, объяснение, обрезка и оплата вывода), `internal/domain/policy_matching_test.go` (круговой проход документа, строгость, проверка значений), `v1/matches_test.go` (отображение и ошибки) и интеграционный тест `TestMatchSearchOverHTTP` на PostgreSQL: скрытые кандидаты и две организации, потребность и ее измененные требования, повторные одинаковые ответы, Backend подтвержден и сети не подтверждены для одного handle, профиль без грейда, опубликованный настоящими операциями профиля, согласия и публикации и убранный отзывом C2, кандидат один в своей когорте, отсутствие контактов и идентификаторов в теле, оплата и история доступа за поиск, организация с лимитом меньше ее банка, предел группы, пакетное чтение доказательств, два одновременных поиска под одним лимитом, демонстрационный предел группы, таксономия политики, отказы доступа и политика без раздела. @@ -861,20 +861,22 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - `organizations`: UUIDv7 `id` (это `org_id` каждого пути организации), `name` (1-200 символов, граница снимка в согласии), `description`, `sphere` (свободный текст; таксономии в PRD нет), четыре столбца публичных контактов (`contact_website`, `contact_email`, `contact_phone`, `contact_telegram`), столбцы проверки `verification_level`, `verification_basis` и `verification_changed_at`, `version` профиля и времена. Каждый текстовый столбец имеет CHECK с тем же форматом и границами, что и контракт (без пробелов и управляющих символов по краям, сайт по `https` без учетных данных). - `organization_representatives`: `organization_id`, `ordinal` (от 0 до 9, то есть не более десяти), `name` и `job_title`; удаляется вместе со строкой организации. Список заменяется целиком при обновлении профиля. - `memberships`: UUIDv7 `id`, `organization_id`, `user_id`, `role`, `state` и времена. `UNIQUE (user_id, organization_id)` допускает одно членство на пару в любом состоянии, а `UNIQUE (organization_id, id)` - цель составных внешних ключей, которыми поздние таблицы (назначения потребностей) привязывают членство к его организации. Оба внешних ключа - `ON DELETE RESTRICT`. +- `holdings`: UUIDv7 `id` (внутренний, API его не показывает), `founder_account_id` - аккаунт, создавший первую организацию холдинга, с `UNIQUE` и внешним ключом на `users` с `ON DELETE RESTRICT`, и `created_at`. Столбец `organizations.holding_id` обязателен, ссылается на холдинг с `ON DELETE RESTRICT` и имеет индекс; миграция `00041_create_holdings.sql` заполняет его по аккаунту самого раннего членства организации. Решения: - Активный контекст. Это не атрибут серверной сессии. Организация - это `org_id` в пути, а сервер выводит право из активного членства на каждом запросе, поэтому удаление, приостановка или выход закрывают следующее чтение без чего-либо, что нужно сбрасывать. `ListMyOrganizations` - справочник, из которого клиент выбирает; запоминание последнего выбора - удобство браузера. Контекст берется только из активных членств вызывающего, а прекращенное членство сразу закрывает чтение. Переключение очищает клиентские запросы с областью организации. - Роль и состояние только в членстве. `OrganizationRole` - `owner`, `recruiter`, `hiring_manager` или `technical_expert` (2.2, Q3 и матрица FR07 в PRD), а `MembershipState` - `active`, `suspended`, `removed` или `left`; каждое задано CHECK, а не enum PostgreSQL, поэтому новое значение - изменение ограничения в миграции. Состояния `invited` нет: в 6.4 PRD `MemberInvite` - отдельная сущность, приглашение на email, у которого еще может не быть аккаунта, а строка членства появляется, когда владелец адреса его принимает. В `organizations` нет столбца роли, владельца или участника (интеграционный тест читает каталог, чтобы это доказать), а в `Organization`, `OrganizationCreate` и `OrganizationUpdate` нет такого поля. Компанией управляет только владелец (`OrganizationRole.CanManageOrganization`); остальная матрица применяется операциями, которыми она управляет, а в MVP остальные роли ничего не дают. - Уровень проверки. `verification_level` - от `e0` до `e3` с `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), а один CHECK связывает каждый уровень с его основаниями. Столбцы отделены от профиля: `UpdateOrganizationProfile` никогда их не называет, `domain.NewOrganization` не может выбрать уровень и начинает каждую организацию с `e0` на основании `confirmed_email`, `Organization.ApplyProfile` сохраняет проверку, а в контракте нет операции или поля запроса, которые ее задают. Тест обновляет профиль после того, как процесс сдвинул уровень, и проверяет, что он остается. E1-E3 задаются процессами проверки, которых еще нет; запланированный процесс проверки добавляет E0/E1 с доказательствами, областью действия и историей только на добавление и будет обновлять эти столбцы вместе со строкой истории, а сначала обязан записать историю из текущей строки каждой существующей организации (уровень, основание и время как сохранены), чтобы в истории не было разрыва до первого процесса. `OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням квот продуктовой политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику (механизм квот читает ступень и обязан отказывать по умолчанию для организации с `e3`: квота не выдается, действие отклоняется, возврата на другую ступень нет). +- Холдинг. Организации одного аккаунта-основателя образуют холдинг. `CreateWithOwner` в той же транзакции сохраняет организацию в холдинге владельца и создает холдинг при первой организации аккаунта (`INSERT ... ON CONFLICT (founder_account_id) DO NOTHING`, затем чтение), поэтому параллельные создания одного аккаунта дают один холдинг. Холдинг не несет профиля и прав: он задает только область общего пула E0 квот (приглашения и просмотры карточек). Число организаций на аккаунт не ограничено; слияние холдингов разных владельцев не моделируется. Правила пула и блокировок - в [Квотах компании](COMPANY_QUOTAS.md#пул-холдинга). - У организации есть владелец. Отложенный constraint trigger (`organizations_owner_required`, SQLSTATE 23514) при фиксации отказывает организации без членства `owner` в состоянии `active`, поэтому создание организации без владельца падает, каким бы кодом ее ни вставили, а `CreateWithOwner` сохраняет организацию, представителей и владельца в одной транзакции. Удаление или понижение последнего владельца позже - правило управления участниками, а не этого ограничения, которое иначе блокировало бы решение платформы о недобросовестной организации. - Обновление. `UpdateProfile` - один оператор, который применяется только когда сохраненная версия равна версии, прочитанной вызывающим, и увеличивает ее на единицу. Тот же оператор требует активного членства исполнителя с управляющей ролью (роли берутся из `domain.ManagerRoles`, а не из SQL), поэтому членство, закончившееся после чтения вызывающего, все равно останавливает запись. Если оператор ничего не нашел, адаптер читает членство и отвечает `ErrOrganizationNotFound` (неизвестная организация или нет активного членства), `ErrOrganizationManagerRequired` или `ErrOrganizationVersionConflict` в этом порядке, поэтому устаревшая версия ничего не сообщает постороннему. Затем список представителей заменяется в той же транзакции под блокировкой строки обновления. Оператор блокирует строку организации (`FOR UPDATE`), а затем строку членства исполнителя `FOR SHARE`, поэтому отзыв, зафиксированный, пока оператор ждет блокировку членства, проверяется заново и останавливает запись (интеграционный тест держит отзыв открытым, ставит обновление за ним в очередь и фиксирует отзыв). Порядок блокировок у каждого писателя: сначала организации, затем членства; управление участниками, которое меняет членство и организацию вместе, и tenant-репозиторий обязаны брать блокировки в этом порядке, иначе две транзакции могут взаимно заблокироваться. - Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала согласий создавать настоящие организации, а ключу `invitation_id` нужны настоящие приглашения; оба появятся с принятием приглашения, первым писателем строк C4 с настоящим приглашением. Таблицы приглашений (миграция 00037) и потребности ссылаются на организации, аккаунты и версии политики с `ON DELETE RESTRICT`, поэтому организацию с потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD). -- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять ограниченной очисткой после окна повтора; физическое удаление может произойти позже при возобновлении создания организаций; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (для создания организаций и применения квот нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации). +- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять ограниченной очисткой после окна повтора; физическое удаление может произойти позже при возобновлении создания организаций; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и решение владельца о числе организаций на аккаунт (лимита нет, E0-квоты холдинга общие) описаны в [api/README.md](../../api/README.md#организации). Что гарантируют порты (`outbound.OrganizationRepositories`, доступны только через `UnitOfWork`, потому что запись требует транзакции): -- `Organizations().CreateWithOwner` сохраняет организацию и членство владельца и проверяет, что владелец - активное членство `owner` именно этой организации. Неизвестный аккаунт возвращает `ErrUserNotFound` и прерывает внешнюю транзакцию. +- `Organizations().CreateWithOwner` сохраняет организацию и членство владельца и проверяет, что владелец - активное членство `owner` именно этой организации. Организация попадает в холдинг аккаунта владельца; холдинг создается в той же транзакции, если его еще нет. Неизвестный аккаунт возвращает `ErrUserNotFound` и прерывает внешнюю транзакцию. - `GetForMember` читает организацию, ее представителей (собранных в JSON тем же оператором) и активное членство вызывающего из одного снимка и возвращает их либо `ErrOrganizationNotFound` одинаково для неизвестной организации, аккаунта без членства и участника в состоянии `suspended`, `removed` или `left`. `ListForUser` постранично отдает активные организации одного аккаунта от нового членства к старому с идентификатором организации как разрешением ничьей. `UpdateProfile` описан выше. - `Memberships().Insert` возвращает `ErrMembershipExists` для повторной пары в любом состоянии, `ErrOrganizationNotFound` для неизвестной организации и `ErrUserNotFound` для неизвестного аккаунта; `Get` возвращает членство в любом состоянии или `ErrMembershipNotFound`, а вызывающий проверяет `GrantsAccess`. Метода, который меняет роль или состояние, пока нет. @@ -941,13 +943,13 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове ### Черновики приглашений -Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет; отправка описана в [Отправке приглашений](#отправка-приглашений). Отзыв, повышение вилки, чтение контактов, принятие и отмена участия после общих проверок по-прежнему отвечают 501; чтение, просмотр и отказ кандидата описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата). Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`. +Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет; отправка описана в [Отправке приглашений](#отправка-приглашений). Отзыв, повышение вилки, чтение контактов и отмена участия после общих проверок по-прежнему отвечают 501; чтение, просмотр, отказ и принятие кандидата описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата) и [Принятии кандидатом](#принятие-кандидатом). Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`. Таблицы: - `invitations`: UUIDv7 `id`, `organization_id`, внутренний `candidate_id` (его не сериализуют, не логируют и не печатают), необязательная связь с потребностью (`need_id` с `need_requirements_version`, привязанные составными внешними ключами к сохраненной версии потребности той же организации), `state` (все четырнадцать состояний контракта, поэтому последующим операциям не нужно менять ограничение), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7 или 14), `policy_version_id` (версия продуктовой политики, разрешившая срок), `response_deadline_at`, `salary_raise_used`, `created_by`, а также `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. Ограничения CHECK связывают дедлайн с доставкой (оба заданы или оба null), оставляют черновик без доставки, просмотра, ответа и повышения и связывают причину истечения с состоянием. Триггер хранит неизменными столбцы идентичности, требует, чтобы каждый UPDATE увеличивал `version` ровно на единицу, а `terms_version` не более чем на единицу, и не дает отменить повышение или сдвинуть доставку, дедлайн и срок после доставки. Второй триггер запрещает DELETE. Внешние ключи на организации, аккаунты и версии политики - `ON DELETE RESTRICT`, поэтому аккаунт с приглашениями нельзя удалить, пока процедура удаления их не закроет. - `invitation_terms_versions`: `(invitation_id, version)`, условия в виде снимка JSONB и вилка еще раз в типизированных столбцах (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Ограничения повторяют денежные правила в целых числах: обе границы от 1000 до 100 000 000 рублей с шагом 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` и `5 * (B - A) <= A + B` (ширина 10-40% от середины), RUB, месяц и `net` или `gross`. Снимок обязан содержать все двенадцать условий, а его вилка - совпадать с типизированными столбцами. Триггер запрещает UPDATE и DELETE: версия условий неизменяема, изменение добавляет следующую версию. Приглашение указывает на текущую версию отложенным составным внешним ключом, поэтому первая версия вставляется в той же транзакции. -- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created`, `draft_updated`, с миграции 00038 `delivered`, с миграции 00039 `viewed` и `declined`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются. +- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created`, `draft_updated`, с миграции 00038 `delivered`, с миграции 00039 `viewed` и `declined`, с миграции 00040 `accepted`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются. - `invitation_creation_results`: исходный ответ идемпотентного создания, привязанный к общей записи идемпотентности и удаляемый вместе с ней. В нем условия, псевдоним и нет идентификатора кандидата. Решения: @@ -962,7 +964,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Блокировки. Создание и изменение сначала берут исключительную блокировку организации (`CompanyQuotaRepository.LockOrganization`), как чтение карточки и поиск, и только потом разделяемую блокировку проверки членства, блокировки когорты при создании или блокировку строки приглашения при изменении. Поэтому команды одной организации встают в очередь, а не блокируют друг друга при повышении блокировки, и следующая команда, которая тоже списывает ресурсы организации, например отправка, сохраняет тот же порядок. Изменение блокирует строку приглашения отдельным запросом (`LockInvitation`) и читает ее после: блокирующее чтение с соединением таблицы условий после ожидания чужой фиксации сопоставило бы новый `terms_version` со строкой условий, взятой до ожидания, и ничего не нашло бы. Создание повторяется ограниченное число раз, если видимая когорта изменилась во время блокировки. - Индикатор. `salary_fit` всегда `not_available`, а `contact_access` - `not_granted` без полей. Индикатору нужен минимум кандидата, а его вычисление до появления лимита из трех установок в день и семидневного отключения позволило бы организации подбирать минимум правками черновика, поэтому пока не считается и не применяется ни то ни другое. -Как подключаются следующие операции: правила пары читают индекс по организации и кандидату. Контактное разрешение, ключ C4 на `invitations` и ключи журнала согласий на `organizations` и `invitations` появятся вместе с принятием, первым писателем строк C4 с настоящим приглашением. +Как подключаются следующие операции: правила пары читают индекс по организации и кандидату. Контактное разрешение появляется с принятием ([Принятие кандидатом](#принятие-кандидатом)). Колонки C4 журнала согласий пока не имеют внешних ключей на `organizations` и `invitations`; это последующая задача. Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, предел ожидающих приглашений на потребность, повышение, отзыв, сторона кандидата сверх списка приглашений, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована. @@ -997,16 +999,34 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Приватность отказа. Организация читает только `declined` и `responded_at`: ни одна ее операция не читает `invitation_declines`, а событие аудита не называет причину. Комментарий не логируется, не попадает в уведомления и не копируется в сохраненный исход; кандидат читает причину и комментарий обратно в `decline`. - Порядок проверок после границы: кандидат (403), ключ (422 или повтор), приглашение (404, сохраняется), тот же отказ на отклоненном приглашении (200 с новым ключом или старой версией), другая причина или комментарий на отклоненном приглашении, иное терминальное состояние или прошедший срок (409 при любой версии, сохраняется), версия (412, не сохраняется), затем состояние без открытого ответа (409, сохраняется). `invitation_decline_results` хранит только исход и приглашение: отклоненное приглашение и его отказ не меняются, поэтому повтор собирает тот же ответ, а комментарий хранится в одном месте. - Срок. Истечение пока не реализовано, поэтому ни чтение, ни команда не выполняют переход в `expired`. Просмотр в момент срока и позже ничего не меняет, а отказ в момент срока и позже отвечает 409 `state_conflict`, как контракт требует для опоздавшей команды; приглашение остается `delivered` или `viewed` с прошедшим сроком, пока не появится истечение. Условные UPDATE повторяют проверку срока, поэтому команда не пересечет его между проверкой и записью. -- Согласие и разрешение. Принятие не реализовано, поэтому принять приглашение сейчас нельзя, и `contact_consent` и `contact_grant` всегда null, как требует контракт, когда принятие невозможно. Оба поля появятся вместе с `AcceptMyInvitation`. +- Согласие и разрешение. Отказ не создает ни согласия, ни разрешения, поэтому после отказа `contact_consent` и `contact_grant` равны null. Принятие описано в [Принятии кандидатом](#принятие-кандидатом). - Скрытие. Чтение кандидата показывает организацию-отправителя и после того, как кандидат скрыл от нее профиль: скрытие не дает организации видеть кандидата, а кандидату нужно знать, кто прислал предложение, чтобы ответить. Исходящее содержимое, наоборот, следует скрытию: уведомление о приглашении во входящих теряет содержимое (`ResolveInvitationNotice`). - Блокировки. Команда кандидата блокирует только строку приглашения (`LockCandidateInvitation`) после собственной записи идемпотентности кандидата и никогда не блокирует организацию. Команда организации берет сначала блокировку организации, а потом строку приглашения, поэтому порядки не пересекаются: команда кандидата не ждет блокировку организации, удерживая строку. - Правила базы миграции 00039: виды событий `viewed` и `declined` без измененных полей; `invitations_answer_matches_state` (у доставленного приглашения нет просмотра и ответа, у просмотренного есть просмотр, у отклоненного есть ответ, и ни то ни другое не раньше доставки); триггер `invitations_guard_answer`, который не дает сдвинуть или отменить просмотр или ответ и выйти из `declined`; `invitation_declines` с известными причинами, границей комментария, триггером, который привязывает строку к отклоненному приглашению с тем же моментом ответа, и запретом UPDATE и DELETE; отложенный ограничивающий триггер `invitations_require_decline`, чтобы отклоненное приглашение без записи отказа не зафиксировалось. Откат миграции отказывает, пока есть просмотр, отказ или сохраненный исход. - Уведомление. В контракте нет вида уведомления об ответе, поэтому организация пока не получает записи во входящих о просмотре или отказе; состояние она видит в своем списке приглашений. Уведомление об ответе запланировано как изменение контракта. -Не реализовано: истечение по сроку и его применение при чтении, принятие с C4 и контактное разрешение, отмена участия, встречное предложение, которое дало бы `counter`, агрегаты причин отказа с минимальным размером группы, метрики отзывчивости, 30-дневная пауза после отказа и уведомление организации об ответе. +Не реализовано: истечение по сроку и его применение при чтении, отмена участия, встречное предложение, которое дало бы `counter`, агрегаты причин отказа с минимальным размером группы, метрики отзывчивости, 30-дневная пауза после отказа и уведомление организации об ответе. Тесты: `domain/invitation_answer_test.go` (просмотр только из `delivered` до срока, отказ из `delivered`, `viewed` и `counter`, отклонение терминальных и опоздавших приглашений, правила комментария, правила сохраненного ответа, маскирование), `usecase/invitation/answer_test.go` (чтение без побочного эффекта, сохранение срока, повторы, порядок проверок, чужие вызывающие, неверные комментарии), `adapter/primary/http/v1/invitation_candidate_test.go` (статусы и ответ без данных кандидата) и интеграционные `TestCandidateInvitationViewAndDeclineOverHTTP` (чтение и просмотр с тем же сроком, одновременные просмотры с одним событием, отказ с `other` без комментария и без согласия C4, сохраненное событие ответа, повторы и конфликты, комментарий скрыт от организации и аудита, чужие кандидаты и работодатели, CSRF и Origin, скрытие, устаревшая версия, опоздавшая команда) и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`. +### Принятие кандидатом + +Реализовано: `AcceptMyInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Код: `domain/invitation_answer.go` (`Accept`), `domain/contact_grant.go`, `usecase/invitation/accept.go` и `view.go` (вид кандидата с предложением согласия и разрешением), `usecase/consent` (`GrantContact`, запись C4), HTTP-обработчик `adapter/primary/http/v1/invitation_candidate.go`, адаптер `adapter/secondary/postgres/invitation_accept.go` с `db/queries/invitation_answers.sql` и `db/queries/contact_grants.sql`, миграция `00040_accept_invitations.sql`. + +- Одна транзакция. Кандидат принимает текущие условия с согласием C4 из `delivered` или `viewed` до срока, при версии приглашения и версии условий, которые он прочитал. Транзакция берет собственную запись идемпотентности, затем только строку приглашения (`LockCandidateInvitation`) и далее по порядку: переводит приглашение в `accepted` одним условным UPDATE (`responded_at` - время ответа, `version` плюс один; срок и условия сохраняются), записывает согласие C4 в журнал согласий через `consent.Service.GrantContact` (опубликованный текст, название организации в том виде, в котором его показали, выбранные поля, приглашение и его версия условий), сохраняет разрешение ровно на эти поля и добавляет событие аудита `accepted`, которое не называет полей. Сбой любого шага откатывает всю транзакцию. +- Порядок проверок. Порядок контракта: кандидат (403), ключ (422 или повтор), приглашение (404, сохраняется), повтор принятого приглашения (200), терминальное состояние или прошедший срок (409 `state_conflict`, сохраняется), версии (412 `version_conflict`, не сохраняется), любое состояние, кроме `delivered` и `viewed` (409, сохраняется), правила согласия (400 по указателю `/consent_c4/text_version` для текста, который не опубликован, и `/consent_c4/fields/N` для вида контакта, которого нет в профиле). Вид считается имеющимся, если профиль хранит его как подтвержденный claim; предположение, которое никто не подтвердил, не раскрывается. +- Повторы. Принятое приглашение, у которого разрешение имеет ту же версию условий и тот же набор полей, отвечает 200 тем же приглашением под тем же или новым ключом и при более старом `expected_version`, и ничего не записывает. Другая версия условий или другой набор полей отвечают 409 `state_conflict` и сохраняются под ключом. Исходы под ключом: `accepted`, `not_found`, `state_conflict`; устаревшая версия и отказ по согласию не сохраняются. +- Разрешение. `contact_grants` хранит организацию, кандидата, исходное приглашение (одно разрешение на приглашение), запись согласия (одну на разрешение), канонический набор полей, версию условий, версию текста согласия, время выдачи и отметку отзыва (`revoked_at` и `revocation_reason`). Эта задача отметку не ставит; отзыв - отдельная операция. Составные внешние ключи связывают разрешение с приглашением той же организации и того же кандидата и с записью C4 того же субъекта, организации, приглашения и версии условий. Триггер проверяет, что поля, версия текста и время выдачи совпадают с записью; второй триггер запрещает DELETE и любое изменение, кроме одной отметки отзыва. Отложенный триггер ограничения не дает зафиксировать принятое приглашение без разрешения. Разрешение хранит виды контактов, но не их значения. +- Вид кандидата. Пока принятие возможно, `contact_consent` содержит отрисованный текст C4 и виды, которые есть в профиле, в порядке контракта; ничего не выбрано заранее. Поле равно null, если в профиле нет подтвержденного вида. После принятия `contact_grant` содержит выбранные виды, статус, версию условий, версию текста согласия и `readable`. `readable` истинно только тогда, когда организация может читать профиль сейчас: публикация действует и кандидат не скрыл организацию. Иначе `blocked_by` равно `visibility`. У отказанного приглашения оба поля равны null. +- Решение о видимости. Принятие разрешено, пока профиль скрыт от организации или не опубликован, как показывает пример контракта с заблокированным разрешением. Принятие не публикует профиль, не меняет публикацию и не снимает и не добавляет скрытие. Разрешение остается сохраненным и станет читаемым, когда кандидат опубликует профиль или уберет скрытие организации: `readable` пересчитывается при каждом чтении, поэтому само разрешение не меняется. Чтение контактов через разрешение - отдельная операция; организация по-прежнему видит `contact_access` как не выданный. +- Конкурентность. Командой кандидата блокировка организации не берется. Два конкурентных принятия одной версии дают один переход: второе ждет строку и затем отвечает как повтор - 200 тем же ответом при тех же условиях и полях и 409 при другом наборе полей. +- Часы. Время ответа берется у сервиса приглашений, время выдачи разрешения - у сервиса согласий. В продакшене оба читают часы процесса, поэтому могут расходиться на микросекунды; разрешение сохраняет время согласия. Повтор сохраненного принятия восстанавливает ответ из приглашения и разрешения. Таблица исходов не хранит копию ответа, поэтому позднее изменение состояния было бы видно в повторе, как и для отказа. +- Ключи журнала. Колонки C4 в журнале согласий пока не имеют внешних ключей на `organizations` и `invitations`: тесты журнала пишут записи C4 с синтетическими идентификаторами. Составные ключи разрешения сохраняют согласованность принятия без этой правки; ключи журнала требуют фикстур с настоящими приглашениями и остаются последующей задачей. + +Не реализовано: чтение контактов через разрешение, отзыв разрешения (после закрытия публикации, скрытия, отзыва согласия или отмены участия), встречное предложение, истечение по сроку и отмена участия. + +Тесты: `domain/contact_grant_test.go` (разрешение из записи согласия, правила области и отзыва, вид видимости, отрисовка предложения и `Accept`), `usecase/invitation/accept_test.go` (порядок проверок, повторы, устаревшие условия, поздние команды, указатели согласия, видимость без изменения публикации), `adapter/primary/http/v1/invitation_candidate_test.go` (коды отказов) и интеграционные `TestCandidateInvitationAcceptOverHTTP` (разрешение только на email, повторы и конфликты, устаревшие и поднятые условия, конкурентные принятия, скрытый профиль, поздний ответ, проверки согласия и видов, журнал сервера) и `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` на настоящем PostgreSQL. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности. diff --git a/docs/ru/COMPANY_QUOTAS.md b/docs/ru/COMPANY_QUOTAS.md index 16dbab0..725fa72 100644 --- a/docs/ru/COMPANY_QUOTAS.md +++ b/docs/ru/COMPANY_QUOTAS.md @@ -14,9 +14,9 @@ Вызывайте `companyquota.Service.ReserveInvitation` или `ReserveCardView`, передавая репозитории текущего `outbound.UnitOfWork`. Репозиторий из `UnitOfWork.CompanyQuotas()` привязан к транзакции и не должен сохраняться после нее. Резервирование квоты и связанное с ним бизнес-изменение выполняются в одной транзакции, чтобы откат отменял обе записи. Сервис создается с часами приложения и один раз читает действующую политику на операцию. -Проверка доступа к компании остается ответственностью вызывающего кода. В той же транзакции нужно повторно проверить активное членство и права владельца. Писатели соблюдают такой порядок блокировок: компания, активное членство, запись приглашения или видимости, затем использование квоты. Адаптер квот первым блокирует строку компании; вызывающий код может повторно заблокировать ту же строку в этой транзакции. Не меняйте этот порядок на обратный. +Проверка доступа к компании остается ответственностью вызывающего кода. В той же транзакции нужно повторно проверить активное членство и права владельца. Писатели соблюдают такой порядок блокировок: компания, для компании на E0 - ее холдинг (см. [Пул холдинга](#пул-холдинга)), активное членство, запись приглашения или видимости, затем использование квоты. Адаптер квот первым блокирует строку компании, а для компании на E0 сразу после нее - строку холдинга; вызывающий код может повторно заблокировать эти строки в этой транзакции. Не меняйте этот порядок на обратный. -Блокировка компании сериализует параллельные резервирования. Пока она удерживается, адаптер проверяет существующую запись, считает активное окно и добавляет или обновляет использование. Решение либо разрешает операцию, либо запрещает ее; повторное использование означает разрешение. При отказе запись использования не создается, а `RetryAt` содержит ближайший момент освобождения места по истечении активной записи. +Блокировка компании сериализует параллельные резервирования одной компании, а блокировка холдинга сериализует общий пул E0. Пока они удерживаются, адаптер проверяет существующую запись, считает активное окно и добавляет или обновляет использование. Решение либо разрешает операцию, либо запрещает ее; повторное использование означает разрешение. При отказе запись использования не создается, а `RetryAt` содержит ближайший момент освобождения места по истечении активной записи. ## Окна и повторы @@ -24,10 +24,24 @@ Просмотр карточки определяется парой `(organization_id, candidate_id)`. Повторный просмотр того же кандидата в активном окне не расходует еще один слот уникального просмотра. Время `last_seen_at` обновляется монотонно: часы приложения, переведенные назад, не уменьшают сохраненное время. -Для активного окна используется строгое сравнение с границей. Запись ровно в момент `now - window` уже истекла. Использование приглашений считается за скользящие 7 дней, просмотры карточек - за скользящие 24 часа. Лимиты общие для запросов и пользователей компании. +Для активного окна используется строгое сравнение с границей. Запись ровно в момент `now - window` уже истекла. Использование приглашений считается за скользящие 7 дней, просмотры карточек - за скользящие 24 часа. Лимиты общие для запросов и пользователей компании; исключение - компания на E0, которая делит свои лимиты с остальными E0-компаниями своего холдинга (см. [Пул холдинга](#пул-холдинга)). Истекшие записи просмотров удаляются партиями максимум по 100 только после успешного разрешенного резервирования. Истечение окна логическое; очистка не обещает удаление в точно заданный момент. При удалении аккаунта кандидата его запись просмотра удаляется каскадно. При удалении компании удаляются обе таблицы квот. Для использования приглашений нет внешнего ключа на приглашение, поэтому будущее удаление приглашения не сможет удалить ключ идемпотентности. +## Пул холдинга + +Холдинг объединяет компании, созданные одним аккаунтом-основателем; его хранит таблица `holdings`, миграция `00041_create_holdings.sql`. `CreateWithOwner` сохраняет каждую новую компанию в холдинге аккаунта-владельца в той же транзакции. Холдинг аккаунта создается с его первой компанией, а параллельные создания одного аккаунта дают один холдинг: вставка игнорирует уже существующий ключ основателя, а затем транзакция читает сохраненный холдинг. Холдинг не несет ни профиля, ни права; его единственный эффект - общий пул E0. + +Лимиты E0 (в подключенной демо-политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа) общие для E0-компаний одного холдинга. Резервирование E0 считает строки использования всех компаний холдинга, чей уровень проверки в момент подсчета равен E0. Каждая строка использования остается за компанией, которая ее потребила, а использование компании, которая уже не E0, выходит из общего пула. Компания на E1 и выше считает только свое использование и имеет собственный пул, поэтому ее использование не входит в пул E0. + +Идемпотентность остается на уровне компании. Тот же ID приглашения или повторный просмотр одного кандидата той же компанией внутри окна не списываются второй раз. Один кандидат, просмотренный двумя компаниями одного холдинга, - два списания общего пула. + +Блокировки: для компании на E0 `CompanyQuotaRepository.LockOrganization` и каждое резервирование берут строку холдинга с `FOR NO KEY UPDATE` сразу после строки компании. Поэтому резервирования одного пула идут друг за другом, а второе считает использование, которое первое уже зафиксировало: подсчет начинается после блокировки холдинга. Каждый писатель берет блокировку компании раньше блокировки холдинга, а ни один код не берет блокировку компании, удерживая блокировку холдинга, поэтому блокировка холдинга не добавляет цикл в документированный порядок. Цена: поиски E0, чтения карточек и черновики или отправки приглашений одного холдинга ждут друг друга, пока открыты их транзакции; поиск держит блокировку на всю транзакцию ранжирования. + +Миграция дает каждому основателю один холдинг: основатель компании - аккаунт ее самого раннего членства, то есть владельца, созданного вместе с компанией, а холдинг датируется первой компанией. Откат отказывает, пока холдинг объединяет несколько компаний, потому что схема без холдингов не сохранила бы их общий пул E0. Слияние холдингов разных владельцев не входит в объем. + ## Проверки +`TestHoldings` в `backend/integration_test/holding_test.go` проверяет общий пул E0 двух компаний одного аккаунта при отдельном пуле компании на E1, отдельный холдинг второго аккаунта, выход использования из пула при повышении компании, параллельные резервирования двух компаний, которые никогда не превышают общий лимит, параллельные создания, заканчивающиеся одним холдингом, и отказ создания с неизвестным основателем. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` в `backend/integration_test/holding_migration_test.go` проверяет заполнение и защищенный откат миграции. + `TestCompanyQuota` в `backend/integration_test/company_quota_test.go` проверяет настоящий адаптер PostgreSQL на изолированной базе. Тест покрывает параллельные резервирования E0, границы E0 и E1, точные границы окон и `RetryAt`, повтор того же ID приглашения, повторный просмотр в рамках компании, монотонное обновление, откат, изменение снимка политики или компании, разрешенное резервирование при включенной E2 и сохраненной проверке компании, отказ для поддельного снимка E2 при сохраненном E0, отказ для выключенной E2 и E3, а также очистку после удаления кандидата. Проверки доставки приглашения нет, поскольку этот процесс пока не реализован.