diff --git a/api/README.en.md b/api/README.en.md index 04c6837..53739cd 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -459,7 +459,7 @@ Planned contract changes (new enum values; like the catalog codes, generated cli ### Invitations and contact grants -The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). `SendOrganizationInvitation` and `ListMyInvitations` are implemented as well: the send checks the owner, the key, the version, the state, and the current visibility of the candidate and charges the weekly organization quota, while the pending limit of a need and the 30-day pause are not checked yet; a success means the invitation is already in `ListMyInvitations`, and the notification and the email follow through the outbox ([architecture](../docs/en/ARCHITECTURE.md#sending-invitations)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. +The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). `SendOrganizationInvitation` and `ListMyInvitations` are implemented as well: the send checks the owner, the key, the version, the state, and the current visibility of the candidate and charges the weekly organization quota, while the pending limit of a need and the 30-day pause are not checked yet; a success means the invitation is already in `ListMyInvitations`, and the notification and the email follow through the outbox ([architecture](../docs/en/ARCHITECTURE.md#sending-invitations)). `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` are implemented as described below, with two limits until the related operations exist: no read or command applies the due expiry, so a view at the deadline or later changes nothing and a late decline answers 409 `state_conflict` while the state stays `delivered` or `viewed`; and `contact_consent` and `contact_grant` are always null, because an acceptance is impossible before `AcceptMyInvitation` is implemented ([architecture](../docs/en/ARCHITECTURE.md#candidate-view-and-decline)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | diff --git a/api/README.md b/api/README.md index 6067feb..f0e316c 100644 --- a/api/README.md +++ b/api/README.md @@ -459,7 +459,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Приглашения и контактные разрешения -Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Сторона организации в черновике реализована: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` следуют правилам ниже, но `salary_fit` всегда равен `not_available`, а лимит вилки и счетчик `withheld` пока не применяются ([backend](../backend/README.md#черновики-приглашений)). Реализованы также `SendOrganizationInvitation` и `ListMyInvitations`: отправка проверяет владельца, ключ, версию, состояние и текущую видимость кандидата и списывает недельную квоту организации, а предел ожидающих на потребность и 30-дневная пауза пока не проверяются; успех означает, что приглашение уже есть в `ListMyInvitations`, а уведомление и письмо идут следом через outbox ([архитектура](../docs/ru/ARCHITECTURE.md#отправка-приглашений)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. +Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Сторона организации в черновике реализована: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` следуют правилам ниже, но `salary_fit` всегда равен `not_available`, а лимит вилки и счетчик `withheld` пока не применяются ([backend](../backend/README.md#черновики-приглашений)). Реализованы также `SendOrganizationInvitation` и `ListMyInvitations`: отправка проверяет владельца, ключ, версию, состояние и текущую видимость кандидата и списывает недельную квоту организации, а предел ожидающих на потребность и 30-дневная пауза пока не проверяются; успех означает, что приглашение уже есть в `ListMyInvitations`, а уведомление и письмо идут следом через outbox ([архитектура](../docs/ru/ARCHITECTURE.md#отправка-приглашений)). `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` реализованы, как описано ниже, с двумя ограничениями до появления связанных операций: ни чтение, ни команда не применяют наступившее истечение, поэтому просмотр в момент срока и позже ничего не меняет, а опоздавший отказ отвечает 409 `state_conflict`, пока состояние остается `delivered` или `viewed`; `contact_consent` и `contact_grant` всегда null, потому что принять приглашение до реализации `AcceptMyInvitation` нельзя ([архитектура](../docs/ru/ARCHITECTURE.md#просмотр-и-отказ-кандидата)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | diff --git a/backend/README.en.md b/backend/README.en.md index 5c1cf13..e4d3993 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -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`). 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. +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, the acceptance, and the cancellation 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). @@ -66,6 +66,8 @@ The integration tests `TestOrganizationInvitationDraftsOverHTTP` (the router, se Sending is implemented: `POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send` (`usecase/invitation/send.go`) and the candidate's list `GET /api/v1/me/invitations` (`usecase/invitation/candidate_inbox.go`). One transaction takes the organization lock, the owner membership, the key, and the invitation row, checks the version and the state, resolves the stored candidate through the card visibility barrier again (409 when hidden, C2 revoked, or suppressed), charges the organization quota through `companyquota.Service.ReserveInvitation` (429 with `Retry-After`), moves the draft to `delivered` with `response_deadline_at = delivered_at + response_period_days`, appends the `delivered` audit event, and writes the outbox events `invitation.delivered` and `notification.mail_requested` (`usecase/notification/invitation.go`). A success therefore means the invitation is already in the candidate's list; the notification and the email follow through the consumers, and neither they nor their retries change the deadline. A repeat with the same key replays the stored outcome, and a send of a delivered invitation answers 200 with its current state without a second charge. Migration `00038_send_invitations.sql` adds the `delivered` event kind, `invitation_send_results` (the 200, 404, or 409 kept under the key), and the foreign key from `company_invitation_quota_usage` to `invitations`; its rollback refuses while a delivery event or a stored outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#sending-invitations). `TestOrganizationInvitationSendOverHTTP` and `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage` cover it against a real PostgreSQL. +The candidate's read, view, and decline are implemented: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view`, and `POST .../decline` (`usecase/invitation/view.go` and `decline.go`). The read records nothing; the view moves `delivered` to `viewed` before the deadline, keeps the deadline, and otherwise answers with the invitation as it is; the decline moves `delivered`, `viewed`, or the planned `counter` to `declined` before the deadline with a reason and an optional comment and creates no consent or grant. Both commands lock only the invitation row, never the organization, and append the audit events `viewed` and `declined`. A late decline answers 409, since the expiry is not implemented yet, and `contact_consent` and `contact_grant` stay null until the acceptance exists. Migration `00039_answer_invitations.sql` adds the event kinds, the state rules of the view and the answer, `invitation_declines` (the reason and the comment, which the organization never reads), and `invitation_decline_results` (the outcome under the key); its rollback refuses while a view, a decline, or an outcome exists. Details are in [architecture](../docs/en/ARCHITECTURE.md#candidate-view-and-decline). `TestCandidateInvitationViewAndDeclineOverHTTP` and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` cover it against a real PostgreSQL. + ## 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. diff --git a/backend/README.md b/backend/README.md index fa7cfdc..77518f1 100644 --- a/backend/README.md +++ b/backend/README.md @@ -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#приглашения-и-контактные-разрешения). @@ -66,6 +66,8 @@ Реализована отправка: `POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send` (`usecase/invitation/send.go`) и список кандидата `GET /api/v1/me/invitations` (`usecase/invitation/candidate_inbox.go`). Одна транзакция берет блокировку организации, членство владельца, ключ и строку приглашения, проверяет версию и состояние, снова разрешает сохраненного кандидата через барьер видимости карточки (409 при скрытии, отзыве C2 или подавлении), списывает квоту организации через `companyquota.Service.ReserveInvitation` (429 с `Retry-After`), переводит черновик в `delivered` с `response_deadline_at = delivered_at + response_period_days`, добавляет событие аудита `delivered` и пишет события outbox `invitation.delivered` и `notification.mail_requested` (`usecase/notification/invitation.go`). Поэтому успех означает, что приглашение уже в списке кандидата; уведомление и письмо идут следом через обработчики, и ни они, ни их повторы срок не меняют. Повтор с тем же ключом возвращает сохраненный исход, а отправка доставленного приглашения отвечает 200 с текущим состоянием без второго списания. Миграция `00038_send_invitations.sql` добавляет вид события `delivered`, `invitation_send_results` (200, 404 или 409 под ключом) и внешний ключ из `company_invitation_quota_usage` на `invitations`; ее откат отказывает, пока есть событие доставки или сохраненный исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#отправка-приглашений). `TestOrganizationInvitationSendOverHTTP` и `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage` проверяют это на настоящем PostgreSQL. +Реализованы чтение, просмотр и отказ кандидата: `GET /api/v1/me/invitations/{invitation_id}`, `POST .../view` и `POST .../decline` (`usecase/invitation/view.go` и `decline.go`). Чтение ничего не записывает; просмотр переводит `delivered` в `viewed` до срока, сохраняет срок, а иначе отвечает приглашением как есть; отказ переводит `delivered`, `viewed` или запланированное `counter` в `declined` до срока с причиной и необязательным комментарием и не создает ни согласия, ни разрешения. Обе команды блокируют только строку приглашения, но не организацию, и добавляют события аудита `viewed` и `declined`. Опоздавший отказ отвечает 409, потому что истечение еще не реализовано, а `contact_consent` и `contact_grant` остаются null, пока нет принятия. Миграция `00039_answer_invitations.sql` добавляет виды событий, правила состояния для просмотра и ответа, `invitation_declines` (причина и комментарий, которые организация никогда не читает) и `invitation_decline_results` (исход под ключом); ее откат отказывает, пока есть просмотр, отказ или исход. Подробности - в [архитектуре](../docs/ru/ARCHITECTURE.md#просмотр-и-отказ-кандидата). `TestCandidateInvitationViewAndDeclineOverHTTP` и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback` проверяют это на настоящем PostgreSQL. + ## Обращения в поддержку Подтвержденные аккаунты создают и просматривают список собственных обращений через `/api/v1/me/support-cases`, а отдельное дело читают по его ID. Владение обращением не зависит от доступа к спорному действию. Ссылка на объект содержит только тип и ID; сервер проверяет область доступа и не копирует приватное содержимое объекта. Работодатели отправляют общие запросы поддержки. Кандидаты также могут запросить ручную оценку без предыдущей попытки и согласия C3. Такой запрос ожидает эксперта, не назначает грейд и не выдает согласие. diff --git a/backend/db/migrations/00039_answer_invitations.sql b/backend/db/migrations/00039_answer_invitations.sql new file mode 100644 index 0000000..62c12fb --- /dev/null +++ b/backend/db/migrations/00039_answer_invitations.sql @@ -0,0 +1,216 @@ +-- +goose Up +-- The candidate's view and decline of a delivered invitation. The view moves +-- `delivered` to `viewed` and keeps the deadline. The decline moves +-- `delivered`, `viewed`, or the planned `counter` to the terminal `declined` +-- and stores the structured reason and the optional comment in their own +-- table, which only the candidate reads back. Neither creates a consent or a +-- contact grant. Each appends an audit event that names the version and the +-- actor and holds no reason or comment. +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ('draft_created', 'draft_updated', 'delivered', 'viewed', 'declined') +); + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_answer_changes_no_field CHECK ( + kind NOT IN ('viewed', 'declined') OR cardinality(changed_fields) = 0 +); + +-- A viewed invitation records its view, a declined one its answer, and +-- neither precedes the delivery. A delivered invitation has neither yet. +ALTER TABLE invitations +ADD CONSTRAINT invitations_answer_matches_state CHECK ( + (state <> 'delivered' OR (viewed_at IS NULL AND responded_at IS NULL)) + AND (state <> 'viewed' OR (viewed_at IS NOT NULL AND responded_at IS NULL)) + AND (state <> 'declined' OR responded_at IS NOT NULL) + AND (viewed_at IS NULL OR (delivered_at IS NOT NULL AND viewed_at >= delivered_at)) + AND ( + responded_at IS NULL + OR (delivered_at IS NOT NULL AND responded_at >= delivered_at) + ) +); + +-- The structured decline of one invitation. The organization never reads +-- this table: a reason such as `salary` would tell it that the hidden minimum +-- is above the range. The comment is the candidate's private text. +CREATE TABLE invitation_declines ( + invitation_id uuid NOT NULL, + organization_id uuid NOT NULL, + reason text NOT NULL, + comment text, + declined_at timestamptz NOT NULL, + CONSTRAINT invitation_declines_pkey PRIMARY KEY (invitation_id), + CONSTRAINT invitation_declines_invitation_fkey FOREIGN KEY ( + organization_id, invitation_id + ) REFERENCES invitations (organization_id, id) ON DELETE RESTRICT, + CONSTRAINT invitation_declines_reason_known CHECK ( + reason IN ( + 'salary', 'tasks', 'stack', 'work_format', 'package', 'company', + 'not_looking', 'other_offer', 'other' + ) + ), + -- The contract bound of InvitationDeclineComment: 1 to 500 characters, + -- at least one of them not white space. + CONSTRAINT invitation_declines_comment_bounded CHECK ( + comment IS NULL + OR ( + char_length(comment) BETWEEN 1 AND 500 + AND comment ~ '[^[:space:]]' + ) + ) +); + +-- Outcome of an idempotent decline, kept beside the generic idempotency +-- record and removed with it after the 24-hour replay window. It holds no +-- copy of the response: a declined invitation and its decline never change, +-- so a replay rebuilds the same answer, and the comment is stored once. The +-- invitation is intentionally not a foreign key: the outcome of a missing +-- invitation names an identifier that does not exist. +CREATE TABLE invitation_decline_results ( + scope_hash bytea NOT NULL, + invitation_id uuid NOT NULL, + outcome text NOT NULL, + CONSTRAINT invitation_decline_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT invitation_decline_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT invitation_decline_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT invitation_decline_results_outcome CHECK ( + outcome IN ('declined', 'not_found', 'state_conflict') + ) +); + +-- A view and an answer are never undone or moved, and a declined invitation +-- never leaves its terminal state. +-- +goose StatementBegin +CREATE FUNCTION invitations_guard_answer() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (OLD.viewed_at IS NOT NULL AND NEW.viewed_at IS DISTINCT FROM OLD.viewed_at) + OR (OLD.responded_at IS NOT NULL AND NEW.responded_at IS DISTINCT FROM OLD.responded_at) + OR (OLD.state = 'declined' AND NEW.state <> 'declined') THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_answer_immutable', + TABLE = 'invitations', + MESSAGE = 'a view, an answer, and a decline are never undone'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitations_guard_answer +BEFORE UPDATE ON invitations +FOR EACH ROW EXECUTE FUNCTION invitations_guard_answer(); + +-- A decline row describes the declined invitation it belongs to, answered at +-- the moment of the decline. +-- +goose StatementBegin +CREATE FUNCTION invitation_declines_match_invitation() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM invitations + WHERE + invitations.organization_id = NEW.organization_id + AND invitations.id = NEW.invitation_id + AND invitations.state = 'declined' + AND invitations.responded_at = NEW.declined_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_declines_match_invitation', + TABLE = 'invitation_declines', + MESSAGE = 'a decline belongs to a declined invitation'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitation_declines_match_invitation +BEFORE INSERT ON invitation_declines +FOR EACH ROW EXECUTE FUNCTION invitation_declines_match_invitation(); + +CREATE TRIGGER invitation_declines_immutable +BEFORE UPDATE OR DELETE ON invitation_declines +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +-- Every declined invitation has its decline by the end of the transaction +-- that declined it. +-- +goose StatementBegin +CREATE FUNCTION invitations_require_decline() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM invitation_declines + WHERE + invitation_declines.organization_id = NEW.organization_id + AND invitation_declines.invitation_id = NEW.id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_decline_recorded', + TABLE = 'invitations', + MESSAGE = 'a declined invitation records its decline'; + END IF; + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +CREATE CONSTRAINT TRIGGER invitations_require_decline +AFTER UPDATE ON invitations +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW +WHEN (new.state = 'declined' AND old.state <> 'declined') +EXECUTE FUNCTION invitations_require_decline(); + +-- +goose Down +-- A rollback must not silently remove a view, a decline, or a stored outcome. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitation_events WHERE kind IN ('viewed', 'declined')) + OR EXISTS (SELECT 1 FROM invitations WHERE viewed_at IS NOT NULL OR state = 'declined') + OR EXISTS (SELECT 1 FROM invitation_declines) + OR EXISTS (SELECT 1 FROM invitation_decline_results) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_answers_retained', + TABLE = 'invitation_events', + MESSAGE = 'viewed and declined invitations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER invitations_require_decline ON invitations; +DROP TRIGGER invitations_guard_answer ON invitations; +DROP TABLE invitation_decline_results; +DROP TABLE invitation_declines; +DROP FUNCTION invitations_require_decline(); +DROP FUNCTION invitation_declines_match_invitation(); +DROP FUNCTION invitations_guard_answer(); + +ALTER TABLE invitations +DROP CONSTRAINT invitations_answer_matches_state; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_answer_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', 'delivered') +); diff --git a/backend/db/queries/invitation_answers.sql b/backend/db/queries/invitation_answers.sql new file mode 100644 index 0000000..30468bc --- /dev/null +++ b/backend/db/queries/invitation_answers.sql @@ -0,0 +1,129 @@ +-- Read one delivered invitation addressed to the candidate with the current +-- name of the organization that sent it. A draft and an invitation of +-- another candidate find nothing. +-- name: ReadCandidateInvitationEntry :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, + 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.id = sqlc.arg(invitation_id) + AND invitation.delivered_at IS NOT NULL; + +-- Lock one delivered invitation addressed to the candidate. Only the +-- invitation row is locked, never the organization. +-- name: LockCandidateInvitation :one +SELECT id +FROM invitations +WHERE + candidate_id = sqlc.arg(candidate_id) + AND id = sqlc.arg(invitation_id) + AND delivered_at IS NOT NULL +FOR UPDATE; + +-- The compare-and-swap of the first view: it applies only to a delivered +-- invitation at the version the caller read and before its deadline, and it +-- keeps the deadline. +-- name: RecordInvitationView :one +UPDATE invitations +SET + state = 'viewed', + version = sqlc.arg(next_version), + viewed_at = sqlc.arg(viewed_at), + updated_at = sqlc.arg(viewed_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state = 'delivered' + AND version = sqlc.arg(expected_version) + AND response_deadline_at > sqlc.arg(viewed_at) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- The compare-and-swap of a decline: it applies only to an answerable +-- invitation at the version the caller read and before its deadline. +-- name: DeclineInvitation :one +UPDATE invitations +SET + state = 'declined', + version = sqlc.arg(next_version), + responded_at = sqlc.arg(declined_at), + updated_at = sqlc.arg(declined_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state IN ('delivered', 'viewed', 'counter') + AND version = sqlc.arg(expected_version) + AND response_deadline_at > sqlc.arg(declined_at) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- name: InsertInvitationDecline :exec +INSERT INTO invitation_declines ( + invitation_id, + organization_id, + reason, + comment, + declined_at +) VALUES ( + sqlc.arg(invitation_id), + sqlc.arg(organization_id), + sqlc.arg(reason), + sqlc.narg(comment), + sqlc.arg(declined_at) +); + +-- name: ReadInvitationDecline :one +SELECT + invitation_id, + organization_id, + reason, + comment, + declined_at +FROM invitation_declines +WHERE + organization_id = sqlc.arg(organization_id) + AND invitation_id = sqlc.arg(invitation_id); + +-- name: InsertInvitationDeclineResult :exec +INSERT INTO invitation_decline_results ( + scope_hash, + invitation_id, + outcome +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(invitation_id), + sqlc.arg(outcome) +); + +-- name: GetInvitationDeclineResult :one +SELECT + invitation_id, + outcome +FROM invitation_decline_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/integration_test/invitation_answer_http_test.go b/backend/integration_test/invitation_answer_http_test.go new file mode 100644 index 0000000..7ac8dbc --- /dev/null +++ b/backend/integration_test/invitation_answer_http_test.go @@ -0,0 +1,645 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "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/policy" +) + +const ( + // invitationAnswerMigrationVersion adds the view and the decline: their + // audit events, the stored decline, and the stored decline outcomes. + invitationAnswerMigrationVersion = 39 + invitationAnswersRetained = "invitation_answers_retained" + // invitationDeclineComment is the candidate's private comment. It is + // read back by the candidate only. + invitationDeclineComment = "Private decline comment of the candidate" +) + +// candidateInvitationHTTPBody is the invitation as the candidate reads it. +type candidateInvitationHTTPBody struct { + ID uuid.UUID `json:"id"` + Organization struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + } `json:"organization"` + State string `json:"state"` + ExpiryReason *string `json:"expiry_reason"` + Version int64 `json:"version"` + TermsVersion int64 `json:"terms_version"` + Terms json.RawMessage `json:"terms"` + ResponseDeadlineAt string `json:"response_deadline_at"` + DeliveredAt string `json:"delivered_at"` + ViewedAt *string `json:"viewed_at"` + RespondedAt *string `json:"responded_at"` + UpdatedAt string `json:"updated_at"` + ContactConsent json.RawMessage `json:"contact_consent"` + Decline *struct { + Reason string `json:"reason"` + Comment *string `json:"comment"` + DeclinedAt string `json:"declined_at"` + } `json:"decline"` + ContactGrant json.RawMessage `json:"contact_grant"` +} + +func decodeCandidateInvitationHTTP(t *testing.T, response *httptest.ResponseRecorder, wantStatus int) candidateInvitationHTTPBody { + t.Helper() + if response.Code != wantStatus { + t.Fatalf("response = %d %s, want %d", response.Code, response.Body.String(), wantStatus) + } + if response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("Cache-Control = %q, want no-store", response.Header().Get("Cache-Control")) + } + var body candidateInvitationHTTPBody + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode candidate invitation %s: %v", response.Body.String(), err) + } + return body +} + +// invitationAnswerCounts are the rows that a view or a decline may write for +// one invitation, and the C4 consents of its candidate, which neither may +// create. +type invitationAnswerCounts struct { + viewedEvents, declinedEvents, declines, c4Consents int +} + +func readInvitationAnswerCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationAnswerCounts { + t.Helper() + var counts invitationAnswerCounts + if err := harness.pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'viewed'), + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'declined'), + (SELECT count(*) FROM invitation_declines WHERE invitation_id = $1), + (SELECT count(*) FROM consent_records WHERE subject_id = $2 AND purpose = 'c4')`, + invitationID, candidateID).Scan(&counts.viewedEvents, &counts.declinedEvents, &counts.declines, &counts.c4Consents); err != nil { + t.Fatalf("count the rows of an answer: %v", err) + } + return counts +} + +func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolated := *env + isolated.Config.DatabaseURL = databaseURL + setupPool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + harness := newInvitationHTTPHarness(ctx, t, &isolated) + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) + origin := env.Config.AppPublicURL + now := harness.clock.Now() + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + account := func(email string, scenario domain.Scenario) domain.User { + return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) + } + ownerA, ownerB := account("answer-owner-a@example.test", domain.ScenarioEmployer), account("answer-owner-b@example.test", domain.ScenarioEmployer) + sessionA := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()) + sessionB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionA, "answer-company-a") + orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionB, "answer-company-b") + var nameA string + if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, orgA).Scan(&nameA); err != nil { + t.Fatalf("read organization name: %v", err) + } + + identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, + organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now}, + ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now} + 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) + } + } + // Seven published candidates form the visible cohort. The first three + // can sign in. + target := account("answer-target@example.test", domain.ScenarioCandidate) + other := account("answer-other@example.test", domain.ScenarioCandidate) + hider := account("answer-hider@example.test", domain.ScenarioCandidate) + cohort := []domain.User{target, other, hider} + for index := range 4 { + candidate := privacy.candidate(t, fmt.Sprintf("answer-visible-%d@example.test", index)) + verifyPrivacyCohortCandidate(t, privacy, candidate) + cohort = append(cohort, candidate) + } + for _, candidate := range cohort { + publishCandidate(candidate) + } + login := func(candidate domain.User) organizationHTTPSession { + return loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) + } + sessionTarget, sessionOther, sessionHider := login(target), login(other), login(hider) + + 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-answer-key-%d", keySequence) + } + 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 + } + organizationPath := func(organizationID, invitationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID) + } + 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) + } + deliver := func(organizationID uuid.UUID, session organizationHTTPSession, candidate domain.User, change func(body, terms map[string]any)) invitationHTTPBody { + t.Helper() + draft := draftFor(organizationID, session, candidate, change) + response := request(http.MethodPost, organizationPath(organizationID, draft.ID)+"/send", fmt.Sprintf(`{"expected_version":%d}`, draft.Version), session, nextKey()) + return decodeInvitationHTTP(t, response, http.StatusOK) + } + myPath := func(invitationID uuid.UUID) string { return "/api/v1/me/invitations/" + invitationID.String() } + declineBody := func(version int64, reason string, comment *string) string { + body := map[string]any{"expected_version": version, "reason": reason} + if comment != nil { + body["comment"] = *comment + } + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal decline: %v", err) + } + return string(encoded) + } + decline := func(session organizationHTTPSession, invitationID uuid.UUID, body, key string) *httptest.ResponseRecorder { + return request(http.MethodPost, myPath(invitationID)+"/decline", body, session, key) + } + 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", "candidate_handle", "salary_fit", "email", "phone", "telegram", "full_name", "salary_minimum"} { + if strings.Contains(text, `"`+field+`":`) { + t.Errorf("%s contains the key %q: %s", label, field, text) + } + } + } + requireNoDeclineDetails := func(label, text string) { + t.Helper() + for _, private := range []string{invitationDeclineComment, `"decline"`, `"reason"`, `"comment"`} { + if strings.Contains(text, private) { + t.Errorf("%s discloses the decline detail %s: %s", label, private, text) + } + } + } + + t.Run("opening the terms records the view and keeps the deadline", func(t *testing.T) { + sent := deliver(orgA, sessionA, target, nil) + read := request(http.MethodGet, myPath(sent.ID), "", sessionTarget, "") + opened := decodeCandidateInvitationHTTP(t, read, http.StatusOK) + requireNoCandidateData("candidate read", read.Body.String()) + if opened.State != "delivered" || opened.Version != sent.Version || opened.ViewedAt != nil || opened.Organization.ID != orgA || + opened.Organization.Name != nameA || opened.ResponseDeadlineAt != *sent.ResponseDeadlineAt || opened.Decline != nil || + string(opened.ContactConsent) != "null" || string(opened.ContactGrant) != "null" || len(opened.Terms) == 0 { + t.Fatalf("read = %+v, want the delivered invitation with its terms and no side effect", opened) + } + // A read records nothing: it is free of side effects by contract. + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts.viewedEvents != 0 { + t.Fatalf("a read stored %+v", counts) + } + + harness.clock.Advance(time.Hour) + response := request(http.MethodPost, myPath(sent.ID)+"/view", "", sessionTarget, "") + viewed := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + requireNoCandidateData("view response", response.Body.String()) + if viewed.State != "viewed" || viewed.Version != sent.Version+1 || viewed.TermsVersion != sent.TermsVersion || viewed.ViewedAt == nil || + viewed.ResponseDeadlineAt != opened.ResponseDeadlineAt || viewed.DeliveredAt != opened.DeliveredAt { + t.Fatalf("viewed = %+v, want viewed with the same deadline %s", viewed, opened.ResponseDeadlineAt) + } + var storedDeadline, storedDelivered time.Time + if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at, delivered_at FROM invitations WHERE id = $1`, sent.ID). + Scan(&storedDeadline, &storedDelivered); err != nil || !storedDeadline.Equal(storedDelivered.Add(7*24*time.Hour)) { + t.Fatalf("stored deadline = %s after %s, %v; want seven days after the delivery", storedDeadline, storedDelivered, err) + } + + // Repeats, concurrent ones included, change nothing and record one + // event. + harness.clock.Advance(time.Hour) + for _, repeat := range parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, myPath(sent.ID)+"/view", "", origin, sessionTarget, "", 3) { + again := decodeCandidateInvitationHTTP(t, repeat, http.StatusOK) + if again.Version != viewed.Version || *again.ViewedAt != *viewed.ViewedAt { + t.Fatalf("repeated view = %+v, want the first view", again) + } + } + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{viewedEvents: 1}) { + t.Fatalf("views stored %+v, want one view event", counts) + } + // The organization sees the state and the time of the view only. + organization := decodeInvitationHTTP(t, request(http.MethodGet, organizationPath(orgA, sent.ID), "", sessionA, ""), http.StatusOK) + if organization.State != "viewed" || organization.ViewedAt == nil || *organization.ViewedAt != *viewed.ViewedAt || + organization.ResponseDeadlineAt == nil || *organization.ResponseDeadlineAt != viewed.ResponseDeadlineAt { + t.Fatalf("organization reads %+v, want the view and the same deadline", organization) + } + // The inbox shows the view as well. + listed := request(http.MethodGet, "/api/v1/me/invitations", "", sessionTarget, "") + if listed.Code != http.StatusOK || !strings.Contains(listed.Body.String(), `"state":"viewed"`) { + t.Fatalf("inbox = %d %s, want the viewed invitation", listed.Code, listed.Body.String()) + } + }) + + t.Run("a decline with the reason other and no comment is an answer without a grant", func(t *testing.T) { + sent := deliver(orgA, sessionA, other, nil) + harness.clock.Advance(time.Minute) + key := nextKey() + response := decline(sessionOther, sent.ID, declineBody(sent.Version, "other", nil), key) + declined := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + requireNoCandidateData("decline response", response.Body.String()) + if declined.State != "declined" || declined.Version != sent.Version+1 || declined.RespondedAt == nil || declined.Decline == nil || + declined.Decline.Reason != "other" || declined.Decline.Comment != nil || declined.Decline.DeclinedAt != *declined.RespondedAt || + string(declined.ContactConsent) != "null" || string(declined.ContactGrant) != "null" || + declined.ResponseDeadlineAt != *sent.ResponseDeadlineAt { + t.Fatalf("declined = %+v, want declined with the reason other, no comment, and no grant", declined) + } + counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID) + if counts != (invitationAnswerCounts{declinedEvents: 1, declines: 1}) { + t.Fatalf("decline stored %+v, want one decline event, one decline, and no C4 consent", counts) + } + // The stored answer event is the response that the responsiveness + // metrics count: in time, by the candidate, without a reason. + var actor uuid.UUID + var occurred, deadline time.Time + var fields int + if err := harness.pool.QueryRow(ctx, ` + SELECT event.actor_id, event.occurred_at, invitation.response_deadline_at, cardinality(event.changed_fields) + FROM invitation_events AS event JOIN invitations AS invitation ON invitation.id = event.invitation_id + WHERE event.invitation_id = $1 AND event.kind = 'declined'`, sent.ID).Scan(&actor, &occurred, &deadline, &fields); err != nil { + t.Fatalf("read the decline event: %v", err) + } + if actor != other.ID || !occurred.Before(deadline) || fields != 0 { + t.Fatalf("decline event by the candidate %v at %s before %s with %d fields", actor == other.ID, occurred, deadline, fields) + } + + // Repeats: the same key replays the original, and the same decline + // with a new key and the older version answers 200 without a second + // event. Another reason or a reused key with another body does not. + original := response.Body.String() + harness.clock.Advance(time.Hour) + if replay := decline(sessionOther, sent.ID, declineBody(sent.Version, "other", nil), key); replay.Code != http.StatusOK || replay.Body.String() != original { + t.Fatalf("replay = %d %s, want the original 200", replay.Code, replay.Body.String()) + } + if again := decline(sessionOther, sent.ID, declineBody(sent.Version, "other", nil), nextKey()); again.Code != http.StatusOK || again.Body.String() != original { + t.Fatalf("the same decline with a new key = %d %s, want the original answer", again.Code, again.Body.String()) + } + requireSessionProblem(t, decline(sessionOther, sent.ID, declineBody(declined.Version, "salary", nil), nextKey()), http.StatusConflict, "state_conflict") + requireSessionProblem(t, decline(sessionOther, sent.ID, declineBody(sent.Version, "stack", nil), key), http.StatusUnprocessableEntity, "idempotency_key_reused") + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID); counts != (invitationAnswerCounts{declinedEvents: 1, declines: 1}) { + t.Fatalf("repeats stored %+v, want the first decline only", counts) + } + // A view of a declined invitation changes nothing. + if viewed := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", sessionOther, ""), http.StatusOK); viewed.State != "declined" || viewed.Version != declined.Version { + t.Fatalf("view of a declined invitation = %+v", viewed) + } + + // The organization sees the state and the time of the answer only. + organizationRead := request(http.MethodGet, organizationPath(orgA, sent.ID), "", sessionA, "") + organization := decodeInvitationHTTP(t, organizationRead, http.StatusOK) + requireNoDeclineDetails("organization read", organizationRead.Body.String()) + listed := request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations", orgA), "", sessionA, "") + requireNoDeclineDetails("organization list", listed.Body.String()) + if organization.State != "declined" || organization.RespondedAt == nil || *organization.RespondedAt != *declined.RespondedAt || + organization.ContactAccess.Status != "not_granted" { + t.Fatalf("organization reads %+v, want declined with the time of the answer and no access", organization) + } + }) + + t.Run("a decline from viewed keeps the comment for the candidate only", func(t *testing.T) { + sent := deliver(orgA, sessionA, target, nil) + viewed := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", sessionTarget, ""), http.StatusOK) + comment := invitationDeclineComment + key := nextKey() + // Concurrent requests with one key answer once. + responses := parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, myPath(sent.ID)+"/decline", + declineBody(viewed.Version, "salary", &comment), origin, sessionTarget, key, 2) + if responses[0].Code != http.StatusOK || responses[0].Body.String() != responses[1].Body.String() { + t.Fatalf("concurrent declines = %d %s and %d %s, want one identical 200", + responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) + } + declined := decodeCandidateInvitationHTTP(t, responses[0], http.StatusOK) + if declined.State != "declined" || declined.Decline == nil || declined.Decline.Reason != "salary" || + declined.Decline.Comment == nil || *declined.Decline.Comment != comment { + t.Fatalf("declined = %+v, want the reason and the comment read back", declined) + } + reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", sessionTarget, ""), http.StatusOK) + if reread.Decline == nil || reread.Decline.Comment == nil || *reread.Decline.Comment != comment || reread.Version != declined.Version { + t.Fatalf("reread = %+v, want the stored decline", reread) + } + organizationRead := request(http.MethodGet, organizationPath(orgA, sent.ID), "", sessionA, "") + requireNoDeclineDetails("organization read", organizationRead.Body.String()) + var events string + if err := harness.pool.QueryRow(ctx, `SELECT string_agg(row_to_json(invitation_events)::text, ' ') FROM invitation_events WHERE invitation_id = $1`, sent.ID).Scan(&events); err != nil { + t.Fatalf("read the audit events: %v", err) + } + if strings.Contains(events, comment) || strings.Contains(events, "salary") { + t.Fatalf("audit events hold the decline details: %s", events) + } + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{viewedEvents: 1, declinedEvents: 1, declines: 1}) { + t.Fatalf("decline from viewed stored %+v", counts) + } + // The comment rules of the contract and an unstorable value. + fresh := deliver(orgA, sessionA, target, nil) + tooLong := strings.Repeat("я", 501) + for name, body := range map[string]string{ + "white space": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":" "}`, + "unicode spaces": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":"  "}`, + "NUL": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":"a\u0000b"}`, + "too long": declineBody(fresh.Version, "other", &tooLong), + } { + response := decline(sessionTarget, fresh.ID, body, nextKey()) + if response.Code != http.StatusBadRequest { + t.Errorf("%s: decline = %d %s, want 400", name, response.Code, response.Body.String()) + } + } + requireInvitationValidation(t, decline(sessionTarget, fresh.ID, `{"expected_version":1,"reason":"rude"}`, nextKey()), "/reason", "") + requireInvitationValidation(t, decline(sessionTarget, fresh.ID, `{"expected_version":1,"reason":"other","state":"declined"}`, nextKey()), "", "") + requireInvitationValidation(t, decline(sessionTarget, fresh.ID, declineBody(fresh.Version, "other", nil), ""), "/Idempotency-Key", "") + if counts := readInvitationAnswerCounts(ctx, t, harness, fresh.ID, target.ID); counts.declines != 0 { + t.Fatalf("an invalid decline stored %+v", counts) + } + }) + + t.Run("another candidate and an employer learn nothing of the invitation", func(t *testing.T) { + sent := deliver(orgA, sessionA, target, nil) + draft := draftFor(orgA, sessionA, target, nil) + for name, invitationID := range map[string]uuid.UUID{"another candidate's": sent.ID, "unknown": uuid.New()} { + for _, response := range []*httptest.ResponseRecorder{ + request(http.MethodGet, myPath(invitationID), "", sessionOther, ""), + request(http.MethodPost, myPath(invitationID)+"/view", "", sessionOther, ""), + decline(sessionOther, invitationID, declineBody(sent.Version, "other", nil), nextKey()), + } { + requireSessionProblem(t, response, http.StatusNotFound, "not_found") + if strings.Contains(response.Body.String(), "role_title") || strings.Contains(response.Body.String(), nameA) { + t.Errorf("%s invitation: the refusal shows the terms: %s", name, response.Body.String()) + } + } + } + // A draft is not in the candidate's inbox, even for its candidate. + requireSessionProblem(t, request(http.MethodGet, myPath(draft.ID), "", sessionTarget, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodPost, myPath(draft.ID)+"/view", "", sessionTarget, ""), http.StatusNotFound, "not_found") + // The sending organization and another one have no candidate inbox. + for _, session := range []organizationHTTPSession{sessionA, sessionB} { + requireSessionProblem(t, request(http.MethodGet, myPath(sent.ID), "", session, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", session, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, decline(session, sent.ID, declineBody(sent.Version, "other", nil), nextKey()), http.StatusForbidden, "forbidden") + } + // Unsafe commands need the session's CSRF token and the exact Origin. + withoutToken := organizationHTTPSession{cookie: sessionTarget.cookie} + requireSessionProblem(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", withoutToken, ""), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, decline(withoutToken, sent.ID, declineBody(sent.Version, "other", nil), nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, myPath(sent.ID)+"/decline", + declineBody(sent.Version, "other", nil), "https://attacker.example", sessionTarget, nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, request(http.MethodGet, myPath(sent.ID), "", organizationHTTPSession{}, ""), http.StatusUnauthorized, "unauthenticated") + requireInvitationValidation(t, request(http.MethodGet, "/api/v1/me/invitations/1", "", sessionTarget, ""), "/invitation_id", "") + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{}) { + t.Fatalf("refused callers stored %+v", counts) + } + // The candidate's own list never names another candidate's invitation. + listed := request(http.MethodGet, "/api/v1/me/invitations?limit=100", "", sessionOther, "") + if listed.Code != http.StatusOK || strings.Contains(listed.Body.String(), sent.ID.String()) || strings.Contains(listed.Body.String(), draft.ID.String()) { + t.Fatalf("another candidate's list = %d %s", listed.Code, listed.Body.String()) + } + }) + + t.Run("the hiding of the organization does not hide it from the candidate", func(t *testing.T) { + sent := deliver(orgB, sessionB, hider, nil) + privacy.hide(t, hider.ID, orgB, harness.clock.Now()) + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", sessionHider, ""), http.StatusOK) + if read.Organization.ID != orgB || read.Organization.Name == "" { + t.Fatalf("read after the hiding = %+v, want the sending organization", read.Organization) + } + declined := decodeCandidateInvitationHTTP(t, decline(sessionHider, sent.ID, declineBody(sent.Version, "company", nil), nextKey()), http.StatusOK) + if declined.State != "declined" { + t.Fatalf("decline after the hiding = %+v", declined) + } + }) + + t.Run("a stale version is not stored and a late decline is refused whatever the version", func(t *testing.T) { + sent := deliver(orgA, sessionA, other, func(body, terms map[string]any) { body["response_period_days"] = 3 }) + key := nextKey() + requireSessionProblem(t, decline(sessionOther, sent.ID, declineBody(sent.Version+1, "tasks", nil), key), http.StatusPreconditionFailed, "version_conflict") + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID); counts.declines != 0 { + t.Fatalf("a stale decline stored %+v", counts) + } + var stored int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitation_decline_results WHERE invitation_id = $1`, sent.ID).Scan(&stored); err != nil || stored != 0 { + t.Fatalf("stale outcomes = %d, %v; want none", stored, err) + } + + // At the deadline the view changes nothing and the decline is late: + // 409 even with a stale version, stored under its key. + // The response shows whole seconds, so the exact stored deadline is + // read from the database. + var exactDeadline time.Time + if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, sent.ID).Scan(&exactDeadline); err != nil { + t.Fatalf("read the deadline: %v", err) + } + harness.clock.Set(exactDeadline.UTC()) + lateSession := login(other) + late := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", lateSession, ""), http.StatusOK) + if late.State != "delivered" || late.Version != sent.Version || late.ViewedAt != nil { + t.Fatalf("late view = %+v, want the invitation unchanged", late) + } + lateKey := nextKey() + for range 2 { + requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(sent.Version+3, "tasks", nil), lateKey), http.StatusConflict, "state_conflict") + } + requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(sent.Version, "tasks", nil), key), http.StatusConflict, "state_conflict") + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID); counts != (invitationAnswerCounts{}) { + t.Fatalf("late commands stored %+v", counts) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitation_decline_results WHERE invitation_id = $1 AND outcome = 'state_conflict'`, sent.ID).Scan(&stored); err != nil || stored != 2 { + t.Fatalf("stored late refusals = %d, %v; want one per key", stored, err) + } + }) + + t.Run("keeps the decline comment and candidate values out of logs", func(t *testing.T) { + requireNoCandidateData("server log", harness.logs.String()) + if strings.Contains(harness.logs.String(), invitationDeclineComment) { + t.Fatal("the server log holds the decline comment") + } + }) +} + +func TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback(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, invitationAnswerMigrationVersion) + + store := func(t *testing.T, work func(context.Context, outbound.UnitOfWork) error) error { + t.Helper() + return fixture.transactor.WithinTransaction(ctx, work) + } + deliverDraft := func(t *testing.T) domain.Invitation { + t.Helper() + draft := fixture.draft(t) + delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + event, err := delivered.DeliveryEvent(fixture.owner.ID) + if err != nil { + t.Fatalf("DeliveryEvent() error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) + }); err != nil { + t.Fatalf("Deliver() through the repository error = %v", err) + } + return delivered + } + + delivered := deliverDraft(t) + viewed, _, err := delivered.RecordView(delivered.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("RecordView() error = %v", err) + } + viewEvent, err := viewed.AnswerEvent(fixture.candidate.ID) + if err != nil { + t.Fatalf("AnswerEvent() error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().RecordView(ctx, delivered.Version(), viewed, viewEvent) + }); err != nil { + t.Fatalf("RecordView() through the repository error = %v", err) + } + // A second view of the same version loses the race. + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().RecordView(ctx, delivered.Version(), viewed, viewEvent) + }); !errors.Is(err, outbound.ErrInvitationVersionConflict) { + t.Fatalf("second RecordView() error = %v, want ErrInvitationVersionConflict", err) + } + comment := "Synthetic decline comment" + declined, declineRecord, err := viewed.Decline(domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther, Comment: &comment}, viewed.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("Decline() error = %v", err) + } + declineEvent, err := declined.AnswerEvent(fixture.candidate.ID) + if err != nil { + t.Fatalf("AnswerEvent() error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Decline(ctx, viewed.Version(), declined, declineRecord, declineEvent) + }); err != nil { + t.Fatalf("Decline() through the repository error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + read, err := unit.Invitations().GetDecline(ctx, declined.OrganizationID(), declined.ID()) + if err == nil && (!read.Choice.Equal(declineRecord.Choice) || !read.DeclinedAt.Equal(declineRecord.DeclinedAt)) { + return fmt.Errorf("stored decline differs: %v", read.Choice.Reason) + } + return err + }); err != nil { + t.Fatalf("GetDecline() error = %v", err) + } + + // The database guards the answers against other writers. + _, err = pool.Exec(ctx, `UPDATE invitations SET viewed_at = viewed_at + interval '1 second', version = version + 1 WHERE id = $1`, declined.ID()) + assertPgError(t, "move the view", err, privacyIntegrityViolation, "invitations_answer_immutable") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'viewed', responded_at = NULL, version = version + 1 WHERE id = $1`, declined.ID()) + assertPgError(t, "leave the decline", err, privacyIntegrityViolation, "invitations_answer_immutable") + _, err = pool.Exec(ctx, `UPDATE invitation_declines SET reason = 'salary' WHERE invitation_id = $1`, declined.ID()) + assertPgError(t, "change the decline", err, privacyIntegrityViolation, "invitation_declines_immutable") + _, err = pool.Exec(ctx, `DELETE FROM invitation_declines WHERE invitation_id = $1`, declined.ID()) + assertPgError(t, "delete the decline", err, privacyIntegrityViolation, "invitation_declines_immutable") + other := deliverDraft(t) + _, err = pool.Exec(ctx, `INSERT INTO invitation_declines (invitation_id, organization_id, reason, declined_at) VALUES ($1, $2, 'other', now())`, + other.ID(), other.OrganizationID()) + assertPgError(t, "decline row of an undeclined invitation", err, privacyIntegrityViolation, "invitation_declines_match_invitation") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'declined', responded_at = delivered_at + interval '1 minute', updated_at = delivered_at + interval '1 minute', version = version + 1 WHERE id = $1`, other.ID()) + assertPgError(t, "decline without its record", err, privacyIntegrityViolation, "invitations_decline_recorded") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'viewed', version = version + 1 WHERE id = $1`, other.ID()) + assertPgError(t, "viewed without a view", err, privacyCheckViolation, "invitations_answer_matches_state") + _, err = pool.Exec(ctx, `INSERT INTO invitation_events (id, invitation_id, organization_id, version, terms_version, kind, actor_id, changed_fields, occurred_at) + SELECT $1, id, organization_id, version + 1, terms_version, 'viewed', created_by, ARRAY['terms'], now() FROM invitations WHERE id = $2`, uuid.New(), other.ID()) + assertPgError(t, "view event with a field", err, privacyCheckViolation, "invitation_events_answer_changes_no_field") + + _, err = migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a declined invitation", err, privacyIntegrityViolation, invitationAnswersRetained) + if _, err := pool.Exec(ctx, `TRUNCATE invitation_decline_results, invitation_declines, 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 != invitationAnswerMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationAnswerMigrationVersion) + } + var remaining int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name IN ('invitation_declines', 'invitation_decline_results')`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("answer tables left after the rollback: %d, %v", remaining, err) + } + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } +} diff --git a/backend/integration_test/organizations_test.go b/backend/integration_test/organizations_test.go index ac83397..e5deefe 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -40,7 +40,7 @@ var ( // users and organizations. Creation snapshots reference idempotency records. organizationTables = []pgx.Identifier{ {"candidate_card_access_events"}, - {"invitation_creation_results"}, {"invitation_send_results"}, + {"invitation_creation_results"}, {"invitation_send_results"}, {"invitation_decline_results"}, {"invitation_declines"}, {"invitation_events"}, {"invitation_terms_versions"}, {"invitations"}, {"organization_need_versions"}, {"organization_needs"}, {"organization_need_creation_results"}, diff --git a/backend/integration_test/policy_test.go b/backend/integration_test/policy_test.go index 62be8f6..278c772 100644 --- a/backend/integration_test/policy_test.go +++ b/backend/integration_test/policy_test.go @@ -252,7 +252,7 @@ func TestPolicyVersions(t *testing.T) { assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks, assessment_synthetic_category_reviews, candidate_assessment_categories, skill_evidence_facts, skill_evidence_skills, - invitations, invitation_terms_versions, invitation_events`}, + invitations, invitation_terms_versions, invitation_events, invitation_declines`}, } for _, statement := range statements { _, err := fixture.pool.Exec(ctx, statement.sql, statement.args...) diff --git a/backend/internal/adapter/primary/http/v1/invitation.go b/backend/internal/adapter/primary/http/v1/invitation.go index a4f3e9f..ce04b3e 100644 --- a/backend/internal/adapter/primary/http/v1/invitation.go +++ b/backend/internal/adapter/primary/http/v1/invitation.go @@ -19,7 +19,7 @@ import ( const defaultInvitationLimit = 20 // InvitationOperations are the owner-scoped invitation reads and commands and -// the candidate's read of the own inbox served by HTTP. +// the candidate's inbox, read, view, and decline 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) @@ -27,6 +27,9 @@ type InvitationOperations interface { 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) + GetMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) + ViewMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) + DeclineMine(ctx context.Context, command invitationusecase.DeclineCommand) (domain.CandidateInvitationView, error) } // InvitationHandler serves the organization side of invitation drafts and diff --git a/backend/internal/adapter/primary/http/v1/invitation_candidate.go b/backend/internal/adapter/primary/http/v1/invitation_candidate.go new file mode 100644 index 0000000..6664075 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/invitation_candidate.go @@ -0,0 +1,156 @@ +package v1 + +import ( + "context" + "errors" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + "lincodex/backend/internal/domain" + invitationusecase "lincodex/backend/internal/usecase/invitation" +) + +func (handler *Handler) GetMyInvitation(ctx context.Context, params api.GetMyInvitationParams) (api.GetMyInvitationRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.GetMyInvitation(ctx, params) + } + return handler.invitation.GetMyInvitation(ctx, params) +} + +func (handler *Handler) ViewMyInvitation(ctx context.Context, params api.ViewMyInvitationParams) (api.ViewMyInvitationRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.ViewMyInvitation(ctx, params) + } + return handler.invitation.ViewMyInvitation(ctx, params) +} + +func (handler *Handler) DeclineMyInvitation(ctx context.Context, request *api.InvitationDeclineRequest, params api.DeclineMyInvitationParams) (api.DeclineMyInvitationRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.DeclineMyInvitation(ctx, request, params) + } + return handler.invitation.DeclineMyInvitation(ctx, request, params) +} + +func (handler *InvitationHandler) GetMyInvitation(ctx context.Context, params api.GetMyInvitationParams) (api.GetMyInvitationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.GetMyInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + view, err := handler.operations.GetMine(ctx, principal.UserID, params.InvitationID) + if err != nil { + switch classifyInvitationError(err) { + case invitationFailureForbidden: + return (*api.GetMyInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case invitationFailureNotFound: + return (*api.GetMyInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureInvalid, + invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther: + return nil, err + } + return nil, err + } + return &api.CandidateInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: candidateInvitationResponse(view)}, nil +} + +func (handler *InvitationHandler) ViewMyInvitation(ctx context.Context, params api.ViewMyInvitationParams) (api.ViewMyInvitationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.ViewMyInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + view, err := handler.operations.ViewMine(ctx, principal.UserID, params.InvitationID) + if err != nil { + switch classifyInvitationError(err) { + case invitationFailureForbidden: + return (*api.ViewMyInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case invitationFailureNotFound: + return (*api.ViewMyInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureInvalid, + invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther: + return nil, err + } + return nil, err + } + return &api.CandidateInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: candidateInvitationResponse(view)}, nil +} + +func (handler *InvitationHandler) DeclineMyInvitation( + ctx context.Context, + request *api.InvitationDeclineRequest, + params api.DeclineMyInvitationParams, +) (api.DeclineMyInvitationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.DeclineMyInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if request == nil { + return (*api.DeclineMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil + } + choice := domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineReason(request.Reason)} + if comment, set := request.Comment.Get(); set { + text := string(comment) + choice.Comment = &text + } + view, err := handler.operations.DeclineMine(ctx, invitationusecase.DeclineCommand{ + ActorID: principal.UserID, InvitationID: params.InvitationID, IdempotencyKey: params.IdempotencyKey, + ExpectedVersion: int64(request.ExpectedVersion), Choice: choice, + }) + if err != nil { + return invitationDeclineFailure(ctx, err) + } + return &api.CandidateInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: candidateInvitationResponse(view)}, nil +} + +func invitationDeclineFailure(ctx context.Context, err error) (api.DeclineMyInvitationRes, error) { + if errors.Is(err, invitationusecase.ErrAnswerBlocked) { + return (*api.DeclineMyInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil + } + switch classifyInvitationError(err) { + case invitationFailureForbidden: + return (*api.DeclineMyInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case invitationFailureNotFound: + return (*api.DeclineMyInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case invitationFailureKeyReused: + return (*api.DeclineMyInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil + case invitationFailureBadKey: + return (*api.DeclineMyInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil + case invitationFailureInvalid: + return (*api.DeclineMyInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil + case invitationFailureVersionConflict: + return (*api.DeclineMyInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil + case invitationFailureStateConflict, invitationFailureOther: + return nil, err + } + return nil, err +} + +// candidateInvitationResponse maps the candidate's view. The consent offer +// and the contact grant belong to the acceptance, which is not served yet, +// so an acceptance is impossible now and both are null, as the contract +// requires when no acceptance can be made. +func candidateInvitationResponse(view domain.CandidateInvitationView) api.CandidateInvitation { + response := api.CandidateInvitation{ + ID: view.ID, + Organization: api.InvitationOrganization{ID: view.Organization.ID, Name: view.Organization.Name}, + State: api.InvitationState(view.State), ExpiryReason: invitationExpiryResponse(view.ExpiryReason), + Version: api.InvitationVersion(view.Version), TermsVersion: api.InvitationTermsVersion(view.TermsVersion), + Terms: invitationTermsResponse(view.Terms), ResponseDeadlineAt: api.Timestamp(view.ResponseDeadlineAt), + DeliveredAt: api.Timestamp(view.DeliveredAt), ViewedAt: nullableTimestamp(view.ViewedAt), + RespondedAt: nullableTimestamp(view.RespondedAt), UpdatedAt: api.Timestamp(view.UpdatedAt), + } + response.ContactConsent.SetToNull() + response.ContactGrant.SetToNull() + if view.Decline == nil { + response.Decline.SetToNull() + return response + } + record := api.InvitationDeclineRecord{ + Reason: api.InvitationDeclineReason(view.Decline.Reason), DeclinedAt: api.Timestamp(view.Decline.DeclinedAt), + } + if view.Decline.Comment == nil { + record.Comment.SetToNull() + } else { + record.Comment.SetTo(api.InvitationDeclineComment(*view.Decline.Comment)) + } + response.Decline.SetTo(record) + return response +} diff --git a/backend/internal/adapter/primary/http/v1/invitation_candidate_test.go b/backend/internal/adapter/primary/http/v1/invitation_candidate_test.go new file mode 100644 index 0000000..9a08d83 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/invitation_candidate_test.go @@ -0,0 +1,96 @@ +package v1 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + invitationusecase "lincodex/backend/internal/usecase/invitation" +) + +func TestInvitationDeclineFailuresMapToTheContractStatuses(t *testing.T) { + ctx := context.Background() + field := &domain.InvitationFieldError{Pointer: "/comment", Reason: "x"} + for name, test := range map[string]struct { + err error + want string + }{ + "employer": {invitationusecase.ErrForbidden, "*api.DeclineMyInvitationForbidden"}, + "unknown": {fmt.Errorf("wrapped: %w", outbound.ErrInvitationNotFound), "*api.DeclineMyInvitationNotFound"}, + "reused key": {invitationusecase.ErrIdempotencyKeyReused, "*api.DeclineMyInvitationUnprocessableEntity"}, + "bad key": {invitationusecase.ErrInvalidIdempotencyKey, "*api.DeclineMyInvitationBadRequest"}, + "comment": {fmt.Errorf("wrapped: %w", field), "*api.DeclineMyInvitationBadRequest"}, + "stale version": {domain.ErrInvitationVersionConflict, "*api.DeclineMyInvitationPreconditionFailed"}, + "terminal or late": {fmt.Errorf("wrapped: %w", invitationusecase.ErrAnswerBlocked), "*api.DeclineMyInvitationConflict"}, + } { + response, unexpected := invitationDeclineFailure(ctx, test.err) + if unexpected != nil || fmt.Sprintf("%T", response) != test.want { + t.Errorf("%s: failure = %T, %v; want %s", name, response, unexpected, test.want) + } + } + if _, unexpected := invitationDeclineFailure(ctx, errors.New("storage failed")); unexpected == nil { + t.Error("an unknown failure produced a public response instead of reaching the responder") + } +} + +// The candidate's response carries the own decline and nothing of the +// candidate: no identifier, handle, salary indicator, need, or contact. The +// consent offer and the grant are null until an acceptance exists. +func TestCandidateInvitationResponseCarriesTheDeclineAndNoCandidateData(t *testing.T) { + candidateID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + policyID, err := domain.NewPolicyVersionID() + if err != nil { + t.Fatalf("NewPolicyVersionID() error = %v", err) + } + now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC) + draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{ + ID: uuid.Must(uuid.NewV7()), OrganizationID: organizationID, CandidateID: candidateID, ActorID: uuid.Must(uuid.NewV7()), + PolicyVersionID: policyID, At: now, + Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationTermsFromRequest(invitationTestTerms())}, + }) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + delivered, err := draft.Deliver(now) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + declined, decline, err := delivered.Decline(domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther}, now.Add(time.Hour)) + if err != nil { + t.Fatalf("Decline() error = %v", err) + } + view, err := declined.CandidateView(domain.InvitationOrganizationRef{ID: organizationID, Name: "Acme"}, &decline) + if err != nil { + t.Fatalf("CandidateView() error = %v", err) + } + encoded, err := json.Marshal(candidateInvitationResponse(view)) + if err != nil { + t.Fatalf("marshal response: %v", err) + } + text := string(encoded) + if strings.Contains(text, candidateID.String()) { + t.Errorf("response carries the candidate identifier: %s", text) + } + for _, key := range []string{"candidate_handle", "candidate_id", "salary_fit", "need", "email", "phone", "telegram", "full_name"} { + if strings.Contains(text, `"`+key+`":`) { + t.Errorf("response carries %s: %s", key, text) + } + } + for _, want := range []string{ + `"state":"declined"`, `"decline":{"reason":"other","comment":null,"declined_at":"2026-10-09T11:00:00Z"}`, + `"contact_consent":null`, `"contact_grant":null`, `"organization":{"id":"` + organizationID.String() + `","name":"Acme"}`, + `"response_deadline_at":"2026-10-16T10:00:00Z"`, + } { + if !strings.Contains(text, want) { + t.Errorf("response lacks %s: %s", want, text) + } + } +} diff --git a/backend/internal/adapter/secondary/postgres/invitation_answer.go b/backend/internal/adapter/secondary/postgres/invitation_answer.go new file mode 100644 index 0000000..3f138f2 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/invitation_answer.go @@ -0,0 +1,244 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var _ outbound.InvitationDeclineResultRepository = invitationRepository{} + +func (unit *UnitOfWork) InvitationDeclineResults() outbound.InvitationDeclineResultRepository { + return invitationRepository{queries: unit.queries} +} + +func (repository invitationRepository) GetCandidateEntry( + ctx context.Context, + candidateID, invitationID uuid.UUID, +) (outbound.CandidateInvitationEntry, error) { + const location = "invitationRepository.GetCandidateEntry" + if candidateID == uuid.Nil || invitationID == uuid.Nil { + return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - candidate and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation) + } + row, err := repository.queries.ReadCandidateInvitationEntry(ctx, sqlc.ReadCandidateInvitationEntryParams{ + CandidateID: pgUUID(candidateID), InvitationID: pgUUID(invitationID), + }) + if err != nil { + return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err)) + } + return restoreCandidateInvitationRow(location, sqlc.ListCandidateInvitationsRow(row), candidateID) +} + +func (repository invitationRepository) GetCandidateEntryForUpdate( + ctx context.Context, + candidateID, invitationID uuid.UUID, +) (outbound.CandidateInvitationEntry, error) { + const location = "invitationRepository.GetCandidateEntryForUpdate" + if candidateID == uuid.Nil || invitationID == uuid.Nil { + return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - candidate and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation) + } + // The row is locked by a statement of its own and read afterwards, as + // for the organization side: a locking read joined to the terms would, + // after waiting for a concurrent commit, pair the new terms version with + // the terms row it fetched before the wait. + if _, err := repository.queries.LockCandidateInvitation(ctx, sqlc.LockCandidateInvitationParams{ + CandidateID: pgUUID(candidateID), InvitationID: pgUUID(invitationID), + }); err != nil { + return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - lock invitation: %w", location, mapInvitationNoRows(err)) + } + entry, err := repository.GetCandidateEntry(ctx, candidateID, invitationID) + if err != nil { + return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - read locked invitation: %w", location, err) + } + return entry, nil +} + +func (repository invitationRepository) RecordView( + ctx context.Context, + expectedVersion int64, + next domain.Invitation, + event domain.InvitationEvent, +) error { + const location = "invitationRepository.RecordView" + stored := next.Stored() + if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationViewed) || + stored.ViewedAt == nil || event.Kind != domain.InvitationEventViewed { + return fmt.Errorf("%s - the next version must be the view 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.RecordInvitationView(ctx, sqlc.RecordInvitationViewParams{ + NextVersion: stored.Version, ViewedAt: pgTime(*stored.ViewedAt), OrganizationID: pgUUID(stored.OrganizationID), + InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, + }) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - record view: %w", location, outbound.ErrInvitationVersionConflict) + } + if err != nil { + return fmt.Errorf("%s - record view: %w", location, mapInvitationError(err)) + } + return repository.insertEvent(ctx, location, event) +} + +func (repository invitationRepository) Decline( + ctx context.Context, + expectedVersion int64, + next domain.Invitation, + decline domain.InvitationDecline, + event domain.InvitationEvent, +) error { + const location = "invitationRepository.Decline" + stored := next.Stored() + if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationDeclined) || + stored.RespondedAt == nil || event.Kind != domain.InvitationEventDeclined { + return fmt.Errorf("%s - the next version must be the decline that follows the expected one: %w", location, domain.ErrInvalidInvitation) + } + if err := decline.Validate(); err != nil { + return fmt.Errorf("%s - validate decline: %w", location, err) + } + if decline.InvitationID != stored.ID || decline.OrganizationID != stored.OrganizationID || !decline.DeclinedAt.Equal(*stored.RespondedAt) { + return fmt.Errorf("%s - the decline must describe the declined version: %w", location, domain.ErrInvalidInvitation) + } + if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil { + return err + } + _, err := repository.queries.DeclineInvitation(ctx, sqlc.DeclineInvitationParams{ + NextVersion: stored.Version, DeclinedAt: pgTime(*stored.RespondedAt), OrganizationID: pgUUID(stored.OrganizationID), + InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, + }) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - decline invitation: %w", location, outbound.ErrInvitationVersionConflict) + } + if err != nil { + return fmt.Errorf("%s - decline invitation: %w", location, mapInvitationError(err)) + } + comment := pgtype.Text{} + if decline.Choice.Comment != nil { + comment = pgtype.Text{String: *decline.Choice.Comment, Valid: true} + } + if err := repository.queries.InsertInvitationDecline(ctx, sqlc.InsertInvitationDeclineParams{ + InvitationID: pgUUID(decline.InvitationID), OrganizationID: pgUUID(decline.OrganizationID), + Reason: string(decline.Choice.Reason), Comment: comment, DeclinedAt: pgTime(decline.DeclinedAt), + }); err != nil { + return fmt.Errorf("%s - store decline: %w", location, mapInvitationError(err)) + } + return repository.insertEvent(ctx, location, event) +} + +func (repository invitationRepository) GetDecline( + ctx context.Context, + organizationID, invitationID uuid.UUID, +) (domain.InvitationDecline, error) { + const location = "invitationRepository.GetDecline" + if organizationID == uuid.Nil || invitationID == uuid.Nil { + return domain.InvitationDecline{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation) + } + row, err := repository.queries.ReadInvitationDecline(ctx, sqlc.ReadInvitationDeclineParams{ + OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.InvitationDecline{}, fmt.Errorf("%s - read decline: %w", location, outbound.ErrInvitationDeclineNotFound) + } + if err != nil { + return domain.InvitationDecline{}, fmt.Errorf("%s - read decline: %w", location, mapInvitationError(err)) + } + if !row.InvitationID.Valid || !row.OrganizationID.Valid || !row.DeclinedAt.Valid { + return domain.InvitationDecline{}, fmt.Errorf("%s - stored decline has no scope: %w", location, domain.ErrInvalidInvitation) + } + decline := domain.InvitationDecline{ + InvitationID: uuid.UUID(row.InvitationID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes), + Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineReason(row.Reason)}, + DeclinedAt: row.DeclinedAt.Time.UTC(), + } + if row.Comment.Valid { + comment := row.Comment.String + decline.Choice.Comment = &comment + } + if decline.InvitationID != invitationID || decline.OrganizationID != organizationID { + return domain.InvitationDecline{}, fmt.Errorf("%s - stored decline has another scope: %w", location, domain.ErrInvalidInvitation) + } + if err := decline.Validate(); err != nil { + return domain.InvitationDecline{}, fmt.Errorf("%s - validate stored decline: %w", location, err) + } + return decline, nil +} + +func (repository invitationRepository) SaveDeclineResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, + result outbound.InvitationDeclineResult, +) error { + const location = "invitationRepository.SaveDeclineResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) { + return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) + } + if err := validateInvitationDeclineResult(result); err != nil { + return fmt.Errorf("%s - validate outcome: %w", location, err) + } + if err := repository.queries.InsertInvitationDeclineResult(ctx, sqlc.InsertInvitationDeclineResultParams{ + ScopeHash: scope[:], InvitationID: pgUUID(result.InvitationID), Outcome: string(result.Outcome), + }); err != nil { + return fmt.Errorf("%s - store outcome: %w", location, mapInvitationDeclineResultError(err)) + } + return nil +} + +func (repository invitationRepository) GetDeclineResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, +) (outbound.InvitationDeclineResult, error) { + const location = "invitationRepository.GetDeclineResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) { + return outbound.InvitationDeclineResult{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) + } + row, err := repository.queries.GetInvitationDeclineResult(ctx, scope[:]) + if errors.Is(err, pgx.ErrNoRows) { + return outbound.InvitationDeclineResult{}, outbound.ErrInvitationDeclineResultNotFound + } + if err != nil { + return outbound.InvitationDeclineResult{}, fmt.Errorf("%s - read outcome: %w", location, mapInvitationError(err)) + } + if !row.InvitationID.Valid { + return outbound.InvitationDeclineResult{}, fmt.Errorf("%s - stored outcome has no invitation: %w", location, domain.ErrInvalidInvitation) + } + result := outbound.InvitationDeclineResult{ + InvitationID: uuid.UUID(row.InvitationID.Bytes), Outcome: outbound.InvitationDeclineOutcome(row.Outcome), + } + if err := validateInvitationDeclineResult(result); err != nil { + return outbound.InvitationDeclineResult{}, fmt.Errorf("%s - validate stored outcome: %w", location, err) + } + return result, nil +} + +func validateInvitationDeclineResult(result outbound.InvitationDeclineResult) error { + const location = "postgres.validateInvitationDeclineResult" + switch result.Outcome { + case outbound.InvitationDeclineDeclined: + if result.InvitationID == uuid.Nil { + return fmt.Errorf("%s - a declined outcome names the invitation: %w", location, domain.ErrInvalidInvitation) + } + case outbound.InvitationDeclineNotFound, outbound.InvitationDeclineStateConflict: + // A refusal names the identifier of the path, which may name nothing. + default: + return fmt.Errorf("%s - outcome is unknown: %w", location, domain.ErrInvalidInvitation) + } + return nil +} + +func mapInvitationDeclineResultError(err error) error { + var pgError *pgconn.PgError + if errors.As(err, &pgError) && pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_decline_results_idempotency_fkey" { + return fmt.Errorf("postgres.mapInvitationDeclineResultError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound) + } + return mapInvitationError(err) +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/invitation_answers.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/invitation_answers.sql.go new file mode 100644 index 0000000..352b9a7 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/invitation_answers.sql.go @@ -0,0 +1,322 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: invitation_answers.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const declineInvitation = `-- name: DeclineInvitation :one +UPDATE invitations +SET + state = 'declined', + version = $1, + responded_at = $2, + updated_at = $2 +WHERE + organization_id = $3 + AND id = $4 + AND state IN ('delivered', 'viewed', 'counter') + AND version = $5 + AND response_deadline_at > $2 + AND $1::bigint = $5::bigint + 1 +RETURNING id +` + +type DeclineInvitationParams struct { + NextVersion int64 + DeclinedAt pgtype.Timestamptz + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + ExpectedVersion int64 +} + +// The compare-and-swap of a decline: it applies only to an answerable +// invitation at the version the caller read and before its deadline. +func (q *Queries) DeclineInvitation(ctx context.Context, arg DeclineInvitationParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, declineInvitation, + arg.NextVersion, + arg.DeclinedAt, + arg.OrganizationID, + arg.InvitationID, + arg.ExpectedVersion, + ) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + +const getInvitationDeclineResult = `-- name: GetInvitationDeclineResult :one +SELECT + invitation_id, + outcome +FROM invitation_decline_results +WHERE scope_hash = $1 +` + +type GetInvitationDeclineResultRow struct { + InvitationID pgtype.UUID + Outcome string +} + +func (q *Queries) GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, error) { + row := q.db.QueryRow(ctx, getInvitationDeclineResult, scopeHash) + var i GetInvitationDeclineResultRow + err := row.Scan(&i.InvitationID, &i.Outcome) + return i, err +} + +const insertInvitationDecline = `-- name: InsertInvitationDecline :exec +INSERT INTO invitation_declines ( + invitation_id, + organization_id, + reason, + comment, + declined_at +) VALUES ( + $1, + $2, + $3, + $4, + $5 +) +` + +type InsertInvitationDeclineParams struct { + InvitationID pgtype.UUID + OrganizationID pgtype.UUID + Reason string + Comment pgtype.Text + DeclinedAt pgtype.Timestamptz +} + +func (q *Queries) InsertInvitationDecline(ctx context.Context, arg InsertInvitationDeclineParams) error { + _, err := q.db.Exec(ctx, insertInvitationDecline, + arg.InvitationID, + arg.OrganizationID, + arg.Reason, + arg.Comment, + arg.DeclinedAt, + ) + return err +} + +const insertInvitationDeclineResult = `-- name: InsertInvitationDeclineResult :exec +INSERT INTO invitation_decline_results ( + scope_hash, + invitation_id, + outcome +) VALUES ( + $1, + $2, + $3 +) +` + +type InsertInvitationDeclineResultParams struct { + ScopeHash []byte + InvitationID pgtype.UUID + Outcome string +} + +func (q *Queries) InsertInvitationDeclineResult(ctx context.Context, arg InsertInvitationDeclineResultParams) error { + _, err := q.db.Exec(ctx, insertInvitationDeclineResult, arg.ScopeHash, arg.InvitationID, arg.Outcome) + return err +} + +const lockCandidateInvitation = `-- name: LockCandidateInvitation :one +SELECT id +FROM invitations +WHERE + candidate_id = $1 + AND id = $2 + AND delivered_at IS NOT NULL +FOR UPDATE +` + +type LockCandidateInvitationParams struct { + CandidateID pgtype.UUID + InvitationID pgtype.UUID +} + +// Lock one delivered invitation addressed to the candidate. Only the +// invitation row is locked, never the organization. +func (q *Queries) LockCandidateInvitation(ctx context.Context, arg LockCandidateInvitationParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, lockCandidateInvitation, arg.CandidateID, arg.InvitationID) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + +const readCandidateInvitationEntry = `-- name: ReadCandidateInvitationEntry :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, + 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.id = $2 + AND invitation.delivered_at IS NOT NULL +` + +type ReadCandidateInvitationEntryParams struct { + CandidateID pgtype.UUID + InvitationID pgtype.UUID +} + +type ReadCandidateInvitationEntryRow 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 +} + +// Read one delivered invitation addressed to the candidate with the current +// name of the organization that sent it. A draft and an invitation of +// another candidate find nothing. +func (q *Queries) ReadCandidateInvitationEntry(ctx context.Context, arg ReadCandidateInvitationEntryParams) (ReadCandidateInvitationEntryRow, error) { + row := q.db.QueryRow(ctx, readCandidateInvitationEntry, arg.CandidateID, arg.InvitationID) + var i ReadCandidateInvitationEntryRow + 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, + &i.OrganizationName, + ) + return i, err +} + +const readInvitationDecline = `-- name: ReadInvitationDecline :one +SELECT + invitation_id, + organization_id, + reason, + comment, + declined_at +FROM invitation_declines +WHERE + organization_id = $1 + AND invitation_id = $2 +` + +type ReadInvitationDeclineParams struct { + OrganizationID pgtype.UUID + InvitationID pgtype.UUID +} + +func (q *Queries) ReadInvitationDecline(ctx context.Context, arg ReadInvitationDeclineParams) (InvitationDecline, error) { + row := q.db.QueryRow(ctx, readInvitationDecline, arg.OrganizationID, arg.InvitationID) + var i InvitationDecline + err := row.Scan( + &i.InvitationID, + &i.OrganizationID, + &i.Reason, + &i.Comment, + &i.DeclinedAt, + ) + return i, err +} + +const recordInvitationView = `-- name: RecordInvitationView :one +UPDATE invitations +SET + state = 'viewed', + version = $1, + viewed_at = $2, + updated_at = $2 +WHERE + organization_id = $3 + AND id = $4 + AND state = 'delivered' + AND version = $5 + AND response_deadline_at > $2 + AND $1::bigint = $5::bigint + 1 +RETURNING id +` + +type RecordInvitationViewParams struct { + NextVersion int64 + ViewedAt pgtype.Timestamptz + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + ExpectedVersion int64 +} + +// The compare-and-swap of the first view: it applies only to a delivered +// invitation at the version the caller read and before its deadline, and it +// keeps the deadline. +func (q *Queries) RecordInvitationView(ctx context.Context, arg RecordInvitationViewParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, recordInvitationView, + arg.NextVersion, + arg.ViewedAt, + arg.OrganizationID, + arg.InvitationID, + arg.ExpectedVersion, + ) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 841b9b2..0eae178 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -597,6 +597,20 @@ type InvitationCreationResult struct { Snapshot []byte } +type InvitationDecline struct { + InvitationID pgtype.UUID + OrganizationID pgtype.UUID + Reason string + Comment pgtype.Text + DeclinedAt pgtype.Timestamptz +} + +type InvitationDeclineResult struct { + ScopeHash []byte + InvitationID pgtype.UUID + Outcome string +} + type InvitationEvent struct { ID pgtype.UUID InvitationID pgtype.UUID diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 9500f1a..77c493b 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -157,6 +157,9 @@ type Querier interface { // The caller appends the matching outbox intent in the same transaction only // when this insert returns a row. CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error) + // The compare-and-swap of a decline: it applies only to an answerable + // invitation at the version the caller read and before its deadline. + DeclineInvitation(ctx context.Context, arg DeclineInvitationParams) (pgtype.UUID, error) // A newly reserved generic idempotency window can replace an expired typed // outcome before the new immutable response is inserted. DeleteAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) error @@ -302,6 +305,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) + GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, 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) @@ -477,6 +481,8 @@ type Querier interface { // inserted in one caller-owned transaction. The deferred reference to the // current terms version is checked when the transaction commits. InsertInvitation(ctx context.Context, arg InsertInvitationParams) error + InsertInvitationDecline(ctx context.Context, arg InsertInvitationDeclineParams) error + InsertInvitationDeclineResult(ctx context.Context, arg InsertInvitationDeclineResultParams) error InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error InsertInvitationSendResult(ctx context.Context, arg InsertInvitationSendResultParams) error InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error @@ -716,6 +722,9 @@ type Querier interface { // Acquired after C3, candidate/specialization scope, and attempt row locks. // This independent lock serializes current category upgrades for one scope. LockCandidateAssessmentCategory(ctx context.Context, arg LockCandidateAssessmentCategoryParams) error + // Lock one delivered invitation addressed to the candidate. Only the + // invitation row is locked, never the organization. + LockCandidateInvitation(ctx context.Context, arg LockCandidateInvitationParams) (pgtype.UUID, error) // Locks the candidate's published row only when it refers to a C2 record // revoked by this transaction. The setting remains linked to that immutable // record; ReadCandidatePublication computes the effective closed state and @@ -846,6 +855,10 @@ type Querier interface { // 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) + // Read one delivered invitation addressed to the candidate with the current + // name of the organization that sent it. A draft and an invitation of + // another candidate find nothing. + ReadCandidateInvitationEntry(ctx context.Context, arg ReadCandidateInvitationEntryParams) (ReadCandidateInvitationEntryRow, 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 @@ -888,6 +901,7 @@ type Querier interface { // and the invitation scope the row, so another organization's identifier // finds nothing. ReadInvitation(ctx context.Context, arg ReadInvitationParams) (ReadInvitationRow, error) + ReadInvitationDecline(ctx context.Context, arg ReadInvitationDeclineParams) (InvitationDecline, error) // Read one historical terms version of one invitation of one organization. ReadInvitationTermsVersion(ctx context.Context, arg ReadInvitationTermsVersionParams) (string, error) // Read one historical version without exposing another organization's record. @@ -933,6 +947,10 @@ type Querier interface { // the delivery is no longer pending or waiting, or another worker holds it. // now is the application clock. RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error) + // The compare-and-swap of the first view: it applies only to a delivered + // invitation at the version the caller read and before its deadline, and it + // keeps the deadline. + RecordInvitationView(ctx context.Context, arg RecordInvitationViewParams) (pgtype.UUID, error) // Records the latest settled outcome of a send under the reservation. RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error) RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error) diff --git a/backend/internal/domain/invitation.go b/backend/internal/domain/invitation.go index f60dd37..e67e1c2 100644 --- a/backend/internal/domain/invitation.go +++ b/backend/internal/domain/invitation.go @@ -223,6 +223,7 @@ func RestoreInvitation(stored StoredInvitation) (Invitation, error) { const location = "domain.RestoreInvitation" for _, defect := range []func(StoredInvitation) string{ storedInvitationIdentityDefect, storedInvitationVersionDefect, storedInvitationLifecycleDefect, + storedInvitationAnswerDefect, } { if reason := defect(stored); reason != "" { return Invitation{}, fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidInvitation) diff --git a/backend/internal/domain/invitation_answer.go b/backend/internal/domain/invitation_answer.go new file mode 100644 index 0000000..d913621 --- /dev/null +++ b/backend/internal/domain/invitation_answer.go @@ -0,0 +1,348 @@ +package domain + +import ( + "errors" + "fmt" + "log/slog" + "slices" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/google/uuid" +) + +// ErrInvitationNotAnswerable reports a candidate command that the state or +// the deadline of the invitation does not allow, such as a decline of a +// withdrawn invitation or one received at the deadline or later. The API +// answers 409 state_conflict. +var ErrInvitationNotAnswerable = errors.New("invitation state does not allow the answer") + +const ( + // InvitationEventViewed is the audit event of the first view of the + // terms: the invitation moved from delivered to viewed. + InvitationEventViewed InvitationEventKind = "viewed" + // InvitationEventDeclined is the audit event of a decline. It is the + // candidate's answer for the responsiveness metrics, never a consent or + // a hire, and it holds neither the reason nor the comment. + InvitationEventDeclined InvitationEventKind = "declined" +) + +const ( + // maxInvitationDeclineCommentRunes matches InvitationDeclineComment. + maxInvitationDeclineCommentRunes = 500 + redactedInvitationDecline = "[redacted invitation decline]" +) + +var ( + // terminalInvitationStates are the final states that no command leaves. + terminalInvitationStates = []InvitationState{ + InvitationDeclined, InvitationExpired, InvitationWithdrawn, InvitationCancelledByCandidate, + } + // answerableInvitationStates allow the candidate's answer: the delivered + // and viewed invitation and the planned counter offer. + answerableInvitationStates = []InvitationState{InvitationDelivered, InvitationViewed, InvitationCounter} + // answerEventKinds name the audit event of each answer state. + answerEventKinds = map[InvitationState]InvitationEventKind{ + InvitationViewed: InvitationEventViewed, InvitationDeclined: InvitationEventDeclined, + } +) + +// InvitationDeclineReason is the structured reason of a decline. Every reason +// is neutral, and none requires a comment. +type InvitationDeclineReason string + +const ( + InvitationDeclineSalary InvitationDeclineReason = "salary" + InvitationDeclineTasks InvitationDeclineReason = "tasks" + InvitationDeclineStack InvitationDeclineReason = "stack" + InvitationDeclineWorkFormat InvitationDeclineReason = "work_format" + InvitationDeclinePackage InvitationDeclineReason = "package" + InvitationDeclineCompany InvitationDeclineReason = "company" + InvitationDeclineNotLooking InvitationDeclineReason = "not_looking" + InvitationDeclineOtherOffer InvitationDeclineReason = "other_offer" + InvitationDeclineOther InvitationDeclineReason = "other" +) + +func (reason InvitationDeclineReason) IsKnown() bool { + switch reason { + case InvitationDeclineSalary, InvitationDeclineTasks, InvitationDeclineStack, InvitationDeclineWorkFormat, + InvitationDeclinePackage, InvitationDeclineCompany, InvitationDeclineNotLooking, InvitationDeclineOtherOffer, + InvitationDeclineOther: + return true + default: + return false + } +} + +// InvitationDeclineChoice is what the candidate sends with a decline: the +// reason and an optional comment. The comment is private to the candidate: +// the organization never reads it, and it is never logged or notified. +type InvitationDeclineChoice struct { + Reason InvitationDeclineReason + Comment *string +} + +// Validate repeats the schema rules that a stored choice must satisfy and +// refuses what PostgreSQL text cannot hold. A comment has 1 to 500 +// characters, at least one that is not white space in the Unicode sense, and +// no control character other than a line break or a tab. +func (choice InvitationDeclineChoice) Validate() error { + if !choice.Reason.IsKnown() { + return invalidInvitationField("/reason", "must be a known decline reason") + } + if choice.Comment == nil { + return nil + } + comment := *choice.Comment + if comment == "" || !utf8.ValidString(comment) || utf8.RuneCountInString(comment) > maxInvitationDeclineCommentRunes { + return invalidInvitationField("/comment", "must have 1 to 500 characters") + } + if strings.TrimFunc(comment, unicode.IsSpace) == "" { + return invalidInvitationField("/comment", "must contain a character that is not white space") + } + for _, character := range comment { + if unicode.IsControl(character) && character != '\n' && character != '\r' && character != '\t' { + return invalidInvitationField("/comment", "must not contain control characters") + } + } + return nil +} + +// Equal reports whether both choices have the same reason and comment. An +// absent comment equals another absent comment only. +func (choice InvitationDeclineChoice) Equal(other InvitationDeclineChoice) bool { + if choice.Reason != other.Reason || (choice.Comment == nil) != (other.Comment == nil) { + return false + } + return choice.Comment == nil || *choice.Comment == *other.Comment +} + +func (choice InvitationDeclineChoice) String() string { return redactedInvitationDecline } +func (choice InvitationDeclineChoice) GoString() string { return redactedInvitationDecline } +func (choice InvitationDeclineChoice) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedInvitationDecline) +} +func (choice InvitationDeclineChoice) LogValue() slog.Value { + return slog.StringValue(redactedInvitationDecline) +} + +// InvitationDecline is the stored decline of one invitation. Only the +// candidate reads it back; the organization sees the state and the time of +// the answer only, because a reason such as salary would tell it that the +// hidden minimum is above the range. +type InvitationDecline struct { + InvitationID uuid.UUID + OrganizationID uuid.UUID + Choice InvitationDeclineChoice + DeclinedAt time.Time +} + +// Validate checks a decline before it is stored or after it is read. +func (decline InvitationDecline) Validate() error { + if decline.InvitationID == uuid.Nil || decline.OrganizationID == uuid.Nil || !validInvitationTime(decline.DeclinedAt) { + return fmt.Errorf("InvitationDecline.Validate - identifiers and time must be set: %w", ErrInvalidInvitation) + } + return decline.Choice.Validate() +} + +func (decline InvitationDecline) String() string { return redactedInvitationDecline } +func (decline InvitationDecline) GoString() string { return redactedInvitationDecline } +func (decline InvitationDecline) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedInvitationDecline) +} +func (decline InvitationDecline) LogValue() slog.Value { + return slog.StringValue(redactedInvitationDecline) +} + +// IsTerminal reports a final state that no candidate or organization command +// leaves: declined, expired, withdrawn, or cancelled by the candidate. +func (invitation Invitation) IsTerminal() bool { + return slices.Contains(terminalInvitationStates, invitation.State()) +} + +// ResponseDeadlinePassed reports whether a command received at the time is +// late: at the deadline or later. An undelivered draft has no deadline. +func (invitation Invitation) ResponseDeadlinePassed(at time.Time) bool { + deadline := invitation.record.ResponseDeadlineAt + return deadline != nil && !at.Before(*deadline) +} + +// answerable reports the states from which the candidate may still answer: +// the delivered and viewed invitation and the planned counter offer. +func (invitation Invitation) answerable() bool { + return slices.Contains(answerableInvitationStates, invitation.State()) +} + +// RecordView returns the next version in the state viewed when the candidate +// opens the terms of a delivered invitation before its deadline. In every +// other state, and at the deadline or later, the view changes nothing and +// RecordView returns the invitation as it is with changed false. The view +// never moves the deadline. +func (invitation Invitation) RecordView(at time.Time) (Invitation, bool, error) { + const location = "Invitation.RecordView" + if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) { + return Invitation{}, false, fmt.Errorf("%s - view time must be set and not before the last change: %w", location, ErrInvalidInvitation) + } + if invitation.State() != InvitationDelivered || !invitation.IsDelivered() || invitation.ResponseDeadlinePassed(at) { + return invitation, false, nil + } + at = at.UTC() + next := invitation.Stored() + next.State = string(InvitationViewed) + next.Version++ + next.UpdatedAt = at + next.ViewedAt = &at + viewed, err := RestoreInvitation(next) + if err != nil { + return Invitation{}, false, fmt.Errorf("%s - restore viewed invitation: %w", location, err) + } + return viewed, true, nil +} + +// Decline returns the next version in the terminal state declined with the +// stored decline. It is allowed from delivered, viewed, and the planned +// counter offer before the deadline; any other state or a late command +// returns ErrInvitationNotAnswerable. A decline creates no consent and no +// contact grant. +func (invitation Invitation) Decline(choice InvitationDeclineChoice, at time.Time) (Invitation, InvitationDecline, error) { + const location = "Invitation.Decline" + if err := choice.Validate(); err != nil { + return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - validate choice: %w", location, err) + } + if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) { + return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - decline time must be set and not before the last change: %w", location, ErrInvalidInvitation) + } + if !invitation.answerable() || !invitation.IsDelivered() || invitation.ResponseDeadlinePassed(at) { + return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - %w", location, ErrInvitationNotAnswerable) + } + at = at.UTC() + next := invitation.Stored() + next.State = string(InvitationDeclined) + next.Version++ + next.UpdatedAt = at + next.RespondedAt = &at + declined, err := RestoreInvitation(next) + if err != nil { + return Invitation{}, InvitationDecline{}, fmt.Errorf("%s - restore declined invitation: %w", location, err) + } + decline := InvitationDecline{ + InvitationID: next.ID, OrganizationID: next.OrganizationID, DeclinedAt: at, + Choice: InvitationDeclineChoice{Reason: choice.Reason, Comment: cloneString(choice.Comment)}, + } + return declined, decline, nil +} + +// AnswerEvent builds the audit event of the version that a view or a +// decline by actor has just produced. It names no field and holds neither +// the reason nor the comment of a decline. +func (invitation Invitation) AnswerEvent(actorID uuid.UUID) (InvitationEvent, error) { + const location = "Invitation.AnswerEvent" + if actorID == uuid.Nil { + return InvitationEvent{}, fmt.Errorf("%s - actor must be set: %w", location, ErrInvalidInvitation) + } + kind, ok := answerEventKinds[invitation.State()] + if !ok { + return InvitationEvent{}, fmt.Errorf("%s - the invitation must be viewed or declined: %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: kind, + ActorID: actorID, ChangedFields: []InvitationChangedField{}, OccurredAt: invitation.record.UpdatedAt, + }, nil +} + +// storedInvitationAnswerDefect checks the view and the answer against the +// state: a delivered invitation has neither, a viewed one has its view, a +// declined one has its answer, and neither precedes the delivery. +func storedInvitationAnswerDefect(stored StoredInvitation) string { + state := InvitationState(stored.State) + switch { + case state == InvitationDelivered && (stored.ViewedAt != nil || stored.RespondedAt != nil): + return "a delivered invitation has no view or answer" + case state == InvitationViewed && (stored.ViewedAt == nil || stored.RespondedAt != nil): + return "a viewed invitation has a view and no answer" + case state == InvitationDeclined && stored.RespondedAt == nil: + return "a declined invitation has an answer" + case stored.ViewedAt != nil && (stored.DeliveredAt == nil || stored.ViewedAt.Before(*stored.DeliveredAt)): + return "a view follows the delivery" + case stored.RespondedAt != nil && (stored.DeliveredAt == nil || stored.RespondedAt.Before(*stored.DeliveredAt)): + return "an answer follows the delivery" + } + return "" +} + +// InvitationDeclineView is the candidate's own decline as the candidate +// reads it back. +type InvitationDeclineView struct { + Reason InvitationDeclineReason + Comment *string + DeclinedAt time.Time +} + +// CandidateInvitationView is a delivered invitation as the addressed +// candidate reads it: the organization, the current terms with their +// version, the state, the deadline, and the candidate's own decline. It has +// no candidate identifier, handle, need, salary indicator, or contact value. +// The consent offer and the contact grant belong to the acceptance and are +// absent until it exists. +type CandidateInvitationView struct { + ID uuid.UUID + Organization InvitationOrganizationRef + State InvitationState + ExpiryReason *InvitationExpiryReason + Version int64 + TermsVersion int64 + Terms InvitationTerms + ResponseDeadlineAt time.Time + DeliveredAt time.Time + ViewedAt *time.Time + RespondedAt *time.Time + UpdatedAt time.Time + Decline *InvitationDeclineView +} + +// CandidateView returns the invitation for the candidate it is addressed to. +// The decline must be given exactly when the invitation is declined, and it +// must belong to this invitation. +func (invitation Invitation) CandidateView(organization InvitationOrganizationRef, decline *InvitationDecline) (CandidateInvitationView, error) { + const location = "Invitation.CandidateView" + stored := invitation.Stored() + if stored.DeliveredAt == nil || stored.ResponseDeadlineAt == nil { + return CandidateInvitationView{}, fmt.Errorf("%s - only a delivered invitation is shown to the candidate: %w", location, ErrInvalidInvitation) + } + if organization.ID != stored.OrganizationID || organization.Name == "" { + return CandidateInvitationView{}, fmt.Errorf("%s - the organization must be the sender: %w", location, ErrInvalidInvitation) + } + if (invitation.State() == InvitationDeclined) != (decline != nil) || + (decline != nil && (decline.InvitationID != stored.ID || decline.OrganizationID != stored.OrganizationID)) { + return CandidateInvitationView{}, fmt.Errorf("%s - the decline must belong to a declined invitation: %w", location, ErrInvalidInvitation) + } + snapshot := invitation.Snapshot() + view := CandidateInvitationView{ + ID: stored.ID, Organization: organization, State: snapshot.State, ExpiryReason: snapshot.ExpiryReason, + Version: stored.Version, TermsVersion: stored.TermsVersion, Terms: stored.Terms, + ResponseDeadlineAt: *stored.ResponseDeadlineAt, DeliveredAt: *stored.DeliveredAt, + ViewedAt: stored.ViewedAt, RespondedAt: stored.RespondedAt, UpdatedAt: stored.UpdatedAt, + } + if decline != nil { + view.Decline = &InvitationDeclineView{ + Reason: decline.Choice.Reason, Comment: cloneString(decline.Choice.Comment), DeclinedAt: decline.DeclinedAt.UTC(), + } + } + return view, nil +} + +func (view CandidateInvitationView) String() string { return redactedInvitation } +func (view CandidateInvitationView) GoString() string { return redactedInvitation } +func (view CandidateInvitationView) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedInvitation) +} +func (view CandidateInvitationView) LogValue() slog.Value { + return slog.StringValue(redactedInvitation) +} diff --git a/backend/internal/domain/invitation_answer_test.go b/backend/internal/domain/invitation_answer_test.go new file mode 100644 index 0000000..5d029d2 --- /dev/null +++ b/backend/internal/domain/invitation_answer_test.go @@ -0,0 +1,225 @@ +package domain + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +// deliveredTestInvitation returns a draft delivered an hour after it was +// created, with the default seven-day deadline. +func deliveredTestInvitation(t *testing.T) (Invitation, NewInvitationDraftInput) { + t.Helper() + input := validInvitationDraftInput() + draft, err := NewInvitationDraft(input) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + delivered, err := draft.Deliver(input.At.Add(time.Hour)) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + return delivered, input +} + +// withState restores the invitation in another state, as a later operation +// would store it. +func withState(t *testing.T, invitation Invitation, state InvitationState, change func(*StoredInvitation)) Invitation { + t.Helper() + stored := invitation.Stored() + stored.State = string(state) + stored.Version++ + if change != nil { + change(&stored) + } + restored, err := RestoreInvitation(stored) + if err != nil { + t.Fatalf("RestoreInvitation(%s) error = %v", state, err) + } + return restored +} + +func TestRecordViewMovesOnlyADeliveredInvitationBeforeItsDeadline(t *testing.T) { + delivered, input := deliveredTestInvitation(t) + deadline := *delivered.Snapshot().ResponseDeadlineAt + viewedAt := deadline.Add(-time.Microsecond) + viewed, changed, err := delivered.RecordView(viewedAt) + if err != nil || !changed { + t.Fatalf("RecordView() = %v, %v; want a change", changed, err) + } + snapshot := viewed.Snapshot() + if snapshot.State != InvitationViewed || snapshot.Version != delivered.Version()+1 || snapshot.TermsVersion != delivered.TermsVersion() || + !snapshot.ViewedAt.Equal(viewedAt) || !snapshot.ResponseDeadlineAt.Equal(deadline) || !snapshot.UpdatedAt.Equal(viewedAt) { + t.Fatalf("viewed = %+v, want the next version viewed with the same deadline", snapshot) + } + event, err := viewed.AnswerEvent(input.ActorID) + if err != nil || event.Kind != InvitationEventViewed || event.Version != snapshot.Version || len(event.ChangedFields) != 0 || !event.OccurredAt.Equal(viewedAt) { + t.Fatalf("AnswerEvent() = %+v, %v", event, err) + } + + // A repeat, a late view, and a view of another state change nothing. + for name, test := range map[string]struct { + invitation Invitation + at time.Time + }{ + "viewed": {viewed, viewedAt}, + "at the deadline": {delivered, deadline}, + "after it": {delivered, deadline.Add(time.Hour)}, + "declined": {withState(t, delivered, InvitationDeclined, func(s *StoredInvitation) { s.RespondedAt = &viewedAt }), deadline.Add(-time.Second)}, + "withdrawn": {withState(t, delivered, InvitationWithdrawn, nil), viewedAt}, + "planned counter": {withState(t, viewed, InvitationCounter, nil), viewedAt}, + "expired by timing": {withState(t, delivered, InvitationExpired, func(s *StoredInvitation) { reason := string(InvitationExpiryTimeout); s.ExpiryReason = &reason }), viewedAt}, + } { + same, changed, err := test.invitation.RecordView(test.at) + if err != nil || changed || same.Version() != test.invitation.Version() || same.State() != test.invitation.State() { + t.Errorf("RecordView(%s) = %s v%d, %v, %v; want no change", name, same.State(), same.Version(), changed, err) + } + } + if _, _, err := delivered.RecordView(delivered.UpdatedAt().Add(-time.Second)); !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("RecordView(before the last change) error = %v, want ErrInvalidInvitation", err) + } + if _, err := delivered.AnswerEvent(input.ActorID); !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("AnswerEvent(delivered) error = %v, want ErrInvalidInvitation", err) + } +} + +func TestDeclineIsAllowedFromDeliveredViewedAndCounterBeforeTheDeadline(t *testing.T) { + delivered, input := deliveredTestInvitation(t) + deadline := *delivered.Snapshot().ResponseDeadlineAt + viewed, _, err := delivered.RecordView(delivered.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("RecordView() error = %v", err) + } + counter := withState(t, viewed, InvitationCounter, nil) + choice := InvitationDeclineChoice{Reason: InvitationDeclineOther} + for name, invitation := range map[string]Invitation{"delivered": delivered, "viewed": viewed, "counter": counter} { + at := deadline.Add(-time.Microsecond) + declined, decline, err := invitation.Decline(choice, at) + if err != nil { + t.Fatalf("Decline(%s) error = %v", name, err) + } + snapshot := declined.Snapshot() + if snapshot.State != InvitationDeclined || snapshot.Version != invitation.Version()+1 || !snapshot.RespondedAt.Equal(at) || + !snapshot.ResponseDeadlineAt.Equal(deadline) || !declined.IsTerminal() { + t.Fatalf("declined %s = %+v", name, snapshot) + } + if decline.InvitationID != invitation.ID() || decline.OrganizationID != invitation.OrganizationID() || + decline.Choice.Reason != InvitationDeclineOther || decline.Choice.Comment != nil || !decline.DeclinedAt.Equal(at) { + t.Fatalf("decline of %s = %+v", name, decline) + } + event, err := declined.AnswerEvent(input.CandidateID) + if err != nil || event.Kind != InvitationEventDeclined || event.ActorID != input.CandidateID || len(event.ChangedFields) != 0 { + t.Fatalf("AnswerEvent(%s) = %+v, %v", name, event, err) + } + view, err := declined.CandidateView(InvitationOrganizationRef{ID: input.OrganizationID, Name: "Org"}, &decline) + if err != nil || view.Decline == nil || view.Decline.Reason != InvitationDeclineOther || view.Decline.Comment != nil { + t.Fatalf("CandidateView(%s) = %+v, %v", name, view, err) + } + } +} + +func TestDeclineRefusesTerminalAndLateInvitations(t *testing.T) { + delivered, _ := deliveredTestInvitation(t) + deadline := *delivered.Snapshot().ResponseDeadlineAt + responded := delivered.UpdatedAt().Add(time.Minute) + choice := InvitationDeclineChoice{Reason: InvitationDeclineSalary} + draft, err := NewInvitationDraft(validInvitationDraftInput()) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + for name, test := range map[string]struct { + invitation Invitation + at time.Time + }{ + "at the deadline": {delivered, deadline}, + "draft": {draft, draft.UpdatedAt()}, + "declined": {withState(t, delivered, InvitationDeclined, func(s *StoredInvitation) { s.RespondedAt = &responded }), responded}, + "accepted": {withState(t, delivered, InvitationAccepted, func(s *StoredInvitation) { s.RespondedAt = &responded }), responded}, + "withdrawn": {withState(t, delivered, InvitationWithdrawn, nil), responded}, + "cancelled": {withState(t, delivered, InvitationCancelledByCandidate, nil), responded}, + } { + if _, _, err := test.invitation.Decline(choice, test.at); !errors.Is(err, ErrInvitationNotAnswerable) { + t.Errorf("Decline(%s) error = %v, want ErrInvitationNotAnswerable", name, err) + } + } +} + +func TestDeclineChoiceValidatesTheReasonAndTheComment(t *testing.T) { + text := func(value string) *string { return &value } + for name, comment := range map[string]*string{ + "absent": nil, "line breaks": text("Не подходит\nстек"), "500 characters": text(strings.Repeat("я", 500)), + "leading space": text(" ok"), + } { + if err := (InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: comment}).Validate(); err != nil { + t.Errorf("Validate(%s) error = %v", name, err) + } + } + for name, test := range map[string]struct { + choice InvitationDeclineChoice + pointer string + }{ + "unknown reason": {InvitationDeclineChoice{Reason: "rude"}, "/reason"}, + "empty": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("")}, "/comment"}, + "white space": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text(" \n  ")}, "/comment"}, + "501 characters": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text(strings.Repeat("я", 501))}, "/comment"}, + "NUL": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("a\x00b")}, "/comment"}, + "invalid UTF-8": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("a\xffb")}, "/comment"}, + "escape characters": {InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("a\x1bb")}, "/comment"}, + } { + err := test.choice.Validate() + field, ok := errors.AsType[*InvitationFieldError](err) + if !ok || field.Pointer != test.pointer { + t.Errorf("Validate(%s) error = %v, want a field error at %s", name, err, test.pointer) + } + } + same := InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("x")} + if !same.Equal(InvitationDeclineChoice{Reason: InvitationDeclineOther, Comment: text("x")}) || + same.Equal(InvitationDeclineChoice{Reason: InvitationDeclineOther}) || + same.Equal(InvitationDeclineChoice{Reason: InvitationDeclineStack, Comment: text("x")}) { + t.Fatal("Equal does not compare the reason and the comment") + } +} + +func TestStoredAnswersMustMatchTheState(t *testing.T) { + delivered, _ := deliveredTestInvitation(t) + before := delivered.Snapshot().DeliveredAt.Add(-time.Second) + after := delivered.Snapshot().DeliveredAt.Add(time.Second) + for name, change := range map[string]func(*StoredInvitation){ + "delivered with a view": func(s *StoredInvitation) { s.ViewedAt = &after }, + "viewed without a view": func(s *StoredInvitation) { s.State = string(InvitationViewed) }, + "declined without time": func(s *StoredInvitation) { s.State = string(InvitationDeclined) }, + "view before delivery": func(s *StoredInvitation) { s.State = string(InvitationViewed); s.ViewedAt = &before }, + "answer before delivery": func(s *StoredInvitation) { s.State = string(InvitationDeclined); s.RespondedAt = &before }, + } { + stored := delivered.Stored() + change(&stored) + if _, err := RestoreInvitation(stored); !errors.Is(err, ErrInvalidInvitation) { + t.Errorf("RestoreInvitation(%s) error = %v, want ErrInvalidInvitation", name, err) + } + } +} + +func TestDeclineValuesAreRedacted(t *testing.T) { + comment := "private-decline-comment" + decline := InvitationDecline{ + InvitationID: uuid.New(), OrganizationID: uuid.New(), DeclinedAt: time.Now(), + Choice: InvitationDeclineChoice{Reason: InvitationDeclineSalary, Comment: &comment}, + } + delivered, input := deliveredTestInvitation(t) + view, err := delivered.CandidateView(InvitationOrganizationRef{ID: input.OrganizationID, Name: "Org"}, nil) + if err != nil { + t.Fatalf("CandidateView() error = %v", err) + } + for _, value := range []any{decline, decline.Choice, view} { + for _, format := range []string{"%v", "%+v", "%#v", "%s"} { + if output := fmt.Sprintf(format, value); strings.Contains(output, comment) || strings.Contains(output, string(InvitationDeclineSalary)) || + strings.Contains(output, input.CandidateID.String()) { + t.Errorf("%s of %T discloses a private value: %s", format, value, output) + } + } + } +} diff --git a/backend/internal/port/outbound/invitations.go b/backend/internal/port/outbound/invitations.go index ae76fc7..982fb12 100644 --- a/backend/internal/port/outbound/invitations.go +++ b/backend/internal/port/outbound/invitations.go @@ -28,6 +28,14 @@ var ( // ErrInvitationSendResultNotFound reports a missing outcome of a send for // a live idempotency record. ErrInvitationSendResultNotFound = errors.New("organization invitation send result not found") + + // ErrInvitationDeclineNotFound reports a declined invitation without its + // stored decline. + ErrInvitationDeclineNotFound = errors.New("invitation decline not found") + + // ErrInvitationDeclineResultNotFound reports a missing outcome of a + // decline for a live idempotency record. + ErrInvitationDeclineResultNotFound = errors.New("invitation decline result not found") ) // MaxInvitationPageSize is the largest organization-scoped or candidate page @@ -40,6 +48,7 @@ type InvitationRepositories interface { Invitations() InvitationRepository InvitationCreationResults() InvitationCreationResultRepository InvitationSendResults() InvitationSendResultRepository + InvitationDeclineResults() InvitationDeclineResultRepository } // InvitationRepository stores invitations, their immutable terms versions, and @@ -92,6 +101,35 @@ type InvitationRepository interface { // 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) + + // GetCandidateEntry returns a delivered invitation addressed to the + // candidate with the current name of the organization that sent it. A + // draft, an invitation of another candidate, and an unknown identifier + // return ErrInvitationNotFound alike. + GetCandidateEntry(ctx context.Context, candidateID, invitationID uuid.UUID) (CandidateInvitationEntry, error) + + // GetCandidateEntryForUpdate is GetCandidateEntry that also holds the + // row lock of the invitation until the surrounding transaction ends. It + // locks nothing else, so a candidate command never waits for an + // organization lock while it holds the invitation row. + GetCandidateEntryForUpdate(ctx context.Context, candidateID, invitationID uuid.UUID) (CandidateInvitationEntry, error) + + // RecordView moves a delivered invitation from expectedVersion to the + // viewed version of next before its deadline and records the audit + // event. It returns ErrInvitationVersionConflict when the stored row is + // not delivered at expectedVersion or its deadline has passed. + RecordView(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error + + // Decline moves an answerable invitation from expectedVersion to the + // declined version of next before its deadline, stores the decline, and + // records the audit event. It returns ErrInvitationVersionConflict when + // the stored row is not answerable at expectedVersion or its deadline has + // passed. + Decline(ctx context.Context, expectedVersion int64, next domain.Invitation, decline domain.InvitationDecline, event domain.InvitationEvent) error + + // GetDecline returns the stored decline of the invitation or + // ErrInvitationDeclineNotFound. + GetDecline(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.InvitationDecline, error) } // InvitationCreationResultRepository stores the original response of a @@ -180,3 +218,31 @@ type InvitationPage struct { func InvitationCreationPosition(invitation domain.Invitation) InvitationListPosition { return InvitationListPosition{CreatedAt: invitation.CreatedAt(), InvitationID: invitation.ID()} } + +// InvitationDeclineOutcome is the stored result of a decline under an +// Idempotency-Key. The contract stores a success, a missing invitation, and a +// state conflict; other failures are not stored. +type InvitationDeclineOutcome string + +const ( + InvitationDeclineDeclined InvitationDeclineOutcome = "declined" + InvitationDeclineNotFound InvitationDeclineOutcome = "not_found" + InvitationDeclineStateConflict InvitationDeclineOutcome = "state_conflict" +) + +// InvitationDeclineResult is the outcome of one decline. It keeps no copy of +// the response: a declined invitation is terminal and its decline is +// immutable, so a replay rebuilds the same response from them, and the +// comment is stored once. +type InvitationDeclineResult struct { + InvitationID uuid.UUID + Outcome InvitationDeclineOutcome +} + +// InvitationDeclineResultRepository stores the outcome of an idempotent +// decline. The scope references the generic idempotency record, so the +// outcome is removed when that record is purged. +type InvitationDeclineResultRepository interface { + SaveDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result InvitationDeclineResult) error + GetDeclineResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (InvitationDeclineResult, error) +} diff --git a/backend/internal/usecase/invitation/answer_test.go b/backend/internal/usecase/invitation/answer_test.go new file mode 100644 index 0000000..14ed39f --- /dev/null +++ b/backend/internal/usecase/invitation/answer_test.go @@ -0,0 +1,267 @@ +package invitation + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func (repository testInvitations) GetCandidateEntry(ctx context.Context, candidateID, invitationID uuid.UUID) (outbound.CandidateInvitationEntry, error) { + invitation, err := repository.GetForCandidate(ctx, candidateID, invitationID) + if err != nil { + return outbound.CandidateInvitationEntry{}, err + } + return outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: "Test organization"}, nil +} + +func (repository testInvitations) GetCandidateEntryForUpdate(ctx context.Context, candidateID, invitationID uuid.UUID) (outbound.CandidateInvitationEntry, error) { + return repository.GetCandidateEntry(ctx, candidateID, invitationID) +} + +func (repository testInvitations) RecordView(_ 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.InvitationDelivered { + return outbound.ErrInvitationVersionConflict + } + repository.state.invitations[next.ID()] = next + repository.state.events = append(repository.state.events, event) + return nil +} + +func (repository testInvitations) Decline(_ context.Context, expectedVersion int64, next domain.Invitation, decline domain.InvitationDecline, event domain.InvitationEvent) error { + current, ok := repository.state.invitations[next.ID()] + if !ok || current.Version() != expectedVersion { + return outbound.ErrInvitationVersionConflict + } + repository.state.invitations[next.ID()] = next + repository.state.declines[next.ID()] = decline + repository.state.events = append(repository.state.events, event) + return nil +} + +func (repository testInvitations) GetDecline(_ context.Context, organizationID, invitationID uuid.UUID) (domain.InvitationDecline, error) { + decline, ok := repository.state.declines[invitationID] + if !ok || decline.OrganizationID != organizationID { + return domain.InvitationDecline{}, outbound.ErrInvitationDeclineNotFound + } + return decline, nil +} + +func (repository testInvitations) SaveDeclineResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationDeclineResult) error { + repository.state.declineResults[scope] = result + return nil +} + +func (repository testInvitations) GetDeclineResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationDeclineResult, error) { + result, ok := repository.state.declineResults[scope] + if !ok { + return outbound.InvitationDeclineResult{}, outbound.ErrInvitationDeclineResultNotFound + } + return result, nil +} + +// deliveredTo sends a new draft to a new candidate who can sign in and +// returns the delivered invitation with the candidate. +func (test *harness) deliveredTo(t *testing.T) (domain.OrganizationInvitationView, uuid.UUID) { + t.Helper() + draft, _, candidateID := test.draftFor(t, nil) + sent, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-"+draft.ID.String())) + if err != nil { + t.Fatalf("Send() error = %v", err) + } + verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC) + test.transactor.mu.Lock() + test.transactor.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &verified} + test.transactor.mu.Unlock() + return sent, candidateID +} + +func declineCommand(actorID, invitationID uuid.UUID, version int64, key string, reason domain.InvitationDeclineReason, comment *string) DeclineCommand { + return DeclineCommand{ + ActorID: actorID, InvitationID: invitationID, IdempotencyKey: key, ExpectedVersion: version, + Choice: domain.InvitationDeclineChoice{Reason: reason, Comment: comment}, + } +} + +func TestGetMineHasNoSideEffectAndViewMineKeepsTheDeadline(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + events := len(test.transactor.snapshot().events) + + read, err := test.service.GetMine(t.Context(), candidateID, sent.ID) + if err != nil { + t.Fatalf("GetMine() error = %v", err) + } + if read.State != domain.InvitationDelivered || read.Version != sent.Version || read.ViewedAt != nil || read.Decline != nil || + read.Organization.ID != test.organizationID || read.Organization.Name == "" || read.Terms.RoleTitle == "" { + t.Fatalf("read = %+v, want the delivered invitation unchanged", read) + } + if len(test.transactor.snapshot().events) != events { + t.Fatal("a read recorded an event") + } + + viewedAt := sent.DeliveredAt.Add(time.Hour) + test.setTime(viewedAt) + viewed, err := test.service.ViewMine(t.Context(), candidateID, sent.ID) + if err != nil { + t.Fatalf("ViewMine() error = %v", err) + } + if viewed.State != domain.InvitationViewed || viewed.Version != sent.Version+1 || viewed.TermsVersion != sent.TermsVersion || + viewed.ViewedAt == nil || !viewed.ViewedAt.Equal(viewedAt) || !viewed.ResponseDeadlineAt.Equal(*sent.ResponseDeadlineAt) { + t.Fatalf("viewed = %+v, want viewed now with the deadline of the delivery", viewed) + } + state := test.transactor.snapshot() + last := state.events[len(state.events)-1] + if len(state.events) != events+1 || last.Kind != domain.InvitationEventViewed || last.ActorID != candidateID || last.Version != viewed.Version { + t.Fatalf("events = %+v, want one view event by the candidate", state.events[events:]) + } + + // A repeat changes nothing and records nothing. + test.setTime(viewedAt.Add(time.Hour)) + again, err := test.service.ViewMine(t.Context(), candidateID, sent.ID) + if err != nil || again.Version != viewed.Version || !again.ViewedAt.Equal(viewedAt) { + t.Fatalf("repeated view = %+v, %v; want the first view", again, err) + } + if len(test.transactor.snapshot().events) != events+1 { + t.Fatal("a repeated view recorded an event") + } +} + +func TestViewMineAtTheDeadlineChangesNothing(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + test.setTime(*sent.ResponseDeadlineAt) + view, err := test.service.ViewMine(t.Context(), candidateID, sent.ID) + if err != nil || view.State != domain.InvitationDelivered || view.Version != sent.Version || view.ViewedAt != nil { + t.Fatalf("late view = %+v, %v; want the delivered invitation unchanged", view, err) + } +} + +func TestDeclineMineWithOtherAndNoCommentIsAStoredAnswer(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + notified := len(test.transactor.snapshot().notified) + declinedAt := sent.DeliveredAt.Add(2 * time.Hour) + test.setTime(declinedAt) + command := declineCommand(candidateID, sent.ID, sent.Version, "decline-1", domain.InvitationDeclineOther, nil) + + declined, err := test.service.DeclineMine(t.Context(), command) + if err != nil { + t.Fatalf("DeclineMine() error = %v", err) + } + if declined.State != domain.InvitationDeclined || declined.Version != sent.Version+1 || declined.RespondedAt == nil || + !declined.RespondedAt.Equal(declinedAt) || declined.Decline == nil || declined.Decline.Reason != domain.InvitationDeclineOther || + declined.Decline.Comment != nil || !declined.Decline.DeclinedAt.Equal(declinedAt) || + !declined.ResponseDeadlineAt.Equal(*sent.ResponseDeadlineAt) { + t.Fatalf("declined = %+v, want declined now with the reason other and no comment", declined) + } + state := test.transactor.snapshot() + last := state.events[len(state.events)-1] + if last.Kind != domain.InvitationEventDeclined || last.ActorID != candidateID || last.Version != declined.Version || + len(last.ChangedFields) != 0 || len(state.notified) != notified { + t.Fatalf("event %+v and %d notifications, want one decline event and no notification", last, len(state.notified)-notified) + } + + // The same key replays, and the same decline under a new key with the + // older version answers with the declined invitation. + test.setTime(declinedAt.Add(time.Hour)) + for _, repeat := range []DeclineCommand{command, declineCommand(candidateID, sent.ID, sent.Version, "decline-2", domain.InvitationDeclineOther, nil)} { + again, err := test.service.DeclineMine(t.Context(), repeat) + if err != nil || again.Version != declined.Version || !again.Decline.DeclinedAt.Equal(declinedAt) { + t.Fatalf("repeat %s = %+v, %v; want the original decline", repeat.IdempotencyKey, again, err) + } + } + if events := len(test.transactor.snapshot().events); events != len(state.events) { + t.Fatalf("repeats recorded %d events", events-len(state.events)) + } + comment := "Не подходит стек" + if _, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, declined.Version, "decline-3", domain.InvitationDeclineOther, &comment)); !errors.Is(err, ErrAnswerBlocked) { + t.Fatalf("another comment on a declined invitation error = %v, want ErrAnswerBlocked", err) + } + if _, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, sent.Version, "decline-1", domain.InvitationDeclineSalary, nil)); !errors.Is(err, ErrIdempotencyKeyReused) { + t.Fatalf("the same key with another reason error = %v, want ErrIdempotencyKeyReused", err) + } +} + +func TestDeclineMineFollowsTheOrderOfChecks(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + + // A stale version answers 412 and is not stored under the key. + if _, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, sent.Version+1, "stale", domain.InvitationDeclineStack, nil)); !errors.Is(err, domain.ErrInvitationVersionConflict) { + t.Fatalf("stale decline error = %v, want ErrInvitationVersionConflict", err) + } + if state := test.transactor.snapshot(); len(state.declineResults) != 0 || state.invitations[sent.ID].State() != domain.InvitationDelivered { + t.Fatal("a stale decline stored an outcome or changed the invitation") + } + + // At the deadline a decline is late whatever the version, and the + // refusal is stored. + test.setTime(*sent.ResponseDeadlineAt) + late := declineCommand(candidateID, sent.ID, sent.Version+5, "late", domain.InvitationDeclineStack, nil) + for range 2 { + if _, err := test.service.DeclineMine(t.Context(), late); !errors.Is(err, ErrAnswerBlocked) { + t.Fatalf("late decline error = %v, want ErrAnswerBlocked", err) + } + } + if state := test.transactor.snapshot(); len(state.declineResults) != 1 || state.invitations[sent.ID].State() != domain.InvitationDelivered { + t.Fatal("a late decline was not stored once or changed the invitation") + } + + // An unknown identifier is not found and stored as well. + unknown := declineCommand(candidateID, uuid.New(), 1, "unknown", domain.InvitationDeclineOther, nil) + for range 2 { + if _, err := test.service.DeclineMine(t.Context(), unknown); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Fatalf("unknown decline error = %v, want ErrInvitationNotFound", err) + } + } +} + +func TestCandidateCommandsShowNothingOfAnotherCandidatesInvitation(t *testing.T) { + test := newHarness(t) + sent, _ := test.deliveredTo(t) + _, stranger := test.deliveredTo(t) + draft, _, _ := test.draftFor(t, nil) + for name, invitationID := range map[string]uuid.UUID{"of another candidate": sent.ID, "draft": draft.ID, "unknown": uuid.New()} { + if _, err := test.service.GetMine(t.Context(), stranger, invitationID); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Errorf("GetMine(%s) error = %v, want ErrInvitationNotFound", name, err) + } + if _, err := test.service.ViewMine(t.Context(), stranger, invitationID); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Errorf("ViewMine(%s) error = %v, want ErrInvitationNotFound", name, err) + } + if _, err := test.service.DeclineMine(t.Context(), declineCommand(stranger, invitationID, 2, "foreign-"+name, domain.InvitationDeclineOther, nil)); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Errorf("DeclineMine(%s) error = %v, want ErrInvitationNotFound", name, err) + } + } + // The employer that sent it has no candidate inbox. + if _, err := test.service.GetMine(t.Context(), test.actorID, sent.ID); !errors.Is(err, ErrForbidden) { + t.Fatalf("GetMine(employer) error = %v, want ErrForbidden", err) + } + if _, err := test.service.DeclineMine(t.Context(), declineCommand(test.actorID, sent.ID, sent.Version, "employer", domain.InvitationDeclineOther, nil)); !errors.Is(err, ErrForbidden) { + t.Fatalf("DeclineMine(employer) error = %v, want ErrForbidden", err) + } + if state := test.transactor.snapshot(); state.invitations[sent.ID].State() != domain.InvitationDelivered { + t.Fatal("a foreign caller changed the invitation") + } +} + +func TestDeclineMineRefusesAnUnstorableCommentBeforeAnyRead(t *testing.T) { + test := newHarness(t) + sent, candidateID := test.deliveredTo(t) + for name, comment := range map[string]string{"only non-breaking spaces": "  ", "NUL": "ok\x00", "too long": strings.Repeat("я", 501)} { + _, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, sent.Version, "bad-"+name, domain.InvitationDeclineOther, &comment)) + if pointer := fieldPointer(t, err); pointer != "/comment" { + t.Errorf("%s: pointer = %s, want /comment", name, pointer) + } + } + if state := test.transactor.snapshot(); len(state.declineResults) != 0 || len(state.declines) != 0 { + t.Fatal("an invalid comment stored an outcome or a decline") + } +} diff --git a/backend/internal/usecase/invitation/decline.go b/backend/internal/usecase/invitation/decline.go new file mode 100644 index 0000000..6c30a9e --- /dev/null +++ b/backend/internal/usecase/invitation/decline.go @@ -0,0 +1,298 @@ +package invitation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// ErrAnswerBlocked reports a candidate answer that the state of the invitation +// or its deadline does not allow: a terminal state, another reason or comment +// on a declined invitation, a state without an open answer, or a command at +// the deadline or later. The API answers 409 state_conflict. +var ErrAnswerBlocked = errors.New("candidate invitation answer is not allowed") + +const ( + declineOperation = "candidate_invitation.decline" + declineLocation = "invitation.Service.DeclineMine" +) + +// DeclineCommand binds the session candidate and the path to one structured +// decline over the invitation version the client read. +type DeclineCommand struct { + ActorID uuid.UUID + InvitationID uuid.UUID + IdempotencyKey string + ExpectedVersion int64 + Choice domain.InvitationDeclineChoice +} + +type declineRequest struct { + fingerprint [outbound.IdempotencyDigestSize]byte + scope [outbound.IdempotencyDigestSize]byte + record outbound.IdempotencyRecord + now time.Time +} + +// declineOutcome is what a committed decline transaction decided: the +// invitation, or a refusal that the contract stores under the key and that +// the caller returns after the commit. +type declineOutcome struct { + view domain.CandidateInvitationView + refusal error +} + +// declineFingerprint is the canonical request of a decline. An absent comment +// and null are the same request. +type declineFingerprint struct { + InvitationID uuid.UUID `json:"invitation_id"` + ExpectedVersion int64 `json:"expected_version"` + Reason domain.InvitationDeclineReason `json:"reason"` + Comment *string `json:"comment"` +} + +// DeclineMine declines an invitation of the session candidate with a +// structured reason. In one transaction it checks the candidate, the key, +// the invitation, the repeat of the same decline, a terminal state or a +// passed deadline, the version, and the state, then moves the invitation to +// declined, stores the decline, and appends the audit event. The decline is +// the candidate's answer for the responsiveness metrics; it creates no +// consent and no contact grant, and the organization sees only the state and +// the time of the answer. +// +// Locks: the idempotency record of the candidate's own key and then only the +// invitation row, never the organization, as for the view. +func (service *Service) DeclineMine(ctx context.Context, command DeclineCommand) (domain.CandidateInvitationView, error) { + request, err := service.prepareDecline(command) + if err != nil { + return domain.CandidateInvitationView{}, err + } + var outcome declineOutcome + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + outcome, err = service.declineInTransaction(ctx, unit, command, request) + return err + }) + if err != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", declineLocation, err) + } + if outcome.refusal != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - %w", declineLocation, outcome.refusal) + } + return outcome.view, nil +} + +// prepareDecline validates the request before any storage is read, in the +// order of the contract: the request is validated before the account. +func (service *Service) prepareDecline(command DeclineCommand) (declineRequest, error) { + const location = "invitation.Service.prepareDecline" + switch { + case command.ActorID == uuid.Nil: + return declineRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden) + case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize: + return declineRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey) + case command.ExpectedVersion < 1: + return declineRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"}) + } + if err := command.Choice.Validate(); err != nil { + return declineRequest{}, fmt.Errorf("%s - validate choice: %w", location, err) + } + now, err := service.now(location) + if err != nil { + return declineRequest{}, err + } + // The fingerprint covers the path and the body, so one key used for + // another invitation, version, reason, or comment is a reused key. + canonical, err := json.Marshal(declineFingerprint{ + InvitationID: command.InvitationID, ExpectedVersion: command.ExpectedVersion, + Reason: command.Choice.Reason, Comment: command.Choice.Comment, + }) + if err != nil { + return declineRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, err) + } + fingerprint := service.keyring.Fingerprint(canonical) + scope := service.keyring.IdempotencyScope(declineOperation, command.IdempotencyKey, command.ActorID.String()) + return declineRequest{ + fingerprint: fingerprint, scope: scope, now: now, + record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)}, + }, nil +} + +// declineInTransaction follows the order of checks of the contract after the +// HTTP boundary: the account (403), the key (422 or a replay), the invitation +// (404, stored), the repeat of the same decline (200), a terminal state or a +// passed deadline (409 whatever the version, stored), the version (412, not +// stored), and any other state without an open answer (409, stored). +func (service *Service) declineInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command DeclineCommand, + request declineRequest, +) (declineOutcome, error) { + if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil { + return declineOutcome{}, err + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return declineOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", declineLocation, err) + } + if !created { + return replayDecline(ctx, unit, request, command, stored) + } + entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true) + if errors.Is(err, outbound.ErrInvitationNotFound) { + return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineNotFound) + } + if err != nil { + return declineOutcome{}, err + } + return service.declineFound(ctx, unit, command, request, entry) +} + +// declineFound applies the checks that follow a found invitation: the repeat +// of the same decline, a terminal state or a passed deadline, the version, +// and the state, and then stores the decline. +func (service *Service) declineFound( + ctx context.Context, + unit outbound.UnitOfWork, + command DeclineCommand, + request declineRequest, + entry outbound.CandidateInvitationEntry, +) (declineOutcome, error) { + current := entry.Invitation + at := notBefore(request.now, current.UpdatedAt()) + if current.State() == domain.InvitationDeclined { + previous, err := unit.Invitations().GetDecline(ctx, current.OrganizationID(), current.ID()) + if err != nil { + return declineOutcome{}, fmt.Errorf("%s - read decline: %w", declineLocation, err) + } + if previous.Choice.Equal(command.Choice) { + // The same decline answers with the invitation as it is, whatever + // the key or the version, and records nothing again. + return completeDecline(ctx, unit, request, entry) + } + return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict) + } + if current.IsTerminal() || current.ResponseDeadlinePassed(at) { + return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict) + } + if command.ExpectedVersion != current.Version() { + return declineOutcome{}, fmt.Errorf("%s - compare expected version: %w", declineLocation, domain.ErrInvitationVersionConflict) + } + declined, decline, err := current.Decline(command.Choice, at) + if errors.Is(err, domain.ErrInvitationNotAnswerable) { + return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict) + } + if err != nil { + return declineOutcome{}, fmt.Errorf("%s - decline invitation: %w", declineLocation, err) + } + event, err := declined.AnswerEvent(command.ActorID) + if err != nil { + return declineOutcome{}, fmt.Errorf("%s - build audit event: %w", declineLocation, err) + } + if err := unit.Invitations().Decline(ctx, current.Version(), declined, decline, event); err != nil { + if errors.Is(err, outbound.ErrInvitationVersionConflict) { + return declineOutcome{}, fmt.Errorf("%s - store decline: %w", declineLocation, domain.ErrInvitationVersionConflict) + } + return declineOutcome{}, fmt.Errorf("%s - store decline: %w", declineLocation, err) + } + entry.Invitation = declined + return completeDecline(ctx, unit, request, entry) +} + +// completeDecline stores the successful outcome under the key and builds the +// response with the stored decline. +func completeDecline( + ctx context.Context, + unit outbound.UnitOfWork, + request declineRequest, + entry outbound.CandidateInvitationEntry, +) (declineOutcome, error) { + view, err := candidateView(ctx, unit, entry) + if err != nil { + return declineOutcome{}, err + } + result := outbound.InvitationDeclineResult{InvitationID: entry.Invitation.ID(), Outcome: outbound.InvitationDeclineDeclined} + if err := finishDecline(ctx, unit, request, result); err != nil { + return declineOutcome{}, err + } + return declineOutcome{view: view}, nil +} + +// refuseDecline stores a refusal that the contract keeps under the key and +// lets the transaction commit, since nothing else was written. +func refuseDecline( + ctx context.Context, + unit outbound.UnitOfWork, + command DeclineCommand, + request declineRequest, + outcome outbound.InvitationDeclineOutcome, +) (declineOutcome, error) { + result := outbound.InvitationDeclineResult{InvitationID: command.InvitationID, Outcome: outcome} + if err := finishDecline(ctx, unit, request, result); err != nil { + return declineOutcome{}, err + } + return declineOutcome{refusal: declineRefusal(outcome)}, nil +} + +func finishDecline(ctx context.Context, unit outbound.UnitOfWork, request declineRequest, result outbound.InvitationDeclineResult) error { + if err := unit.InvitationDeclineResults().SaveDeclineResult(ctx, request.scope, result); err != nil { + return fmt.Errorf("%s - store outcome: %w", declineLocation, err) + } + if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { + return fmt.Errorf("%s - purge expired idempotency records: %w", declineLocation, err) + } + return nil +} + +func declineRefusal(outcome outbound.InvitationDeclineOutcome) error { + if outcome == outbound.InvitationDeclineNotFound { + return outbound.ErrInvitationNotFound + } + return ErrAnswerBlocked +} + +// replayDecline returns the stored outcome of the same request, or refuses a +// key used with another request. A stored success is rebuilt from the +// declined invitation and its decline: both are final, so the replay shows +// the same answer without a second copy of the comment. +func replayDecline( + ctx context.Context, + unit outbound.UnitOfWork, + request declineRequest, + command DeclineCommand, + stored outbound.IdempotencyRecord, +) (declineOutcome, error) { + if stored.Fingerprint != request.fingerprint { + return declineOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", declineLocation, ErrIdempotencyKeyReused) + } + original, err := unit.InvitationDeclineResults().GetDeclineResult(ctx, request.scope) + if err != nil { + return declineOutcome{}, fmt.Errorf("%s - read original outcome: %w", declineLocation, err) + } + if original.InvitationID != command.InvitationID { + return declineOutcome{}, fmt.Errorf("%s - validate original outcome: %w", declineLocation, domain.ErrInvalidInvitation) + } + if original.Outcome != outbound.InvitationDeclineDeclined { + return declineOutcome{refusal: declineRefusal(original.Outcome)}, nil + } + entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, false) + if err != nil { + return declineOutcome{}, err + } + if entry.Invitation.State() != domain.InvitationDeclined { + return declineOutcome{}, fmt.Errorf("%s - validate original response: %w", declineLocation, domain.ErrInvalidInvitation) + } + view, err := candidateView(ctx, unit, entry) + if err != nil { + return declineOutcome{}, err + } + return declineOutcome{view: view}, nil +} diff --git a/backend/internal/usecase/invitation/service.go b/backend/internal/usecase/invitation/service.go index af62a3c..7697e77 100644 --- a/backend/internal/usecase/invitation/service.go +++ b/backend/internal/usecase/invitation/service.go @@ -1,9 +1,11 @@ // 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. +// idempotent send that delivers a draft to the candidate's inbox. On the +// candidate's side it lists that inbox, reads one invitation, records the +// view, and records a structured decline. The acceptance, the cancellation, +// and the contact grant belong to later operations that build on the same +// records. package invitation import ( @@ -92,7 +94,7 @@ type Dependencies struct { } // Service applies organization-scoped invitation commands and reads, and the -// candidate's read of the own inbox. +// candidate's reads, view, and decline of the own invitations. type Service struct { transactor outbound.Transactor keyring Keyring diff --git a/backend/internal/usecase/invitation/service_test.go b/backend/internal/usecase/invitation/service_test.go index 5257597..6757718 100644 --- a/backend/internal/usecase/invitation/service_test.go +++ b/backend/internal/usecase/invitation/service_test.go @@ -43,6 +43,10 @@ type testState struct { results map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView sendResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult needVersions map[[3]string]bool + // declines holds the stored declines by invitation, and declineResults + // the decline outcomes kept under a key. + declines map[uuid.UUID]domain.InvitationDecline + declineResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult // charged lists the invitations charged against the organization quota, // and notified the delivered invitations that were notified. charged []uuid.UUID @@ -53,10 +57,12 @@ func newTestState() testState { return testState{ users: map[uuid.UUID]domain.User{}, memberships: map[[2]uuid.UUID]domain.Membership{}, 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{}, + 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{}, + declines: map[uuid.UUID]domain.InvitationDecline{}, + declineResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationDeclineResult{}, } } @@ -87,6 +93,12 @@ func (state testState) clone() testState { for key, found := range state.needVersions { cloned.needVersions[key] = found } + for id, decline := range state.declines { + cloned.declines[id] = decline + } + for scope, result := range state.declineResults { + cloned.declineResults[scope] = result + } cloned.charged = slices.Clone(state.charged) cloned.notified = slices.Clone(state.notified) return cloned @@ -143,6 +155,9 @@ func (unit *testUnit) InvitationCreationResults() outbound.InvitationCreationRes func (unit *testUnit) InvitationSendResults() outbound.InvitationSendResultRepository { return testInvitations{state: unit.state} } +func (unit *testUnit) InvitationDeclineResults() outbound.InvitationDeclineResultRepository { + return testInvitations{state: unit.state} +} type testUsers struct { outbound.UserRepository @@ -217,6 +232,7 @@ func (repository testIdempotency) PurgeExpired(_ context.Context, at time.Time, delete(repository.state.idempotency, scope) delete(repository.state.results, scope) delete(repository.state.sendResults, scope) + delete(repository.state.declineResults, scope) deleted++ } } diff --git a/backend/internal/usecase/invitation/view.go b/backend/internal/usecase/invitation/view.go new file mode 100644 index 0000000..270aab1 --- /dev/null +++ b/backend/internal/usecase/invitation/view.go @@ -0,0 +1,152 @@ +package invitation + +import ( + "context" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + getMineLocation = "invitation.Service.GetMine" + viewMineLocation = "invitation.Service.ViewMine" +) + +// GetMine reads one invitation delivered to the session candidate with the +// current terms. Reading has no side effect: it never records a view, so a +// prefetch or a cache refresh never changes what the organization sees. A +// draft, an invitation of another candidate, and an unknown identifier are +// not found alike. +func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) { + if actorID == uuid.Nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", getMineLocation, ErrForbidden) + } + var view domain.CandidateInvitationView + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, actorID); err != nil { + return err + } + entry, err := readCandidateEntry(ctx, unit, actorID, invitationID, false) + if err != nil { + return err + } + view, err = candidateView(ctx, unit, entry) + return err + }) + if err != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", getMineLocation, err) + } + return view, nil +} + +// ViewMine records that the session candidate opened the terms. A delivered +// invitation moves to viewed with the next version and keeps its deadline; +// every other state, and a view at the deadline or later, changes nothing and +// returns the invitation as it is. The command is idempotent by its effect, +// so it takes neither a key nor an expected version. +// +// Locks: only the invitation row, never the organization. A candidate +// command therefore never holds the row while it waits for an organization +// lock, and an organization command that holds the organization lock and +// waits for the row cannot deadlock with it. +func (service *Service) ViewMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) { + if actorID == uuid.Nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", viewMineLocation, ErrForbidden) + } + now, err := service.now(viewMineLocation) + if err != nil { + return domain.CandidateInvitationView{}, err + } + var view domain.CandidateInvitationView + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeCandidate(ctx, unit, actorID); err != nil { + return err + } + entry, err := readCandidateEntry(ctx, unit, actorID, invitationID, true) + if err != nil { + return err + } + current := entry.Invitation + viewed, changed, err := current.RecordView(notBefore(now, current.UpdatedAt())) + if err != nil { + return fmt.Errorf("%s - record view: %w", viewMineLocation, err) + } + if changed { + event, err := viewed.AnswerEvent(actorID) + if err != nil { + return fmt.Errorf("%s - build audit event: %w", viewMineLocation, err) + } + if err := unit.Invitations().RecordView(ctx, current.Version(), viewed, event); err != nil { + return fmt.Errorf("%s - store view: %w", viewMineLocation, err) + } + entry.Invitation = viewed + } + view, err = candidateView(ctx, unit, entry) + return err + }) + if err != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", viewMineLocation, err) + } + return view, nil +} + +// readCandidateEntry reads, and with forUpdate locks, a delivered invitation +// addressed to the candidate. The nil identifier finds nothing. +func readCandidateEntry( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, invitationID uuid.UUID, + forUpdate bool, +) (outbound.CandidateInvitationEntry, error) { + const location = "invitation.readCandidateEntry" + if invitationID == uuid.Nil { + return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - the nil identifier names no invitation: %w", location, outbound.ErrInvitationNotFound) + } + read := unit.Invitations().GetCandidateEntry + if forUpdate { + read = unit.Invitations().GetCandidateEntryForUpdate + } + entry, err := read(ctx, actorID, invitationID) + if err != nil { + return outbound.CandidateInvitationEntry{}, fmt.Errorf("%s - read invitation: %w", location, err) + } + return entry, nil +} + +// candidateView builds the candidate's response with the own decline of a +// declined invitation. The organization is shown by its current name even +// when the candidate has hidden the profile from it: the hiding stops the +// organization from seeing the candidate, while the candidate needs to know +// who sent the offer to answer it. Pushed content, such as the inbox +// notification, follows the hiding instead. +func candidateView(ctx context.Context, unit outbound.UnitOfWork, entry outbound.CandidateInvitationEntry) (domain.CandidateInvitationView, error) { + const location = "invitation.candidateView" + var decline *domain.InvitationDecline + if entry.Invitation.State() == domain.InvitationDeclined { + stored, err := unit.Invitations().GetDecline(ctx, entry.Invitation.OrganizationID(), entry.Invitation.ID()) + if err != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - read decline: %w", location, err) + } + decline = &stored + } + view, err := entry.Invitation.CandidateView(domain.InvitationOrganizationRef{ + ID: entry.Invitation.OrganizationID(), Name: entry.OrganizationName, + }, decline) + if err != nil { + return domain.CandidateInvitationView{}, fmt.Errorf("%s - build view: %w", location, err) + } + return view, nil +} + +// notBefore keeps a clock that stepped back from recording a change before +// the last one. +func notBefore(now, last time.Time) time.Time { + if now.Before(last) { + return last + } + return now +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 5313cd1..408264c 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -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 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`. +Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in [Sending invitations](#sending-invitations). Withdrawal, the salary raise, the contact read, the acceptance, and the cancellation still answer 501 after the common checks; the candidate's read, view, and decline are described in [Candidate view and decline](#candidate-view-and-decline). Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`. Tables: - `invitations`: UUIDv7 `id`, `organization_id`, the internal `candidate_id` (never serialized, logged, or printed), the optional need link (`need_id` with `need_requirements_version`, bound by composite foreign keys to a stored version of a need of the same organization), `state` (all fourteen states of the contract, so the later operations need no constraint change), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7, or 14), `policy_version_id` (the product policy version that allowed the period), `response_deadline_at`, `salary_raise_used`, `created_by`, and `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. CHECK constraints tie the deadline to the delivery (both set or both null), keep a draft free of delivery, view, answer, and raise, and tie the expiry reason to the state. A trigger keeps the identity columns, makes every UPDATE advance `version` by exactly one and `terms_version` by at most one, and refuses to undo a raise or to move the delivery, the deadline, or the period after a delivery. A second trigger refuses DELETE. The foreign keys to organizations, accounts, and policy versions are `ON DELETE RESTRICT`, so an account with invitations is undeletable until a deletion procedure settles them. - `invitation_terms_versions`: `(invitation_id, version)`, the terms as a JSONB snapshot, and the salary again in typed columns (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Constraints repeat the money rules in integers: both bounds from 1000 to 100 000 000 rubles in steps of 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B` (a width of 10% to 40% of the midpoint), RUB, month, and `net` or `gross`. The snapshot must hold all twelve terms and its salary must equal the typed columns. A trigger refuses UPDATE and DELETE: a version of the terms is immutable, and a change appends the next version. The invitation points at its current version by a deferred composite foreign key, so the first version is inserted in the same transaction. -- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created`, `draft_updated`, 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_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created`, `draft_updated`, since migration 00038 `delivered`, and since migration 00039 `viewed` and `declined`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only. - `invitation_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: @@ -982,10 +982,31 @@ Implemented: `SendOrganizationInvitation` and the candidate's list of invitation - 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. +Not implemented: the pending limit per need and the pause after a decline or a no deal (both planned in the contract), the acceptance and the cancellation (the read, the view, and the decline are in [Candidate view and decline](#candidate-view-and-decline)), 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`. +### Candidate view and decline + +Implemented: `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_answer.go`, `usecase/invitation/view.go` and `decline.go`, the HTTP handler `adapter/primary/http/v1/invitation_candidate.go`, the adapter `adapter/secondary/postgres/invitation_answer.go` with `db/queries/invitation_answers.sql`, and migration `00039_answer_invitations.sql`. + +- Read without a side effect. `GetMyInvitation` reads a delivered invitation by the candidate of the session and the invitation, with the current terms and the current name of the sending organization; it records nothing. The view is the explicit command `ViewMyInvitation`, as the contract requires, so a prefetch, a retry, or a cache refresh never changes what the organization sees. A draft, an invitation of another candidate, and an unknown identifier answer the same 404; an employer account answers 403. +- View. In `delivered` before the deadline the command moves the invitation to `viewed` with one conditional UPDATE (`state`, `version` plus one, `viewed_at`, `updated_at`), keeps `response_deadline_at`, and appends the audit event `viewed`. In every other state, and at the deadline or later, it changes nothing and answers 200 with the invitation as it is. It takes neither a key nor a version; concurrent views queue on the row lock, and the first one wins. +- Decline. Allowed from `delivered`, `viewed`, and the planned `counter` before the deadline. One transaction moves the invitation to the terminal `declined` (`responded_at`, `version` plus one), stores the reason and the optional comment in `invitation_declines`, appends the audit event `declined`, and keeps the outcome under the key. It writes no consent, no contact grant, and no outbox event. The comment follows the schema rule with the Unicode notion of white space and refuses control characters other than a line break or a tab, because PostgreSQL text cannot hold NUL (400 at `/comment`). +- Responsiveness. The `declined` event (`kind`, `version`, the candidate as `actor_id`, `occurred_at`) is the candidate's answer that the planned responsiveness metrics of the organization count. It is always in time, since a late decline is refused, and it is never a consent or a hire. It holds neither the reason nor the comment. +- Privacy of the decline. The organization reads only `declined` and `responded_at`: none of its operations reads `invitation_declines`, and the audit event names no reason. The comment is never logged, notified, or copied into the stored outcome; the candidate reads both back in `decline`. +- Order of checks after the boundary: the candidate (403), the key (422 or a replay), the invitation (404, stored), the same decline of a declined invitation (200 with a new key or an older version), another reason or comment on a declined invitation, any other terminal state, or a passed deadline (409 whatever the version, stored), the version (412, not stored), then a state without an open answer (409, stored). `invitation_decline_results` keeps only the outcome and the invitation: a declined invitation and its decline never change, so a replay rebuilds the same answer and the comment is stored once. +- Deadline. Expiry is not implemented yet, so no read or command applies the transition to `expired`. A view at the deadline or later changes nothing, and a decline at the deadline or later answers 409 `state_conflict`, as the contract requires for a late command; the invitation stays `delivered` or `viewed` with its passed deadline until the expiry arrives. The conditional UPDATEs repeat the deadline, so a command cannot cross it between the check and the write. +- Consent and grant. Acceptance is not implemented, so an acceptance is impossible now and `contact_consent` and `contact_grant` are always null, as the contract requires when no acceptance can be made. Both arrive with `AcceptMyInvitation`. +- Hiding. The candidate's read shows the sending organization even after the candidate hid the profile from it: the hiding keeps the organization from seeing the candidate, while the candidate must know who sent the offer to answer it. The pushed content follows the hiding instead: the inbox notice of the invitation loses its content (`ResolveInvitationNotice`). +- Locks. A candidate command locks only the invitation row (`LockCandidateInvitation`) after the candidate's own idempotency record, never the organization. An organization command takes the organization lock first and the invitation row afterwards, so the two orders never cross: a candidate command does not wait for an organization lock while it holds the row. +- Database rules of migration 00039: the event kinds `viewed` and `declined` without changed fields; `invitations_answer_matches_state` (a delivered invitation has no view or answer, a viewed one has its view, a declined one its answer, and neither precedes the delivery); the trigger `invitations_guard_answer`, which refuses to move or undo a view or an answer and to leave `declined`; `invitation_declines` with the known reasons, the comment bound, a trigger that ties the row to a declined invitation answered at the same moment, and a refusal of UPDATE and DELETE; and the deferred constraint trigger `invitations_require_decline`, so a declined invitation without its decline cannot commit. The down migration refuses while a view, a decline, or a stored outcome exists. +- Notification. The contract has no notification kind for an answer, so the organization gets no inbox entry for a view or a decline yet; it sees the state in its invitation list. A notice of the answer is planned as a contract change. + +Not implemented: the expiry at the deadline and its application on a read, the acceptance with C4 and the contact grant, the cancellation, the counter offer that would produce `counter`, the decline aggregates with a minimum group size, the responsiveness metrics, the 30-day pause after a decline, and a notification of the organization about an answer. + +Tests: `domain/invitation_answer_test.go` (the view only from `delivered` before the deadline, the decline from `delivered`, `viewed`, and `counter`, the refusal of terminal and late invitations, the comment rules, the stored answer rules, redaction), `usecase/invitation/answer_test.go` (no side effect of a read, the deadline kept, repeats, order of checks, foreign callers, invalid comments), `adapter/primary/http/v1/invitation_candidate_test.go` (statuses and a response without candidate data), and the integration tests `TestCandidateInvitationViewAndDeclineOverHTTP` (the read and the view with the same deadline, concurrent views with one event, a decline with `other` and no comment without a C4 consent, the stored answer event, replays and conflicts, the comment kept from the organization and the audit, foreign candidates and employers, CSRF and Origin, the hiding, a stale version, a late command) and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`. + ## 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/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index db5f172..f3e6653 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -941,13 +941,13 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове ### Черновики приглашений -Реализовано: сторона организации в черновике приглашения, то есть `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`. +Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет; отправка описана в [Отправке приглашений](#отправка-приглашений). Отзыв, повышение вилки, чтение контактов, принятие и отмена участия после общих проверок по-прежнему отвечают 501; чтение, просмотр и отказ кандидата описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата). Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`. Таблицы: - `invitations`: UUIDv7 `id`, `organization_id`, внутренний `candidate_id` (его не сериализуют, не логируют и не печатают), необязательная связь с потребностью (`need_id` с `need_requirements_version`, привязанные составными внешними ключами к сохраненной версии потребности той же организации), `state` (все четырнадцать состояний контракта, поэтому последующим операциям не нужно менять ограничение), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7 или 14), `policy_version_id` (версия продуктовой политики, разрешившая срок), `response_deadline_at`, `salary_raise_used`, `created_by`, а также `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. Ограничения CHECK связывают дедлайн с доставкой (оба заданы или оба null), оставляют черновик без доставки, просмотра, ответа и повышения и связывают причину истечения с состоянием. Триггер хранит неизменными столбцы идентичности, требует, чтобы каждый UPDATE увеличивал `version` ровно на единицу, а `terms_version` не более чем на единицу, и не дает отменить повышение или сдвинуть доставку, дедлайн и срок после доставки. Второй триггер запрещает DELETE. Внешние ключи на организации, аккаунты и версии политики - `ON DELETE RESTRICT`, поэтому аккаунт с приглашениями нельзя удалить, пока процедура удаления их не закроет. - `invitation_terms_versions`: `(invitation_id, version)`, условия в виде снимка JSONB и вилка еще раз в типизированных столбцах (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Ограничения повторяют денежные правила в целых числах: обе границы от 1000 до 100 000 000 рублей с шагом 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` и `5 * (B - A) <= A + B` (ширина 10-40% от середины), RUB, месяц и `net` или `gross`. Снимок обязан содержать все двенадцать условий, а его вилка - совпадать с типизированными столбцами. Триггер запрещает UPDATE и DELETE: версия условий неизменяема, изменение добавляет следующую версию. Приглашение указывает на текущую версию отложенным составным внешним ключом, поэтому первая версия вставляется в той же транзакции. -- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created`, `draft_updated` или, с миграции 00038, `delivered`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются. +- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created`, `draft_updated`, с миграции 00038 `delivered`, с миграции 00039 `viewed` и `declined`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются. - `invitation_creation_results`: исходный ответ идемпотентного создания, привязанный к общей записи идемпотентности и удаляемый вместе с ней. В нем условия, псевдоним и нет идентификатора кандидата. Решения: @@ -982,10 +982,31 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Доступ. Только владелец, как для черновиков: `ownerCompanyOperations` на HTTP-границе и та же проверка в транзакции; другие роли отправлять не могут. Список кандидата требует подтвержденный аккаунт кандидата, работодатель получает 403. - Порядок проверок после границы: владелец, ключ (422 или повтор), приглашение (404), завершенная отправка (200), версия (412), состояние и видимость (409), затем квота (429). -Не реализовано: предел ожидающих приглашений на потребность и пауза после отказа или "сделки нет" (оба запланированы в контракте), чтение одного приглашения кандидатом, просмотр и ответы, истечение по сроку, отправка писем-уведомлений, общий пул E0 холдинга в порте квоты и матрица ролей и назначений сверх владельца. +Не реализовано: предел ожидающих приглашений на потребность и пауза после отказа или "сделки нет" (оба запланированы в контракте), принятие и отмена участия (чтение, просмотр и отказ описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата)), истечение по сроку, отправка писем-уведомлений, общий пул 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`. +### Просмотр и отказ кандидата + +Реализовано: `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Код: `domain/invitation_answer.go`, `usecase/invitation/view.go` и `decline.go`, HTTP-обработчик `adapter/primary/http/v1/invitation_candidate.go`, адаптер `adapter/secondary/postgres/invitation_answer.go` с `db/queries/invitation_answers.sql` и миграция `00039_answer_invitations.sql`. + +- Чтение без побочного эффекта. `GetMyInvitation` читает доставленное приглашение по кандидату из сессии и приглашению, с текущими условиями и текущим названием организации-отправителя, и ничего не записывает. Просмотр - явная команда `ViewMyInvitation`, как требует контракт, поэтому предзагрузка, повтор или обновление кэша не меняют то, что видит организация. Черновик, приглашение другого кандидата и неизвестный идентификатор дают одинаковый 404; аккаунт работодателя получает 403. +- Просмотр. В `delivered` до срока команда переводит приглашение в `viewed` одним условным UPDATE (`state`, `version` плюс один, `viewed_at`, `updated_at`), сохраняет `response_deadline_at` и добавляет событие аудита `viewed`. В любом другом состоянии, а также в момент срока и позже, она ничего не меняет и отвечает 200 с приглашением как есть. Ключа и версии она не принимает; одновременные просмотры встают в очередь на блокировке строки, побеждает первый. +- Отказ. Разрешен из `delivered`, `viewed` и запланированного `counter` до срока. Одна транзакция переводит приглашение в терминальное `declined` (`responded_at`, `version` плюс один), сохраняет причину и необязательный комментарий в `invitation_declines`, добавляет событие аудита `declined` и хранит исход под ключом. Согласия, контактного разрешения и события outbox она не пишет. Комментарий проверяется по правилу схемы с юникодным понятием пробела и не принимает управляющие символы, кроме перевода строки и табуляции, потому что текст PostgreSQL не хранит NUL (400 по `/comment`). +- Отзывчивость. Событие `declined` (`kind`, `version`, кандидат в `actor_id`, `occurred_at`) - ответ кандидата, который будут считать запланированные метрики отзывчивости организации. Оно всегда своевременно, потому что опоздавший отказ отклоняется, и никогда не означает согласие или найм. Ни причины, ни комментария в нем нет. +- Приватность отказа. Организация читает только `declined` и `responded_at`: ни одна ее операция не читает `invitation_declines`, а событие аудита не называет причину. Комментарий не логируется, не попадает в уведомления и не копируется в сохраненный исход; кандидат читает причину и комментарий обратно в `decline`. +- Порядок проверок после границы: кандидат (403), ключ (422 или повтор), приглашение (404, сохраняется), тот же отказ на отклоненном приглашении (200 с новым ключом или старой версией), другая причина или комментарий на отклоненном приглашении, иное терминальное состояние или прошедший срок (409 при любой версии, сохраняется), версия (412, не сохраняется), затем состояние без открытого ответа (409, сохраняется). `invitation_decline_results` хранит только исход и приглашение: отклоненное приглашение и его отказ не меняются, поэтому повтор собирает тот же ответ, а комментарий хранится в одном месте. +- Срок. Истечение пока не реализовано, поэтому ни чтение, ни команда не выполняют переход в `expired`. Просмотр в момент срока и позже ничего не меняет, а отказ в момент срока и позже отвечает 409 `state_conflict`, как контракт требует для опоздавшей команды; приглашение остается `delivered` или `viewed` с прошедшим сроком, пока не появится истечение. Условные UPDATE повторяют проверку срока, поэтому команда не пересечет его между проверкой и записью. +- Согласие и разрешение. Принятие не реализовано, поэтому принять приглашение сейчас нельзя, и `contact_consent` и `contact_grant` всегда null, как требует контракт, когда принятие невозможно. Оба поля появятся вместе с `AcceptMyInvitation`. +- Скрытие. Чтение кандидата показывает организацию-отправителя и после того, как кандидат скрыл от нее профиль: скрытие не дает организации видеть кандидата, а кандидату нужно знать, кто прислал предложение, чтобы ответить. Исходящее содержимое, наоборот, следует скрытию: уведомление о приглашении во входящих теряет содержимое (`ResolveInvitationNotice`). +- Блокировки. Команда кандидата блокирует только строку приглашения (`LockCandidateInvitation`) после собственной записи идемпотентности кандидата и никогда не блокирует организацию. Команда организации берет сначала блокировку организации, а потом строку приглашения, поэтому порядки не пересекаются: команда кандидата не ждет блокировку организации, удерживая строку. +- Правила базы миграции 00039: виды событий `viewed` и `declined` без измененных полей; `invitations_answer_matches_state` (у доставленного приглашения нет просмотра и ответа, у просмотренного есть просмотр, у отклоненного есть ответ, и ни то ни другое не раньше доставки); триггер `invitations_guard_answer`, который не дает сдвинуть или отменить просмотр или ответ и выйти из `declined`; `invitation_declines` с известными причинами, границей комментария, триггером, который привязывает строку к отклоненному приглашению с тем же моментом ответа, и запретом UPDATE и DELETE; отложенный ограничивающий триггер `invitations_require_decline`, чтобы отклоненное приглашение без записи отказа не зафиксировалось. Откат миграции отказывает, пока есть просмотр, отказ или сохраненный исход. +- Уведомление. В контракте нет вида уведомления об ответе, поэтому организация пока не получает записи во входящих о просмотре или отказе; состояние она видит в своем списке приглашений. Уведомление об ответе запланировано как изменение контракта. + +Не реализовано: истечение по сроку и его применение при чтении, принятие с C4 и контактное разрешение, отмена участия, встречное предложение, которое дало бы `counter`, агрегаты причин отказа с минимальным размером группы, метрики отзывчивости, 30-дневная пауза после отказа и уведомление организации об ответе. + +Тесты: `domain/invitation_answer_test.go` (просмотр только из `delivered` до срока, отказ из `delivered`, `viewed` и `counter`, отклонение терминальных и опоздавших приглашений, правила комментария, правила сохраненного ответа, маскирование), `usecase/invitation/answer_test.go` (чтение без побочного эффекта, сохранение срока, повторы, порядок проверок, чужие вызывающие, неверные комментарии), `adapter/primary/http/v1/invitation_candidate_test.go` (статусы и ответ без данных кандидата) и интеграционные `TestCandidateInvitationViewAndDeclineOverHTTP` (чтение и просмотр с тем же сроком, одновременные просмотры с одним событием, отказ с `other` без комментария и без согласия C4, сохраненное событие ответа, повторы и конфликты, комментарий скрыт от организации и аудита, чужие кандидаты и работодатели, CSRF и Origin, скрытие, устаревшая версия, опоздавшая команда) и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.