From 1a067221f7c9be818de1a22f8985247030a0126c Mon Sep 17 00:00:00 2001 From: shira Date: Fri, 9 Oct 2026 16:50:36 +0300 Subject: [PATCH] feat(invitations): send invitations into the candidate inbox atomically --- api/README.en.md | 2 +- api/README.md | 2 +- api/core/components/schemas.yml | 2 +- .../schemas/notification_schemas.yml | 2 +- api/core/openapi.bundle.yml | 4 +- .../routes/organization_invitation_send.yml | 2 +- backend/README.en.md | 8 +- backend/README.md | 8 +- .../db/migrations/00038_send_invitations.sql | 117 +++ backend/db/queries/invitation_delivery.sql | 123 ++++ .../integration_test/company_quota_test.go | 67 +- .../integration_test/invitation_http_test.go | 22 +- .../invitation_send_http_test.go | 676 ++++++++++++++++++ .../integration_test/organizations_test.go | 3 +- .../primary/http/api/oas_handlers_gen.go | 3 +- .../primary/http/api/oas_schemas_gen.go | 8 +- .../primary/http/api/oas_server_gen.go | 3 +- .../primary/http/api/oas_unimplemented_gen.go | 3 +- .../adapter/primary/http/v1/invitation.go | 152 +++- .../primary/http/v1/invitation_cursor.go | 80 ++- .../primary/http/v1/invitation_test.go | 70 ++ .../secondary/postgres/invitation_delivery.go | 253 +++++++ .../postgres/sqlc/invitation_delivery.sql.go | 336 +++++++++ .../adapter/secondary/postgres/sqlc/models.go | 8 + .../secondary/postgres/sqlc/querier.go | 15 + backend/internal/bootstrap/invitation.go | 32 +- backend/internal/domain/invitation.go | 12 + .../internal/domain/invitation_delivery.go | 123 ++++ .../domain/invitation_delivery_test.go | 92 +++ backend/internal/port/outbound/invitations.go | 82 ++- .../usecase/invitation/candidate_inbox.go | 85 +++ backend/internal/usecase/invitation/send.go | 346 +++++++++ .../internal/usecase/invitation/send_test.go | 180 +++++ .../internal/usecase/invitation/service.go | 37 +- .../usecase/invitation/service_test.go | 102 ++- .../usecase/notification/inbox_content.go | 13 +- .../usecase/notification/inbox_test.go | 106 ++- .../usecase/notification/invitation.go | 122 ++++ docs/en/ARCHITECTURE.md | 38 +- docs/en/TESTING.md | 2 +- docs/ru/ARCHITECTURE.md | 38 +- docs/ru/TESTING.md | 2 +- .../api/endpoints/invitation/invitation.ts | 2 +- .../schemas/notification/notification.zod.ts | 2 +- .../notification/notificationKind.zod.ts | 2 +- .../notification/notificationList.zod.ts | 2 +- 46 files changed, 3276 insertions(+), 113 deletions(-) create mode 100644 backend/db/migrations/00038_send_invitations.sql create mode 100644 backend/db/queries/invitation_delivery.sql create mode 100644 backend/integration_test/invitation_send_http_test.go create mode 100644 backend/internal/adapter/secondary/postgres/invitation_delivery.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/invitation_delivery.sql.go create mode 100644 backend/internal/domain/invitation_delivery.go create mode 100644 backend/internal/domain/invitation_delivery_test.go create mode 100644 backend/internal/usecase/invitation/candidate_inbox.go create mode 100644 backend/internal/usecase/invitation/send.go create mode 100644 backend/internal/usecase/invitation/send_test.go create mode 100644 backend/internal/usecase/notification/invitation.go diff --git a/api/README.en.md b/api/README.en.md index fb26547..04c6837 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)). 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)). 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 | | --- | --- | --- | --- | --- | diff --git a/api/README.md b/api/README.md index 1397d5e..6067feb 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#черновики-приглашений)). Бизнес-логика остальных операций еще не реализована: гость получает 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#отправка-приглашений)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index f9ee518..c517ee1 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -6037,7 +6037,7 @@ NotificationKind: description: 'Which event put the notification into the inbox. The inbox stores a reference to the event, never its text. - - invitation_delivered: an invitation reached the candidate''s inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet. + - invitation_delivered: an invitation reached the candidate''s inbox. It does not depend on any email, and a failed or missing email never blocks it. The send of an invitation produces it through the outbox, so the notice appears shortly after the commit of the send, while the invitation itself is in ListMyInvitations from that commit. - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action. diff --git a/api/core/components/schemas/notification_schemas.yml b/api/core/components/schemas/notification_schemas.yml index 8dc4739..48fa86e 100644 --- a/api/core/components/schemas/notification_schemas.yml +++ b/api/core/components/schemas/notification_schemas.yml @@ -4,7 +4,7 @@ schemas: description: |- Which event put the notification into the inbox. The inbox stores a reference to the event, never its text. - - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet. + - invitation_delivered: an invitation reached the candidate's inbox. It does not depend on any email, and a failed or missing email never blocks it. The send of an invitation produces it through the outbox, so the notice appears shortly after the commit of the send, while the invitation itself is in ListMyInvitations from that commit. - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action. Adding a value is a contract change; a client shows an unknown kind with the generic text of an item without content. diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index ae40eef..19401ec 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -2013,7 +2013,7 @@ paths: Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. - The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. Enforcement of the pending limit and the organization quota is planned. + The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are not checked yet. Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. @@ -9898,7 +9898,7 @@ components: description: |- Which event put the notification into the inbox. The inbox stores a reference to the event, never its text. - - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet. + - invitation_delivered: an invitation reached the candidate's inbox. It does not depend on any email, and a failed or missing email never blocks it. The send of an invitation produces it through the outbox, so the notice appears shortly after the commit of the send, while the invitation itself is in ListMyInvitations from that commit. - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action. Adding a value is a contract change; a client shows an unknown kind with the generic text of an item without content. diff --git a/api/core/routes/organization_invitation_send.yml b/api/core/routes/organization_invitation_send.yml index b08c8b6..513857f 100644 --- a/api/core/routes/organization_invitation_send.yml +++ b/api/core/routes/organization_invitation_send.yml @@ -6,7 +6,7 @@ post: Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. - The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. Enforcement of the pending limit and the organization quota is planned. + The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are not checked yet. Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. diff --git a/backend/README.en.md b/backend/README.en.md index 2a3beff..5c1cf13 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -34,7 +34,7 @@ Revoking C2 makes the publication effectively closed and hides its fields throug `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}`, and `PATCH /api/v1/organizations/{org_id}` are implemented. A verified employer creates the organization and its active owner membership in one transaction, starting at `e0` with basis `confirmed_email`. Every read checks active owner membership. Only the active owner can edit; the version advances on change and the verification level is preserved. -The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Invitation routes enforce the common owner check; the draft operations are described under [Invitation drafts](#invitation-drafts), and the other invitation operations answer 501 after that check. +The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Invitation routes enforce the common owner check; the draft operations and the send are described under [Invitation drafts](#invitation-drafts), and the other organization invitation operations answer 501 after that check. `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. @@ -56,7 +56,7 @@ Migration `00026_create_organization_need_creation_results.sql` adds create-resp ## Invitation drafts -The organization side of the invitation draft is implemented: `GET` and `POST /api/v1/organizations/{org_id}/invitations` and `GET` and `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` (`usecase/invitation/`, `adapter/primary/http/v1/invitation.go`). Sending, withdrawal, the salary raise, the contact read, and the candidate operations still answer 501 after the common owner check. A draft is invisible to the candidate and writes no inbox row, event, or quota usage. +The organization side of the invitation draft is implemented: `GET` and `POST /api/v1/organizations/{org_id}/invitations` and `GET` and `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` (`usecase/invitation/`, `adapter/primary/http/v1/invitation.go`). Withdrawal, the salary raise, the contact read, and the candidate operations other than the list still answer 501 after the common checks. A draft is invisible to the candidate and writes no inbox entry, event, or quota usage. Migration `00037_create_invitations.sql` adds `invitations`, the immutable `invitation_terms_versions`, the append-only `invitation_events` (one audit event for each committed version), and `invitation_creation_results` (the original response of an idempotent create). Money is whole rubles in `bigint`; `domain.SalaryRange` is the one implementation of the range rule for needs and invitations, and the terms table repeats it in constraints (bounds and step, `A < B`, a width of 10% to 40% in integer arithmetic), so no other writer can store a range the API refuses. A change of the terms appends the next terms version; the earlier one cannot be updated or deleted. The candidate is stored as an internal `candidate_id` and shown only as the organization-scoped card handle. The down migration refuses while any invitation exists and never deletes one. The tables, decisions, locks, and what is not implemented are in [architecture](../docs/en/ARCHITECTURE.md#invitation-drafts); the contract is in [api/README.en.md](../api/README.en.md#invitations-and-contact-grants). @@ -64,6 +64,8 @@ Migration `00037_create_invitations.sql` adds `invitations`, the immutable `invi The integration tests `TestOrganizationInvitationDraftsOverHTTP` (the router, sessions, CSRF, cohort and hiding fixtures, money boundaries, package conditions, handle refusals, replay, anti-enumeration, listing and cursors, versions and immutable terms, need links, the state conflict, concurrent updates, concurrent creates and updates of one organization without a deadlock, and no candidate value in responses, stored terms, or logs), `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` (the constraints and triggers by direct SQL), and `TestInvitationMigrationRollbackKeepsStoredInvitations` run against a real PostgreSQL. +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. + ## Support cases Verified accounts can create and list their own cases at `/api/v1/me/support-cases` and read a case by its ID. Ownership is independent of access to a disputed action. Object references contain only a type and ID; the server checks their scope and does not copy private object content. Employers can submit general support requests. Candidates can also request manual assessment without a prior attempt or C3 consent. Such a request waits for an expert and does not assign a grade or grant consent. @@ -145,4 +147,4 @@ The inbox stores a reference to a delivered event for one recipient (`notificati The text is resolved when the list is read (`usecase/notification/inbox.go`, `inbox_content.go`): `InboxService` authorizes the cabinet in the read transaction (a verified candidate for `GET /api/v1/me/notifications`; a verified employer with an active membership for `GET /api/v1/organizations/{org_id}/notifications`), then asks the resolver of each item's source type for the content that the recipient may see now. A source that is gone or hidden leaves the item in the list without content. The mark (`POST .../{notification_id}/read`) keeps the first read time and reads no source. A foreign, cross-organization, or unknown item answers 404. -A producer appends an `invitation.delivered` event with the payload `recipient_user_id` and `organization_id` and registers a resolver for its source; the synthetic `notification.synthetic_delivered` event exercises the path and has no product meaning. The contract is in [docs/en/ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#internal-notifications) and [api/README.en.md](../api/README.en.md#notifications); no invitation produces an event yet. +A producer appends an `invitation.delivered` event with the payload `recipient_user_id` and `organization_id` and registers a resolver for its source; the send of an invitation does so, and the synthetic `notification.synthetic_delivered` event exercises the path and has no product meaning. The contract is in [docs/en/ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#internal-notifications) and [api/README.en.md](../api/README.en.md#notifications). diff --git a/backend/README.md b/backend/README.md index 63ba982..fa7cfdc 100644 --- a/backend/README.md +++ b/backend/README.md @@ -34,7 +34,7 @@ Реализованы `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}` и `PATCH /api/v1/organizations/{org_id}`. Подтвержденный работодатель создает организацию и активное членство владельца одной транзакцией; начальный уровень - `e0` с основанием `confirmed_email`. Каждое чтение проверяет активное членство владельца. Изменять профиль может только активный владелец; версия повышается при изменении, уровень проверки сохраняется. -Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Пути приглашений защищены общей проверкой владельца; операции с черновиками описаны в разделе [Черновики приглашений](#черновики-приглашений), остальные операции приглашений после этой проверки отвечают 501. +Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Пути приглашений защищены общей проверкой владельца; операции с черновиками и отправка описаны в разделе [Черновики приглашений](#черновики-приглашений), остальные операции приглашений организации после этой проверки отвечают 501. `TestOrganizationCreationAndOwnerEditingOverHTTP` проверяет в PostgreSQL параллельный повтор, откат при ошибке вставки владельца, запрет чужого доступа, сохранение данных после пересоздания API и повторное использование истекшего ключа. @@ -56,7 +56,7 @@ ## Черновики приглашений -Реализована сторона организации в черновике приглашения: `GET` и `POST /api/v1/organizations/{org_id}/invitations` и `GET` и `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` (`usecase/invitation/`, `adapter/primary/http/v1/invitation.go`). Отправка, отзыв, повышение вилки, чтение контактов и операции кандидата после общей проверки владельца по-прежнему отвечают 501. Кандидат черновик не видит, входящую запись, событие и использование квоты он не пишет. +Реализована сторона организации в черновике приглашения: `GET` и `POST /api/v1/organizations/{org_id}/invitations` и `GET` и `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` (`usecase/invitation/`, `adapter/primary/http/v1/invitation.go`). Отзыв, повышение вилки, чтение контактов и операции кандидата, кроме списка, после общих проверок по-прежнему отвечают 501. Кандидат черновик не видит, входящую запись, событие и использование квоты он не пишет. Миграция `00037_create_invitations.sql` добавляет `invitations`, неизменяемые `invitation_terms_versions`, добавляемые только в конец `invitation_events` (одно событие аудита на каждую зафиксированную версию) и `invitation_creation_results` (исходный ответ идемпотентного создания). Деньги - целые рубли в `bigint`; `domain.SalaryRange` - единственная реализация правила вилки для потребностей и приглашений, а таблица условий повторяет ее в ограничениях (границы и шаг, `A < B`, ширина 10-40% в целых числах), поэтому другой писатель не сохранит вилку, которую API отклоняет. Изменение условий добавляет следующую версию условий; прежнюю нельзя изменить или удалить. Кандидат хранится как внутренний `candidate_id`, а показывается только handle карточки, привязанным к организации. Откат миграции отказывает, пока есть хотя бы одно приглашение, и ничего не удаляет. Таблицы, решения, блокировки и нереализованное описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#черновики-приглашений), контракт - в [api/README.md](../api/README.md#приглашения-и-контактные-разрешения). @@ -64,6 +64,8 @@ Интеграционные тесты `TestOrganizationInvitationDraftsOverHTTP` (роутер, сессии, CSRF, фикстуры когорты и скрытия, границы денег, условия пакета, отказы по handle, повтор, защита от перебора, список и курсоры, версии и неизменяемые условия, связь с потребностью, конфликт состояния, конкурентные изменения, конкурентные создания и изменения одной организации без взаимной блокировки и отсутствие значений кандидата в ответах, сохраненных условиях и логах), `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` (ограничения и триггеры прямым SQL) и `TestInvitationMigrationRollbackKeepsStoredInvitations` работают на настоящем PostgreSQL. +Реализована отправка: `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. + ## Обращения в поддержку Подтвержденные аккаунты создают и просматривают список собственных обращений через `/api/v1/me/support-cases`, а отдельное дело читают по его ID. Владение обращением не зависит от доступа к спорному действию. Ссылка на объект содержит только тип и ID; сервер проверяет область доступа и не копирует приватное содержимое объекта. Работодатели отправляют общие запросы поддержки. Кандидаты также могут запросить ручную оценку без предыдущей попытки и согласия C3. Такой запрос ожидает эксперта, не назначает грейд и не выдает согласие. @@ -144,4 +146,4 @@ Inbox хранит ссылку на доставленное событие д Текст вычисляется при чтении списка (`usecase/notification/inbox.go`, `inbox_content.go`): `InboxService` проверяет кабинет в транзакции чтения (подтвержденный кандидат для `GET /api/v1/me/notifications`; подтвержденный работодатель с активным членством для `GET /api/v1/organizations/{org_id}/notifications`), затем просит преобразователь типа источника каждого элемента дать содержимое, которое получатель вправе видеть сейчас. Исчезнувший или скрытый источник оставляет элемент в списке без содержимого. Отметка (`POST .../{notification_id}/read`) сохраняет первое время прочтения и не читает источник. Чужой элемент, элемент другой организации и неизвестный элемент дают 404. -Источник добавляет событие `invitation.delivered` с payload `recipient_user_id` и `organization_id` и регистрирует преобразователь для своего источника; синтетическое событие `notification.synthetic_delivered` проверяет путь и продуктового смысла не имеет. Контракт описан в [docs/ru/ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#внутренние-уведомления) и [api/README.md](../api/README.md#уведомления); пока ни одно приглашение не создает событие. +Источник добавляет событие `invitation.delivered` с payload `recipient_user_id` и `organization_id` и регистрирует преобразователь для своего источника; так делает отправка приглашения, а синтетическое событие `notification.synthetic_delivered` проверяет путь и продуктового смысла не имеет. Контракт описан в [docs/ru/ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#внутренние-уведомления) и [api/README.md](../api/README.md#уведомления). diff --git a/backend/db/migrations/00038_send_invitations.sql b/backend/db/migrations/00038_send_invitations.sql new file mode 100644 index 0000000..5913d68 --- /dev/null +++ b/backend/db/migrations/00038_send_invitations.sql @@ -0,0 +1,117 @@ +-- +goose Up +-- Sending an invitation. One transaction moves a draft to `delivered`, starts +-- the response deadline, charges the organization quota, appends the audit +-- event, and writes the outbox events of the notification. The send itself is +-- never a stored state: the audit event of the step is `delivered`, and it +-- changes none of the editable draft fields. +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') +); + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_delivery_changes_no_field CHECK ( + kind <> 'delivered' OR cardinality(changed_fields) = 0 +); + +-- Invitation quota usage now names a stored invitation of the same +-- organization, so a charge cannot exist without the invitation it paid for. +-- Before sending existed nothing in the product wrote this table; a row that +-- names no invitation is reported instead of being dropped. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM company_invitation_quota_usage AS usage + WHERE NOT EXISTS ( + SELECT 1 + FROM invitations + WHERE + invitations.organization_id = usage.organization_id + AND invitations.id = usage.invitation_id + ) + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'foreign_key_violation', + CONSTRAINT = 'company_invitation_quota_usage_invitation_fkey', + TABLE = 'company_invitation_quota_usage', + MESSAGE = 'invitation quota usage must name stored invitations'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE company_invitation_quota_usage +ADD CONSTRAINT company_invitation_quota_usage_invitation_fkey +FOREIGN KEY (organization_id, invitation_id) +REFERENCES invitations (organization_id, id) ON DELETE RESTRICT; + +-- Outcome of an idempotent send, kept beside the generic idempotency record +-- and removed with it after the 24-hour replay window. A successful send +-- keeps the original response; a missing invitation and a state conflict +-- keep only the outcome, as the public contract stores them under the key. +-- The invitation is intentionally not a foreign key: the outcome of a missing +-- invitation names an identifier that does not exist. +CREATE TABLE invitation_send_results ( + scope_hash bytea NOT NULL, + organization_id uuid NOT NULL, + invitation_id uuid NOT NULL, + outcome text NOT NULL, + snapshot jsonb, + CONSTRAINT invitation_send_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT invitation_send_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT invitation_send_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT invitation_send_results_outcome CHECK ( + ( + outcome = 'sent' + AND snapshot IS NOT NULL + AND jsonb_typeof(snapshot) = 'object' + AND octet_length(snapshot::text) <= 196608 + ) + OR ( + outcome IN ('not_found', 'state_conflict') + AND snapshot IS NULL + ) + ) +); + +-- +goose Down +-- A rollback must not silently remove delivery history or a stored outcome. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitation_events WHERE kind = 'delivered') + OR EXISTS (SELECT 1 FROM invitation_send_results) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_deliveries_retained', + TABLE = 'invitation_events', + MESSAGE = 'sent invitations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TABLE invitation_send_results; + +ALTER TABLE company_invitation_quota_usage +DROP CONSTRAINT company_invitation_quota_usage_invitation_fkey; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_delivery_changes_no_field; + +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') +); diff --git a/backend/db/queries/invitation_delivery.sql b/backend/db/queries/invitation_delivery.sql new file mode 100644 index 0000000..6574404 --- /dev/null +++ b/backend/db/queries/invitation_delivery.sql @@ -0,0 +1,123 @@ +-- The conditional update is the compare-and-swap of a send: it applies only to +-- a draft whose version is still the one the caller read, records the first +-- delivery with its deadline, and advances the version by one. No row is +-- returned when it lost a race or the invitation is no longer a draft. +-- name: DeliverInvitation :one +UPDATE invitations +SET + state = 'delivered', + version = sqlc.arg(next_version), + delivered_at = sqlc.arg(delivered_at), + response_deadline_at = sqlc.arg(response_deadline_at), + updated_at = sqlc.arg(delivered_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state = 'draft' + AND version = sqlc.arg(expected_version) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- One bounded page of the candidate's inbox: every invitation delivered to +-- the candidate, in any later state, newest first by delivery time. Drafts +-- have no delivery and are never listed. The candidate scopes the rows, so +-- no identifier of another candidate can appear. +-- name: ListCandidateInvitations :many +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms, + organization.name AS organization_name +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +INNER JOIN organizations AS organization + ON organization.id = invitation.organization_id +WHERE + invitation.candidate_id = sqlc.arg(candidate_id) + AND invitation.delivered_at IS NOT NULL + AND ( + sqlc.narg(after_delivered_at)::timestamptz IS NULL + OR (invitation.delivered_at, invitation.id) < ( + sqlc.narg(after_delivered_at)::timestamptz, + sqlc.narg(after_invitation_id)::uuid + ) + ) +ORDER BY invitation.delivered_at DESC, invitation.id DESC +LIMIT sqlc.arg(row_limit); + +-- Read one delivered invitation addressed to the candidate. A draft and an +-- invitation of another candidate find nothing. +-- name: ReadCandidateInvitation :one +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +WHERE + invitation.candidate_id = sqlc.arg(candidate_id) + AND invitation.id = sqlc.arg(invitation_id) + AND invitation.delivered_at IS NOT NULL; + +-- name: InsertInvitationSendResult :exec +INSERT INTO invitation_send_results ( + scope_hash, + organization_id, + invitation_id, + outcome, + snapshot +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(organization_id), + sqlc.arg(invitation_id), + sqlc.arg(outcome), + sqlc.narg(snapshot)::jsonb +); + +-- name: GetInvitationSendResult :one +SELECT + organization_id, + invitation_id, + outcome, + -- A refusal has no snapshot; the empty text stands for it. + coalesce(snapshot::text, '')::text AS snapshot +FROM invitation_send_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/integration_test/company_quota_test.go b/backend/integration_test/company_quota_test.go index 7f43289..889a5fe 100644 --- a/backend/integration_test/company_quota_test.go +++ b/backend/integration_test/company_quota_test.go @@ -31,6 +31,11 @@ type companyQuotaFixture struct { organizations organizationFixture policies outbound.PolicyRepository version domain.PolicyVersion + // invitationAuthor and invitationCandidate are the accounts of the drafts + // that invitation usage names: a charge refers to a stored invitation of + // the same organization. + invitationAuthor uuid.UUID + invitationCandidate uuid.UUID } func TestCompanyQuota(t *testing.T) { @@ -59,6 +64,8 @@ func TestCompanyQuota(t *testing.T) { 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, } t.Run("E0 shares limits across requests and concurrent final reservations", func(t *testing.T) { @@ -66,7 +73,7 @@ func TestCompanyQuota(t *testing.T) { var firstCandidate uuid.UUID var boundaryCandidate uuid.UUID for range 9 { - fixture.reserveInvitationAllowed(t, organization, uuid.New()) + fixture.reserveInvitationAllowed(t, organization, fixture.newInvitationID(t, organization)) } for index := range 49 { candidateID := fixture.newCandidateID(t) @@ -87,11 +94,12 @@ func TestCompanyQuota(t *testing.T) { results := make(chan result, 4) var workers sync.WaitGroup for range 2 { + invitationID := fixture.newInvitationID(t, organization) workers.Add(1) go func() { defer workers.Done() <-start - decision, err := fixture.reserveInvitation(organization, uuid.New()) + decision, err := fixture.reserveInvitation(organization, invitationID) results <- result{decision: decision, err: err, kind: "invitation"} }() } @@ -156,7 +164,7 @@ func TestCompanyQuota(t *testing.T) { call func(domain.Organization, uuid.UUID) (outbound.CompanyQuotaDecision, error) }{ {name: "card view at the 24-hour boundary", id: boundaryCandidate, call: fixture.reserveCardView}, - {name: "invitation remains charged during the first day", id: uuid.New(), call: fixture.reserveInvitation}, + {name: "invitation remains charged during the first day", id: fixture.newInvitationID(t, organization), call: fixture.reserveInvitation}, } { decision, err := step.call(organization, step.id) if err != nil { @@ -174,7 +182,7 @@ func TestCompanyQuota(t *testing.T) { fixture.assertQuotaRowCounts(t, organization.ID(), 10, 2) fixture.clock.Set(atDay.Add(6 * 24 * time.Hour)) - newInvitation := uuid.New() + newInvitation := fixture.newInvitationID(t, organization) decision, err := fixture.reserveInvitation(organization, newInvitation) if err != nil || !decision.Allowed || decision.Reused { t.Fatalf("ReserveInvitation(at 7 days) = %+v, %v; want a new allowed invitation", decision, err) @@ -183,7 +191,7 @@ func TestCompanyQuota(t *testing.T) { // The same invitation ID stays idempotent beyond the rolling window, // independently of any request idempotency key used by its caller. - oldInvitationID := uuid.New() + oldInvitationID := fixture.newInvitationID(t, organization) fixture.reserveInvitationAllowed(t, organization, oldInvitationID) fixture.clock.Advance(8 * 24 * time.Hour) reused, err := fixture.reserveInvitation(organization, oldInvitationID) @@ -195,9 +203,9 @@ func TestCompanyQuota(t *testing.T) { t.Run("E1 enforces the stored 40 and 150 limits", func(t *testing.T) { organization, _ := fixture.newOrganization(t, "e1-boundary", domain.OrganizationVerificationE1) for range 40 { - fixture.reserveInvitationAllowed(t, organization, uuid.New()) + fixture.reserveInvitationAllowed(t, organization, fixture.newInvitationID(t, organization)) } - deniedInvitation, err := fixture.reserveInvitation(organization, uuid.New()) + deniedInvitation, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization)) if err != nil || deniedInvitation.Allowed || !deniedInvitation.RetryAt.Equal(fixture.clock.Now().Add(7*24*time.Hour)) { t.Fatalf("E1 invitation 41 = %+v, %v; want denial for one week", deniedInvitation, err) } @@ -229,7 +237,7 @@ func TestCompanyQuota(t *testing.T) { fixture.version = activePolicy verified, _ := fixture.newOrganization(t, "active-e2", domain.OrganizationVerificationE2) - invitation, err := fixture.reserveInvitation(verified, uuid.New()) + invitation, err := fixture.reserveInvitation(verified, fixture.newInvitationID(t, verified)) if err != nil || !invitation.Allowed || invitation.Reused { t.Fatalf("ReserveInvitation(verified E2) = %+v, %v; want an allowed new reservation", invitation, err) } @@ -255,7 +263,7 @@ func TestCompanyQuota(t *testing.T) { if err != nil { t.Fatalf("build forged E2 snapshot: %v", err) } - if err := fixture.reserveWithSnapshot(e0Organization, forgedQuota, uuid.New()); !errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) { + if err := fixture.reserveWithSnapshot(e0Organization, forgedQuota, fixture.newInvitationID(t, e0Organization)); !errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) { t.Fatalf("reserve with forged E2 snapshot against stored E0 organization error = %v, want snapshot mismatch", err) } fixture.assertQuotaRowCounts(t, e0Organization.ID(), 0, 0) @@ -285,7 +293,9 @@ func TestCompanyQuota(t *testing.T) { t.Run("candidate deletion clears card-view data but leaves invitation quota evidence", func(t *testing.T) { organization, _ := fixture.newOrganization(t, "candidate-delete", domain.OrganizationVerificationE0) candidateID := fixture.newCandidateID(t) - fixture.reserveInvitationAllowed(t, organization, candidateID) + // The charged invitation names another candidate: a candidate with an + // invitation cannot be deleted until a deletion procedure settles it. + fixture.reserveInvitationAllowed(t, organization, fixture.newInvitationID(t, organization)) fixture.reserveCardViewAllowed(t, organization, candidateID) if _, err := fixture.pool.Exec(fixture.ctx, `DELETE FROM users WHERE id = $1`, candidateID); err != nil { @@ -298,8 +308,9 @@ func TestCompanyQuota(t *testing.T) { organization, _ := fixture.newOrganization(t, "snapshot-check", domain.OrganizationVerificationE0) quota := fixture.quota(t, organization, fixture.version) rollbackMarker := errors.New("test transaction rollback") + rolledBackInvitation := fixture.newInvitationID(t, organization) err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { - decision, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, uuid.New()) + decision, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, rolledBackInvitation) if err != nil { return err } @@ -319,7 +330,7 @@ func TestCompanyQuota(t *testing.T) { WHERE id = $1`, organization.ID(), fixture.clock.Now().Add(-time.Minute)); err != nil { t.Fatalf("change stored organization verification: %v", err) } - staleTrustErr := fixture.reserveWithSnapshot(organization, quota, uuid.New()) + staleTrustErr := fixture.reserveWithSnapshot(organization, quota, fixture.newInvitationID(t, organization)) if !errors.Is(staleTrustErr, outbound.ErrCompanyQuotaSnapshotChanged) { t.Fatalf("reserve with stale organization trust error = %v, want snapshot mismatch", staleTrustErr) } @@ -335,7 +346,7 @@ func TestCompanyQuota(t *testing.T) { if err != nil { t.Fatalf("publish next effective product policy: %v", err) } - stalePolicyErr := fixture.reserveWithSnapshot(policyOrganization, stalePolicyQuota, uuid.New()) + stalePolicyErr := fixture.reserveWithSnapshot(policyOrganization, stalePolicyQuota, fixture.newInvitationID(t, policyOrganization)) if !errors.Is(stalePolicyErr, outbound.ErrCompanyQuotaSnapshotChanged) { t.Fatalf("reserve with stale policy error = %v, want snapshot mismatch", stalePolicyErr) } @@ -353,7 +364,7 @@ func TestCompanyQuota(t *testing.T) { } { t.Run(test.name, func(t *testing.T) { organization, _ := fixture.newOrganization(t, "denied-"+string(test.level), test.level) - _, err := fixture.reserveInvitation(organization, uuid.New()) + _, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization)) if !errors.Is(err, domain.ErrCompanyQuotaDenied) { t.Fatalf("ReserveInvitation(%s) error = %v, want fail-closed denial", test.level, err) } @@ -393,6 +404,34 @@ func (fixture companyQuotaFixture) newOrganization( return stored, owner } +// newInvitationID stores a draft of the organization and returns its +// identifier, so the usage that names it satisfies the foreign key. +func (fixture companyQuotaFixture) newInvitationID(t *testing.T, organization domain.Organization) uuid.UUID { + t.Helper() + invitationID, err := uuid.NewV7() + if err != nil { + t.Fatalf("NewV7() error = %v", err) + } + draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{ + ID: invitationID, OrganizationID: organization.ID(), CandidateID: fixture.invitationCandidate, ActorID: fixture.invitationAuthor, + PolicyVersionID: fixture.version.ID(), At: fixture.clock.Now().Add(-time.Minute), + Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationStorageTerms()}, + }) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + event, err := draft.DraftEvent(fixture.invitationAuthor, nil) + if err != nil { + t.Fatalf("DraftEvent() error = %v", err) + } + if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Create(ctx, draft, event) + }); err != nil { + t.Fatalf("store the draft of the charge: %v", err) + } + return invitationID +} + func (fixture companyQuotaFixture) newCandidateID(t *testing.T) uuid.UUID { t.Helper() candidate := fixture.organizations.identity.createUser( diff --git a/backend/integration_test/invitation_http_test.go b/backend/integration_test/invitation_http_test.go index 3e43fef..0260578 100644 --- a/backend/integration_test/invitation_http_test.go +++ b/backend/integration_test/invitation_http_test.go @@ -34,6 +34,8 @@ import ( "lincodex/backend/internal/usecase/identity" invitationusecase "lincodex/backend/internal/usecase/invitation" needusecase "lincodex/backend/internal/usecase/need" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" "lincodex/backend/internal/usecase/organization" "lincodex/backend/internal/usecase/policy" ) @@ -104,12 +106,29 @@ func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnviro if err != nil { t.Fatalf("candidateview.NewService() error = %v", err) } + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(templates), clock.Now)) + if err != nil { + t.Fatalf("NewInvitationNotifier() error = %v", err) + } invitationService, err := invitationusecase.NewService(invitationusecase.Dependencies{ - Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, Clock: clock.Now, + Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, + 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, }) if err != nil { t.Fatalf("invitation.NewService() error = %v", err) } + inbox, err := notification.NewInboxService(transactor, + notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(false)), clock.Now) + if err != nil { + t.Fatalf("notification.NewInboxService() error = %v", err) + } logs := &strings.Builder{} logger := slog.New(slog.NewJSONHandler(logs, nil)) responder := problem.NewResponder(logger) @@ -119,6 +138,7 @@ func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnviro handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), v1.WithNeed(v1.NewNeedHandler(needService)), v1.WithInvitation(v1.NewInvitationHandler(invitationService)), + v1.WithNotifications(v1.NewNotificationHandler(inbox)), ) router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) diff --git a/backend/integration_test/invitation_send_http_test.go b/backend/integration_test/invitation_send_http_test.go new file mode 100644 index 0000000..b2e0a55 --- /dev/null +++ b/backend/integration_test/invitation_send_http_test.go @@ -0,0 +1,676 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "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/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/usecase/policy" +) + +const ( + // invitationSendMigrationVersion adds sending: the delivery event, the + // stored send outcomes, and the key of quota usage to invitations. + invitationSendMigrationVersion = 38 + invitationDeliveriesRetained = "invitation_deliveries_retained" + // invitationSendE0Quota is the weekly invitation quota of an E0 + // organization in the demo product policy. + invitationSendE0Quota = 10 +) + +// candidateInvitationPage is the part of the candidate's inbox that the tests +// read. A field that must be absent has no member, and the raw text is +// scanned as well. +type candidateInvitationPage struct { + Items []struct { + ID uuid.UUID `json:"id"` + Organization struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + } `json:"organization"` + State string `json:"state"` + Version int64 `json:"version"` + TermsVersion int64 `json:"terms_version"` + RoleTitle string `json:"role_title"` + WorkFormats []string `json:"work_formats"` + ResponseDeadlineAt time.Time `json:"response_deadline_at"` + DeliveredAt time.Time `json:"delivered_at"` + ViewedAt *string `json:"viewed_at"` + } `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +// invitationSendCounts are the rows that one send may create, for one +// invitation: the invitation, its audit events, the outbox events of the +// notification, the charge, and the email request of its candidate. +type invitationSendCounts struct { + invitations, events, deliveredEvents, outboxDelivered, charges, mailRequests int +} + +func readInvitationSendCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationSendCounts { + t.Helper() + var counts invitationSendCounts + if err := harness.pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM invitations WHERE id = $1), + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1), + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'delivered'), + (SELECT count(*) FROM outbox_events WHERE event_type = 'invitation.delivered' AND aggregate_type = 'invitation' AND aggregate_id = $1), + (SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1), + (SELECT count(*) FROM outbox_events WHERE event_type = 'notification.mail_requested' AND ( + aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $2) + OR aggregate_id IN (SELECT id FROM deliveries WHERE recipient_user_id = $2)))`, + invitationID, candidateID).Scan(&counts.invitations, &counts.events, &counts.deliveredEvents, &counts.outboxDelivered, + &counts.charges, &counts.mailRequests); err != nil { + t.Fatalf("count the rows of a send: %v", err) + } + return counts +} + +// outboxEnvelope reads one stored outbox event as the envelope a consumer +// receives for it. +func outboxEnvelope(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, where string, args ...any) outbound.ConsumedEvent { + t.Helper() + var event outbound.ConsumedEvent + var payload string + if err := harness.pool.QueryRow(ctx, ` + SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at + FROM outbox_events WHERE `+where, args...).Scan(&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType, + &event.AggregateID, &event.AggregateVersion, &payload, &event.OccurredAt); err != nil { + t.Fatalf("read the outbox event: %v", err) + } + event.Payload = []byte(payload) + event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond) + return event +} + +func TestOrganizationInvitationSendOverHTTP(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) + // The policy takes effect when it is stored, after the clock of the + // harness was first read. + 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) + } + ownerA, ownerB := account("send-owner-a@example.test", domain.ScenarioEmployer), account("send-owner-b@example.test", domain.ScenarioEmployer) + recruiter := account("send-recruiter@example.test", domain.ScenarioEmployer) + sessionA, sessionB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()), loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()) + sessionRecruiter := loginOrganizationHTTP(t, harness.sessionHTTPHarness, recruiter.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionA, "send-company-a") + orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionB, "send-company-b") + insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA, recruiter.ID, "recruiter", "active", now) + 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) + } + + // Seven published candidates form the visible cohort of both + // organizations. The first two can sign in to read their inbox. + 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} + 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), + 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) + } + } + target := account("send-target@example.test", domain.ScenarioCandidate) + other := account("send-other@example.test", domain.ScenarioCandidate) + cohort := []domain.User{target, other} + for index := range 5 { + candidate := privacy.candidate(t, fmt.Sprintf("send-visible-%d@example.test", index)) + verifyPrivacyCohortCandidate(t, privacy, candidate) + cohort = append(cohort, candidate) + } + for _, candidate := range cohort { + publishCandidate(candidate) + } + sessionTarget := loginOrganizationHTTP(t, harness.sessionHTTPHarness, target.Email.Address()) + sessionOther := loginOrganizationHTTP(t, harness.sessionHTTPHarness, other.Email.Address()) + alias := func(organizationID uuid.UUID, candidate domain.User) string { + t.Helper() + handle, err := harness.key.ForOrganization(organizationID, candidate.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return handle + } + + 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-send-key-%d", keySequence) + } + itemPath := func(organizationID, invitationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID) + } + sendPath := func(organizationID, invitationID uuid.UUID) string { + return itemPath(organizationID, invitationID) + "/send" + } + sendBody := func(version int64) string { return fmt.Sprintf(`{"expected_version":%d}`, version) } + draftFor := func(organizationID uuid.UUID, session organizationHTTPSession, candidate domain.User, change func(body, terms map[string]any)) invitationHTTPBody { + t.Helper() + response := request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID), + invitationCreateJSON(t, alias(organizationID, candidate), change), session, nextKey()) + return decodeInvitationHTTP(t, response, http.StatusCreated) + } + inbox := func(session organizationHTTPSession, query string) (*httptest.ResponseRecorder, candidateInvitationPage) { + t.Helper() + response := request(http.MethodGet, "/api/v1/me/invitations"+query, "", session, "") + var page candidateInvitationPage + if response.Code == http.StatusOK { + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode inbox %s: %v", response.Body.String(), err) + } + } + return response, page + } + candidateMarkers := []string{invitationCandidateName, invitationCandidateContact, invitationCandidateMarker} + for _, candidate := range cohort { + 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", "email", "phone", "telegram", "full_name", "salary_minimum"} { + if strings.Contains(text, `"`+field+`":`) { + t.Errorf("%s contains the key %q: %s", label, field, text) + } + } + } + consumers := postgresadapter.NewEventConsumerStore(harness.pool, notificationConsumerTTL) + + t.Run("delivers a draft into the candidate's inbox before any email", func(t *testing.T) { + draft := draftFor(orgA, sessionA, target, nil) + response := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()) + sent := decodeInvitationHTTP(t, response, http.StatusOK) + requireNoCandidateData("send response", response.Body.String()) + if sent.State != "delivered" || sent.Version != draft.Version+1 || sent.TermsVersion != draft.TermsVersion || + sent.DeliveredAt == nil || sent.ResponseDeadlineAt == nil || sent.CandidateHandle != draft.CandidateHandle { + t.Fatalf("sent invitation = %+v, want the delivered next version of the draft", sent) + } + deliveredAt, deadline := mustParseTimestamp(t, *sent.DeliveredAt), mustParseTimestamp(t, *sent.ResponseDeadlineAt) + if !deadline.Equal(deliveredAt.Add(7 * 24 * time.Hour)) { + t.Fatalf("deadline = %s, want the default 7 days after the delivery %s", deadline, deliveredAt) + } + + // The candidate reads it at once: the commit of the send is the + // delivery, and no email exists yet. + listed, page := inbox(sessionTarget, "") + if listed.Code != http.StatusOK || listed.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("inbox = %d %s", listed.Code, listed.Body.String()) + } + requireNoCandidateData("candidate inbox", listed.Body.String()) + if strings.Contains(listed.Body.String(), "candidate_handle") || strings.Contains(listed.Body.String(), "salary_fit") || + strings.Contains(listed.Body.String(), `"need"`) { + t.Fatalf("candidate inbox shows organization-only fields: %s", listed.Body.String()) + } + if len(page.Items) != 1 { + t.Fatalf("inbox lists %d invitations, want the one delivered", len(page.Items)) + } + item := page.Items[0] + if item.ID != draft.ID || item.State != "delivered" || item.Organization.ID != orgA || item.Organization.Name != nameA || + item.Version != sent.Version || item.RoleTitle == "" || len(item.WorkFormats) != 1 || item.ViewedAt != nil || + !item.DeliveredAt.Equal(deliveredAt) || !item.ResponseDeadlineAt.Equal(deadline) { + t.Fatalf("inbox entry = %+v, want the delivered invitation of organization A", item) + } + var deliveries int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM deliveries WHERE recipient_user_id = $1`, target.ID).Scan(&deliveries); err != nil || deliveries != 0 { + t.Fatalf("deliveries for the candidate = %d, %v; want none before the email job ran", deliveries, err) + } + counts := readInvitationSendCounts(ctx, t, harness, draft.ID, target.ID) + if counts != (invitationSendCounts{invitations: 1, events: 2, deliveredEvents: 1, outboxDelivered: 1, charges: 1, mailRequests: 1}) { + t.Fatalf("send stored %+v, want one invitation, delivery event, outbox event, charge, and email request", counts) + } + var state string + var storedDelivered, storedDeadline time.Time + if err := harness.pool.QueryRow(ctx, `SELECT state, delivered_at, response_deadline_at FROM invitations WHERE id = $1`, draft.ID). + Scan(&state, &storedDelivered, &storedDeadline); err != nil || state != "delivered" || + !storedDelivered.Truncate(time.Second).Equal(deliveredAt) || !storedDeadline.Truncate(time.Second).Equal(deadline) || + !storedDeadline.Equal(storedDelivered.Add(7*24*time.Hour)) { + t.Fatalf("stored invitation = %s %s %s, %v", state, storedDelivered, storedDeadline, err) + } + + // Another candidate and an employer see nothing of it. + if _, others := inbox(sessionOther, ""); len(others.Items) != 0 { + t.Fatalf("another candidate lists %d invitations", len(others.Items)) + } + requireSessionProblem(t, request(http.MethodGet, "/api/v1/me/invitations", "", sessionA, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodGet, "/api/v1/me/invitations", "", organizationHTTPSession{}, ""), http.StatusUnauthorized, "unauthenticated") + if response, _ := inbox(sessionTarget, "?limit=0"); response.Code != http.StatusBadRequest { + t.Fatalf("inbox with limit 0 = %d, want 400", response.Code) + } + + // The in-platform notification arrives through the outbox, and its + // content names the sender and the role, never the candidate. + event := outboxEnvelope(ctx, t, harness, `event_type = 'invitation.delivered' AND aggregate_id = $1`, draft.ID) + if !strings.Contains(string(event.Payload), target.ID.String()) || event.AggregateVersion != sent.Version { + t.Fatalf("outbox event = %+v, want the recipient and the delivered version", event) + } + if !deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event) { + t.Fatal("the inbox consumer did not apply the event") + } + notifications := decodeNotificationPage(t, request(http.MethodGet, "/api/v1/me/notifications", "", sessionTarget, "")) + if len(notifications.Items) != 1 || notifications.Items[0].Kind != "invitation_delivered" || notifications.Items[0].Content == nil || + !strings.Contains(notifications.Items[0].Content.Summary, nameA) || notifications.Items[0].Content.LinkPath == nil || + *notifications.Items[0].Content.LinkPath != "/candidate/invitations" { + t.Fatalf("candidate notifications = %+v, want the invitation notice", notifications.Items) + } + }) + + t.Run("a repeated send stores one invitation, inbox entry, outbox event, and charge", func(t *testing.T) { + draft := draftFor(orgA, sessionA, other, nil) + key := nextKey() + responses := parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), origin, sessionA, key, 2) + if responses[0].Code != http.StatusOK || responses[1].Code != http.StatusOK || responses[0].Body.String() != responses[1].Body.String() { + t.Fatalf("concurrent sends with one key = %d %s and %d %s, want one identical 200", + responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) + } + original := responses[0].Body.String() + sent := decodeInvitationHTTP(t, responses[0], http.StatusOK) + harness.clock.Advance(time.Hour) + if replay := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key); replay.Code != http.StatusOK || replay.Body.String() != original { + t.Fatalf("replay = %d %s, want the original 200", replay.Code, replay.Body.String()) + } + // A new key with the version of the draft answers with the invitation + // as it is now, without a version conflict or a second charge. + again := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()), http.StatusOK) + if again.State != "delivered" || again.Version != sent.Version || *again.DeliveredAt != *sent.DeliveredAt || *again.ResponseDeadlineAt != *sent.ResponseDeadlineAt { + t.Fatalf("send with a new key = %s %d %s %s, want %s %d %s %s", again.State, again.Version, *again.DeliveredAt, *again.ResponseDeadlineAt, + sent.State, sent.Version, *sent.DeliveredAt, *sent.ResponseDeadlineAt) + } + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version+1), sessionA, key), + http.StatusUnprocessableEntity, "idempotency_key_reused") + + counts := readInvitationSendCounts(ctx, t, harness, draft.ID, other.ID) + if counts != (invitationSendCounts{invitations: 1, events: 2, deliveredEvents: 1, outboxDelivered: 1, charges: 1, mailRequests: 1}) { + t.Fatalf("repeated sends stored %+v, want exactly one of each", counts) + } + if _, page := inbox(sessionOther, ""); len(page.Items) != 1 || page.Items[0].ID != draft.ID { + t.Fatalf("candidate inbox = %+v, want exactly one entry", page.Items) + } + // The outbox event reaches the inbox once, however often it is + // delivered. + event := outboxEnvelope(ctx, t, harness, `event_type = 'invitation.delivered' AND aggregate_id = $1`, draft.ID) + deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event) + deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event) + deliverToInbox(ctx, t, consumers, inboxRenamedConsumer, event) + var rows int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM notification_inbox_events WHERE source_id = $1`, draft.ID).Scan(&rows); err != nil || rows != 1 { + t.Fatalf("notification rows for the invitation = %d, %v; want 1", rows, err) + } + }) + + t.Run("fixes the deadline at the delivery while the mail is stopped and its job is retried", func(t *testing.T) { + candidate := cohort[2] + draft := draftFor(orgA, sessionA, candidate, func(body, terms map[string]any) { body["response_period_days"] = 3 }) + sendKey := nextKey() + response := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, sendKey) + sent := decodeInvitationHTTP(t, response, http.StatusOK) + deliveredAt, deadline := mustParseTimestamp(t, *sent.DeliveredAt), mustParseTimestamp(t, *sent.ResponseDeadlineAt) + if sent.ResponsePeriodDays != 3 || !deadline.Equal(deliveredAt.Add(3*24*time.Hour)) { + t.Fatalf("sent = %d days, deadline %s; want 3 days after %s", sent.ResponsePeriodDays, deadline, deliveredAt) + } + + // The mail transport is stopped: deliveries are pinned to the + // disabled provider and nothing is sent. The email job fails once, + // is retried later, and is delivered again by the bus. + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + stopped, err := domain.NewMailProviderAccount("disabled", "default") + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + mailJob := notification.NewDeliveryHandler(notification.NewTemplateRenderer(templates), stopped, harness.clock.Now, slog.New(slog.DiscardHandler)) + event := outboxEnvelope(ctx, t, harness, + `event_type = 'notification.mail_requested' AND aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $1)`, candidate.ID) + failure := errors.New("the mail job failed") + harness.clock.Advance(2 * time.Hour) + if _, err := consumers.ApplyOnce(ctx, notification.DeliveryConsumerName, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := mailJob.Handle(ctx, unit, event); err != nil { + return err + } + return failure + }); !errors.Is(err, failure) { + t.Fatalf("failed mail job error = %v, want the injected failure", err) + } + harness.clock.Advance(time.Hour) + for attempt, want := range []bool{true, false} { + applied, err := consumers.ApplyOnce(ctx, notification.DeliveryConsumerName, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + return mailJob.Handle(ctx, unit, event) + }) + if err != nil || applied != want { + t.Fatalf("mail job attempt %d = %v, %v; want applied %v", attempt, applied, err, want) + } + } + var status, provider, subject, textBody, htmlBody string + if err := harness.pool.QueryRow(ctx, `SELECT status, provider, subject, text_body, html_body FROM deliveries WHERE recipient_user_id = $1`, candidate.ID). + Scan(&status, &provider, &subject, &textBody, &htmlBody); err != nil { + t.Fatalf("read the email delivery: %v", err) + } + if status != "pending" || provider != "disabled" { + t.Fatalf("email delivery = %s via %s, want a pending delivery of the stopped transport", status, provider) + } + requireNoCandidateData("email", subject+"\n"+textBody+"\n"+htmlBody) + if !strings.Contains(textBody, "/candidate/invitations") { + t.Fatalf("email text has no link to the inbox: %s", textBody) + } + + // The business answer stays a success, and the deadline is still the + // one fixed at the delivery. + if replay := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, sendKey); replay.Code != http.StatusOK || replay.Body.String() != response.Body.String() { + t.Fatalf("replay after the mail job = %d %s, want the original 200", replay.Code, replay.Body.String()) + } + read := decodeInvitationHTTP(t, request(http.MethodGet, itemPath(orgA, draft.ID), "", sessionA, ""), http.StatusOK) + if read.State != "delivered" || *read.DeliveredAt != *sent.DeliveredAt || *read.ResponseDeadlineAt != *sent.ResponseDeadlineAt || read.Version != sent.Version { + t.Fatalf("invitation after the mail job = %s %d %s %s, want %s %d %s %s", read.State, read.Version, *read.DeliveredAt, *read.ResponseDeadlineAt, + sent.State, sent.Version, *sent.DeliveredAt, *sent.ResponseDeadlineAt) + } + // The database refuses to move a delivery or a deadline. + _, err = harness.pool.Exec(ctx, `UPDATE invitations SET response_deadline_at = response_deadline_at + interval '1 day', version = version + 1 WHERE id = $1`, draft.ID) + assertPgError(t, "move the deadline", err, privacyIntegrityViolation, "invitations_history_immutable") + }) + + t.Run("rechecks the visibility of the candidate and stores the refusal", func(t *testing.T) { + candidate := cohort[3] + draft := draftFor(orgA, sessionA, candidate, nil) + privacy.hide(t, candidate.ID, orgA, now) + key := nextKey() + refused := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key) + requireSessionProblem(t, refused, http.StatusConflict, "state_conflict") + requireNoCandidateData("refusal", refused.Body.String()) + counts := readInvitationSendCounts(ctx, t, harness, draft.ID, candidate.ID) + if counts != (invitationSendCounts{invitations: 1, events: 1}) { + t.Fatalf("a refused send stored %+v, want only the draft", counts) + } + 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("lift the hiding: %v", err) + } + // The refusal is stored under its key; a new key sends the draft once + // the candidate is visible again. + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key), http.StatusConflict, "state_conflict") + if sent := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()), http.StatusOK); sent.State != "delivered" { + t.Fatalf("send after the hiding was lifted = %+v", sent) + } + + // A revoked publication answers the same way. + revokedCandidate := cohort[4] + revokedDraft := draftFor(orgA, sessionA, revokedCandidate, nil) + privacy.revokeC2(t, revokedCandidate.ID, now.Add(time.Minute)) + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, revokedDraft.ID), sendBody(revokedDraft.Version), sessionA, nextKey()), http.StatusConflict, "state_conflict") + if counts := readInvitationSendCounts(ctx, t, harness, revokedDraft.ID, revokedCandidate.ID); counts.deliveredEvents != 0 || counts.charges != 0 || counts.outboxDelivered != 0 { + t.Fatalf("a send to a revoked publication stored %+v", counts) + } + }) + + t.Run("refuses a stale version without storing it and stores an unknown invitation", func(t *testing.T) { + draft := draftFor(orgA, sessionA, target, nil) + updated := decodeInvitationHTTP(t, request(http.MethodPatch, itemPath(orgA, draft.ID), `{"expected_version":1,"response_period_days":14}`, sessionA, ""), http.StatusOK) + key := nextKey() + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key), http.StatusPreconditionFailed, "version_conflict") + if counts := readInvitationSendCounts(ctx, t, harness, draft.ID, target.ID); counts.deliveredEvents != 0 || counts.charges != 0 { + t.Fatalf("a stale send stored %+v", counts) + } + // Nothing was kept under the key, so the corrected request with the + // same key sends the terms that were read. + sent := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(updated.Version), sessionA, key), http.StatusOK) + if sent.ResponsePeriodDays != 14 || sent.State != "delivered" { + t.Fatalf("send of the read version = %+v", sent) + } + + unknownKey, unknownID := nextKey(), uuid.New() + for range 2 { + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, unknownID), sendBody(1), sessionA, unknownKey), http.StatusNotFound, "not_found") + } + foreign := draftFor(orgB, sessionB, target, nil) + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, foreign.ID), sendBody(foreign.Version), sessionA, nextKey()), http.StatusNotFound, "not_found") + if counts := readInvitationSendCounts(ctx, t, harness, foreign.ID, target.ID); counts.deliveredEvents != 0 { + t.Fatalf("a send through another organization delivered %+v", counts) + } + }) + + t.Run("only the active owner sends, with the CSRF token and a key", func(t *testing.T) { + draft := draftFor(orgA, sessionA, other, nil) + path, body := sendPath(orgA, draft.ID), sendBody(draft.Version) + requireSessionProblem(t, request(http.MethodPost, path, body, sessionRecruiter, nextKey()), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, path, body, sessionTarget, nextKey()), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, path, body, sessionB, nextKey()), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodPost, path, body, organizationHTTPSession{cookie: sessionA.cookie}, nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, path, body, "https://attacker.example", sessionA, nextKey()), + http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, request(http.MethodPost, path, body, organizationHTTPSession{}, nextKey()), http.StatusUnauthorized, "unauthenticated") + requireInvitationValidation(t, request(http.MethodPost, path, body, sessionA, ""), "/Idempotency-Key", "") + requireInvitationValidation(t, request(http.MethodPost, path, `{"expected_version":1,"state":"delivered"}`, sessionA, nextKey()), "", "") + if counts := readInvitationSendCounts(ctx, t, harness, draft.ID, other.ID); counts.deliveredEvents != 0 || counts.charges != 0 { + t.Fatalf("refused callers delivered %+v", counts) + } + current := decodeInvitationHTTP(t, request(http.MethodGet, itemPath(orgA, draft.ID), "", sessionA, ""), http.StatusOK) + if current.State != "draft" { + t.Fatalf("a refused caller changed the draft: %+v", current) + } + }) + + t.Run("lists the candidate's inbox newest first with a bound cursor", func(t *testing.T) { + var total int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitations WHERE candidate_id = $1 AND delivered_at IS NOT NULL`, target.ID).Scan(&total); err != nil { + t.Fatalf("count delivered invitations: %v", err) + } + if total < 2 { + t.Fatalf("the candidate has %d delivered invitations, want at least 2 to page", total) + } + seen := map[uuid.UUID]bool{} + var previous time.Time + query := "?limit=1" + for { + response, page := inbox(sessionTarget, query) + if response.Code != http.StatusOK || len(page.Items) != 1 { + t.Fatalf("inbox page = %d %s", response.Code, response.Body.String()) + } + item := page.Items[0] + if seen[item.ID] || (!previous.IsZero() && item.DeliveredAt.After(previous)) { + t.Fatalf("inbox entry %+v is repeated or out of order", item) + } + seen[item.ID], previous = true, item.DeliveredAt + if !page.Page.HasMore { + break + } + query = "?limit=1&cursor=" + *page.Page.NextCursor + } + if len(seen) != total { + t.Fatalf("pages listed %d invitations, want %d", len(seen), total) + } + _, first := inbox(sessionTarget, "?limit=1") + if response, _ := inbox(sessionOther, "?cursor="+*first.Page.NextCursor); response.Code != http.StatusBadRequest { + t.Fatalf("a cursor of another candidate = %d, want 400", response.Code) + } + }) + + t.Run("charges the weekly organization quota once per invitation", func(t *testing.T) { + var used int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, orgB).Scan(&used); err != nil { + t.Fatalf("count the charges of organization B: %v", err) + } + for range invitationSendE0Quota - used { + draft := draftFor(orgB, sessionB, cohort[5], nil) + decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgB, draft.ID), sendBody(draft.Version), sessionB, nextKey()), http.StatusOK) + } + over := draftFor(orgB, sessionB, cohort[5], nil) + key := nextKey() + for range 2 { + limited := request(http.MethodPost, sendPath(orgB, over.ID), sendBody(over.Version), sessionB, key) + requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.Header().Get("Retry-After") == "" { + t.Fatal("the quota refusal has no Retry-After") + } + } + if counts := readInvitationSendCounts(ctx, t, harness, over.ID, cohort[5].ID); counts.deliveredEvents != 0 || counts.charges != 0 || counts.outboxDelivered != 0 { + t.Fatalf("a send over the quota stored %+v", counts) + } + var charges int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, orgB).Scan(&charges); err != nil || charges != invitationSendE0Quota { + t.Fatalf("charges of organization B = %d, %v; want the quota of %d", charges, err, invitationSendE0Quota) + } + // The quota of another organization is its own. + draft := draftFor(orgA, sessionA, cohort[5], nil) + decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()), http.StatusOK) + // A week later the oldest charges expire, and the same key sends: the + // refusal was not stored under it. The sessions of the week before + // have expired, so the owner signs in again. + harness.clock.Advance(8 * 24 * time.Hour) + laterB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()) + if sent := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgB, over.ID), sendBody(over.Version), laterB, key), http.StatusOK); sent.State != "delivered" { + t.Fatalf("send after the window = %+v", sent) + } + }) + + t.Run("keeps every candidate value out of logs and stored outcomes", func(t *testing.T) { + requireNoCandidateData("server log", harness.logs.String()) + var stored string + if err := harness.pool.QueryRow(ctx, `SELECT coalesce(string_agg(snapshot::text, ' '), '') FROM invitation_send_results`).Scan(&stored); err != nil { + t.Fatalf("read stored outcomes: %v", err) + } + requireNoCandidateData("stored send outcomes", stored) + var mail string + if err := harness.pool.QueryRow(ctx, `SELECT coalesce(string_agg(subject || ' ' || body, ' '), '') FROM mail_requests`).Scan(&mail); err != nil { + t.Fatalf("read mail requests: %v", err) + } + requireNoCandidateData("mail requests", mail) + }) +} + +func mustParseTimestamp(t *testing.T, value string) time.Time { + t.Helper() + parsed, err := time.Parse(time.RFC3339Nano, value) + if err != nil { + t.Fatalf("parse timestamp %q: %v", value, err) + } + return parsed +} + +func TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage(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) + } + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + rollBackAboveVersion(ctx, t, migrator, invitationSendMigrationVersion) + + // Quota usage names a stored invitation of the same organization. + _, err := pool.Exec(ctx, `INSERT INTO company_invitation_quota_usage (organization_id, invitation_id, reserved_at, policy_version_id, + verification_level, verification_basis, verification_changed_at, quota_tier) + SELECT $1, $2, now(), $3, verification_level, verification_basis, verification_changed_at, verification_level + FROM organizations WHERE id = $1`, fixture.organization.ID(), uuid.New(), fixture.policyID.UUID()) + assertPgError(t, "charge without an invitation", err, privacyForeignKeyViolation, "company_invitation_quota_usage_invitation_fkey") + + draft := fixture.draft(t) + delivered, err := draft.Deliver(fixture.now.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 := fixture.transactor.WithinTransaction(ctx, 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) + } + // A second delivery of the same draft version loses the race. + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) + }) + if !errors.Is(err, outbound.ErrInvitationVersionConflict) { + t.Fatalf("second Deliver() error = %v, want ErrInvitationVersionConflict", err) + } + + _, err = migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a delivered invitation", err, privacyIntegrityViolation, invitationDeliveriesRetained) + if _, err := pool.Exec(ctx, `TRUNCATE invitation_send_results, company_invitation_quota_usage, invitation_creation_results, + invitation_events, invitation_terms_versions, invitations`); err != nil { + t.Fatalf("clear the invitation tables: %v", err) + } + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != invitationSendMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationSendMigrationVersion) + } + var remaining int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name = 'invitation_send_results'`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("send outcomes 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/organizations_test.go b/backend/integration_test/organizations_test.go index 56c736d..ac83397 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -40,7 +40,8 @@ var ( // users and organizations. Creation snapshots reference idempotency records. organizationTables = []pgx.Identifier{ {"candidate_card_access_events"}, - {"invitation_creation_results"}, {"invitation_events"}, {"invitation_terms_versions"}, {"invitations"}, + {"invitation_creation_results"}, {"invitation_send_results"}, + {"invitation_events"}, {"invitation_terms_versions"}, {"invitations"}, {"organization_need_versions"}, {"organization_needs"}, {"organization_need_creation_results"}, {"company_invitation_quota_usage"}, {"company_card_view_quota_usage"}, diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index fba7927..883be10 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -14035,7 +14035,8 @@ func (s *Server) handleSearchOrganizationMatchesRequest(args [1]string, argsEsca // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, // both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and -// Retry-After. Enforcement of the pending limit and the organization quota is planned. +// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are +// not checked yet. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 0ce86a0..ba86802 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -20754,10 +20754,10 @@ func (s *NotificationContent) SetLinkPath(val NilString) { // Which event put the notification into the inbox. The inbox stores a reference to the event, never // its text. // -// - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform -// delivery state of the invitation: it does not depend on any email, and a failed or missing email -// never blocks it. The invitation operations are planned; no invitation produces a notification -// yet. +// - invitation_delivered: an invitation reached the candidate's inbox. It does not depend on any +// email, and a failed or missing email never blocks it. The send of an invitation produces it +// through the outbox, so the notice appears shortly after the commit of the send, while the +// invitation itself is in ListMyInvitations from that commit. // - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility // check, the list, and the read state). It has no product meaning, needs no action, and is never // produced by a user action. diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index 96c4bad..1d37895 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -1725,7 +1725,8 @@ type Handler interface { // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, // both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and - // Retry-After. Enforcement of the pending limit and the organization quota is planned. + // Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are + // not checked yet. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index c0fb67c..886174d 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -1916,7 +1916,8 @@ func (UnimplementedHandler) SearchOrganizationMatches(ctx context.Context, req M // answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the // organization and the candidate after a decline or a no deal, regardless of the member or the need, // both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and -// Retry-After. Enforcement of the pending limit and the organization quota is planned. +// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are +// not checked yet. // // Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, // and a send of an invitation that was already sent answers 200 with the invitation in its current diff --git a/backend/internal/adapter/primary/http/v1/invitation.go b/backend/internal/adapter/primary/http/v1/invitation.go index 47dc9b2..a4f3e9f 100644 --- a/backend/internal/adapter/primary/http/v1/invitation.go +++ b/backend/internal/adapter/primary/http/v1/invitation.go @@ -18,18 +18,22 @@ import ( const defaultInvitationLimit = 20 -// InvitationOperations are the owner-scoped invitation draft reads and -// commands served by HTTP. +// InvitationOperations are the owner-scoped invitation reads and commands and +// the candidate's read of the own inbox served by HTTP. type InvitationOperations interface { Create(ctx context.Context, command invitationusecase.CreateCommand) (domain.OrganizationInvitationView, error) Get(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.OrganizationInvitationView, error) List(ctx context.Context, command invitationusecase.ListCommand) (invitationusecase.Page, error) Update(ctx context.Context, command invitationusecase.UpdateCommand) (domain.OrganizationInvitationView, error) + Send(ctx context.Context, command invitationusecase.SendCommand) (domain.OrganizationInvitationView, error) + ListMine(ctx context.Context, command invitationusecase.CandidateListCommand) (invitationusecase.CandidatePage, error) } -// InvitationHandler serves the organization side of invitation drafts. The -// organization comes from the path and the server-side membership, never from -// a body, and the candidate is only ever named by the opaque card handle. +// InvitationHandler serves the organization side of invitation drafts and +// their sending, and the candidate's inbox. The organization comes from the +// path and the server-side membership, never from a body, the candidate is +// only ever named by the opaque card handle, and the candidate's inbox is +// bound to the session. type InvitationHandler struct { operations InvitationOperations } @@ -69,6 +73,20 @@ func (handler *Handler) UpdateOrganizationInvitation(ctx context.Context, reques return handler.invitation.UpdateOrganizationInvitation(ctx, request, params) } +func (handler *Handler) SendOrganizationInvitation(ctx context.Context, request *api.InvitationCommand, params api.SendOrganizationInvitationParams) (api.SendOrganizationInvitationRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.SendOrganizationInvitation(ctx, request, params) + } + return handler.invitation.SendOrganizationInvitation(ctx, request, params) +} + +func (handler *Handler) ListMyInvitations(ctx context.Context, params api.ListMyInvitationsParams) (api.ListMyInvitationsRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.ListMyInvitations(ctx, params) + } + return handler.invitation.ListMyInvitations(ctx, params) +} + func (handler *InvitationHandler) CreateOrganizationInvitation( ctx context.Context, request *api.OrganizationInvitationCreate, @@ -203,6 +221,66 @@ func (handler *InvitationHandler) UpdateOrganizationInvitation( return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil } +func (handler *InvitationHandler) SendOrganizationInvitation( + ctx context.Context, + request *api.InvitationCommand, + params api.SendOrganizationInvitationParams, +) (api.SendOrganizationInvitationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.SendOrganizationInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if request == nil { + return (*api.SendOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil + } + view, err := handler.operations.Send(ctx, invitationusecase.SendCommand{ + ActorID: principal.UserID, OrganizationID: params.OrgID, InvitationID: params.InvitationID, + IdempotencyKey: params.IdempotencyKey, ExpectedVersion: int64(request.ExpectedVersion), + }) + if err != nil { + return invitationSendFailure(ctx, err) + } + return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil +} + +func (handler *InvitationHandler) ListMyInvitations(ctx context.Context, params api.ListMyInvitationsParams) (api.ListMyInvitationsRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.ListMyInvitationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + command, pointer := candidateInvitationListCommand(principal.UserID, params) + if pointer != "" { + return (*api.ListMyInvitationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil + } + page, err := handler.operations.ListMine(ctx, command) + if err != nil { + if errors.Is(err, invitationusecase.ErrForbidden) { + return (*api.ListMyInvitationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + } + return nil, err + } + items := make([]api.CandidateInvitationSummary, 0, len(page.Items)) + for _, item := range page.Items { + items = append(items, candidateInvitationSummary(item)) + } + next := api.NilString{} + next.SetToNull() + if page.HasMore && len(page.Items) > 0 { + last := page.Items[len(page.Items)-1] + cursor, err := encodeCandidateInvitationCursor(principal.UserID, outbound.CandidateInvitationPosition{ + DeliveredAt: last.DeliveredAt, InvitationID: last.ID, + }) + if err != nil { + return nil, fmt.Errorf("InvitationHandler.ListMyInvitations - encode cursor: %w", err) + } + next.SetTo(cursor) + } + return &api.CandidateInvitationListHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: api.CandidateInvitationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}}, + }, nil +} + // invitationFailure is the public classification of a usecase error. Every // kind has one fixed problem, so a response never depends on which of two // indistinguishable causes happened. @@ -232,7 +310,7 @@ func classifyInvitationError(err error) invitationFailure { return invitationFailureBadKey case errors.Is(err, domain.ErrInvitationVersionConflict), errors.Is(err, outbound.ErrInvitationVersionConflict): return invitationFailureVersionConflict - case errors.Is(err, domain.ErrInvitationNotDraft): + case errors.Is(err, domain.ErrInvitationNotDraft), errors.Is(err, invitationusecase.ErrSendBlocked): return invitationFailureStateConflict case errors.Is(err, domain.ErrInvalidInvitation), errors.Is(err, domain.ErrInvalidSalaryRange): if _, ok := errors.AsType[*domain.InvitationFieldError](err); ok { @@ -301,6 +379,52 @@ func invitationUpdateFailure(ctx context.Context, err error) (api.UpdateOrganiza return nil, err } +func invitationSendFailure(ctx context.Context, err error) (api.SendOrganizationInvitationRes, error) { + // The organization quota is a 429 with the time when it frees room; it is + // not stored under the key, so a later retry can succeed. + if limited, ok := errors.AsType[*invitationusecase.QuotaExceededError](err); ok { + return problem.RateLimited(ctx, wholeSeconds(time.Until(limited.RetryAt))), nil + } + switch classifyInvitationError(err) { + case invitationFailureForbidden: + return (*api.SendOrganizationInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case invitationFailureNotFound: + return (*api.SendOrganizationInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case invitationFailureKeyReused: + return (*api.SendOrganizationInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil + case invitationFailureBadKey: + return (*api.SendOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil + case invitationFailureInvalid: + return (*api.SendOrganizationInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil + case invitationFailureVersionConflict: + return (*api.SendOrganizationInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil + case invitationFailureStateConflict: + return (*api.SendOrganizationInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil + case invitationFailureOther: + return nil, err + } + return nil, err +} + +func candidateInvitationListCommand(actorID uuid.UUID, params api.ListMyInvitationsParams) (invitationusecase.CandidateListCommand, string) { + limit, ok := params.Limit.Get() + if !ok { + limit = defaultInvitationLimit + } + if limit < 1 || limit > outbound.MaxInvitationPageSize { + return invitationusecase.CandidateListCommand{}, "limit" + } + command := invitationusecase.CandidateListCommand{ActorID: actorID, Limit: limit} + if cursor, ok := params.Cursor.Get(); ok { + position, err := decodeCandidateInvitationCursor(cursor, actorID) + if err != nil { + return invitationusecase.CandidateListCommand{}, "cursor" + } + command.After = &position + } + return command, "" +} + func invitationListCommand(actorID uuid.UUID, params api.ListOrganizationInvitationsParams) (invitationusecase.ListCommand, string) { limit, ok := params.Limit.Get() if !ok { @@ -493,3 +617,19 @@ func organizationInvitationSummary(view domain.OrganizationInvitationView) api.O CreatedAt: api.Timestamp(view.CreatedAt), UpdatedAt: api.Timestamp(view.UpdatedAt), } } + +func candidateInvitationSummary(summary domain.CandidateInvitationSummary) api.CandidateInvitationSummary { + formats := make([]api.WorkFormat, 0, len(summary.WorkFormats)) + for _, format := range summary.WorkFormats { + formats = append(formats, api.WorkFormat(format)) + } + return api.CandidateInvitationSummary{ + ID: summary.ID, + Organization: api.InvitationOrganization{ID: summary.Organization.ID, Name: summary.Organization.Name}, + State: api.InvitationState(summary.State), ExpiryReason: invitationExpiryResponse(summary.ExpiryReason), + Version: api.InvitationVersion(summary.Version), TermsVersion: api.InvitationTermsVersion(summary.TermsVersion), + RoleTitle: api.InvitationRoleTitle(summary.RoleTitle), Salary: salaryRangeResponse(summary.Salary), WorkFormats: formats, + ResponseDeadlineAt: api.Timestamp(summary.ResponseDeadlineAt), DeliveredAt: api.Timestamp(summary.DeliveredAt), + ViewedAt: nullableTimestamp(summary.ViewedAt), UpdatedAt: api.Timestamp(summary.UpdatedAt), + } +} diff --git a/backend/internal/adapter/primary/http/v1/invitation_cursor.go b/backend/internal/adapter/primary/http/v1/invitation_cursor.go index e2869b0..d27c4d7 100644 --- a/backend/internal/adapter/primary/http/v1/invitation_cursor.go +++ b/backend/internal/adapter/primary/http/v1/invitation_cursor.go @@ -13,43 +13,79 @@ import ( ) const ( - invitationCursorVersion = 1 - invitationCursorBytes = 61 - maxInvitationCursorTime = uint64(253402300799) + // invitationCursorVersion marks a page of one organization's invitations; + // candidateInvitationCursorVersion marks a page of one candidate's inbox. + // A cursor of one listing is refused by the other. + invitationCursorVersion = 1 + candidateInvitationCursorVersion = 2 + invitationCursorBytes = 61 + maxInvitationCursorTime = uint64(253402300799) ) // encodeInvitationCursor binds the position to the account and the // organization that read the page, so a cursor of another reader or tenant is // refused instead of continuing a foreign listing. func encodeInvitationCursor(actorID, organizationID uuid.UUID, position outbound.InvitationListPosition) (string, error) { - seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond() - if actorID == uuid.Nil || organizationID == uuid.Nil || position.InvitationID == uuid.Nil || position.CreatedAt.IsZero() || - position.CreatedAt.Year() < 1 || position.CreatedAt.Year() > 9999 || seconds < 0 || uint64(seconds) > maxInvitationCursorTime || - nanos < 0 || nanos >= 1_000_000_000 || nanos%int(time.Microsecond) != 0 { - return "", errors.New("invitation cursor requires an actor, organization, and valid page position") + if organizationID == uuid.Nil { + return "", errors.New("invitation cursor requires an organization") } - var value [invitationCursorBytes]byte - value[0] = invitationCursorVersion - copy(value[1:17], actorID[:]) - copy(value[17:33], organizationID[:]) - binary.BigEndian.PutUint64(value[33:41], uint64(seconds)) - binary.BigEndian.PutUint32(value[41:45], uint32(nanos)) - copy(value[45:61], position.InvitationID[:]) - return base64.RawURLEncoding.EncodeToString(value[:]), nil + return encodeInvitationPosition(invitationCursorVersion, actorID, organizationID, position.CreatedAt, position.InvitationID) } func decodeInvitationCursor(cursor string, actorID, organizationID uuid.UUID) (outbound.InvitationListPosition, error) { + if organizationID == uuid.Nil { + return outbound.InvitationListPosition{}, errors.New("invitation cursor requires an organization") + } + at, invitationID, err := decodeInvitationPosition(cursor, invitationCursorVersion, actorID, organizationID) + if err != nil { + return outbound.InvitationListPosition{}, err + } + return outbound.InvitationListPosition{CreatedAt: at, InvitationID: invitationID}, nil +} + +// encodeCandidateInvitationCursor binds the position of the candidate's inbox +// to the candidate who read the page. +func encodeCandidateInvitationCursor(actorID uuid.UUID, position outbound.CandidateInvitationPosition) (string, error) { + return encodeInvitationPosition(candidateInvitationCursorVersion, actorID, actorID, position.DeliveredAt, position.InvitationID) +} + +func decodeCandidateInvitationCursor(cursor string, actorID uuid.UUID) (outbound.CandidateInvitationPosition, error) { + at, invitationID, err := decodeInvitationPosition(cursor, candidateInvitationCursorVersion, actorID, actorID) + if err != nil { + return outbound.CandidateInvitationPosition{}, err + } + return outbound.CandidateInvitationPosition{DeliveredAt: at, InvitationID: invitationID}, nil +} + +func encodeInvitationPosition(version byte, actorID, scopeID uuid.UUID, at time.Time, invitationID uuid.UUID) (string, error) { + seconds, nanos := at.Unix(), at.Nanosecond() + if actorID == uuid.Nil || scopeID == uuid.Nil || invitationID == uuid.Nil || at.IsZero() || + at.Year() < 1 || at.Year() > 9999 || seconds < 0 || uint64(seconds) > maxInvitationCursorTime || + nanos < 0 || nanos >= 1_000_000_000 || nanos%int(time.Microsecond) != 0 { + return "", errors.New("invitation cursor requires an actor, a scope, and a valid page position") + } + var value [invitationCursorBytes]byte + value[0] = version + copy(value[1:17], actorID[:]) + copy(value[17:33], scopeID[:]) + binary.BigEndian.PutUint64(value[33:41], uint64(seconds)) + binary.BigEndian.PutUint32(value[41:45], uint32(nanos)) + copy(value[45:61], invitationID[:]) + return base64.RawURLEncoding.EncodeToString(value[:]), nil +} + +func decodeInvitationPosition(cursor string, version byte, actorID, scopeID uuid.UUID) (time.Time, uuid.UUID, error) { value, err := base64.RawURLEncoding.DecodeString(cursor) - if err != nil || len(value) != invitationCursorBytes || actorID == uuid.Nil || organizationID == uuid.Nil || - base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != invitationCursorVersion || - uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != organizationID { - return outbound.InvitationListPosition{}, errors.New("invitation cursor is invalid") + if err != nil || len(value) != invitationCursorBytes || actorID == uuid.Nil || scopeID == uuid.Nil || + base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != version || + uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != scopeID { + return time.Time{}, uuid.Nil, errors.New("invitation cursor is invalid") } seconds := binary.BigEndian.Uint64(value[33:41]) nanos := binary.BigEndian.Uint32(value[41:45]) invitationID := uuid.UUID(value[45:61]) if seconds > uint64(math.MaxInt64) || seconds > maxInvitationCursorTime || nanos >= 1_000_000_000 || nanos%1_000 != 0 || invitationID == uuid.Nil { - return outbound.InvitationListPosition{}, errors.New("invitation cursor position is invalid") + return time.Time{}, uuid.Nil, errors.New("invitation cursor position is invalid") } - return outbound.InvitationListPosition{CreatedAt: time.Unix(int64(seconds), int64(nanos)).UTC(), InvitationID: invitationID}, nil + return time.Unix(int64(seconds), int64(nanos)).UTC(), invitationID, nil } diff --git a/backend/internal/adapter/primary/http/v1/invitation_test.go b/backend/internal/adapter/primary/http/v1/invitation_test.go index 66c88e1..0ff2054 100644 --- a/backend/internal/adapter/primary/http/v1/invitation_test.go +++ b/backend/internal/adapter/primary/http/v1/invitation_test.go @@ -191,3 +191,73 @@ func TestInvitationCursorIsBoundToActorAndOrganization(t *testing.T) { t.Error("a cursor with trailing data was accepted") } } + +func TestInvitationSendFailuresMapToTheContractStatuses(t *testing.T) { + ctx := context.Background() + send := func(err error) any { + response, unexpected := invitationSendFailure(ctx, err) + if unexpected != nil { + return unexpected + } + return fmt.Sprintf("%T", response) + } + for name, test := range map[string]struct { + err error + want string + }{ + "forbidden": {fmt.Errorf("wrapped: %w", outbound.ErrOrganizationManagerRequired), "*api.SendOrganizationInvitationForbidden"}, + "unknown invitation": {fmt.Errorf("wrapped: %w", outbound.ErrInvitationNotFound), "*api.SendOrganizationInvitationNotFound"}, + "reused key": {invitationusecase.ErrIdempotencyKeyReused, "*api.SendOrganizationInvitationUnprocessableEntity"}, + "bad key": {invitationusecase.ErrInvalidIdempotencyKey, "*api.SendOrganizationInvitationBadRequest"}, + "stale version": {fmt.Errorf("wrapped: %w", domain.ErrInvitationVersionConflict), "*api.SendOrganizationInvitationPreconditionFailed"}, + "blocked send": {fmt.Errorf("wrapped: %w", invitationusecase.ErrSendBlocked), "*api.SendOrganizationInvitationConflict"}, + "quota": {&invitationusecase.QuotaExceededError{RetryAt: time.Now().Add(90 * time.Second)}, "*api.TooManyRequestsHeaders"}, + } { + if got := send(test.err); got != test.want { + t.Errorf("%s: send failure = %v, want %s", name, got, test.want) + } + } + response, err := invitationSendFailure(ctx, fmt.Errorf("wrapped: %w", &invitationusecase.QuotaExceededError{RetryAt: time.Now().Add(90 * time.Second)})) + limited, ok := response.(*api.TooManyRequestsHeaders) + if err != nil || !ok || limited.Response.Code != api.ProblemCodeRateLimited { + t.Fatalf("quota failure = %T, %v; want 429 rate_limited", response, err) + } + if wait, set := limited.RetryAfter.Get(); !set || wait < 89 || wait > 90 { + t.Fatalf("Retry-After = %d, %v; want the seconds until the quota frees room", wait, set) + } + if _, passedOn := send(errors.New("storage failed")).(error); !passedOn { + t.Error("an unknown failure produced a public response instead of reaching the responder") + } +} + +func TestCandidateInvitationCursorIsBoundToTheCandidateAndItsListing(t *testing.T) { + actorID := uuid.Must(uuid.NewV7()) + position := outbound.CandidateInvitationPosition{ + DeliveredAt: time.Date(2026, time.October, 9, 10, 0, 0, 123456000, time.UTC), InvitationID: uuid.Must(uuid.NewV7()), + } + cursor, err := encodeCandidateInvitationCursor(actorID, position) + if err != nil { + t.Fatalf("encodeCandidateInvitationCursor() error = %v", err) + } + decoded, err := decodeCandidateInvitationCursor(cursor, actorID) + if err != nil || !decoded.DeliveredAt.Equal(position.DeliveredAt) || decoded.InvitationID != position.InvitationID { + t.Fatalf("decodeCandidateInvitationCursor() = %+v, %v; want the same position", decoded, err) + } + if _, err := decodeCandidateInvitationCursor(cursor, uuid.Must(uuid.NewV7())); err == nil { + t.Error("a cursor of another candidate was accepted") + } + // An organization cursor of the same account does not continue the + // candidate's inbox, and the other way round. + organizationCursor, err := encodeInvitationCursor(actorID, actorID, outbound.InvitationListPosition{ + CreatedAt: position.DeliveredAt, InvitationID: position.InvitationID, + }) + if err != nil { + t.Fatalf("encodeInvitationCursor() error = %v", err) + } + if _, err := decodeCandidateInvitationCursor(organizationCursor, actorID); err == nil { + t.Error("an organization cursor continued the candidate's inbox") + } + if _, err := decodeInvitationCursor(cursor, actorID, actorID); err == nil { + t.Error("a candidate cursor continued an organization listing") + } +} diff --git a/backend/internal/adapter/secondary/postgres/invitation_delivery.go b/backend/internal/adapter/secondary/postgres/invitation_delivery.go new file mode 100644 index 0000000..a251159 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/invitation_delivery.go @@ -0,0 +1,253 @@ +package postgres + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "unicode/utf8" + + "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.InvitationSendResultRepository = invitationRepository{} + +// maxInvitationOrganizationNameRunes is the bound of the organization name +// that the candidate's inbox shows, as in the public contract. +const maxInvitationOrganizationNameRunes = 200 + +func (unit *UnitOfWork) InvitationSendResults() outbound.InvitationSendResultRepository { + return invitationRepository{queries: unit.queries} +} + +func (repository invitationRepository) Deliver( + ctx context.Context, + expectedVersion int64, + next domain.Invitation, + event domain.InvitationEvent, +) error { + const location = "invitationRepository.Deliver" + stored := next.Stored() + if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationDelivered) || + stored.DeliveredAt == nil || stored.ResponseDeadlineAt == nil || event.Kind != domain.InvitationEventDelivered { + return fmt.Errorf("%s - the next version must be the delivery 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.DeliverInvitation(ctx, sqlc.DeliverInvitationParams{ + NextVersion: stored.Version, DeliveredAt: pgTime(*stored.DeliveredAt), ResponseDeadlineAt: pgTime(*stored.ResponseDeadlineAt), + OrganizationID: pgUUID(stored.OrganizationID), InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, + }) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - deliver draft: %w", location, outbound.ErrInvitationVersionConflict) + } + if err != nil { + return fmt.Errorf("%s - deliver draft: %w", location, mapInvitationError(err)) + } + return repository.insertEvent(ctx, location, event) +} + +func (repository invitationRepository) ListForCandidate( + ctx context.Context, + query outbound.CandidateInvitationListQuery, +) (outbound.CandidateInvitationPage, error) { + const location = "invitationRepository.ListForCandidate" + if query.CandidateID == uuid.Nil { + return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidInvitation) + } + if query.Limit < 1 || query.Limit > outbound.MaxInvitationPageSize { + return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxInvitationPageSize, domain.ErrInvalidInvitation) + } + params := sqlc.ListCandidateInvitationsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1} + if query.After != nil { + after := *query.After + if after.InvitationID == uuid.Nil || !validStoredInvitationTime(after.DeliveredAt) { + return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - pagination position is invalid: %w", location, domain.ErrInvalidInvitation) + } + params.AfterDeliveredAt = pgTime(after.DeliveredAt) + params.AfterInvitationID = pgUUID(after.InvitationID) + } + rows, err := repository.queries.ListCandidateInvitations(ctx, params) + if err != nil { + return outbound.CandidateInvitationPage{}, fmt.Errorf("%s - select invitations: %w", location, mapInvitationError(err)) + } + page := outbound.CandidateInvitationPage{HasMore: len(rows) > int(query.Limit)} + if page.HasMore { + rows = rows[:query.Limit] + } + page.Items = make([]outbound.CandidateInvitationEntry, 0, len(rows)) + for _, row := range rows { + entry, err := restoreCandidateInvitationRow(location, row, query.CandidateID) + if err != nil { + return outbound.CandidateInvitationPage{}, err + } + page.Items = append(page.Items, entry) + } + return page, nil +} + +func (repository invitationRepository) GetForCandidate( + ctx context.Context, + candidateID, invitationID uuid.UUID, +) (domain.Invitation, error) { + const location = "invitationRepository.GetForCandidate" + if candidateID == uuid.Nil || invitationID == uuid.Nil { + return domain.Invitation{}, fmt.Errorf("%s - candidate and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation) + } + row, err := repository.queries.ReadCandidateInvitation(ctx, sqlc.ReadCandidateInvitationParams{ + CandidateID: pgUUID(candidateID), InvitationID: pgUUID(invitationID), + }) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err)) + } + if !row.OrganizationID.Valid || !row.CandidateID.Valid || uuid.UUID(row.CandidateID.Bytes) != candidateID { + return domain.Invitation{}, fmt.Errorf("%s - invitation row has an invalid scope: %w", location, domain.ErrInvalidInvitation) + } + return restoreInvitationRow(location, sqlc.ListInvitationsRow(row), uuid.UUID(row.OrganizationID.Bytes)) +} + +func (repository invitationRepository) SaveSendResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, + result outbound.InvitationSendResult, +) error { + const location = "invitationRepository.SaveSendResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) { + return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) + } + if err := validateInvitationSendResult(result); err != nil { + return fmt.Errorf("%s - validate outcome: %w", location, err) + } + var snapshot []byte + if result.View != nil { + encoded, err := encodeInvitationCreationResult(*result.View) + if err != nil { + return fmt.Errorf("%s - encode response: %w", location, err) + } + snapshot = encoded + } + if err := repository.queries.InsertInvitationSendResult(ctx, sqlc.InsertInvitationSendResultParams{ + ScopeHash: scope[:], OrganizationID: pgUUID(result.OrganizationID), InvitationID: pgUUID(result.InvitationID), + Outcome: string(result.Outcome), Snapshot: snapshot, + }); err != nil { + return fmt.Errorf("%s - store outcome: %w", location, mapInvitationSendResultError(err)) + } + return nil +} + +func (repository invitationRepository) GetSendResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, +) (outbound.InvitationSendResult, error) { + const location = "invitationRepository.GetSendResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) { + return outbound.InvitationSendResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) + } + row, err := repository.queries.GetInvitationSendResult(ctx, scope[:]) + if errors.Is(err, pgx.ErrNoRows) { + return outbound.InvitationSendResult{}, outbound.ErrInvitationSendResultNotFound + } + if err != nil { + return outbound.InvitationSendResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err)) + } + if !row.OrganizationID.Valid || !row.InvitationID.Valid { + return outbound.InvitationSendResult{}, fmt.Errorf("%s - stored outcome has no scope: %w", location, domain.ErrInvalidInvitation) + } + result := outbound.InvitationSendResult{ + OrganizationID: uuid.UUID(row.OrganizationID.Bytes), InvitationID: uuid.UUID(row.InvitationID.Bytes), + Outcome: outbound.InvitationSendOutcome(row.Outcome), + } + if row.Snapshot != "" { + view, err := decodeInvitationSendView(location, []byte(row.Snapshot)) + if err != nil { + return outbound.InvitationSendResult{}, err + } + result.View = &view + } + if err := validateInvitationSendResult(result); err != nil { + return outbound.InvitationSendResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err) + } + return result, nil +} + +// decodeInvitationSendView restores the original response of a send. It +// shares the shape and the checks of a stored creation response. +func decodeInvitationSendView(location string, encoded []byte) (domain.OrganizationInvitationView, error) { + var view domain.OrganizationInvitationView + decoder := json.NewDecoder(bytes.NewReader(encoded)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&view); err != nil || decoder.More() { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - stored response has an unexpected shape: %w", location, domain.ErrInvalidInvitation) + } + if err := validateInvitationCreationResult(view); err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate stored response: %w", location, err) + } + return view, nil +} + +func validateInvitationSendResult(result outbound.InvitationSendResult) error { + const location = "postgres.validateInvitationSendResult" + // The invitation of a refusal is the identifier of the path, which may + // name nothing, even the nil identifier; only a sent outcome names a real + // invitation. + if result.OrganizationID == uuid.Nil { + return fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidInvitation) + } + switch result.Outcome { + case outbound.InvitationSendSent: + if result.View == nil || result.View.ID != result.InvitationID || result.View.OrganizationID != result.OrganizationID || + !result.View.State.IsKnown() || result.View.DeliveredAt == nil { + return fmt.Errorf("%s - a sent outcome must hold the delivered invitation: %w", location, domain.ErrInvalidInvitation) + } + case outbound.InvitationSendNotFound, outbound.InvitationSendStateConflict: + if result.View != nil { + return fmt.Errorf("%s - a refused outcome holds no response: %w", location, domain.ErrInvalidInvitation) + } + default: + return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation) + } + return nil +} + +func restoreCandidateInvitationRow( + location string, + row sqlc.ListCandidateInvitationsRow, + candidateID uuid.UUID, +) (outbound.CandidateInvitationEntry, error) { + if !row.OrganizationID.Valid || !row.CandidateID.Valid || uuid.UUID(row.CandidateID.Bytes) != candidateID || + !utf8.ValidString(row.OrganizationName) || row.OrganizationName == "" || + utf8.RuneCountInString(row.OrganizationName) > maxInvitationOrganizationNameRunes { + return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - invitation row has an invalid scope or sender: %w", location, domain.ErrInvalidInvitation) + } + invitation, err := restoreInvitationRow(location, sqlc.ListInvitationsRow{ + ID: row.ID, OrganizationID: row.OrganizationID, CandidateID: row.CandidateID, NeedID: row.NeedID, + NeedRequirementsVersion: row.NeedRequirementsVersion, State: row.State, ExpiryReason: row.ExpiryReason, + Version: row.Version, TermsVersion: row.TermsVersion, ResponsePeriodDays: row.ResponsePeriodDays, + PolicyVersionID: row.PolicyVersionID, ResponseDeadlineAt: row.ResponseDeadlineAt, SalaryRaiseUsed: row.SalaryRaiseUsed, + CreatedBy: row.CreatedBy, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, DeliveredAt: row.DeliveredAt, + ViewedAt: row.ViewedAt, RespondedAt: row.RespondedAt, Terms: row.Terms, + }, uuid.UUID(row.OrganizationID.Bytes)) + if err != nil { + return outbound.CandidateInvitationEntry{}, err + } + if !invitation.IsDelivered() { + return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - an undelivered invitation is not in the inbox: %w", location, domain.ErrInvalidInvitation) + } + return outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: row.OrganizationName}, nil +} + +func mapInvitationSendResultError(err error) error { + var pgError *pgconn.PgError + if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_send_results_idempotency_fkey" { + return fmt.Errorf("postgres.mapInvitationSendResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound) + } + return mapInvitationError(err) +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/invitation_delivery.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/invitation_delivery.sql.go new file mode 100644 index 0000000..cb771e7 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/invitation_delivery.sql.go @@ -0,0 +1,336 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: invitation_delivery.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const deliverInvitation = `-- name: DeliverInvitation :one +UPDATE invitations +SET + state = 'delivered', + version = $1, + delivered_at = $2, + response_deadline_at = $3, + updated_at = $2 +WHERE + organization_id = $4 + AND id = $5 + AND state = 'draft' + AND version = $6 + AND $1::bigint = $6::bigint + 1 +RETURNING id +` + +type DeliverInvitationParams struct { + NextVersion int64 + DeliveredAt pgtype.Timestamptz + ResponseDeadlineAt pgtype.Timestamptz + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + ExpectedVersion int64 +} + +// The conditional update is the compare-and-swap of a send: it applies only to +// a draft whose version is still the one the caller read, records the first +// delivery with its deadline, and advances the version by one. No row is +// returned when it lost a race or the invitation is no longer a draft. +func (q *Queries) DeliverInvitation(ctx context.Context, arg DeliverInvitationParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, deliverInvitation, + arg.NextVersion, + arg.DeliveredAt, + arg.ResponseDeadlineAt, + arg.OrganizationID, + arg.InvitationID, + arg.ExpectedVersion, + ) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + +const getInvitationSendResult = `-- name: GetInvitationSendResult :one +SELECT + organization_id, + invitation_id, + outcome, + -- A refusal has no snapshot; the empty text stands for it. + coalesce(snapshot::text, '')::text AS snapshot +FROM invitation_send_results +WHERE scope_hash = $1 +` + +type GetInvitationSendResultRow struct { + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + Outcome string + Snapshot string +} + +func (q *Queries) GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error) { + row := q.db.QueryRow(ctx, getInvitationSendResult, scopeHash) + var i GetInvitationSendResultRow + err := row.Scan( + &i.OrganizationID, + &i.InvitationID, + &i.Outcome, + &i.Snapshot, + ) + return i, err +} + +const insertInvitationSendResult = `-- name: InsertInvitationSendResult :exec +INSERT INTO invitation_send_results ( + scope_hash, + organization_id, + invitation_id, + outcome, + snapshot +) VALUES ( + $1, + $2, + $3, + $4, + $5::jsonb +) +` + +type InsertInvitationSendResultParams struct { + ScopeHash []byte + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + Outcome string + Snapshot []byte +} + +func (q *Queries) InsertInvitationSendResult(ctx context.Context, arg InsertInvitationSendResultParams) error { + _, err := q.db.Exec(ctx, insertInvitationSendResult, + arg.ScopeHash, + arg.OrganizationID, + arg.InvitationID, + arg.Outcome, + arg.Snapshot, + ) + return err +} + +const listCandidateInvitations = `-- name: ListCandidateInvitations :many +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms, + organization.name AS organization_name +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +INNER JOIN organizations AS organization + ON organization.id = invitation.organization_id +WHERE + invitation.candidate_id = $1 + AND invitation.delivered_at IS NOT NULL + AND ( + $2::timestamptz IS NULL + OR (invitation.delivered_at, invitation.id) < ( + $2::timestamptz, + $3::uuid + ) + ) +ORDER BY invitation.delivered_at DESC, invitation.id DESC +LIMIT $4 +` + +type ListCandidateInvitationsParams struct { + CandidateID pgtype.UUID + AfterDeliveredAt pgtype.Timestamptz + AfterInvitationID pgtype.UUID + RowLimit int32 +} + +type ListCandidateInvitationsRow struct { + ID pgtype.UUID + OrganizationID pgtype.UUID + CandidateID pgtype.UUID + NeedID pgtype.UUID + NeedRequirementsVersion pgtype.Int8 + State string + ExpiryReason pgtype.Text + Version int64 + TermsVersion int64 + ResponsePeriodDays int16 + PolicyVersionID pgtype.UUID + ResponseDeadlineAt pgtype.Timestamptz + SalaryRaiseUsed bool + CreatedBy pgtype.UUID + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + DeliveredAt pgtype.Timestamptz + ViewedAt pgtype.Timestamptz + RespondedAt pgtype.Timestamptz + Terms string + OrganizationName string +} + +// One bounded page of the candidate's inbox: every invitation delivered to +// the candidate, in any later state, newest first by delivery time. Drafts +// have no delivery and are never listed. The candidate scopes the rows, so +// no identifier of another candidate can appear. +func (q *Queries) ListCandidateInvitations(ctx context.Context, arg ListCandidateInvitationsParams) ([]ListCandidateInvitationsRow, error) { + rows, err := q.db.Query(ctx, listCandidateInvitations, + arg.CandidateID, + arg.AfterDeliveredAt, + arg.AfterInvitationID, + arg.RowLimit, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListCandidateInvitationsRow + for rows.Next() { + var i ListCandidateInvitationsRow + if err := rows.Scan( + &i.ID, + &i.OrganizationID, + &i.CandidateID, + &i.NeedID, + &i.NeedRequirementsVersion, + &i.State, + &i.ExpiryReason, + &i.Version, + &i.TermsVersion, + &i.ResponsePeriodDays, + &i.PolicyVersionID, + &i.ResponseDeadlineAt, + &i.SalaryRaiseUsed, + &i.CreatedBy, + &i.CreatedAt, + &i.UpdatedAt, + &i.DeliveredAt, + &i.ViewedAt, + &i.RespondedAt, + &i.Terms, + &i.OrganizationName, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const readCandidateInvitation = `-- name: ReadCandidateInvitation :one +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +WHERE + invitation.candidate_id = $1 + AND invitation.id = $2 + AND invitation.delivered_at IS NOT NULL +` + +type ReadCandidateInvitationParams struct { + CandidateID pgtype.UUID + InvitationID pgtype.UUID +} + +type ReadCandidateInvitationRow struct { + ID pgtype.UUID + OrganizationID pgtype.UUID + CandidateID pgtype.UUID + NeedID pgtype.UUID + NeedRequirementsVersion pgtype.Int8 + State string + ExpiryReason pgtype.Text + Version int64 + TermsVersion int64 + ResponsePeriodDays int16 + PolicyVersionID pgtype.UUID + ResponseDeadlineAt pgtype.Timestamptz + SalaryRaiseUsed bool + CreatedBy pgtype.UUID + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + DeliveredAt pgtype.Timestamptz + ViewedAt pgtype.Timestamptz + RespondedAt pgtype.Timestamptz + Terms string +} + +// Read one delivered invitation addressed to the candidate. A draft and an +// invitation of another candidate find nothing. +func (q *Queries) ReadCandidateInvitation(ctx context.Context, arg ReadCandidateInvitationParams) (ReadCandidateInvitationRow, error) { + row := q.db.QueryRow(ctx, readCandidateInvitation, arg.CandidateID, arg.InvitationID) + var i ReadCandidateInvitationRow + err := row.Scan( + &i.ID, + &i.OrganizationID, + &i.CandidateID, + &i.NeedID, + &i.NeedRequirementsVersion, + &i.State, + &i.ExpiryReason, + &i.Version, + &i.TermsVersion, + &i.ResponsePeriodDays, + &i.PolicyVersionID, + &i.ResponseDeadlineAt, + &i.SalaryRaiseUsed, + &i.CreatedBy, + &i.CreatedAt, + &i.UpdatedAt, + &i.DeliveredAt, + &i.ViewedAt, + &i.RespondedAt, + &i.Terms, + ) + return i, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 919f467..841b9b2 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -609,6 +609,14 @@ type InvitationEvent struct { OccurredAt pgtype.Timestamptz } +type InvitationSendResult struct { + ScopeHash []byte + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + Outcome string + Snapshot []byte +} + type InvitationTermsVersion struct { InvitationID pgtype.UUID OrganizationID pgtype.UUID diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index cd65cc4..9500f1a 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -201,6 +201,11 @@ type Querier interface { // The restricting foreign key is checked at the end of the statement, after // these rows are gone. DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) + // The conditional update is the compare-and-swap of a send: it applies only to + // a draft whose version is still the one the caller read, records the first + // delivery with its deadline, and advances the version by one. No row is + // returned when it lost a race or the invitation is no longer a draft. + DeliverInvitation(ctx context.Context, arg DeliverInvitationParams) (pgtype.UUID, error) // Lock order. Every transaction that writes mail_quota_usage first creates // and locks all the usage rows it will touch with EnsureMailQuotaRows and // LockMailQuotaRows, which both work in (period_kind, period_start) order, @@ -297,6 +302,7 @@ type Querier interface { // Explains why ConsumeEmailToken matched no row. GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error) + GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error) // The caller holds the attempt row lock, so the last mark is stable. GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error) GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error) @@ -472,6 +478,7 @@ type Querier interface { // current terms version is checked when the transaction commits. InsertInvitation(ctx context.Context, arg InsertInvitationParams) error InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error + InsertInvitationSendResult(ctx context.Context, arg InsertInvitationSendResultParams) error InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error @@ -592,6 +599,11 @@ type Querier interface { // (hidden_at, organization_id) position of the last record of the previous // page. ListCandidateHiddenOrganizations(ctx context.Context, arg ListCandidateHiddenOrganizationsParams) ([]ListCandidateHiddenOrganizationsRow, error) + // One bounded page of the candidate's inbox: every invitation delivered to + // the candidate, in any later state, newest first by delivery time. Drafts + // have no delivery and are never listed. The candidate scopes the rows, so + // no identifier of another candidate can appear. + ListCandidateInvitations(ctx context.Context, arg ListCandidateInvitationsParams) ([]ListCandidateInvitationsRow, error) // The same selection for the candidate's own card preview, so the candidate // sees what an organization would read. It is scoped by the owner and runs // after the caller locked the effective C2 and publication; it does not apply @@ -831,6 +843,9 @@ type Querier interface { // Deletes at most batch_limit expired records. Locked rows are skipped, so // the statement never waits for a concurrent reservation. PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error) + // Read one delivered invitation addressed to the candidate. A draft and an + // invitation of another candidate find nothing. + ReadCandidateInvitation(ctx context.Context, arg ReadCandidateInvitationParams) (ReadCandidateInvitationRow, error) // Queries of the candidate visibility settings: the publication of // the card, the search status, the hidden organizations, and the history of // these settings. Every statement is scoped by the candidate's user_id, and diff --git a/backend/internal/bootstrap/invitation.go b/backend/internal/bootstrap/invitation.go index 64be4b6..98f43c5 100644 --- a/backend/internal/bootstrap/invitation.go +++ b/backend/internal/bootstrap/invitation.go @@ -6,18 +6,27 @@ import ( "log/slog" "time" + "github.com/google/uuid" + "lincodex/backend/config" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/companyquota" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/invitation" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" ) const invitationPoolMaxConns = 4 -// newInvitationHandler builds the invitation draft operations. They resolve a -// card handle through the same visibility service as the card read and the -// search, so the pseudonym key and the cohort rules are the ones of the cards. +// newInvitationHandler builds the invitation operations. They resolve a card +// handle through the same visibility service as the card read and the search, +// so the pseudonym key and the cohort rules are the ones of the cards. A send +// charges the shared company quota and records its notification and email +// through the outbox of the same transaction. func newInvitationHandler( ctx context.Context, settings config.Config, @@ -45,8 +54,23 @@ func newInvitationHandler( pool.Close() return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create view service: %w", err) } + renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create mail renderer: %w", err) + } + notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(renderer), time.Now)) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create notifier: %w", err) + } + quota := companyquota.NewService(time.Now) service, err := invitation.NewService(invitation.Dependencies{ - Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, Clock: time.Now, + Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, + 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, }) if err != nil { pool.Close() diff --git a/backend/internal/domain/invitation.go b/backend/internal/domain/invitation.go index 54d61cb..f60dd37 100644 --- a/backend/internal/domain/invitation.go +++ b/backend/internal/domain/invitation.go @@ -232,7 +232,11 @@ func RestoreInvitation(stored StoredInvitation) (Invitation, error) { return Invitation{}, fmt.Errorf("%s - validate terms: %w", location, err) } stored.Terms = stored.Terms.Clone() + // Every time of an invitation is kept in UTC, whatever the time zone of + // the storage session, so a response is the same after a read. stored.CreatedAt, stored.UpdatedAt = stored.CreatedAt.UTC(), stored.UpdatedAt.UTC() + stored.ResponseDeadlineAt, stored.DeliveredAt = utcInvitationTime(stored.ResponseDeadlineAt), utcInvitationTime(stored.DeliveredAt) + stored.ViewedAt, stored.RespondedAt = utcInvitationTime(stored.ViewedAt), utcInvitationTime(stored.RespondedAt) if stored.Need != nil { need := *stored.Need stored.Need = &need @@ -286,6 +290,14 @@ func storedInvitationLifecycleDefect(stored StoredInvitation) string { return "" } +func utcInvitationTime(value *time.Time) *time.Time { + if value == nil { + return nil + } + converted := value.UTC() + return &converted +} + func validInvitationTime(value time.Time) bool { return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 } diff --git a/backend/internal/domain/invitation_delivery.go b/backend/internal/domain/invitation_delivery.go new file mode 100644 index 0000000..1ae2b55 --- /dev/null +++ b/backend/internal/domain/invitation_delivery.go @@ -0,0 +1,123 @@ +package domain + +import ( + "fmt" + "log/slog" + "time" + + "github.com/google/uuid" +) + +// InvitationEventDelivered is the audit event of a send. Sending itself is an +// internal step and never a state: the event records the version at which +// the draft became a delivered invitation. +const InvitationEventDelivered InvitationEventKind = "delivered" + +// IsDelivered reports whether the invitation has reached the candidate's +// inbox. A delivery is never undone, so every later state keeps it. +func (invitation Invitation) IsDelivered() bool { return invitation.record.DeliveredAt != nil } + +// Deliver returns the draft as the next version in the state delivered. The +// response deadline starts at the delivery: deliveredAt plus the response +// period of the draft, in whole calendar days. The deadline is fixed here and +// nothing else moves it, so a notification or its retries cannot change it. +func (invitation Invitation) Deliver(deliveredAt time.Time) (Invitation, error) { + const location = "Invitation.Deliver" + if invitation.State() != InvitationDraft || invitation.IsDelivered() { + return Invitation{}, fmt.Errorf("%s - only an unsent draft can be delivered: %w", location, ErrInvitationNotDraft) + } + if !validInvitationTime(deliveredAt) || deliveredAt.Before(invitation.record.UpdatedAt) { + return Invitation{}, fmt.Errorf("%s - delivery time must be set and not before the last change: %w", location, ErrInvalidInvitation) + } + deliveredAt = deliveredAt.UTC() + deadline := deliveredAt.Add(CalendarDays(invitation.record.ResponsePeriodDays).Duration()) + next := invitation.Stored() + next.State = string(InvitationDelivered) + next.Version++ + next.UpdatedAt = deliveredAt + next.DeliveredAt = &deliveredAt + next.ResponseDeadlineAt = &deadline + delivered, err := RestoreInvitation(next) + if err != nil { + return Invitation{}, fmt.Errorf("%s - restore delivered invitation: %w", location, err) + } + return delivered, nil +} + +// DeliveryEvent builds the audit event of the delivered version this +// invitation has just reached. It names the actor who sent it and no field. +func (invitation Invitation) DeliveryEvent(actorID uuid.UUID) (InvitationEvent, error) { + const location = "Invitation.DeliveryEvent" + if actorID == uuid.Nil { + return InvitationEvent{}, fmt.Errorf("%s - actor must be set: %w", location, ErrInvalidInvitation) + } + if invitation.State() != InvitationDelivered || !invitation.IsDelivered() { + return InvitationEvent{}, fmt.Errorf("%s - the invitation must be delivered: %w", location, ErrInvalidInvitation) + } + id, err := uuid.NewV7() + if err != nil { + return InvitationEvent{}, fmt.Errorf("%s - generate event ID: %w", location, err) + } + return InvitationEvent{ + ID: id, InvitationID: invitation.record.ID, OrganizationID: invitation.record.OrganizationID, + Version: invitation.record.Version, TermsVersion: invitation.record.TermsVersion, Kind: InvitationEventDelivered, + ActorID: actorID, ChangedFields: []InvitationChangedField{}, OccurredAt: *invitation.record.DeliveredAt, + }, nil +} + +// InvitationOrganizationRef names the organization that sent an invitation, +// as the candidate sees it. +type InvitationOrganizationRef struct { + ID uuid.UUID + Name string +} + +// CandidateInvitationSummary is an invitation in the inbox of the candidate it +// is addressed to: the organization, the state, the versions, the role, the +// salary range, the work formats, and the deadline. It has no candidate +// identifier, handle, need, or salary indicator. +type CandidateInvitationSummary struct { + ID uuid.UUID + Organization InvitationOrganizationRef + State InvitationState + ExpiryReason *InvitationExpiryReason + Version int64 + TermsVersion int64 + RoleTitle string + Salary SalaryRange + WorkFormats []NeedWorkFormat + ResponseDeadlineAt time.Time + DeliveredAt time.Time + ViewedAt *time.Time + UpdatedAt time.Time +} + +// CandidateSummary returns the inbox entry of a delivered invitation for the +// organization that sent it. +func (invitation Invitation) CandidateSummary(organization InvitationOrganizationRef) (CandidateInvitationSummary, error) { + const location = "Invitation.CandidateSummary" + stored := invitation.Stored() + if stored.DeliveredAt == nil || stored.ResponseDeadlineAt == nil { + return CandidateInvitationSummary{}, fmt.Errorf("%s - only a delivered invitation is in the inbox: %w", location, ErrInvalidInvitation) + } + if organization.ID != stored.OrganizationID || organization.Name == "" { + return CandidateInvitationSummary{}, fmt.Errorf("%s - the organization must be the sender: %w", location, ErrInvalidInvitation) + } + snapshot := invitation.Snapshot() + return CandidateInvitationSummary{ + ID: stored.ID, Organization: organization, State: snapshot.State, ExpiryReason: snapshot.ExpiryReason, + Version: stored.Version, TermsVersion: stored.TermsVersion, RoleTitle: stored.Terms.RoleTitle, + Salary: stored.Terms.Salary, WorkFormats: stored.Terms.WorkFormats, + ResponseDeadlineAt: stored.ResponseDeadlineAt.UTC(), DeliveredAt: stored.DeliveredAt.UTC(), + ViewedAt: stored.ViewedAt, UpdatedAt: stored.UpdatedAt, + }, nil +} + +func (summary CandidateInvitationSummary) String() string { return redactedInvitation } +func (summary CandidateInvitationSummary) GoString() string { return redactedInvitation } +func (summary CandidateInvitationSummary) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedInvitation) +} +func (summary CandidateInvitationSummary) LogValue() slog.Value { + return slog.StringValue(redactedInvitation) +} diff --git a/backend/internal/domain/invitation_delivery_test.go b/backend/internal/domain/invitation_delivery_test.go new file mode 100644 index 0000000..445338b --- /dev/null +++ b/backend/internal/domain/invitation_delivery_test.go @@ -0,0 +1,92 @@ +package domain + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestDeliverStartsTheDeadlineAtTheDeliveryForEveryPeriod(t *testing.T) { + for _, period := range []CalendarDays{3, 7, 14} { + input := validInvitationDraftInput() + input.Content.ResponsePeriod = period + draft, err := NewInvitationDraft(input) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + deliveredAt := input.At.Add(time.Hour) + delivered, err := draft.Deliver(deliveredAt) + if err != nil { + t.Fatalf("Deliver(%d days) error = %v", period, err) + } + snapshot := delivered.Snapshot() + if snapshot.State != InvitationDelivered || snapshot.Version != draft.Version()+1 || snapshot.TermsVersion != draft.TermsVersion() || + !snapshot.DeliveredAt.Equal(deliveredAt) || !snapshot.ResponseDeadlineAt.Equal(deliveredAt.Add(time.Duration(period)*24*time.Hour)) || + !snapshot.UpdatedAt.Equal(deliveredAt) || !delivered.IsDelivered() || draft.IsDelivered() { + t.Fatalf("delivered %d-day invitation = %+v", period, snapshot) + } + event, err := delivered.DeliveryEvent(input.ActorID) + if err != nil { + t.Fatalf("DeliveryEvent() error = %v", err) + } + if event.Kind != InvitationEventDelivered || event.Version != snapshot.Version || len(event.ChangedFields) != 0 || + !event.OccurredAt.Equal(deliveredAt) { + t.Fatalf("delivery event = %+v", event) + } + } +} + +func TestDeliverRefusesAnythingButAnUnsentDraft(t *testing.T) { + input := validInvitationDraftInput() + draft, err := NewInvitationDraft(input) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + if _, err := draft.Deliver(input.At.Add(-time.Second)); !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("Deliver(before the last change) error = %v, want ErrInvalidInvitation", err) + } + delivered, err := draft.Deliver(input.At) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + if _, err := delivered.Deliver(input.At.Add(time.Hour)); !errors.Is(err, ErrInvitationNotDraft) { + t.Fatalf("Deliver(delivered) error = %v, want ErrInvitationNotDraft", err) + } + if _, err := draft.DeliveryEvent(input.ActorID); !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("DeliveryEvent(draft) error = %v, want ErrInvalidInvitation", err) + } +} + +func TestCandidateSummaryCarriesNoCandidateIdentifier(t *testing.T) { + input := validInvitationDraftInput() + draft, err := NewInvitationDraft(input) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + if _, err := draft.CandidateSummary(InvitationOrganizationRef{ID: input.OrganizationID, Name: "Sender"}); !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("CandidateSummary(draft) error = %v, want ErrInvalidInvitation", err) + } + delivered, err := draft.Deliver(input.At) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + if _, err := delivered.CandidateSummary(InvitationOrganizationRef{ID: uuid.New(), Name: "Other"}); !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("CandidateSummary(other organization) error = %v, want ErrInvalidInvitation", err) + } + summary, err := delivered.CandidateSummary(InvitationOrganizationRef{ID: input.OrganizationID, Name: "Sender"}) + if err != nil { + t.Fatalf("CandidateSummary() error = %v", err) + } + if summary.State != InvitationDelivered || summary.RoleTitle != input.Content.Terms.RoleTitle || !summary.DeliveredAt.Equal(input.At) { + t.Fatalf("summary = %+v", summary) + } + for _, text := range []string{fmt.Sprint(summary), fmt.Sprintf("%+v", summary), fmt.Sprintf("%#v", summary)} { + if strings.Contains(text, input.CandidateID.String()) || strings.Contains(text, summary.RoleTitle) { + t.Fatalf("formatted summary leaks its content: %s", text) + } + } +} diff --git a/backend/internal/port/outbound/invitations.go b/backend/internal/port/outbound/invitations.go index 523e9be..ae76fc7 100644 --- a/backend/internal/port/outbound/invitations.go +++ b/backend/internal/port/outbound/invitations.go @@ -24,10 +24,14 @@ var ( // ErrInvitationCreationResultNotFound reports a missing original response // for a live idempotency record. ErrInvitationCreationResultNotFound = errors.New("organization invitation creation result not found") + + // ErrInvitationSendResultNotFound reports a missing outcome of a send for + // a live idempotency record. + ErrInvitationSendResultNotFound = errors.New("organization invitation send result not found") ) -// MaxInvitationPageSize is the largest organization-scoped page in the -// contract. +// MaxInvitationPageSize is the largest organization-scoped or candidate page +// in the contract. const MaxInvitationPageSize = 100 // InvitationRepositories exposes the invitation storage bound to one @@ -35,6 +39,7 @@ const MaxInvitationPageSize = 100 type InvitationRepositories interface { Invitations() InvitationRepository InvitationCreationResults() InvitationCreationResultRepository + InvitationSendResults() InvitationSendResultRepository } // InvitationRepository stores invitations, their immutable terms versions, and @@ -69,6 +74,24 @@ type InvitationRepository interface { // NeedVersionExists reports whether the need of the organization has had // the requirements version. NeedVersionExists(ctx context.Context, organizationID, needID uuid.UUID, requirementsVersion int64) (bool, error) + + // Deliver moves a draft to its delivered version in the surrounding + // transaction: the invitation row moves from expectedVersion to the + // version of next with the delivery time and the deadline of next, and + // the audit event is recorded. The terms are not touched. It returns + // ErrInvitationVersionConflict when the stored row is not a draft at + // expectedVersion. + Deliver(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error + + // ListForCandidate returns one newest-first page of the invitations + // delivered to the candidate, in any later state, with the name of the + // organization that sent each of them. Drafts are never listed. + ListForCandidate(ctx context.Context, query CandidateInvitationListQuery) (CandidateInvitationPage, error) + + // GetForCandidate returns a delivered invitation addressed to the + // candidate. A draft, an invitation of another candidate, and an unknown + // identifier return ErrInvitationNotFound alike. + GetForCandidate(ctx context.Context, candidateID, invitationID uuid.UUID) (domain.Invitation, error) } // InvitationCreationResultRepository stores the original response of a @@ -79,6 +102,61 @@ type InvitationCreationResultRepository interface { GetCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (domain.OrganizationInvitationView, error) } +// InvitationSendOutcome is the stored result of a send under an +// Idempotency-Key. The contract stores a success, a missing invitation, and a +// state conflict; other failures are not stored. +type InvitationSendOutcome string + +const ( + InvitationSendSent InvitationSendOutcome = "sent" + InvitationSendNotFound InvitationSendOutcome = "not_found" + InvitationSendStateConflict InvitationSendOutcome = "state_conflict" +) + +// InvitationSendResult is the outcome of one send. View is set only for +// InvitationSendSent and is the original response. +type InvitationSendResult struct { + OrganizationID uuid.UUID + InvitationID uuid.UUID + Outcome InvitationSendOutcome + View *domain.OrganizationInvitationView +} + +// InvitationSendResultRepository stores the outcome of an idempotent send. +// The scope references the generic idempotency record, so the outcome is +// removed when that record is purged. +type InvitationSendResultRepository interface { + SaveSendResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationSendResult) error + GetSendResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationSendResult, error) +} + +// CandidateInvitationListQuery selects one page of one candidate's inbox. +type CandidateInvitationListQuery struct { + CandidateID uuid.UUID + After *CandidateInvitationPosition + Limit int32 +} + +// CandidateInvitationPosition is the stable newest-first ordering key of the +// candidate's inbox. +type CandidateInvitationPosition struct { + DeliveredAt time.Time + InvitationID uuid.UUID +} + +// CandidateInvitationEntry is one invitation of the candidate's inbox with +// the current name of the organization that sent it. +type CandidateInvitationEntry struct { + Invitation domain.Invitation + OrganizationName string +} + +// CandidateInvitationPage contains one page of the candidate's inbox. +type CandidateInvitationPage struct { + Items []CandidateInvitationEntry + HasMore bool +} + // InvitationListQuery selects one page within a single organization. type InvitationListQuery struct { OrganizationID uuid.UUID diff --git a/backend/internal/usecase/invitation/candidate_inbox.go b/backend/internal/usecase/invitation/candidate_inbox.go new file mode 100644 index 0000000..3f2acfd --- /dev/null +++ b/backend/internal/usecase/invitation/candidate_inbox.go @@ -0,0 +1,85 @@ +package invitation + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const listMineLocation = "invitation.Service.ListMine" + +// CandidateListCommand selects one page of the inbox of the session candidate. +// The candidate comes only from the session. +type CandidateListCommand struct { + ActorID uuid.UUID + After *outbound.CandidateInvitationPosition + Limit int32 +} + +// CandidatePage is one page of the candidate's inbox, newest first by +// delivery time. +type CandidatePage struct { + Items []domain.CandidateInvitationSummary + HasMore bool +} + +// ListMine reads one page of the invitations delivered to the session +// candidate, in any later state. Listing has no side effect: it records no +// view. Drafts and invitations of other candidates are never listed. +func (service *Service) ListMine(ctx context.Context, command CandidateListCommand) (CandidatePage, error) { + if command.ActorID == uuid.Nil { + return CandidatePage{}, fmt.Errorf("%s - actor ID must be set: %w", listMineLocation, ErrForbidden) + } + if command.Limit < 1 || command.Limit > outbound.MaxInvitationPageSize { + return CandidatePage{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", listMineLocation, outbound.MaxInvitationPageSize, ErrInvalidRequest) + } + var result CandidatePage + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil { + return err + } + page, err := unit.Invitations().ListForCandidate(ctx, outbound.CandidateInvitationListQuery{ + CandidateID: command.ActorID, After: command.After, Limit: command.Limit, + }) + if err != nil { + return fmt.Errorf("%s - list invitations: %w", listMineLocation, err) + } + result = CandidatePage{Items: make([]domain.CandidateInvitationSummary, 0, len(page.Items)), HasMore: page.HasMore} + for _, entry := range page.Items { + summary, err := entry.Invitation.CandidateSummary(domain.InvitationOrganizationRef{ + ID: entry.Invitation.OrganizationID(), Name: entry.OrganizationName, + }) + if err != nil { + return fmt.Errorf("%s - build inbox entry: %w", listMineLocation, err) + } + result.Items = append(result.Items, summary) + } + return nil + }) + if err != nil { + return CandidatePage{}, fmt.Errorf("%s - run transaction: %w", listMineLocation, err) + } + return result, nil +} + +// authorizeCandidate requires an existing candidate account with a confirmed +// email. An employer account, which has no inbox of invitations, is refused. +func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error { + const location = "invitation.authorizeCandidate" + user, err := unit.Users().GetByID(ctx, actorID) + if errors.Is(err, outbound.ErrUserNotFound) { + return fmt.Errorf("%s - require existing candidate account: %w", location, ErrForbidden) + } + if err != nil { + return fmt.Errorf("%s - read account: %w", location, err) + } + if user.Scenario != domain.ScenarioCandidate || !user.EmailVerified() { + return fmt.Errorf("%s - require verified candidate account: %w", location, ErrForbidden) + } + return nil +} diff --git a/backend/internal/usecase/invitation/send.go b/backend/internal/usecase/invitation/send.go new file mode 100644 index 0000000..fa192ef --- /dev/null +++ b/backend/internal/usecase/invitation/send.go @@ -0,0 +1,346 @@ +package invitation + +import ( + "context" + "errors" + "fmt" + "strconv" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/candidateview" +) + +var ( + // ErrSendBlocked reports a send that the state of the invitation or the + // current visibility of its candidate does not allow. The API answers 409 + // state_conflict without telling which rule applied. + ErrSendBlocked = errors.New("organization invitation cannot be sent") + // ErrInvitationQuotaExceeded reports that the rolling invitation quota of + // the organization is spent. QuotaExceededError carries the retry time. + ErrInvitationQuotaExceeded = errors.New("organization invitation quota is exhausted") +) + +// QuotaExceededError carries only the time when the organization quota frees +// room again; it holds no candidate or invitation value. +type QuotaExceededError struct{ RetryAt time.Time } + +func (err *QuotaExceededError) Error() string { return ErrInvitationQuotaExceeded.Error() } +func (err *QuotaExceededError) Unwrap() error { return ErrInvitationQuotaExceeded } + +const ( + sendOperation = "organization_invitation.send" + sendLocation = "invitation.Service.Send" + // maxSendAttempts bounds the repeats of a send after the visible cohort + // changed while it was locked, as for a create. + maxSendAttempts = 3 +) + +// SendCommand binds the authenticated actor and the path to one send of the +// current terms version of a draft. +type SendCommand struct { + ActorID uuid.UUID + OrganizationID uuid.UUID + InvitationID uuid.UUID + IdempotencyKey string + ExpectedVersion int64 +} + +type sendRequest struct { + fingerprint [outbound.IdempotencyDigestSize]byte + scope [outbound.IdempotencyDigestSize]byte + record outbound.IdempotencyRecord + now time.Time +} + +// sendOutcome is what a committed send transaction decided: the invitation, +// or a refusal that the contract stores under the key and that the caller +// returns after the commit. +type sendOutcome struct { + view domain.OrganizationInvitationView + refusal error +} + +// Send delivers the current terms version of a draft to the candidate's +// inbox. In one transaction it checks the owner, the key, the invitation, its +// version and state, and the current visibility of the candidate, spends one +// invitation of the organization quota, records the delivery with its +// deadline and the audit event, and writes the outbox events of the +// notification. The internal sending step is never visible: a success means +// the invitation is already delivered. A send of an invitation that was +// already delivered answers with its current state and charges nothing. +func (service *Service) Send(ctx context.Context, command SendCommand) (domain.OrganizationInvitationView, error) { + request, err := service.prepareSend(command) + if err != nil { + return domain.OrganizationInvitationView{}, err + } + var outcome sendOutcome + for range maxSendAttempts { + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + outcome, err = service.sendInTransaction(ctx, unit, command, request) + return err + }) + if !errors.Is(err, candidateview.ErrConcurrentVisibilityChange) { + break + } + } + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", sendLocation, err) + } + if outcome.refusal != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - %w", sendLocation, outcome.refusal) + } + return outcome.view, nil +} + +func (service *Service) prepareSend(command SendCommand) (sendRequest, error) { + const location = "invitation.Service.prepareSend" + switch { + case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil: + return sendRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden) + case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize: + return sendRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey) + case command.ExpectedVersion < 1: + return sendRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"}) + } + now, err := service.now(location) + if err != nil { + return sendRequest{}, err + } + // The fingerprint covers the path and the body, so one key used for + // another invitation or another version is a reused key. + canonical := []byte(`{"invitation_id":"` + command.InvitationID.String() + `","expected_version":` + + strconv.FormatInt(command.ExpectedVersion, 10) + `}`) + principal := command.ActorID.String() + ":" + command.OrganizationID.String() + fingerprint := service.keyring.Fingerprint(canonical) + scope := service.keyring.IdempotencyScope(sendOperation, command.IdempotencyKey, principal) + return sendRequest{ + fingerprint: fingerprint, scope: scope, now: now, + record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)}, + }, nil +} + +// sendInTransaction follows the order of checks of the contract after the +// HTTP boundary: the owner, the key, the invitation (404, stored), the repeat +// of a completed send (200), the version (412, not stored), the state and the +// visibility of the candidate (409, stored), and the quota (429, not stored). +// The locks follow the order of every invitation command: the organization, +// the membership, the invitation row, and then the cohort of the cards. +func (service *Service) sendInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command SendCommand, + request sendRequest, +) (sendOutcome, error) { + if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, sendLocation); err != nil { + return sendOutcome{}, err + } + if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, sendLocation); err != nil { + return sendOutcome{}, err + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return sendOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", sendLocation, err) + } + if !created { + return replaySend(ctx, unit, request, command, stored) + } + if command.InvitationID == uuid.Nil { + return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendNotFound) + } + current, err := unit.Invitations().GetForUpdate(ctx, command.OrganizationID, command.InvitationID) + if errors.Is(err, outbound.ErrInvitationNotFound) { + return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendNotFound) + } + if err != nil { + return sendOutcome{}, fmt.Errorf("%s - lock invitation: %w", sendLocation, err) + } + if current.IsDelivered() { + // A completed send answers with the current invitation, whatever the + // key or the version, and charges nothing again. + return service.completeSend(ctx, unit, request, current) + } + if command.ExpectedVersion != current.Version() { + return sendOutcome{}, fmt.Errorf("%s - compare expected version: %w", sendLocation, domain.ErrInvitationVersionConflict) + } + if current.State() != domain.InvitationDraft { + return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendStateConflict) + } + visible, err := service.candidateStillVisible(ctx, unit, command, current) + if err != nil { + return sendOutcome{}, err + } + if !visible { + return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendStateConflict) + } + if err := service.chargeQuota(ctx, unit, command, current); err != nil { + return sendOutcome{}, err + } + delivered, err := service.deliver(ctx, unit, command, current, request.now) + if err != nil { + return sendOutcome{}, err + } + return service.completeSend(ctx, unit, request, delivered) +} + +// candidateStillVisible runs the visibility barrier of the card read again: +// a draft keeps its candidate after a revoked publication C2, a hiding of the +// organization, or a cohort that fell below its minimum, and none of them may +// be bypassed by sending an older draft. The answer does not say which rule +// applied. +func (service *Service) candidateStillVisible( + ctx context.Context, + unit outbound.UnitOfWork, + command SendCommand, + current domain.Invitation, +) (bool, error) { + handle, err := service.pseudonymKey.ForOrganization(current.OrganizationID(), current.CandidateID()) + if err != nil { + return false, fmt.Errorf("%s - derive candidate alias: %w", sendLocation, err) + } + candidateID, err := service.candidates(ctx, unit, command.ActorID, command.OrganizationID, handle) + switch { + case errors.Is(err, candidateview.ErrCandidateCardNotFound), errors.Is(err, candidateview.ErrInvalidCandidateHandle): + return false, nil + case err != nil: + return false, fmt.Errorf("%s - check candidate visibility: %w", sendLocation, err) + } + return candidateID == current.CandidateID(), nil +} + +// chargeQuota spends one invitation of the organization quota. The charge is +// keyed by the invitation, so it is written once; a denial writes nothing and +// the whole send rolls back. +func (service *Service) chargeQuota(ctx context.Context, unit outbound.UnitOfWork, command SendCommand, current domain.Invitation) error { + organization, _, err := unit.Organizations().GetForMember(ctx, command.OrganizationID, command.ActorID) + if err != nil { + return fmt.Errorf("%s - read organization: %w", sendLocation, err) + } + decision, err := service.quota(ctx, unit, organization, current.ID()) + if err != nil { + return fmt.Errorf("%s - reserve invitation quota: %w", sendLocation, err) + } + if !decision.Allowed { + return &QuotaExceededError{RetryAt: decision.RetryAt.UTC()} + } + return nil +} + +// deliver stores the delivered version with its deadline and audit event and +// writes the notification events in the same transaction. +func (service *Service) deliver( + ctx context.Context, + unit outbound.UnitOfWork, + command SendCommand, + current domain.Invitation, + now time.Time, +) (domain.Invitation, error) { + // A clock that stepped back must not deliver before the last change. + at := now + if at.Before(current.UpdatedAt()) { + at = current.UpdatedAt() + } + delivered, err := current.Deliver(at) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - deliver draft: %w", sendLocation, err) + } + event, err := delivered.DeliveryEvent(command.ActorID) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - build audit event: %w", sendLocation, err) + } + if err := unit.Invitations().Deliver(ctx, current.Version(), delivered, event); err != nil { + if errors.Is(err, outbound.ErrInvitationVersionConflict) { + return domain.Invitation{}, fmt.Errorf("%s - store delivery: %w", sendLocation, domain.ErrInvitationVersionConflict) + } + return domain.Invitation{}, fmt.Errorf("%s - store delivery: %w", sendLocation, err) + } + if err := service.notifier.InvitationDelivered(ctx, unit, delivered); err != nil { + return domain.Invitation{}, fmt.Errorf("%s - record notification: %w", sendLocation, err) + } + return delivered, nil +} + +// completeSend stores the successful response under the key. +func (service *Service) completeSend( + ctx context.Context, + unit outbound.UnitOfWork, + request sendRequest, + invitation domain.Invitation, +) (sendOutcome, error) { + view, err := service.view(invitation) + if err != nil { + return sendOutcome{}, err + } + result := outbound.InvitationSendResult{ + OrganizationID: invitation.OrganizationID(), InvitationID: invitation.ID(), Outcome: outbound.InvitationSendSent, View: &view, + } + if err := finishSend(ctx, unit, request, result); err != nil { + return sendOutcome{}, err + } + return sendOutcome{view: view}, nil +} + +// refuseSend stores a refusal that the contract keeps under the key and lets +// the transaction commit, since nothing else was written. +func (service *Service) refuseSend( + ctx context.Context, + unit outbound.UnitOfWork, + command SendCommand, + request sendRequest, + outcome outbound.InvitationSendOutcome, +) (sendOutcome, error) { + result := outbound.InvitationSendResult{OrganizationID: command.OrganizationID, InvitationID: command.InvitationID, Outcome: outcome} + if err := finishSend(ctx, unit, request, result); err != nil { + return sendOutcome{}, err + } + return sendOutcome{refusal: sendRefusal(outcome)}, nil +} + +func finishSend(ctx context.Context, unit outbound.UnitOfWork, request sendRequest, result outbound.InvitationSendResult) error { + if err := unit.InvitationSendResults().SaveSendResult(ctx, request.scope, result); err != nil { + return fmt.Errorf("%s - store outcome: %w", sendLocation, err) + } + if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { + return fmt.Errorf("%s - purge expired idempotency records: %w", sendLocation, err) + } + return nil +} + +func sendRefusal(outcome outbound.InvitationSendOutcome) error { + if outcome == outbound.InvitationSendNotFound { + return outbound.ErrInvitationNotFound + } + return ErrSendBlocked +} + +// replaySend returns the stored outcome of the same request, or refuses a key +// used with another request. +func replaySend( + ctx context.Context, + unit outbound.UnitOfWork, + request sendRequest, + command SendCommand, + stored outbound.IdempotencyRecord, +) (sendOutcome, error) { + if stored.Fingerprint != request.fingerprint { + return sendOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", sendLocation, ErrIdempotencyKeyReused) + } + original, err := unit.InvitationSendResults().GetSendResult(ctx, request.scope) + if err != nil { + return sendOutcome{}, fmt.Errorf("%s - read original outcome: %w", sendLocation, err) + } + if original.OrganizationID != command.OrganizationID { + return sendOutcome{}, fmt.Errorf("%s - validate original outcome: %w", sendLocation, domain.ErrInvalidInvitation) + } + if original.Outcome != outbound.InvitationSendSent { + return sendOutcome{refusal: sendRefusal(original.Outcome)}, nil + } + if original.View == nil || original.InvitationID != command.InvitationID { + return sendOutcome{}, fmt.Errorf("%s - validate original response: %w", sendLocation, domain.ErrInvalidInvitation) + } + return sendOutcome{view: *original.View}, nil +} diff --git a/backend/internal/usecase/invitation/send_test.go b/backend/internal/usecase/invitation/send_test.go new file mode 100644 index 0000000..65e85e9 --- /dev/null +++ b/backend/internal/usecase/invitation/send_test.go @@ -0,0 +1,180 @@ +package invitation + +import ( + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// draftFor creates a draft for a new visible candidate and returns it with +// the candidate's handle and identifier. +func (test *harness) draftFor(t *testing.T, period *int32) (domain.OrganizationInvitationView, string, uuid.UUID) { + t.Helper() + handle, candidateID := test.showCandidate(t) + command := test.createCommand(handle, "create-"+handle) + command.ResponsePeriodDays = period + view, err := test.service.Create(t.Context(), command) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + return view, handle, candidateID +} + +func (test *harness) sendCommand(invitationID uuid.UUID, version int64, key string) SendCommand { + return SendCommand{ + ActorID: test.actorID, OrganizationID: test.organizationID, InvitationID: invitationID, + IdempotencyKey: key, ExpectedVersion: version, + } +} + +func TestSendDeliversTheDraftWithTheDeadlineChargeAndNotificationAtOnce(t *testing.T) { + test := newHarness(t) + threeDays := int32(3) + draft, _, _ := test.draftFor(t, &threeDays) + sentAt := time.Date(2026, time.October, 9, 11, 0, 0, 0, time.UTC) + test.setTime(sentAt) + + view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-1")) + if err != nil { + t.Fatalf("Send() error = %v", err) + } + if view.State != domain.InvitationDelivered || view.Version != draft.Version+1 || view.TermsVersion != draft.TermsVersion || + view.DeliveredAt == nil || !view.DeliveredAt.Equal(sentAt) || + view.ResponseDeadlineAt == nil || !view.ResponseDeadlineAt.Equal(sentAt.Add(3*24*time.Hour)) { + t.Fatalf("sent view = %+v, want delivered now with a deadline three days later", view.InvitationSnapshot) + } + state := test.transactor.snapshot() + last := state.events[len(state.events)-1] + if last.Kind != domain.InvitationEventDelivered || last.Version != view.Version || last.ActorID != test.actorID || len(last.ChangedFields) != 0 { + t.Fatalf("audit event = %+v, want one delivery event of the sent version", last) + } + if len(state.charged) != 1 || state.charged[0] != draft.ID || len(state.notified) != 1 || state.notified[0] != draft.ID { + t.Fatalf("charged %v and notified %v, want the invitation once each", state.charged, state.notified) + } +} + +func TestSendRepeatsReturnTheSameInvitationWithoutASecondChargeOrEvent(t *testing.T) { + test := newHarness(t) + draft, _, _ := test.draftFor(t, nil) + first, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-repeat")) + if err != nil { + t.Fatalf("Send() error = %v", err) + } + events := len(test.transactor.snapshot().events) + test.setTime(time.Date(2026, time.October, 10, 10, 0, 0, 0, time.UTC)) + + replay, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-repeat")) + if err != nil || replay.Version != first.Version || !replay.ResponseDeadlineAt.Equal(*first.ResponseDeadlineAt) { + t.Fatalf("replay = %+v, %v; want the original response", replay.InvitationSnapshot, err) + } + // A new key and the older draft version still answer with the current + // invitation instead of a version conflict. + again, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-repeat-new-key")) + if err != nil || again.State != domain.InvitationDelivered || !again.DeliveredAt.Equal(*first.DeliveredAt) { + t.Fatalf("repeat with a new key = %+v, %v; want the delivered invitation", again.InvitationSnapshot, err) + } + state := test.transactor.snapshot() + if len(state.charged) != 1 || len(state.notified) != 1 || len(state.events) != events { + t.Fatalf("repeats charged %d, notified %d, events %d -> %d; want nothing new", len(state.charged), len(state.notified), events, len(state.events)) + } + other, _, _ := test.draftFor(t, nil) + if _, err := test.service.Send(t.Context(), test.sendCommand(other.ID, other.Version, "send-repeat")); !errors.Is(err, ErrIdempotencyKeyReused) { + t.Fatalf("Send(same key, other invitation) error = %v, want ErrIdempotencyKeyReused", err) + } +} + +func TestSendRefusesAStaleVersionWithoutStoringTheOutcome(t *testing.T) { + test := newHarness(t) + draft, _, _ := test.draftFor(t, nil) + if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version+1, "send-stale")); !errors.Is(err, domain.ErrInvitationVersionConflict) { + t.Fatalf("Send(stale) error = %v, want ErrInvitationVersionConflict", err) + } + state := test.transactor.snapshot() + if len(state.sendResults) != 0 || len(state.charged) != 0 || state.invitations[draft.ID].State() != domain.InvitationDraft { + t.Fatalf("a stale send stored %d outcomes and %d charges", len(state.sendResults), len(state.charged)) + } + // Nothing was kept under the key, so the corrected request with the + // same key sends the draft. + if view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-stale")); err != nil || view.State != domain.InvitationDelivered { + t.Fatalf("Send(after stale) = %v, %v; want delivered", view.State, err) + } +} + +func TestSendRefusesACandidateWhoIsNoLongerVisibleAndStoresTheRefusal(t *testing.T) { + test := newHarness(t) + draft, handle, candidateID := test.draftFor(t, nil) + delete(test.visible, handle) + if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-hidden")); !errors.Is(err, ErrSendBlocked) { + t.Fatalf("Send(hidden candidate) error = %v, want ErrSendBlocked", err) + } + state := test.transactor.snapshot() + if state.invitations[draft.ID].State() != domain.InvitationDraft || len(state.charged) != 0 || len(state.notified) != 0 { + t.Fatal("a refused send changed the draft, charged the quota, or notified") + } + // The refusal is stored under the key and replayed. + test.visible[handle] = candidateID + if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-hidden")); !errors.Is(err, ErrSendBlocked) { + t.Fatalf("Send(replay) error = %v, want the stored ErrSendBlocked", err) + } +} + +func TestSendAnswersAnUnknownInvitationAsNotFoundAndStoresIt(t *testing.T) { + test := newHarness(t) + command := test.sendCommand(uuid.New(), 1, "send-unknown") + for range 2 { + if _, err := test.service.Send(t.Context(), command); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Fatalf("Send(unknown) error = %v, want ErrInvitationNotFound", err) + } + } + if state := test.transactor.snapshot(); len(state.sendResults) != 1 { + t.Fatalf("stored %d outcomes, want the one refusal", len(state.sendResults)) + } +} + +func TestSendRefusesAnExhaustedQuotaAndKeepsTheDraft(t *testing.T) { + test := newHarness(t) + test.quotaLeft = 0 + draft, _, _ := test.draftFor(t, nil) + _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-quota")) + limited, ok := errors.AsType[*QuotaExceededError](err) + if !ok || !errors.Is(err, ErrInvitationQuotaExceeded) || limited.RetryAt.IsZero() { + t.Fatalf("Send(no quota) error = %v, want QuotaExceededError with a retry time", err) + } + state := test.transactor.snapshot() + if state.invitations[draft.ID].State() != domain.InvitationDraft || len(state.sendResults) != 0 || len(state.notified) != 0 { + t.Fatal("a refused quota changed the draft or stored the outcome") + } + // Room in the quota lets the same key send the draft. + test.quotaLeft = 1 + if view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-quota")); err != nil || view.State != domain.InvitationDelivered { + t.Fatalf("Send(after quota) = %v, %v; want delivered", view.State, err) + } +} + +func TestListMineShowsOnlyTheDeliveredInvitationsOfTheCandidate(t *testing.T) { + test := newHarness(t) + sent, _, candidateID := test.draftFor(t, nil) + if _, err := test.service.Send(t.Context(), test.sendCommand(sent.ID, sent.Version, "send-list")); err != nil { + t.Fatalf("Send() error = %v", err) + } + verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC) + test.transactor.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &verified} + test.draftFor(t, nil) + + page, err := test.service.ListMine(t.Context(), CandidateListCommand{ActorID: candidateID, Limit: 10}) + if err != nil { + t.Fatalf("ListMine() error = %v", err) + } + if len(page.Items) != 1 || page.Items[0].ID != sent.ID || page.Items[0].State != domain.InvitationDelivered || + page.Items[0].Organization.ID != test.organizationID || page.Items[0].RoleTitle == "" { + t.Fatalf("inbox = %+v, want the one delivered invitation", page.Items) + } + if _, err := test.service.ListMine(t.Context(), CandidateListCommand{ActorID: test.actorID, Limit: 10}); !errors.Is(err, ErrForbidden) { + t.Fatalf("ListMine(employer) error = %v, want ErrForbidden", err) + } +} diff --git a/backend/internal/usecase/invitation/service.go b/backend/internal/usecase/invitation/service.go index a8e59c2..af62a3c 100644 --- a/backend/internal/usecase/invitation/service.go +++ b/backend/internal/usecase/invitation/service.go @@ -1,7 +1,9 @@ -// Package invitation applies the owner-only rules of invitation drafts: the -// terms and their immutable versions, the link to a candidate card of the -// organization, and the idempotent creation. Sending, the candidate's side, and -// the contact grant belong to later operations that build on the same records. +// Package invitation applies the owner-only rules of invitation drafts and of +// their sending: the terms and their immutable versions, the link to a +// candidate card of the organization, the idempotent creation, and the +// idempotent send that delivers a draft to the candidate's inbox. It also +// lists that inbox for the candidate. The candidate's answers and the contact +// grant belong to later operations that build on the same records. package invitation import ( @@ -60,6 +62,21 @@ type Keyring interface { // not use. The identifier it returns never leaves the server. type CandidateResolver func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID, handle string) (uuid.UUID, error) +// InvitationQuota reserves one invitation of the organization quota inside +// the caller's transaction. Bootstrap adapts the shared company-quota usecase, +// so the verification tiers and their limits stay in one place. Repeating an +// 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) + +// 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 +// in the candidate's inbox when the transaction commits, and an email that +// fails or is retried later never changes it. +type DeliveryNotifier interface { + InvitationDelivered(ctx context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) error +} + // Dependencies configure one stateless invitation service. type Dependencies struct { Transactor outbound.Transactor @@ -69,21 +86,27 @@ type Dependencies struct { // a handle in an invitation is the handle of the card. PseudonymKey domain.CandidateViewPseudonymKey Candidates CandidateResolver + Quota InvitationQuota + Notifier DeliveryNotifier Clock func() time.Time } -// Service applies organization-scoped invitation draft commands and reads. +// Service applies organization-scoped invitation commands and reads, and the +// candidate's read of the own inbox. type Service struct { transactor outbound.Transactor keyring Keyring pseudonymKey domain.CandidateViewPseudonymKey candidates CandidateResolver + quota InvitationQuota + notifier DeliveryNotifier 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.Clock == nil { + if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Quota == nil || + deps.Notifier == 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 { @@ -91,7 +114,7 @@ func NewService(deps Dependencies) (*Service, error) { } return &Service{ transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey, - candidates: deps.Candidates, clock: deps.Clock, + candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, clock: deps.Clock, }, nil } diff --git a/backend/internal/usecase/invitation/service_test.go b/backend/internal/usecase/invitation/service_test.go index bfe68ce..5257597 100644 --- a/backend/internal/usecase/invitation/service_test.go +++ b/backend/internal/usecase/invitation/service_test.go @@ -41,7 +41,12 @@ type testState struct { events []domain.InvitationEvent idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord results map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView + sendResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult needVersions map[[3]string]bool + // charged lists the invitations charged against the organization quota, + // and notified the delivered invitations that were notified. + charged []uuid.UUID + notified []uuid.UUID } func newTestState() testState { @@ -50,6 +55,7 @@ func newTestState() testState { invitations: map[uuid.UUID]domain.Invitation{}, terms: map[termsKey]domain.InvitationTerms{}, idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{}, results: map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView{}, + sendResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult{}, needVersions: map[[3]string]bool{}, } } @@ -75,9 +81,14 @@ func (state testState) clone() testState { for scope, result := range state.results { cloned.results[scope] = result } + for scope, result := range state.sendResults { + cloned.sendResults[scope] = result + } for key, found := range state.needVersions { cloned.needVersions[key] = found } + cloned.charged = slices.Clone(state.charged) + cloned.notified = slices.Clone(state.notified) return cloned } @@ -129,6 +140,9 @@ func (unit *testUnit) Invitations() outbound.InvitationRepository { func (unit *testUnit) InvitationCreationResults() outbound.InvitationCreationResultRepository { return testInvitations{state: unit.state, failResultSave: unit.failResultSave} } +func (unit *testUnit) InvitationSendResults() outbound.InvitationSendResultRepository { + return testInvitations{state: unit.state} +} type testUsers struct { outbound.UserRepository @@ -158,6 +172,14 @@ func (repository testOrganizations) LockActiveMembership(_ context.Context, orga return membership, nil } +func (repository testOrganizations) GetForMember(_ context.Context, organizationID, userID uuid.UUID) (domain.Organization, domain.Membership, error) { + membership, ok := repository.state.memberships[[2]uuid.UUID{organizationID, userID}] + if !ok || !membership.GrantsAccess() { + return domain.Organization{}, domain.Membership{}, outbound.ErrOrganizationNotFound + } + return domain.Organization{}, membership, nil +} + type testQuotas struct { outbound.CompanyQuotaRepository } @@ -194,6 +216,7 @@ func (repository testIdempotency) PurgeExpired(_ context.Context, at time.Time, if !record.ExpiresAt.After(at) { delete(repository.state.idempotency, scope) delete(repository.state.results, scope) + delete(repository.state.sendResults, scope) deleted++ } } @@ -255,6 +278,52 @@ func (repository testInvitations) SaveDraft(_ context.Context, expectedVersion i return nil } +func (repository testInvitations) Deliver(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error { + current, ok := repository.state.invitations[next.ID()] + if !ok || current.Version() != expectedVersion || current.State() != domain.InvitationDraft { + return outbound.ErrInvitationVersionConflict + } + repository.state.invitations[next.ID()] = next + repository.state.events = append(repository.state.events, event) + return nil +} + +func (repository testInvitations) ListForCandidate(_ context.Context, query outbound.CandidateInvitationListQuery) (outbound.CandidateInvitationPage, error) { + var items []outbound.CandidateInvitationEntry + for _, invitation := range repository.state.invitations { + if invitation.CandidateID() == query.CandidateID && invitation.IsDelivered() { + items = append(items, outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: "Test organization"}) + } + } + page := outbound.CandidateInvitationPage{HasMore: len(items) > int(query.Limit)} + if page.HasMore { + items = items[:query.Limit] + } + page.Items = items + return page, nil +} + +func (repository testInvitations) GetForCandidate(_ context.Context, candidateID, invitationID uuid.UUID) (domain.Invitation, error) { + invitation, ok := repository.state.invitations[invitationID] + if !ok || invitation.CandidateID() != candidateID || !invitation.IsDelivered() { + return domain.Invitation{}, outbound.ErrInvitationNotFound + } + return invitation, nil +} + +func (repository testInvitations) SaveSendResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationSendResult) error { + repository.state.sendResults[scope] = result + return nil +} + +func (repository testInvitations) GetSendResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationSendResult, error) { + result, ok := repository.state.sendResults[scope] + if !ok { + return outbound.InvitationSendResult{}, outbound.ErrInvitationSendResultNotFound + } + return result, nil +} + func (repository testInvitations) NeedVersionExists(_ context.Context, organizationID, needID uuid.UUID, version int64) (bool, error) { return repository.state.needVersions[[3]string{organizationID.String(), needID.String(), fmt.Sprint(version)}], nil } @@ -276,8 +345,11 @@ func (repository testInvitations) GetCreationResult(_ context.Context, scope [ou } type harness struct { - service *Service - transactor *testTransactor + service *Service + transactor *testTransactor + // quotaLeft is the number of new invitations the organization quota + // still allows. + quotaLeft int key domain.CandidateViewPseudonymKey actorID uuid.UUID organizationID uuid.UUID @@ -305,7 +377,7 @@ func newHarness(t *testing.T) *harness { } test := &harness{ transactor: &testTransactor{state: state, policy: testPolicyVersion(t, now)}, - key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{}, + key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{}, quotaLeft: 10, setTime: func(value time.Time) { current = value }, } test.service, err = NewService(Dependencies{ @@ -317,6 +389,18 @@ func newHarness(t *testing.T) *harness { } return candidateID, nil }, + Quota: func(_ context.Context, unit outbound.UnitOfWork, _ domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + state := unit.(*testUnit).state + if slices.Contains(state.charged, invitationID) { + return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil + } + if len(state.charged) >= test.quotaLeft { + return outbound.CompanyQuotaDecision{RetryAt: current.Add(time.Hour)}, nil + } + state.charged = append(state.charged, invitationID) + return outbound.CompanyQuotaDecision{Allowed: true}, nil + }, + Notifier: testNotifier{}, }) if err != nil { t.Fatalf("NewService() error = %v", err) @@ -337,6 +421,14 @@ func (test *harness) showCandidate(t *testing.T) (string, uuid.UUID) { return handle, candidateID } +type testNotifier struct{} + +func (testNotifier) InvitationDelivered(_ context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) error { + state := unit.(*testUnit).state + state.notified = append(state.notified, invitation.ID()) + return nil +} + func testPolicyVersion(t *testing.T, at time.Time) domain.PolicyVersion { t.Helper() draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ @@ -543,6 +635,10 @@ func TestOnlyTheActiveOwnerOfAnEmployerAccountMayWorkWithInvitations(t *testing. if _, err := test.service.Get(t.Context(), tt.actor, test.organizationID, uuid.New()); !errors.Is(err, tt.want) { t.Errorf("Get() error = %v, want %v", err, tt.want) } + send := SendCommand{ActorID: tt.actor, OrganizationID: test.organizationID, InvitationID: uuid.New(), IdempotencyKey: "send-" + tt.name, ExpectedVersion: 1} + if _, err := test.service.Send(t.Context(), send); !errors.Is(err, tt.want) { + t.Errorf("Send() error = %v, want %v", err, tt.want) + } }) } if state := test.transactor.snapshot(); len(state.invitations) != 0 { diff --git a/backend/internal/usecase/notification/inbox_content.go b/backend/internal/usecase/notification/inbox_content.go index ae55d2b..2a76c72 100644 --- a/backend/internal/usecase/notification/inbox_content.go +++ b/backend/internal/usecase/notification/inbox_content.go @@ -28,13 +28,14 @@ func NewInboxContentResolver(resolvers map[domain.NotificationInboxSourceType]In } // DefaultInboxSourceResolvers lists the source types that have a resolver -// today. The synthetic notice resolver is registered only when -// syntheticEnabled is true (development and browser-test stands); a stored -// synthetic row is then listed without content. The invitation module adds -// domain.NotificationInboxSourceInvitation with its own resolver; the -// handler, the table, and the API need no change. +// today: the delivered invitation, and the synthetic notice. The synthetic +// notice resolver is registered only when syntheticEnabled is true +// (development and browser-test stands); otherwise a stored synthetic row is +// listed without content. func DefaultInboxSourceResolvers(syntheticEnabled bool) map[domain.NotificationInboxSourceType]InboxSourceResolver { - resolvers := map[domain.NotificationInboxSourceType]InboxSourceResolver{} + resolvers := map[domain.NotificationInboxSourceType]InboxSourceResolver{ + domain.NotificationInboxSourceInvitation: ResolveInvitationNotice, + } if syntheticEnabled { resolvers[domain.NotificationInboxSourceOrganization] = ResolveSyntheticNotice } diff --git a/backend/internal/usecase/notification/inbox_test.go b/backend/internal/usecase/notification/inbox_test.go index 36fd4ff..f7a15e0 100644 --- a/backend/internal/usecase/notification/inbox_test.go +++ b/backend/internal/usecase/notification/inbox_test.go @@ -274,12 +274,63 @@ func TestSyntheticNoticeResolverFollowsTheRecipientStanding(t *testing.T) { OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), }) if _, err := resolvers.Resolve(context.Background(), unit, invitation); !errors.Is(err, ErrInboxContentUnavailable) { - t.Fatalf("Resolve(source without a resolver) error = %v, want ErrInboxContentUnavailable", err) + t.Fatalf("Resolve(invitation the recipient cannot read) error = %v, want ErrInboxContentUnavailable", err) + } +} + +func TestResolveInvitationNoticeNamesTheSenderOnlyWhileVisible(t *testing.T) { + t.Parallel() + + fixture := newInboxFixture(t, domain.ScenarioCandidate) + delivered := fixture.deliveredInvitation(t) + entry := fixtureEntry(t, domain.NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID, + EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1, + SourceType: domain.NotificationInboxSourceInvitation, SourceID: delivered.ID(), + OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), + }) + resolvers := NewInboxContentResolver(DefaultInboxSourceResolvers(false)) + content, err := resolvers.Resolve(context.Background(), fixture.unit(), entry) + if err != nil { + t.Fatalf("Resolve(delivered invitation) error = %v", err) + } + if content.Title() != invitationNoticeTitle || content.LinkPath() != candidateInvitationsPath || + !strings.Contains(content.Summary(), "«Север»") || !strings.Contains(content.Summary(), "«Inbox role»") { + t.Fatalf("invitation content = %q / %q / %q", content.Title(), content.Summary(), content.LinkPath()) + } + if strings.Contains(content.Summary(), fixture.user.ID.String()) { + t.Fatal("invitation content names the candidate") + } + + // Another recipient and another organization context find nothing. + foreign := fixtureEntry(t, domain.NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: fixture.organizationID, + EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1, + SourceType: domain.NotificationInboxSourceInvitation, SourceID: delivered.ID(), + OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), + }) + if _, err := ResolveInvitationNotice(context.Background(), fixture.unit(), foreign); !errors.Is(err, ErrInboxContentUnavailable) { + t.Fatalf("ResolveInvitationNotice(other recipient) error = %v, want ErrInboxContentUnavailable", err) + } + otherContext := fixtureEntry(t, domain.NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: fixture.user.ID, OrganizationID: uuid.New(), + EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1, + SourceType: domain.NotificationInboxSourceInvitation, SourceID: delivered.ID(), + OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), + }) + if _, err := ResolveInvitationNotice(context.Background(), fixture.unit(), otherContext); !errors.Is(err, ErrInboxContentUnavailable) { + t.Fatalf("ResolveInvitationNotice(other organization) error = %v, want ErrInboxContentUnavailable", err) + } + // A hidden organization is no longer named. + fixture.repository.organizationName = "" + if _, err := ResolveInvitationNotice(context.Background(), fixture.unit(), entry); !errors.Is(err, ErrInboxContentUnavailable) { + t.Fatalf("ResolveInvitationNotice(hidden sender) error = %v, want ErrInboxContentUnavailable", err) } } type inboxFixture struct { service *InboxService + invitations map[uuid.UUID]domain.Invitation repository *memoryInboxRepository resolver *memoryInboxResolver users map[uuid.UUID]domain.User @@ -298,6 +349,7 @@ func newInboxFixtureWithClock(t *testing.T, scenario domain.Scenario, clock func t.Helper() verifiedAt := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC) fixture := &inboxFixture{ + invitations: map[uuid.UUID]domain.Invitation{}, repository: &memoryInboxRepository{organizationName: "Север"}, resolver: &memoryInboxResolver{unavailable: map[uuid.UUID]bool{}}, users: map[uuid.UUID]domain.User{}, @@ -316,6 +368,39 @@ func newInboxFixtureWithClock(t *testing.T, scenario domain.Scenario, clock func func (fixture *inboxFixture) unit() outbound.UnitOfWork { return inboxTestUnit{fixture: fixture} } +// deliveredInvitation stores a delivered invitation of the fixture +// organization addressed to the fixture user. +func (fixture *inboxFixture) deliveredInvitation(t *testing.T) domain.Invitation { + t.Helper() + policyID, err := domain.NewPolicyVersionID() + if err != nil { + t.Fatalf("NewPolicyVersionID() error = %v", err) + } + none := domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided} + at := time.Date(2026, time.October, 8, 11, 0, 0, 0, time.UTC) + draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{ + ID: uuid.New(), OrganizationID: fixture.organizationID, CandidateID: fixture.user.ID, ActorID: uuid.New(), + PolicyVersionID: policyID, At: at, + Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: domain.InvitationTerms{ + RoleTitle: "Inbox role", Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, + OfferType: domain.InvitationOfferFullTime, Tasks: []string{"Read the inbox"}, Team: "Inbox team", + TechStack: []string{"Go"}, WorkFormats: []domain.NeedWorkFormat{domain.NeedWorkFormatRemote}, + CommunicationMethod: domain.InvitationCommunicationMethod{Channel: domain.InvitationChannelEmail}, + Salary: domain.SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "RUB", Period: "month", TaxBasis: "net"}, + Package: domain.InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none}, + }}, + }) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + delivered, err := draft.Deliver(at.Add(time.Minute)) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + fixture.invitations[delivered.ID()] = delivered + return delivered +} + func (fixture *inboxFixture) entryInput() domain.NotificationInboxEntryInput { return fixtureEntryInput(fixture.user.ID, fixture.organizationID) } @@ -379,6 +464,25 @@ func (unit inboxTestUnit) Organizations() outbound.OrganizationRepository { func (unit inboxTestUnit) NotificationInbox() outbound.NotificationInboxRepository { return unit.fixture.repository } +func (unit inboxTestUnit) Invitations() outbound.InvitationRepository { + return inboxTestInvitations{fixture: unit.fixture} +} + +type inboxTestInvitations struct { + outbound.InvitationRepository + + fixture *inboxFixture +} + +// GetForCandidate answers like the real repository: only a delivered +// invitation addressed to the candidate is found. +func (repository inboxTestInvitations) GetForCandidate(_ context.Context, candidateID, invitationID uuid.UUID) (domain.Invitation, error) { + invitation, ok := repository.fixture.invitations[invitationID] + if !ok || invitation.CandidateID() != candidateID || !invitation.IsDelivered() { + return domain.Invitation{}, outbound.ErrInvitationNotFound + } + return invitation, nil +} type inboxTestUsers struct { outbound.UserRepository diff --git a/backend/internal/usecase/notification/invitation.go b/backend/internal/usecase/notification/invitation.go new file mode 100644 index 0000000..1e98fec --- /dev/null +++ b/backend/internal/usecase/notification/invitation.go @@ -0,0 +1,122 @@ +package notification + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification/mailtemplate" +) + +const ( + // invitationAggregateType is the aggregate of invitation.delivered, which + // is also the source of the inbox content. + invitationAggregateType = "invitation" + // candidateInvitationsPath is the inbox of invitations in the candidate + // cabinet. Both the notification and the email link to it. + candidateInvitationsPath = "/candidate/invitations" + + invitationNoticeTitle = "Новое приглашение" + // invitationNoticeSummary has one slot for the organization name and one + // for the role. + invitationNoticeSummary = "Организация «%s» отправила вам приглашение на роль «%s». Условия и срок ответа указаны в разделе «Приглашения»." + + // The email names neither the organization nor the terms: the candidate + // reads them in the cabinet, where a hiding or a later change applies. + // It never holds a contact or an identifier of the candidate. + invitationMailSubject = "Новое приглашение от работодателя" + invitationMailBody = "Работодатель отправил вам приглашение на платформе Lincodex. Условия, организация и срок ответа указаны в разделе «Приглашения» личного кабинета кандидата." +) + +// InvitationNotifier records the notifications of a delivered invitation in +// the transaction of the send: the invitation.delivered event that the inbox +// consumer turns into the candidate's notification, and a mail request. The +// invitation is delivered when that transaction commits; neither the +// notification nor the email, nor any retry of them, changes its state or +// deadline. +type InvitationNotifier struct { + mail *MailRequester +} + +// NewInvitationNotifier fails at startup without a mail requester. +func NewInvitationNotifier(mail *MailRequester) (*InvitationNotifier, error) { + if mail == nil { + return nil, errors.New("notification.NewInvitationNotifier - mail requester must be set") + } + return &InvitationNotifier{mail: mail}, nil +} + +// InvitationDelivered appends the inbox event and requests the email through +// unit, which must be the transaction that delivered the invitation. The +// event payload names the recipient and the organization only, as the inbox +// contract requires; it never leaves the internal event bus. +func (notifier *InvitationNotifier) InvitationDelivered(ctx context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) error { + const location = "InvitationNotifier.InvitationDelivered" + if invitation.State() != domain.InvitationDelivered || !invitation.IsDelivered() { + return fmt.Errorf("%s - the invitation must be delivered: %w", location, domain.ErrInvalidInvitation) + } + payload, err := json.Marshal(inboxEventPayload{RecipientUserID: invitation.CandidateID(), OrganizationID: invitation.OrganizationID()}) + if err != nil { + return fmt.Errorf("%s - encode payload: %w", location, err) + } + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: string(domain.NotificationInboxInvitationDelivered), + SchemaVersion: inboxPayloadSchemaVersion, + AggregateType: invitationAggregateType, + AggregateID: invitation.ID(), + AggregateVersion: invitation.Version(), + Payload: payload, + }) + if err != nil { + return fmt.Errorf("%s - build event: %w", location, err) + } + if err := unit.Outbox().Append(ctx, event); err != nil { + return fmt.Errorf("%s - append event: %w", location, err) + } + if _, err := notifier.mail.RequestNotification(ctx, unit, NotificationRequest{ + RecipientUserID: invitation.CandidateID(), + Notification: mailtemplate.NotificationData{ + Subject: invitationMailSubject, Body: invitationMailBody, LinkPath: candidateInvitationsPath, + }, + }); err != nil { + return fmt.Errorf("%s - request email: %w", location, err) + } + return nil +} + +// ResolveInvitationNotice resolves the notification of a delivered +// invitation from the current invitation and the recipient's current +// standing. The recipient must be the candidate it was delivered to, and the +// organization is named only while the candidate has not hidden it; +// otherwise the entry stays in the list without content. +func ResolveInvitationNotice(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) { + const location = "notification.ResolveInvitationNotice" + invitation, err := unit.Invitations().GetForCandidate(ctx, entry.RecipientUserID(), entry.SourceID()) + if errors.Is(err, outbound.ErrInvitationNotFound) { + return InboxContent{}, ErrInboxContentUnavailable + } + if err != nil { + return InboxContent{}, fmt.Errorf("%s - read invitation: %w", location, err) + } + if invitation.OrganizationID() != entry.OrganizationID() { + return InboxContent{}, ErrInboxContentUnavailable + } + name, err := unit.NotificationInbox().OrganizationNameForRecipient(ctx, entry.RecipientUserID(), entry.OrganizationID()) + if errors.Is(err, outbound.ErrNotificationInboxSourceNotVisible) { + return InboxContent{}, ErrInboxContentUnavailable + } + if err != nil { + return InboxContent{}, fmt.Errorf("%s - read sender organization: %w", location, err) + } + content, err := NewInboxContent(invitationNoticeTitle, + fmt.Sprintf(invitationNoticeSummary, name, invitation.Snapshot().Terms.RoleTitle), candidateInvitationsPath) + if err != nil { + // A stored name or role that does not fit the presentation is not + // shown. + return InboxContent{}, ErrInboxContentUnavailable + } + return content, nil +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index d20d032..5313cd1 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -6,7 +6,7 @@ This document separates the target product architecture from the technical scaff The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port. -Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks synthetic notices, and no product module produces a real one yet (see [Internal notifications](#internal-notifications)). The organization side of the invitation draft (list, create, read, and update with versioned terms) works through the backend API; sending and the candidate side are not implemented (see [Invitation drafts](#invitation-drafts)). Other product workflows are not implemented: roles, profiles, assessments, grades, sending and answering invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. +Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks its notices; a sent invitation is the first product producer (see [Internal notifications](#internal-notifications)). The organization side of the invitation draft (list, create, read, and update with versioned terms) and the send to the candidate's inbox with the candidate's list of invitations work through the backend API; the candidate's answers are not implemented (see [Invitation drafts](#invitation-drafts) and [Sending invitations](#sending-invitations)). Other product workflows are not implemented: roles, profiles, assessments, grades, answering invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage. @@ -412,22 +412,22 @@ Open points. Sending product notifications and the permission check they need ar ### Internal notifications -Implemented: the inbox of delivered events with a read state, the consumer that fills it, and four operations that list and mark it. No product module produces a notification yet. Invitations, the first planned producer, are not implemented, so the only event that reaches the inbox today is a synthetic one and a real recipient sees an empty list. +Implemented: the inbox of delivered events with a read state, the consumer that fills it, and four operations that list and mark it. The send of an invitation is the first product producer ([Sending invitations](#sending-invitations)); the synthetic event remains for tests and probes. Code: migrations `backend/db/migrations/00032_create_notification_inbox.sql` and `00036_allow_synthetic_notification_event.sql`, queries `backend/db/queries/notification_inbox.sql`, the model `backend/internal/domain/notification_inbox.go`, the port `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), the adapter `adapter/secondary/postgres/notification_inbox.go`, the usecase files `usecase/notification/inbox.go`, `inbox_handler.go`, and `inbox_content.go`, the HTTP handler `adapter/primary/http/v1/notifications.go` with its cursor `notification_cursor.go`, the wiring in `bootstrap/notification.go` and `eventHandlers()`, and the frontend feature `frontend/src/features/notifications/` with the page `frontend/src/pages/notifications/`. The operations are in [api/README.en.md](../../api/README.en.md#notifications). -- The inbox is the delivery state inside the platform. A row means that the notification reached the recipient's cabinet, and `read_at` says that the recipient read it. Mail is another channel with its own state in `deliveries` ([Mail deliveries](#mail-deliveries)), and neither reads the other. The inbox handler never reads `deliveries`, `mail_requests`, or the verification state of an address, so an unverified address, `EMAIL_PROVIDER=disabled`, or a failed send never blocks a notification, and a sent email never counts as seen. When invitations arrive, the delivered state of an invitation is the existence of its inbox row. +- The inbox is the delivery state inside the platform. A row means that the notification reached the recipient's cabinet, and `read_at` says that the recipient read it. Mail is another channel with its own state in `deliveries` ([Mail deliveries](#mail-deliveries)), and neither reads the other. The inbox handler never reads `deliveries`, `mail_requests`, or the verification state of an address, so an unverified address, `EMAIL_PROVIDER=disabled`, or a failed send never blocks a notification, and a sent email never counts as seen. The delivered state of an invitation is its own `delivered_at`, written by the send transaction; the inbox row of its notification follows through the consumer. - A row holds references, not text. `notification_inbox_events` has the key `(recipient_user_id, event_id)` and the columns `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at`, and `read_at`. It stores no title, summary, name, contact, or score. Triggers keep the reference immutable (only the first `read_at` may be set) and refuse a direct delete; deleting the recipient's account removes the rows by cascade, and the organization foreign key is `RESTRICT`. A CHECK allows only the pairs of event type and source type that `domain.NotificationInboxSourceFor` allows, both at schema version 1: `invitation.delivered` with `invitation`, and the synthetic `notification.synthetic_delivered` with `organization`. Migration 00032 is deployed and unchanged; 00036 only widened the CHECK, and its rollback refuses while a synthetic row exists. -- Producer contract. A producer appends, in its own transaction, an event of an allowlisted type with the payload `{"recipient_user_id": ..., "organization_id": ...}` (two identifiers, no unknown field, schema version 1) and the aggregate that the type names. For `invitation.delivered` the aggregate is the `invitation`, which is also the content source. The synthetic event uses a one-off `synthetic_notice` aggregate at version 1, and its source is the organization of the payload; `notification.SyntheticNoticeEventPayload` is the single writer of that payload. The invitation module therefore needs no change in the table, the consumer, or the API: it appends `invitation.delivered` and registers a content resolver for the source `invitation` in `notification.DefaultInboxSourceResolvers()`. Until a resolver exists, an item of that source is listed without content. +- Producer contract. A producer appends, in its own transaction, an event of an allowlisted type with the payload `{"recipient_user_id": ..., "organization_id": ...}` (two identifiers, no unknown field, schema version 1) and the aggregate that the type names. For `invitation.delivered` the aggregate is the `invitation`, which is also the content source. The synthetic event uses a one-off `synthetic_notice` aggregate at version 1, and its source is the organization of the payload; `notification.SyntheticNoticeEventPayload` is the single writer of that payload. The invitation module needed no change in the table, the consumer, or the API: the send transaction appends `invitation.delivered` through `notification.InvitationNotifier`, and `notification.ResolveInvitationNotice` is registered for the source `invitation` in `notification.DefaultInboxSourceResolvers()`. - Synthetic event type. `notification.synthetic_delivered` has no product meaning. It exists so that the whole path (outbox, relay, Kafka, consumer, read-time check, list, read state) can be exercised before a real producer exists and in browser tests. It is off by default: the consumer handles it and the inbox renders it only when `NOTIFICATION_SYNTHETIC_ENABLED=true` (a development or browser-test stand; the e2e overlay sets it). With the switch off the event is acknowledged and ignored and a stored synthetic row is listed without content; the database CHECK allows the type either way, so turning the switch on needs no migration. Only code that can append to the outbox can produce it, and its content is a fixed text that names the sending organization. The browser suite appends it through the `company-fixture` (Go build tag `e2e`), never through a user operation. - Consumer `notification_inbox`. `InboxHandler` handles the allowlisted types. In the transaction of the dedup marker it checks the envelope and the payload and rejects a broken event for good (`ErrEventRejected`), skips a recipient whose account was deleted, and stores the row with `ON CONFLICT DO NOTHING` on the key. A recipient deleted between the check and the insert aborts the insert with a foreign-key error that names the recipient; the handler returns it as a retryable error, and the retry finds the account gone and skips, while a foreign-key error on the organization is rejected for good. Three layers keep one row per recipient and event ID: the consumer marker, the key, and the comparison of a duplicate with the stored metadata, which rejects an event ID that comes again with other metadata instead of overwriting it. A replay under a renamed consumer therefore stores no second row. `occurred_at` is the informational insert time of the outbox row; it orders the list together with the event ID. The consumer group `.notification_inbox` is new, so it starts at the earliest retained event; events of other types are counted as ignored. -- Content is resolved at read time. `InboxService` lists a page and calls the resolver of each item's source type in the transaction that authorized the viewer; the result is never stored. A resolver returns `ErrInboxContentUnavailable` when the source is gone or the recipient may not see it now. The item then stays in the list with `content` null, the client shows a generic line, and an earlier text is never shown. A source type without a resolver is unavailable, never guessed. The one resolver today belongs to the synthetic notice: its fixed Russian text names the sending organization by its current name, which `OrganizationNameForRecipient` reads under the recipient's current standing. A candidate sees the name until they hide the organization, and an employer while their membership is active. A name that does not fit the presentation limits is not shown. A content link is a same-origin path of a narrow alphabet, and the client opens it only inside its own cabinet. +- Content is resolved at read time. `InboxService` lists a page and calls the resolver of each item's source type in the transaction that authorized the viewer; the result is never stored. A resolver returns `ErrInboxContentUnavailable` when the source is gone or the recipient may not see it now. The item then stays in the list with `content` null, the client shows a generic line, and an earlier text is never shown. A source type without a resolver is unavailable, never guessed. The resolver of a delivered invitation reads it only when it is addressed to the recipient and delivered, in the organization of the entry, and names the organization and the role; it shows no candidate value and links to `/candidate/invitations`. The resolver of the synthetic notice uses a fixed Russian text that names the sending organization by its current name, which `OrganizationNameForRecipient` reads under the recipient's current standing. Both read the name that way: a candidate sees the name until they hide the organization, and an employer while their membership is active. A name that does not fit the presentation limits is not shown. A content link is a same-origin path of a narrow alphabet, and the client opens it only inside its own cabinet. - Scope. The candidate cabinet needs a verified candidate account and lists every organization context of the caller. The cabinet of one organization needs an employer account with a verified email (otherwise 403 `email_not_verified`, like the other organization operations) and an active membership of any role in the organization of the path. The membership is locked `FOR SHARE` with `LockActiveMembership` in the transaction of the list or the mark, like the card reads, so a revocation cannot commit between the check and the read and stops the next request. The recipient always comes from the session; the organization of the path narrows the rows and a path identifier alone grants nothing. A candidate on an organization route and an employer on the candidate route get 403. A missing membership, an unknown organization, an item of another account, an item of another organization, and an unknown ID all get the same 404 `not_found`. The organization routes are not in the owner-only list of `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` names them as authorized in their own transaction. - Reading and marking. `GET /api/v1/me/notifications` and `GET /api/v1/organizations/{org_id}/notifications` return a newest-first page with a cursor bound to the account and the cabinet; a cursor of another account or cabinet is a 400. `POST .../{notification_id}/read` stores the first read time and returns it again on every repeat. It reads no source and returns no content, so an item without content can still be marked. All four are `Cache-Control: no-store`; a mark needs the session, the CSRF token, and an allowed Origin, and no Idempotency-Key because it is idempotent by its effect. No problem code was added. - Frontend. `features/notifications` exports `NotificationInbox` (candidate or one organization) and `OrganizationNotificationInbox` (the chooser of the organization in the `organization_id` parameter plus the inbox). The pages `/candidate/notifications` and `/employer/notifications` and an entry "Уведомления" in each shell use them. The list is read on every visit and never kept (`gcTime: 0`), is keyed by account and cabinet, and is dropped when the account or the session changes or when access is refused. States: loading, empty, error with retry, forbidden, an item without content, and "show more". The read state is a word, not only a style, the mark is a native button, and focus moves to the item's heading after it succeeds. - Trade-off: eventual consistency. The row is written by the consumer after the relay and Kafka, so a notification appears seconds after the producer committed, not inside the producer's transaction. The alternative, writing the row in the producer's transaction through `UnitOfWork.NotificationInbox()`, would make it immediate but would tie every producer to the inbox and drop the replay and dead-letter handling that the consumer gives. The browser suite therefore waits for the item and then replays the event. - Tests. Unit: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` and `inbox_handler_test.go` (cabinet checks, membership revocation, resolver fallback, idempotent handler, rejected events, an `invitation.delivered` event under the same contract), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go`, and the feature tests in `frontend/src/features/notifications/`. Integration: `TestNotificationInboxOverHTTP` and `TestSyntheticNotificationMigration*`. Browser: `frontend/e2e/notifications.spec.ts` in the registration mode ([TESTING.md](TESTING.md#browser-e2e-suite)). -- Not implemented: the invitation producer and its content resolver, an unread counter or badge in the shells, live updates (the list is read on a visit and on window focus), archiving or deleting an item, retention of old rows, per-role filtering of employer notifications, a mail preference, and a metric for the inbox. The rows of the synthetic type are never removed by the application. +- Not implemented: an unread counter or badge in the shells, live updates (the list is read on a visit and on window focus), archiving or deleting an item, retention of old rows, per-role filtering of employer notifications, a mail preference, and a metric for the inbox. The rows of the synthetic type are never removed by the application. ### Product policy versions @@ -941,13 +941,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 row, no event, and no quota charge. Sending, withdrawal, the salary raise, the contact read, and every candidate operation of the invitation tag still answer 501 after the common checks. 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 every candidate operation of the invitation tag except `ListMyInvitations` still answer 501 after the common checks. 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` or `draft_updated`), 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`, or, since migration 00038, `delivered`), 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,12 +962,30 @@ 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: sending must resolve the candidate through the same visibility barrier again, because a draft keeps its candidate after a C2 revocation or a hiding, and then moves the draft to `delivered` by one UPDATE of `state`, `delivered_at`, `response_deadline_at`, and `version`, appends an audit event for that version, and writes the `invitation.delivered` outbox event whose inbox resolver for the source `invitation` is the existing plug-in point of [Internal notifications](#internal-notifications); the candidate's inbox reads `invitations` by `candidate_id` and `delivered_at`, and 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, 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. -Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the quota charge and the limit of pending invitations per need, the sending, the raise, the withdrawal, the candidate side, 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. +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. Tests: `domain/salary_range_test.go` and `domain/invitation_test.go` (exact width at 10% and 40%, steps, caps, terms rules with pointers, versions, immutability of earlier values, redaction), `usecase/invitation/service_test.go` (owner policy, handle refusals, order of checks, replay, rollback, versions), `adapter/primary/http/v1/invitation_test.go` (mapping, no candidate field, failure statuses, cursor), and the integration tests `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations`, and `TestInvitationMigrationRollbackKeepsStoredInvitations` against a real PostgreSQL. +### Sending invitations + +Implemented: `SendOrganizationInvitation` and the candidate's list of invitations `ListMyInvitations` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_delivery.go`, `usecase/invitation/send.go` and `candidate_inbox.go`, `usecase/notification/invitation.go`, the HTTP handler `adapter/primary/http/v1/invitation.go` with the cursor in `invitation_cursor.go`, the adapter `adapter/secondary/postgres/invitation_delivery.go` with `db/queries/invitation_delivery.sql`, the wiring in `bootstrap/invitation.go`, and migration `00038_send_invitations.sql`. + +- One transaction. A send takes the organization lock (`CompanyQuotaRepository.LockOrganization`), the owner check of the membership, the Idempotency-Key, and the invitation row lock, in the order of every invitation command, and then the locks of the visible cohort. It runs the visibility barrier of the card read again, spends one invitation of the organization quota, moves the draft to `delivered` with one conditional UPDATE (`state`, `version` plus one, `delivered_at`, `response_deadline_at`, `updated_at`; the terms version stays), appends the audit event `delivered`, and writes the outbox events: `invitation.delivered` for the in-platform notification and `notification.mail_requested` with its `mail_requests` row for the email. The internal sending step is never stored: when the answer arrives, the invitation is `delivered`, it is in the candidate's list, and the charge is recorded. A failure of any step rolls everything back. +- The candidate's inbox entry is the delivered invitation itself. `ListMyInvitations` reads the rows with the candidate of the session and a `delivered_at`, newest first by `(delivered_at, id)` over the partial index of migration 00037, with the current name of the sending organization; a draft has no delivery and is never listed, and listing records no view. The notification of `notification_inbox_events` is written by the inbox consumer from the outbox event, seconds later ([Internal notifications](#internal-notifications)); the invitation does not wait for it. +- Deadline. `response_deadline_at = delivered_at + response_period_days` in whole days, set by the same UPDATE as the first delivery. The trigger of migration 00037 refuses to change the delivery, the deadline, or the period afterwards, and the mail path never touches the invitation, so neither an email nor its retries move the deadline. The mail request becomes a delivery when the delivery consumer handles it; sending notification email is planned. An unverified address, a stopped transport (`EMAIL_PROVIDER=disabled`), or a failed attempt never affects the invitation or the answer of the send. +- Content. The email says only that an employer sent an invitation and links to `/candidate/invitations`: it names neither the organization nor the terms and holds no contact or identifier of the candidate. The notification shows the organization and the role while the candidate has not hidden the organization. The payload of `invitation.delivered` names the recipient and the organization, as the inbox contract requires, and stays on the internal event bus. +- Visibility. A draft keeps its candidate after a C2 revocation, a hiding, or a cohort that fell below its minimum. The send derives the card handle of the stored candidate and resolves it through `candidateview.Service.ResolveCandidateHandle` again; a candidate the organization may no longer see answers 409 `state_conflict` without saying which rule applied. +- Quota. The charge goes through the existing company quota port (`companyquota.Service.ReserveInvitation`) into `company_invitation_quota_usage`, keyed by the invitation, so it is written once. Migration 00038 adds the composite foreign key `(organization_id, invitation_id)` to `invitations`. An exhausted quota answers 429 with `Retry-After`, nothing is stored, and the draft stays. The port counts the pool of one organization; the shared E0 pool of a holding is not implemented in the port yet. +- Idempotency. The scope is the operation, the key, the account, and the organization; the fingerprint covers the invitation of the path and `expected_version`. `invitation_send_results` keeps the outcome under the key for 24 hours together with the generic idempotency record: the original 200, a 404 of an unknown invitation, and a 409. A 400, a 412, and a 429 are not stored, so the corrected request can reuse the key. A send of an invitation that is already delivered answers 200 with its current state even with a new key or an older version and charges nothing. +- Access. Owner only, as for drafts: `ownerCompanyOperations` at the HTTP boundary and the same check in the transaction; no other role may send. The candidate's list requires a verified candidate account, and an employer gets 403. +- Order of checks after the boundary: the owner, the key (422 or a replay), the invitation (404), a completed send (200), the version (412), the state and the visibility (409), then the quota (429). + +Not implemented: the pending limit per need and the pause after a decline or a no deal (both planned in the contract), the candidate's read of one invitation, the view and the answers, the expiry at the deadline, the sending of notification email, the shared E0 pool of a holding in the quota port, and the role and assignment matrix beyond the owner. + +Tests: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, `usecase/notification/inbox_test.go` (the invitation notice), `adapter/primary/http/v1/invitation_test.go` (statuses, `Retry-After`, the candidate cursor), and the integration tests `TestOrganizationInvitationSendOverHTTP` (the inbox before any email, repeats with one row of each kind and one charge, a 3-day deadline with the mail stopped and its job retried, visibility, a stale version, owner only, the quota, paging) and `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage`. + ## Frontend The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index b939644..562609f 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -479,7 +479,7 @@ Integration tests (`make -C backend test-int`; PostgreSQL and Redis, no Kafka): Browser test: `frontend/e2e/notifications.spec.ts` runs in `make -C deploy test-e2e-registration`, whose overlay sets `NOTIFICATION_SYNTHETIC_ENABLED=true`. The `company-fixture` (Go build tag `e2e`, bearer token, synthetic `@example.test` recipients only) appends a synthetic event to the real outbox, so the relay, Kafka, and the `notification_inbox` consumer deliver it; the test waits for the item. It then replays the event through the fixture, which must report that the real consumer had already applied it, and checks that the list still has one item. A candidate then opens the list, marks the item with the keyboard, reloads and sees the state kept, and a second candidate gets an empty list and a 404 for the same ID. After the organization is hidden the item stays without content. A second test reads the organization inbox as an owner, checks a non-member, revokes the membership through the fixture, and checks that the same ID is refused and that the page shows no content. -What these tests do not show: a real invitation (none produces an event yet), the behavior of the inbox when the mail provider fails (the handler reads no mail state by construction, and the unit test covers an unverified address), delivery latency or load, push or live updates, and the layout and the screen-reader behavior of the page (no automated check). +What these tests do not show: a real invitation event through Kafka and the relay (`TestOrganizationInvitationSendOverHTTP` delivers it through the handler storage only), the behavior of the inbox when the mail provider fails (the handler reads no mail state by construction, and the unit test covers an unverified address), delivery latency or load, push or live updates, and the layout and the screen-reader behavior of the page (no automated check). ## Demo seed tests diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 383862a..db5f172 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -6,7 +6,7 @@ Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту. -Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Внутренний inbox уведомлений в обоих кабинетах показывает и отмечает синтетические уведомления, а настоящие пока не создает ни один продуктовый модуль (см. [Внутренние уведомления](#внутренние-уведомления)). Сторона организации в черновике приглашения (список, создание, чтение и изменение с версиями условий) работает через backend API; отправка и сторона кандидата не реализованы (см. [Черновики приглашений](#черновики-приглашений)). Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, отправка приглашений и ответ на них, загрузка и анализ резюме, PDF и интеграция с ФСП. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований, снимков и приглашений (см. [Подбор и объяснение](#подбор-и-объяснение)). ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. +Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Внутренний inbox уведомлений в обоих кабинетах показывает и отмечает уведомления; первый продуктовый источник - отправленное приглашение (см. [Внутренние уведомления](#внутренние-уведомления)). Сторона организации в черновике приглашения (список, создание, чтение и изменение с версиями условий), отправка во входящие кандидата и список приглашений кандидата работают через backend API; ответы кандидата не реализованы (см. [Черновики приглашений](#черновики-приглашений) и [Отправка приглашений](#отправка-приглашений)). Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, ответ на приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований, снимков и приглашений (см. [Подбор и объяснение](#подбор-и-объяснение)). ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md). @@ -412,22 +412,22 @@ Offsets и партиции. Каждый обработчик - один уча ### Внутренние уведомления -Реализовано: inbox доставленных событий с состоянием прочтения, обработчик, который его наполняет, и четыре операции для списка и отметки. Ни один продуктовый модуль пока не создает уведомления. Приглашения, первый запланированный источник, не реализованы, поэтому единственное событие, которое сегодня попадает в inbox, синтетическое, и у настоящего получателя список пуст. +Реализовано: inbox доставленных событий с состоянием прочтения, обработчик, который его наполняет, и четыре операции для списка и отметки. Отправка приглашения - первый продуктовый источник ([Отправка приглашений](#отправка-приглашений)); синтетическое событие остается для тестов и проверок. Код: миграции `backend/db/migrations/00032_create_notification_inbox.sql` и `00036_allow_synthetic_notification_event.sql`, запросы `backend/db/queries/notification_inbox.sql`, модель `backend/internal/domain/notification_inbox.go`, порт `port/outbound/notification_inbox.go` (`UnitOfWork.NotificationInbox()`), адаптер `adapter/secondary/postgres/notification_inbox.go`, файлы usecase `usecase/notification/inbox.go`, `inbox_handler.go` и `inbox_content.go`, HTTP-обработчик `adapter/primary/http/v1/notifications.go` с курсором `notification_cursor.go`, подключение в `bootstrap/notification.go` и `eventHandlers()` и frontend-функция `frontend/src/features/notifications/` со страницей `frontend/src/pages/notifications/`. Операции описаны в [api/README.md](../../api/README.md#уведомления). -- Inbox - состояние доставки внутри платформы. Строка означает, что уведомление дошло до кабинета получателя, а `read_at` - что получатель его прочитал. Почта - другой канал со своим состоянием в `deliveries` ([Доставки писем](#доставки-писем)), и ни один из них не читает другой. Обработчик inbox никогда не читает `deliveries`, `mail_requests` и состояние подтверждения адреса, поэтому неподтвержденный адрес, `EMAIL_PROVIDER=disabled` или неудачная отправка не блокируют уведомление, а отправленное письмо не считается увиденным. Когда появятся приглашения, состояние "доставлено" у приглашения - это существование его строки в inbox. +- Inbox - состояние доставки внутри платформы. Строка означает, что уведомление дошло до кабинета получателя, а `read_at` - что получатель его прочитал. Почта - другой канал со своим состоянием в `deliveries` ([Доставки писем](#доставки-писем)), и ни один из них не читает другой. Обработчик inbox никогда не читает `deliveries`, `mail_requests` и состояние подтверждения адреса, поэтому неподтвержденный адрес, `EMAIL_PROVIDER=disabled` или неудачная отправка не блокируют уведомление, а отправленное письмо не считается увиденным. Состояние "доставлено" у приглашения - это его собственный `delivered_at`, который пишет транзакция отправки; строка inbox его уведомления появляется следом через обработчик. - Строка хранит ссылки, а не текст. В `notification_inbox_events` ключ `(recipient_user_id, event_id)` и столбцы `organization_id`, `event_type`, `schema_version`, `source_type`, `source_id`, `occurred_at` и `read_at`. Заголовка, текста, названия, контакта и оценки там нет. Триггеры делают ссылку неизменяемой (можно только один раз задать `read_at`) и запрещают прямое удаление; удаление аккаунта получателя удаляет строки каскадом, а внешний ключ организации - `RESTRICT`. CHECK пропускает только пары типа события и типа источника из `domain.NotificationInboxSourceFor`, обе в версии схемы 1: `invitation.delivered` с `invitation` и синтетическое `notification.synthetic_delivered` с `organization`. Миграция 00032 уже развернута и не менялась; 00036 только расширила CHECK, а ее откат отказывает, пока есть синтетическая строка. -- Контракт источника. Источник в своей транзакции добавляет событие разрешенного типа с payload `{"recipient_user_id": ..., "organization_id": ...}` (два идентификатора, без неизвестных полей, версия схемы 1) и агрегатом, который назван для типа. У `invitation.delivered` агрегат - это `invitation`, он же источник содержимого. Синтетическое событие использует одноразовый агрегат `synthetic_notice` версии 1, а источник - организация из payload; единственный автор этого payload - `notification.SyntheticNoticeEventPayload`. Поэтому модулю приглашений не нужны изменения в таблице, обработчике и API: он добавляет `invitation.delivered` и регистрирует преобразователь содержимого для источника `invitation` в `notification.DefaultInboxSourceResolvers()`. Пока преобразователя нет, элемент такого источника показывается без содержимого. +- Контракт источника. Источник в своей транзакции добавляет событие разрешенного типа с payload `{"recipient_user_id": ..., "organization_id": ...}` (два идентификатора, без неизвестных полей, версия схемы 1) и агрегатом, который назван для типа. У `invitation.delivered` агрегат - это `invitation`, он же источник содержимого. Синтетическое событие использует одноразовый агрегат `synthetic_notice` версии 1, а источник - организация из payload; единственный автор этого payload - `notification.SyntheticNoticeEventPayload`. Модулю приглашений не понадобились изменения в таблице, обработчике и API: транзакция отправки добавляет `invitation.delivered` через `notification.InvitationNotifier`, а `notification.ResolveInvitationNotice` зарегистрирован для источника `invitation` в `notification.DefaultInboxSourceResolvers()`. - Синтетический тип события. `notification.synthetic_delivered` не имеет продуктового смысла. Он нужен, чтобы пройти весь путь (outbox, relay, Kafka, обработчик, проверка при чтении, список, прочтение) до появления настоящего источника и в браузерных тестах. По умолчанию он выключен: обработчик обрабатывает его, а inbox показывает, только при `NOTIFICATION_SYNTHETIC_ENABLED=true` (стенд разработки или браузерных тестов; overlay e2e включает его). При выключенном флаге событие подтверждается и игнорируется, а сохраненная синтетическая строка показывается без содержимого; CHECK в базе разрешает тип в любом случае, поэтому для включения миграция не нужна. Создать событие может только код, который умеет писать в outbox, а содержимое - фиксированный текст с названием отправляющей организации. Браузерный набор добавляет его через `company-fixture` (тег сборки Go `e2e`), а не через операцию пользователя. - Обработчик `notification_inbox`. `InboxHandler` обрабатывает разрешенные типы. В транзакции dedup-маркера он проверяет конверт и payload и окончательно отклоняет сломанное событие (`ErrEventRejected`), пропускает получателя, чей аккаунт удален, и пишет строку с `ON CONFLICT DO NOTHING` по ключу. Получатель, удаленный между проверкой и вставкой, прерывает вставку внешним ключом получателя; обработчик возвращает это как повторяемую ошибку, и повтор видит, что аккаунта нет, и пропускает событие, а ошибка внешнего ключа организации отклоняет событие окончательно. Одну строку на получателя и ID события держат три слоя: маркер обработчика, ключ и сравнение дубликата с сохраненными метаданными; ID события, который пришел снова с другими метаданными, отклоняется, а не перезаписывается. Поэтому повтор под переименованным обработчиком второй строки не создает. `occurred_at` - информационное время вставки строки outbox; вместе с ID события оно упорядочивает список. Группа `.notification_inbox` новая, поэтому читает с самого раннего сохраненного события; события других типов считаются пропущенными. -- Содержимое вычисляется при чтении. `InboxService` читает страницу и вызывает преобразователь типа источника каждого элемента в той же транзакции, где проверен зритель; результат не сохраняется. Преобразователь возвращает `ErrInboxContentUnavailable`, когда источника нет или получатель сейчас не вправе его видеть. Тогда элемент остается в списке с `content` равным null, клиент показывает общую строку, а прежний текст не показывается никогда. Тип источника без преобразователя недоступен, а не угадывается. Единственный преобразователь сегодня - у синтетического уведомления: его фиксированный русский текст называет организацию-отправителя по ее текущему названию, которое `OrganizationNameForRecipient` читает с учетом текущего положения получателя. Кандидат видит название, пока не скрыл организацию, а работодатель - пока его членство активно. Название, которое не умещается в пределы представления, не показывается. Ссылка в содержимом - путь того же origin из узкого алфавита, и клиент открывает ее только внутри своего кабинета. +- Содержимое вычисляется при чтении. `InboxService` читает страницу и вызывает преобразователь типа источника каждого элемента в той же транзакции, где проверен зритель; результат не сохраняется. Преобразователь возвращает `ErrInboxContentUnavailable`, когда источника нет или получатель сейчас не вправе его видеть. Тогда элемент остается в списке с `content` равным null, клиент показывает общую строку, а прежний текст не показывается никогда. Тип источника без преобразователя недоступен, а не угадывается. Преобразователь доставленного приглашения читает его, только если оно адресовано получателю, доставлено и относится к организации элемента, и называет организацию и роль; значений кандидата он не показывает и ссылается на `/candidate/invitations`. Преобразователь синтетического уведомления использует фиксированный русский текст с названием организации-отправителя. Оба читают текущее название через `OrganizationNameForRecipient` с учетом текущего положения получателя: кандидат видит название, пока не скрыл организацию, а работодатель - пока его членство активно. Название, которое не умещается в пределы представления, не показывается. Ссылка в содержимом - путь того же origin из узкого алфавита, и клиент открывает ее только внутри своего кабинета. - Область доступа. Кабинет кандидата требует подтвержденный аккаунт кандидата и показывает все организации, которые писали вызывающему. Кабинет одной организации требует аккаунт работодателя с подтвержденной почтой (иначе 403 `email_not_verified`, как у других операций организации) и активное членство любой роли в организации из пути. Членство блокируется `FOR SHARE` через `LockActiveMembership` в транзакции списка или отметки, как в чтениях карточки, поэтому отзыв не может зафиксироваться между проверкой и чтением и останавливает следующий же запрос. Получатель всегда берется из сессии; организация из пути только сужает строки, а один идентификатор в пути ничего не дает. Кандидат на маршруте организации и работодатель на маршруте кандидата получают 403. Нет членства, неизвестная организация, элемент другого аккаунта, элемент другой организации и неизвестный ID дают один и тот же 404 `not_found`. Маршруты организации не входят в список только для владельца в `NewCompanyContextMiddleware`; `TestCompanyContextOperationInventoryMatchesOpenAPI` называет их проверяемыми в собственной транзакции. - Чтение и отметка. `GET /api/v1/me/notifications` и `GET /api/v1/organizations/{org_id}/notifications` возвращают страницу от новых к старым с курсором, привязанным к аккаунту и кабинету; курсор другого аккаунта или кабинета - 400. `POST .../{notification_id}/read` сохраняет первое время прочтения и возвращает его при каждом повторе. Он не читает источник и не возвращает содержимое, поэтому элемент без содержимого тоже можно отметить. Все четыре - `Cache-Control: no-store`; отметка требует сессию, CSRF-токен и разрешенный Origin, а Idempotency-Key не нужен, потому что операция идемпотентна по эффекту. Новых кодов problem нет. - Frontend. `features/notifications` экспортирует `NotificationInbox` (кандидат или одна организация) и `OrganizationNotificationInbox` (выбор организации в параметре `organization_id` и сам inbox). Их используют страницы `/candidate/notifications` и `/employer/notifications` и пункт "Уведомления" в каждой оболочке. Список читается при каждом заходе и не сохраняется (`gcTime: 0`), ключ зависит от аккаунта и кабинета, а кэш сбрасывается при смене аккаунта или сессии и при отказе в доступе. Состояния: загрузка, пусто, ошибка с повтором, нет доступа, элемент без содержимого и "Показать еще". Состояние прочтения выражено словом, а не только стилем, отметка - нативная кнопка, и после успеха фокус переходит на заголовок элемента. - Компромисс: согласованность в конечном счете. Строку пишет обработчик после relay и Kafka, поэтому уведомление появляется через секунды после фиксации у источника, а не внутри его транзакции. Альтернатива - писать строку в транзакции источника через `UnitOfWork.NotificationInbox()` - дала бы мгновенность, но привязала бы каждый источник к inbox и лишила бы повторов и dead-letter, которые дает обработчик. Поэтому браузерный набор ждет появления элемента и затем повторяет доставку. - Тесты. Модульные: `domain/notification_inbox_test.go`, `usecase/notification/inbox_test.go` и `inbox_handler_test.go` (проверки кабинета, отзыв членства, запасной вариант преобразователя, идемпотентный обработчик, отклоненные события, событие `invitation.delivered` по тому же контракту), `adapter/primary/http/v1/notifications_test.go`, `adapter/primary/http/notification_contract_test.go`, `bootstrap/consumers_test.go` и тесты функции в `frontend/src/features/notifications/`. Интеграционные: `TestNotificationInboxOverHTTP` и `TestSyntheticNotificationMigration*`. Браузерный: `frontend/e2e/notifications.spec.ts` в режиме регистрации ([TESTING.md](TESTING.md#браузерный-e2e-набор)). -- Не реализовано: источник приглашений и его преобразователь содержимого, счетчик непрочитанного или значок в оболочках, живые обновления (список читается при заходе и при фокусе окна), архивирование и удаление элемента, срок хранения старых строк, фильтрация уведомлений работодателя по ролям, настройка почты и метрика inbox. Строки синтетического типа приложение не удаляет. +- Не реализовано: счетчик непрочитанного или значок в оболочках, живые обновления (список читается при заходе и при фокусе окна), архивирование и удаление элемента, срок хранения старых строк, фильтрация уведомлений работодателя по ролям, настройка почты и метрика inbox. Строки синтетического типа приложение не удаляет. ### Версии продуктовой политики @@ -941,13 +941,13 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове ### Черновики приглашений -Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет. Отправка, отзыв, повышение вилки, чтение контактов и все операции кандидата тега invitation после общих проверок по-прежнему отвечают 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#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет; отправка описана в [Отправке приглашений](#отправка-приглашений). Отзыв, повышение вилки, чтение контактов и все операции кандидата тега invitation, кроме `ListMyInvitations`, после общих проверок по-прежнему отвечают 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`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются. +- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created`, `draft_updated` или, с миграции 00038, `delivered`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются. - `invitation_creation_results`: исходный ответ идемпотентного создания, привязанный к общей записи идемпотентности и удаляемый вместе с ней. В нем условия, псевдоним и нет идентификатора кандидата. Решения: @@ -962,12 +962,30 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Блокировки. Создание и изменение сначала берут исключительную блокировку организации (`CompanyQuotaRepository.LockOrganization`), как чтение карточки и поиск, и только потом разделяемую блокировку проверки членства, блокировки когорты при создании или блокировку строки приглашения при изменении. Поэтому команды одной организации встают в очередь, а не блокируют друг друга при повышении блокировки, и следующая команда, которая тоже списывает ресурсы организации, например отправка, сохраняет тот же порядок. Изменение блокирует строку приглашения отдельным запросом (`LockInvitation`) и читает ее после: блокирующее чтение с соединением таблицы условий после ожидания чужой фиксации сопоставило бы новый `terms_version` со строкой условий, взятой до ожидания, и ничего не нашло бы. Создание повторяется ограниченное число раз, если видимая когорта изменилась во время блокировки. - Индикатор. `salary_fit` всегда `not_available`, а `contact_access` - `not_granted` без полей. Индикатору нужен минимум кандидата, а его вычисление до появления лимита из трех установок в день и семидневного отключения позволило бы организации подбирать минимум правками черновика, поэтому пока не считается и не применяется ни то ни другое. -Как подключаются следующие операции: отправка должна снова проверить кандидата тем же барьером видимости, потому что черновик сохраняет кандидата после отзыва C2 или скрытия, и затем переводит черновик в `delivered` одним UPDATE `state`, `delivered_at`, `response_deadline_at` и `version`, добавляет событие аудита этой версии и пишет событие outbox `invitation.delivered`, а преобразователь входящей записи для источника `invitation` - уже существующая точка подключения [Внутренних уведомлений](#внутренние-уведомления); входящие кандидата читают `invitations` по `candidate_id` и `delivered_at`, а правила пары читают индекс по организации и кандидату. Контактное разрешение, ключ C4 на `invitations` и ключи журнала согласий на `organizations` и `invitations` появятся вместе с принятием, первым писателем строк C4 с настоящим приглашением. +Как подключаются следующие операции: правила пары читают индекс по организации и кандидату. Контактное разрешение, ключ C4 на `invitations` и ключи журнала согласий на `organizations` и `invitations` появятся вместе с принятием, первым писателем строк C4 с настоящим приглашением. -Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, списание квоты и предел ожидающих приглашений на потребность, отправка, повышение, отзыв, сторона кандидата, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована. +Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, предел ожидающих приглашений на потребность, повышение, отзыв, сторона кандидата сверх списка приглашений, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована. Тесты: `domain/salary_range_test.go` и `domain/invitation_test.go` (точная ширина на 10% и 40%, шаг, пределы, правила условий с pointer, версии, неизменность прежних значений, скрытие при печати), `usecase/invitation/service_test.go` (политика владельца, отказы по handle, порядок проверок, повтор, откат, версии), `adapter/primary/http/v1/invitation_test.go` (преобразование, отсутствие полей кандидата, статусы отказов, курсор) и интеграционные `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` и `TestInvitationMigrationRollbackKeepsStoredInvitations` на настоящем PostgreSQL. +### Отправка приглашений + +Реализовано: `SendOrganizationInvitation` и список приглашений кандидата `ListMyInvitations` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Код: `domain/invitation_delivery.go`, `usecase/invitation/send.go` и `candidate_inbox.go`, `usecase/notification/invitation.go`, HTTP-обработчик `adapter/primary/http/v1/invitation.go` с курсором в `invitation_cursor.go`, адаптер `adapter/secondary/postgres/invitation_delivery.go` с `db/queries/invitation_delivery.sql`, подключение в `bootstrap/invitation.go` и миграция `00038_send_invitations.sql`. + +- Одна транзакция. Отправка берет блокировку организации (`CompanyQuotaRepository.LockOrganization`), проверку владельца по членству, Idempotency-Key и блокировку строки приглашения в порядке всех команд приглашений, а затем блокировки видимой когорты. Она снова проходит барьер видимости чтения карточки, списывает одно приглашение из квоты организации, переводит черновик в `delivered` одним условным UPDATE (`state`, `version` плюс один, `delivered_at`, `response_deadline_at`, `updated_at`; версия условий не меняется), добавляет событие аудита `delivered` и пишет события outbox: `invitation.delivered` для уведомления внутри платформы и `notification.mail_requested` со строкой `mail_requests` для письма. Внутренний шаг отправки не сохраняется: к моменту ответа приглашение уже `delivered`, лежит в списке кандидата, а списание записано. Ошибка любого шага откатывает все. +- Входящая запись кандидата - само доставленное приглашение. `ListMyInvitations` читает строки с кандидатом из сессии и `delivered_at`, от новых к старым по `(delivered_at, id)` по частичному индексу миграции 00037, с текущим названием организации-отправителя; у черновика доставки нет, и он не показывается, а список не записывает просмотр. Уведомление в `notification_inbox_events` пишет обработчик inbox из события outbox через секунды ([Внутренние уведомления](#внутренние-уведомления)); приглашение его не ждет. +- Срок. `response_deadline_at = delivered_at + response_period_days` в целых днях, его задает тот же UPDATE, что и первую доставку. Триггер миграции 00037 запрещает потом менять доставку, срок и период, а почтовый путь приглашения не трогает, поэтому ни письмо, ни его повторы срок не сдвигают. Запрос письма становится доставкой, когда его обрабатывает обработчик доставок; отправка писем-уведомлений запланирована. Неподтвержденный адрес, остановленный транспорт (`EMAIL_PROVIDER=disabled`) и неудачная попытка не влияют ни на приглашение, ни на ответ отправки. +- Содержимое. Письмо сообщает только, что работодатель прислал приглашение, и ссылается на `/candidate/invitations`: в нем нет ни организации, ни условий, ни контакта или идентификатора кандидата. Уведомление показывает организацию и роль, пока кандидат не скрыл организацию. Payload `invitation.delivered` называет получателя и организацию, как требует контракт inbox, и остается во внутренней шине событий. +- Видимость. Черновик сохраняет кандидата после отзыва C2, скрытия или падения когорты ниже минимума. Отправка выводит handle карточки сохраненного кандидата и снова разрешает его через `candidateview.Service.ResolveCandidateHandle`; кандидат, которого организация больше не вправе видеть, дает 409 `state_conflict` без указания, какое правило сработало. +- Квота. Списание идет через существующий порт квоты компании (`companyquota.Service.ReserveInvitation`) в `company_invitation_quota_usage` с ключом по приглашению, поэтому пишется один раз. Миграция 00038 добавляет составной внешний ключ `(organization_id, invitation_id)` на `invitations`. Исчерпанная квота дает 429 с `Retry-After`, ничего не сохраняется, черновик остается. Порт считает пул одной организации; общий пул E0 холдинга в порте пока не реализован. +- Идемпотентность. Область ключа - операция, ключ, аккаунт и организация; отпечаток покрывает приглашение из пути и `expected_version`. `invitation_send_results` хранит исход под ключом 24 часа вместе с общей записью идемпотентности: исходный 200, 404 неизвестного приглашения и 409. 400, 412 и 429 не сохраняются, поэтому исправленный запрос может использовать тот же ключ. Отправка уже доставленного приглашения отвечает 200 с текущим состоянием даже с новым ключом или старой версией и ничего не списывает. +- Доступ. Только владелец, как для черновиков: `ownerCompanyOperations` на HTTP-границе и та же проверка в транзакции; другие роли отправлять не могут. Список кандидата требует подтвержденный аккаунт кандидата, работодатель получает 403. +- Порядок проверок после границы: владелец, ключ (422 или повтор), приглашение (404), завершенная отправка (200), версия (412), состояние и видимость (409), затем квота (429). + +Не реализовано: предел ожидающих приглашений на потребность и пауза после отказа или "сделки нет" (оба запланированы в контракте), чтение одного приглашения кандидатом, просмотр и ответы, истечение по сроку, отправка писем-уведомлений, общий пул E0 холдинга в порте квоты и матрица ролей и назначений сверх владельца. + +Тесты: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, `usecase/notification/inbox_test.go` (уведомление о приглашении), `adapter/primary/http/v1/invitation_test.go` (статусы, `Retry-After`, курсор кандидата) и интеграционные `TestOrganizationInvitationSendOverHTTP` (входящие до любого письма, повторы с одной строкой каждого вида и одним списанием, срок 3 дня при остановленной почте и повторе ее задания, видимость, устаревшая версия, только владелец, квота, страницы) и `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage`. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index efa334c..f83c7e5 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -479,7 +479,7 @@ Unit-тесты (`make -C backend test`) проверяют правила жу Браузерный тест: `frontend/e2e/notifications.spec.ts` запускается в `make -C deploy test-e2e-registration`, overlay которого задает `NOTIFICATION_SYNTHETIC_ENABLED=true`. `company-fixture` (тег сборки Go `e2e`, bearer-токен, только синтетические получатели `@example.test`) добавляет синтетическое событие в настоящий outbox, поэтому relay, Kafka и обработчик `notification_inbox` доставляют его; тест ждет появления элемента. Затем он повторяет событие через fixture, который обязан сообщить, что настоящий обработчик уже применил его, и проверяет, что в списке по-прежнему один элемент. Кандидат открывает список, отмечает элемент с клавиатуры, перезагружает страницу и видит сохраненное состояние, а второй кандидат получает пустой список и 404 на тот же ID. После скрытия организации элемент остается без содержимого. Второй тест читает inbox организации как владелец, проверяет не участника, отзывает членство через fixture и проверяет, что тот же ID отклоняется, а страница не показывает содержимое. -Чего эти тесты не показывают: настоящее приглашение (пока ни одно не создает событие), поведение inbox при сбое почтового провайдера (по построению обработчик не читает состояние почты, а модульный тест покрывает неподтвержденный адрес), задержку доставки и нагрузку, push и живые обновления, а также вёрстку и работу страницы со скринридером (автоматической проверки нет). +Чего эти тесты не показывают: событие настоящего приглашения через Kafka и relay (`TestOrganizationInvitationSendOverHTTP` доставляет его только через хранилище обработчика), поведение inbox при сбое почтового провайдера (по построению обработчик не читает состояние почты, а модульный тест покрывает неподтвержденный адрес), задержку доставки и нагрузку, push и живые обновления, а также вёрстку и работу страницы со скринридером (автоматической проверки нет). ## Тесты демонстрационного seed diff --git a/frontend/src/shared/api/endpoints/invitation/invitation.ts b/frontend/src/shared/api/endpoints/invitation/invitation.ts index b7cb743..a5e3339 100644 --- a/frontend/src/shared/api/endpoints/invitation/invitation.ts +++ b/frontend/src/shared/api/endpoints/invitation/invitation.ts @@ -518,7 +518,7 @@ export const useUpdateOrganizationInvitation = , * * Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. * - * The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. Enforcement of the pending limit and the organization quota is planned. + * The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are not checked yet. * * Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. * diff --git a/frontend/src/shared/api/schemas/notification/notification.zod.ts b/frontend/src/shared/api/schemas/notification/notification.zod.ts index 8da246d..56f5ffa 100644 --- a/frontend/src/shared/api/schemas/notification/notification.zod.ts +++ b/frontend/src/shared/api/schemas/notification/notification.zod.ts @@ -17,7 +17,7 @@ export const notificationContentOneLinkPathRegExp = new RegExp('^/[A-Za-z0-9/_-] export const Notification = zod.object({ "id": zod.uuid().describe('Identifier of the item. It equals the identifier of the event that produced it, so a repeated delivery of the same event is the same item.'), - "kind": zod.enum(['invitation_delivered', 'synthetic']).describe('Which event put the notification into the inbox. The inbox stores a reference to the event, never its text.\n\n- invitation_delivered: an invitation reached the candidate\'s inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet.\n- synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action.\n\nAdding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.'), + "kind": zod.enum(['invitation_delivered', 'synthetic']).describe('Which event put the notification into the inbox. The inbox stores a reference to the event, never its text.\n\n- invitation_delivered: an invitation reached the candidate\'s inbox. It does not depend on any email, and a failed or missing email never blocks it. The send of an invitation produces it through the outbox, so the notice appears shortly after the commit of the send, while the invitation itself is in ListMyInvitations from that commit.\n- synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action.\n\nAdding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.'), "organization_id": zod.uuid().describe('The organization context of the item: the organization that sent it to a candidate, or the organization whose cabinet holds it for an employer. The identifier is not a right to read the organization.'), "delivered_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "read_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time.'), diff --git a/frontend/src/shared/api/schemas/notification/notificationKind.zod.ts b/frontend/src/shared/api/schemas/notification/notificationKind.zod.ts index 5cdf118..630c57c 100644 --- a/frontend/src/shared/api/schemas/notification/notificationKind.zod.ts +++ b/frontend/src/shared/api/schemas/notification/notificationKind.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const NotificationKind = zod.enum(['invitation_delivered', 'synthetic']).describe('Which event put the notification into the inbox. The inbox stores a reference to the event, never its text.\n\n- invitation_delivered: an invitation reached the candidate\'s inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet.\n- synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action.\n\nAdding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.') +export const NotificationKind = zod.enum(['invitation_delivered', 'synthetic']).describe('Which event put the notification into the inbox. The inbox stores a reference to the event, never its text.\n\n- invitation_delivered: an invitation reached the candidate\'s inbox. It does not depend on any email, and a failed or missing email never blocks it. The send of an invitation produces it through the outbox, so the notice appears shortly after the commit of the send, while the invitation itself is in ListMyInvitations from that commit.\n- synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action.\n\nAdding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.') export type NotificationKind = zod.input; export type NotificationKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/notification/notificationList.zod.ts b/frontend/src/shared/api/schemas/notification/notificationList.zod.ts index 13872d5..32106e1 100644 --- a/frontend/src/shared/api/schemas/notification/notificationList.zod.ts +++ b/frontend/src/shared/api/schemas/notification/notificationList.zod.ts @@ -24,7 +24,7 @@ export const notificationListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$ export const NotificationList = zod.object({ "items": zod.array(zod.object({ "id": zod.uuid().describe('Identifier of the item. It equals the identifier of the event that produced it, so a repeated delivery of the same event is the same item.'), - "kind": zod.enum(['invitation_delivered', 'synthetic']).describe('Which event put the notification into the inbox. The inbox stores a reference to the event, never its text.\n\n- invitation_delivered: an invitation reached the candidate\'s inbox. This is the in-platform delivery state of the invitation: it does not depend on any email, and a failed or missing email never blocks it. The invitation operations are planned; no invitation produces a notification yet.\n- synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action.\n\nAdding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.'), + "kind": zod.enum(['invitation_delivered', 'synthetic']).describe('Which event put the notification into the inbox. The inbox stores a reference to the event, never its text.\n\n- invitation_delivered: an invitation reached the candidate\'s inbox. It does not depend on any email, and a failed or missing email never blocks it. The send of an invitation produces it through the outbox, so the notice appears shortly after the commit of the send, while the invitation itself is in ListMyInvitations from that commit.\n- synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action.\n\nAdding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.'), "organization_id": zod.uuid().describe('The organization context of the item: the organization that sent it to a candidate, or the organization whose cabinet holds it for an employer. The identifier is not a right to read the organization.'), "delivered_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), "read_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time.'),