diff --git a/api/README.en.md b/api/README.en.md index adb9ff6..fb26547 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 operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. +The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The organization side of the draft is implemented: `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` follow the rules below, except that `salary_fit` is always `not_available` and the salary limit and the withheld counter are not enforced yet ([backend](../backend/README.en.md#invitation-drafts)). The business logic of the other operations is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | diff --git a/api/README.md b/api/README.md index e943f3b..1397d5e 100644 --- a/api/README.md +++ b/api/README.md @@ -459,7 +459,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Приглашения и контактные разрешения -Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 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#черновики-приглашений)). Бизнес-логика остальных операций еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | diff --git a/backend/README.en.md b/backend/README.en.md index 465ad2a..2a3beff 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -34,7 +34,7 @@ Revoking C2 makes the publication effectively closed and hides its fields throug `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}`, and `PATCH /api/v1/organizations/{org_id}` are implemented. A verified employer creates the organization and its active owner membership in one transaction, starting at `e0` with basis `confirmed_email`. Every read checks active owner membership. Only the active owner can edit; the version advances on change and the verification level is preserved. -The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Invitation routes still enforce the common owner check before the 501 fallback; their business operations remain unimplemented. +The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Invitation routes enforce the common owner check; the draft operations are described under [Invitation drafts](#invitation-drafts), and the other invitation operations answer 501 after that check. `TestOrganizationCreationAndOwnerEditingOverHTTP` checks concurrent replay, rollback on owner insertion failure, cross-account denial, persisted reads after rebuilding the API, and reuse of an expired key against PostgreSQL. @@ -54,6 +54,16 @@ Source text is parsed locally by deterministic rules into unconfirmed suggestion Migration `00026_create_organization_need_creation_results.sql` adds create-response storage and 8 KiB of database representation headroom for JSONB whitespace. The compact domain snapshot limit remains 256 KiB. Its down migration refuses to discard live replay results or restore the previous database bound over larger stored snapshots. Check those conditions before rollback; it does not remove need history to make a downgrade succeed. +## Invitation drafts + +The organization side of the invitation draft is implemented: `GET` and `POST /api/v1/organizations/{org_id}/invitations` and `GET` and `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` (`usecase/invitation/`, `adapter/primary/http/v1/invitation.go`). Sending, withdrawal, the salary raise, the contact read, and the candidate operations still answer 501 after the common owner check. A draft is invisible to the candidate and writes no inbox row, event, or quota usage. + +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). + +`candidateview.Service.ResolveCandidateHandle` resolves the handle in the create transaction with the checks of a card read (membership, effective C2 publication, hiding of the organization, minimum cohort) and charges no quota. An unknown handle, a handle of another organization, a hidden or unpublished candidate, and a suppressed card give the same 400 at `/candidate_handle`. The create is idempotent for 24 hours and replays the stored 201. An update answers 200 for a body that changes nothing, then compares the version (412), then the state (409), then the rules (400). Both commands take the organization lock before the membership and invitation locks. `salary_fit` is `not_available` until the limit against probing the minimum exists. + +The integration tests `TestOrganizationInvitationDraftsOverHTTP` (the router, sessions, CSRF, cohort and hiding fixtures, money boundaries, package conditions, handle refusals, replay, anti-enumeration, listing and cursors, versions and immutable terms, need links, the state conflict, concurrent updates, concurrent creates and updates of one organization without a deadlock, and no candidate value in responses, stored terms, or logs), `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` (the constraints and triggers by direct SQL), and `TestInvitationMigrationRollbackKeepsStoredInvitations` run against a real PostgreSQL. + ## 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 da76e06..63ba982 100644 --- a/backend/README.md +++ b/backend/README.md @@ -34,7 +34,7 @@ Реализованы `POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}` и `PATCH /api/v1/organizations/{org_id}`. Подтвержденный работодатель создает организацию и активное членство владельца одной транзакцией; начальный уровень - `e0` с основанием `confirmed_email`. Каждое чтение проверяет активное членство владельца. Изменять профиль может только активный владелец; версия повышается при изменении, уровень проверки сохраняется. -Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Пути приглашений защищены общей проверкой владельца до ответа 501; их бизнес-операции пока не реализованы. +Одинаковые `Idempotency-Key` и тело возвращают исходный снимок `201` в течение 24 часов, даже после редактирования профиля. Миграция `00019_create_organization_creation_results.sql` хранит снимок отдельно от действующей организации. 24 часа задают логическое окно повтора. Ограниченная очистка запускается при успешных созданиях; физическое удаление может произойти позже и удаляет снимок вместе с общей записью idempotency. `GET /api/v1/me/organizations` постранично возвращает активные членства текущего работодателя. Пути приглашений защищены общей проверкой владельца; операции с черновиками описаны в разделе [Черновики приглашений](#черновики-приглашений), остальные операции приглашений после этой проверки отвечают 501. `TestOrganizationCreationAndOwnerEditingOverHTTP` проверяет в PostgreSQL параллельный повтор, откат при ошибке вставки владельца, запрет чужого доступа, сохранение данных после пересоздания API и повторное использование истекшего ключа. @@ -54,6 +54,16 @@ Миграция `00026_create_organization_need_creation_results.sql` добавляет хранение ответа создания и запас 8 KiB для пробелов в представлении JSONB. Ограничение компактного доменного снимка остается 256 KiB. Обратная миграция отказывается удалять действующие результаты повторов или восстанавливать прежний предел БД поверх более крупных сохраненных снимков. Перед откатом нужно проверить эти условия; история потребностей не удаляется ради успешного отката. +## Черновики приглашений + +Реализована сторона организации в черновике приглашения: `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#приглашения-и-контактные-разрешения). + +`candidateview.Service.ResolveCandidateHandle` разрешает handle в транзакции создания проверками чтения карточки (членство, действующая публикация C2, скрытие организации, минимальная когорта) и не списывает квоту. Неизвестный handle, handle другой организации, скрытый или неопубликованный кандидат и подавленная карточка дают один и тот же 400 на `/candidate_handle`. Создание идемпотентно 24 часа и повторяет сохраненный 201. Изменение отвечает 200 на тело, которое ничего не меняет, затем сравнивает версию (412), затем состояние (409), затем правила (400). Обе команды берут блокировку организации до блокировок членства и приглашения. `salary_fit` равен `not_available`, пока нет лимита против подбора минимума. + +Интеграционные тесты `TestOrganizationInvitationDraftsOverHTTP` (роутер, сессии, CSRF, фикстуры когорты и скрытия, границы денег, условия пакета, отказы по handle, повтор, защита от перебора, список и курсоры, версии и неизменяемые условия, связь с потребностью, конфликт состояния, конкурентные изменения, конкурентные создания и изменения одной организации без взаимной блокировки и отсутствие значений кандидата в ответах, сохраненных условиях и логах), `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` (ограничения и триггеры прямым SQL) и `TestInvitationMigrationRollbackKeepsStoredInvitations` работают на настоящем PostgreSQL. + ## Обращения в поддержку Подтвержденные аккаунты создают и просматривают список собственных обращений через `/api/v1/me/support-cases`, а отдельное дело читают по его ID. Владение обращением не зависит от доступа к спорному действию. Ссылка на объект содержит только тип и ID; сервер проверяет область доступа и не копирует приватное содержимое объекта. Работодатели отправляют общие запросы поддержки. Кандидаты также могут запросить ручную оценку без предыдущей попытки и согласия C3. Такой запрос ожидает эксперта, не назначает грейд и не выдает согласие. diff --git a/backend/db/migrations/00037_create_invitations.sql b/backend/db/migrations/00037_create_invitations.sql new file mode 100644 index 0000000..43bc5a3 --- /dev/null +++ b/backend/db/migrations/00037_create_invitations.sql @@ -0,0 +1,349 @@ +-- +goose Up +-- Invitation storage. An invitation names one candidate for one organization. +-- Its terms live in immutable numbered versions: every change of the terms +-- appends the next version, and the invitation row only points at the current +-- one. The salary range is kept in typed columns next to the JSON snapshot, so +-- the database itself refuses a range that breaks the money rules. Amounts are +-- whole rubles, as in the API contract; there are no minor units and no +-- floating-point columns. +-- +-- The candidate column is internal. API responses show the candidate only +-- through the organization-scoped alias that the server derives on every read. +CREATE TABLE invitations ( + id uuid NOT NULL, + organization_id uuid NOT NULL, + candidate_id uuid NOT NULL, + need_id uuid, + need_requirements_version bigint, + state text NOT NULL, + expiry_reason text, + version bigint NOT NULL, + terms_version bigint NOT NULL, + response_period_days smallint NOT NULL, + -- The product policy that allowed the chosen response period. + policy_version_id uuid NOT NULL, + response_deadline_at timestamptz, + salary_raise_used boolean NOT NULL DEFAULT FALSE, + created_by uuid NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + delivered_at timestamptz, + viewed_at timestamptz, + responded_at timestamptz, + CONSTRAINT invitations_pkey PRIMARY KEY (id), + CONSTRAINT invitations_organization_id_id_key UNIQUE (organization_id, id), + CONSTRAINT invitations_organization_fkey FOREIGN KEY (organization_id) + REFERENCES organizations (id) ON DELETE RESTRICT, + -- A candidate with invitations cannot be deleted until a deletion + -- procedure settles them, like an account with consent evidence. + CONSTRAINT invitations_candidate_fkey FOREIGN KEY (candidate_id) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT invitations_created_by_fkey FOREIGN KEY (created_by) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT invitations_policy_version_fkey FOREIGN KEY (policy_version_id) + REFERENCES policy_versions (id) ON DELETE RESTRICT, + -- The need link is informational and must name a requirements version + -- that the need of the same organization has stored. + CONSTRAINT invitations_need_fkey FOREIGN KEY (organization_id, need_id) + REFERENCES organization_needs (organization_id, id) ON DELETE RESTRICT, + CONSTRAINT invitations_need_version_fkey FOREIGN KEY ( + organization_id, need_id, need_requirements_version + ) REFERENCES organization_need_versions (organization_id, need_id, version) + ON DELETE RESTRICT, + CONSTRAINT invitations_need_pair CHECK ( + (need_id IS NULL) = (need_requirements_version IS NULL) + ), + CONSTRAINT invitations_state_known CHECK ( + state IN ( + 'draft', 'delivered', 'viewed', 'counter', 'accepted', + 'interview_scheduled', 'interviewed', 'negotiation', + 'terms_agreed', 'no_deal', 'declined', 'expired', 'withdrawn', + 'cancelled_by_candidate' + ) + ), + CONSTRAINT invitations_expiry_reason CHECK ( + (state = 'expired') = (expiry_reason IS NOT NULL) + AND ( + expiry_reason IS NULL + OR expiry_reason IN ('invitation_timeout', 'negotiation_timeout') + ) + ), + CONSTRAINT invitations_version_positive CHECK (version > 0), + CONSTRAINT invitations_terms_version_range CHECK ( + terms_version > 0 AND terms_version <= version + ), + CONSTRAINT invitations_response_period CHECK ( + response_period_days IN (3, 7, 14) + ), + -- The deadline starts with the first delivery and is set together with it. + CONSTRAINT invitations_deadline_with_delivery CHECK ( + (response_deadline_at IS NULL) = (delivered_at IS NULL) + AND (response_deadline_at IS NULL OR response_deadline_at > delivered_at) + ), + -- A draft is invisible to the candidate and has no delivery, view, + -- answer, or raise yet. + CONSTRAINT invitations_draft_is_unsent CHECK ( + state <> 'draft' + OR ( + delivered_at IS NULL + AND viewed_at IS NULL + AND responded_at IS NULL + AND NOT salary_raise_used + ) + ), + CONSTRAINT invitations_timestamps CHECK (updated_at >= created_at) +); + +CREATE TABLE invitation_terms_versions ( + invitation_id uuid NOT NULL, + organization_id uuid NOT NULL, + version bigint NOT NULL, + terms jsonb NOT NULL, + salary_from bigint NOT NULL, + salary_to bigint NOT NULL, + salary_currency text NOT NULL, + salary_period text NOT NULL, + salary_tax_basis text NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT invitation_terms_versions_pkey PRIMARY KEY (invitation_id, version), + CONSTRAINT invitation_terms_versions_invitation_fkey FOREIGN KEY ( + organization_id, invitation_id + ) REFERENCES invitations (organization_id, id) ON DELETE RESTRICT, + CONSTRAINT invitation_terms_versions_version_positive CHECK (version > 0), + -- Money rules (PRD FR13) in integer arithmetic: positive bounds that are + -- multiples of 1000, A < B, and a width 2 * (B - A) / (A + B) from 10% to + -- 40%, that is 20 * (B - A) >= A + B and 5 * (B - A) <= A + B. The bounds + -- are capped at 100 000 000 rubles, so no product overflows. + CONSTRAINT invitation_terms_versions_salary_bounds CHECK ( + salary_from BETWEEN 1000 AND 100000000 + AND salary_to BETWEEN 1000 AND 100000000 + AND salary_from % 1000 = 0 + AND salary_to % 1000 = 0 + AND salary_from < salary_to + ), + CONSTRAINT invitation_terms_versions_salary_width CHECK ( + 20 * (salary_to - salary_from) >= salary_from + salary_to + AND 5 * (salary_to - salary_from) <= salary_from + salary_to + ), + CONSTRAINT invitation_terms_versions_salary_basis CHECK ( + salary_currency = 'RUB' + AND salary_period = 'month' + AND salary_tax_basis IN ('net', 'gross') + ), + -- The snapshot is a complete object whose salary equals the typed columns. + -- jsonb::text adds structural whitespace, so the size bound leaves room. + CONSTRAINT invitation_terms_versions_snapshot_shape CHECK ( + jsonb_typeof(terms) = 'object' + AND terms ?& ARRAY[ + 'role_title', 'specialization', 'grade', 'offer_type', 'tasks', + 'team', 'tech_stack', 'work_formats', 'location', + 'communication_method', 'salary', 'package' + ] + AND jsonb_typeof(terms -> 'salary') = 'object' + AND CASE + WHEN jsonb_typeof(terms #> '{salary,salary_from}') = 'number' + AND jsonb_typeof(terms #> '{salary,salary_to}') = 'number' + THEN (terms #>> '{salary,salary_from}') = salary_from::text + AND (terms #>> '{salary,salary_to}') = salary_to::text + ELSE FALSE + END + AND (terms #>> '{salary,currency}') = salary_currency + AND (terms #>> '{salary,period}') = salary_period + AND (terms #>> '{salary,tax_basis}') = salary_tax_basis + AND octet_length(terms::text) <= 131072 + ) +); + +-- The current terms version must exist for the same invitation. Deferral lets +-- creation insert the invitation and its first terms in one transaction. +ALTER TABLE invitations + ADD CONSTRAINT invitations_current_terms_fkey + FOREIGN KEY (id, terms_version) + REFERENCES invitation_terms_versions (invitation_id, version) + DEFERRABLE INITIALLY DEFERRED; + +-- The changed fields of an audit event are a duplicate-free subset of the +-- editable parts of a draft. +-- +goose StatementBegin +CREATE FUNCTION invitation_changed_fields_are_valid(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + fields <@ ARRAY['terms', 'need', 'response_period_days']::text [] + AND array_position(fields, NULL) IS NULL + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +-- One audit event per committed invitation version. The event names the +-- actor and what changed, never the content: the terms are in their own +-- immutable versions. +CREATE TABLE invitation_events ( + id uuid NOT NULL, + invitation_id uuid NOT NULL, + organization_id uuid NOT NULL, + version bigint NOT NULL, + terms_version bigint NOT NULL, + kind text NOT NULL, + actor_id uuid NOT NULL, + changed_fields text [] NOT NULL, + occurred_at timestamptz NOT NULL, + CONSTRAINT invitation_events_pkey PRIMARY KEY (id), + CONSTRAINT invitation_events_version_key UNIQUE (invitation_id, version), + CONSTRAINT invitation_events_invitation_fkey FOREIGN KEY ( + organization_id, invitation_id + ) REFERENCES invitations (organization_id, id) ON DELETE RESTRICT, + CONSTRAINT invitation_events_actor_fkey FOREIGN KEY (actor_id) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT invitation_events_terms_version_fkey FOREIGN KEY ( + invitation_id, terms_version + ) REFERENCES invitation_terms_versions (invitation_id, version) + ON DELETE RESTRICT, + CONSTRAINT invitation_events_version_positive CHECK ( + version > 0 AND terms_version > 0 AND terms_version <= version + ), + CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ('draft_created', 'draft_updated') + ), + CONSTRAINT invitation_events_creation_is_first CHECK ( + (kind = 'draft_created') = (version = 1) + ), + CONSTRAINT invitation_events_changed_fields CHECK ( + invitation_changed_fields_are_valid(changed_fields) + ) +); + +-- Original response of an idempotent create, kept beside the generic +-- idempotency record and removed with it after the 24-hour replay window. +-- The live invitation is intentionally not a foreign key. +CREATE TABLE invitation_creation_results ( + scope_hash bytea NOT NULL, + snapshot jsonb NOT NULL, + CONSTRAINT invitation_creation_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT invitation_creation_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT invitation_creation_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT invitation_creation_results_snapshot_bounded CHECK ( + jsonb_typeof(snapshot) = 'object' + AND octet_length(snapshot::text) <= 196608 + ) +); + +-- Newest-first list of one organization. +CREATE INDEX invitations_organization_created_idx +ON invitations (organization_id, created_at DESC, id DESC); + +-- Pair rules of the organization and the candidate, such as the pause after a +-- decline, read the invitations of one pair. +CREATE INDEX invitations_organization_candidate_idx +ON invitations (organization_id, candidate_id, created_at DESC); + +-- The candidate's inbox reads the invitations that were delivered to them. +CREATE INDEX invitations_candidate_delivered_idx +ON invitations (candidate_id, delivered_at DESC, id DESC) +WHERE delivered_at IS NOT NULL; + +-- Identity and history rules. An invitation is never deleted, its identity +-- never changes, every committed change advances the version by one, a terms +-- version advances by at most one, and a raise or a deadline is never undone. +-- TRUNCATE remains available to reset isolated integration databases. +-- +goose StatementBegin +CREATE FUNCTION invitations_guard_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.organization_id IS DISTINCT FROM OLD.organization_id + OR NEW.candidate_id IS DISTINCT FROM OLD.candidate_id + OR NEW.created_by IS DISTINCT FROM OLD.created_by + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_identity_immutable', + TABLE = 'invitations', + MESSAGE = 'invitation identity is immutable'; + END IF; + IF NEW.version <> OLD.version + 1 + OR (NEW.terms_version <> OLD.terms_version AND NEW.terms_version <> OLD.terms_version + 1) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_version_step', + TABLE = 'invitations', + MESSAGE = 'invitation versions advance by exactly one step'; + END IF; + IF (OLD.salary_raise_used AND NOT NEW.salary_raise_used) + OR (OLD.delivered_at IS NOT NULL AND ( + NEW.delivered_at IS DISTINCT FROM OLD.delivered_at + OR NEW.response_deadline_at IS DISTINCT FROM OLD.response_deadline_at + OR NEW.response_period_days IS DISTINCT FROM OLD.response_period_days + )) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_history_immutable', + TABLE = 'invitations', + MESSAGE = 'a raise, a delivery, and a deadline are never undone'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitations_guard_update +BEFORE UPDATE ON invitations +FOR EACH ROW EXECUTE FUNCTION invitations_guard_update(); + +-- Terms versions and audit events are append-only. +-- +goose StatementBegin +CREATE FUNCTION invitations_refuse_history_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = TG_TABLE_NAME || '_immutable', + TABLE = TG_TABLE_NAME, + MESSAGE = 'invitation history is append-only: add a new version instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitations_refuse_delete +BEFORE DELETE ON invitations +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +CREATE TRIGGER invitation_terms_versions_immutable +BEFORE UPDATE OR DELETE ON invitation_terms_versions +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +CREATE TRIGGER invitation_events_immutable +BEFORE UPDATE OR DELETE ON invitation_events +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +-- +goose Down +-- A rollback must not silently remove stored invitations or their history. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitations) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_retained', + TABLE = 'invitations', + MESSAGE = 'invitations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TABLE invitation_creation_results; +DROP TABLE invitation_events; +ALTER TABLE invitations DROP CONSTRAINT invitations_current_terms_fkey; +DROP TABLE invitation_terms_versions; +DROP TABLE invitations; +DROP FUNCTION invitation_changed_fields_are_valid(text []); +DROP FUNCTION invitations_refuse_history_change(); +DROP FUNCTION invitations_guard_update(); diff --git a/backend/db/queries/invitations.sql b/backend/db/queries/invitations.sql new file mode 100644 index 0000000..a202050 --- /dev/null +++ b/backend/db/queries/invitations.sql @@ -0,0 +1,224 @@ +-- The invitation row, its first terms version, and its first audit event are +-- inserted in one caller-owned transaction. The deferred reference to the +-- current terms version is checked when the transaction commits. +-- name: InsertInvitation :exec +INSERT INTO invitations ( + id, + organization_id, + candidate_id, + need_id, + need_requirements_version, + state, + version, + terms_version, + response_period_days, + policy_version_id, + created_by, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(organization_id), + sqlc.arg(candidate_id), + sqlc.narg(need_id), + sqlc.narg(need_requirements_version), + sqlc.arg(state), + sqlc.arg(version), + sqlc.arg(terms_version), + sqlc.arg(response_period_days), + sqlc.arg(policy_version_id), + sqlc.arg(created_by), + sqlc.arg(created_at), + sqlc.arg(updated_at) +); + +-- name: InsertInvitationTermsVersion :exec +INSERT INTO invitation_terms_versions ( + invitation_id, + organization_id, + version, + terms, + salary_from, + salary_to, + salary_currency, + salary_period, + salary_tax_basis, + created_at +) VALUES ( + sqlc.arg(invitation_id), + sqlc.arg(organization_id), + sqlc.arg(version), + sqlc.arg(terms)::jsonb, + sqlc.arg(salary_from), + sqlc.arg(salary_to), + sqlc.arg(salary_currency), + sqlc.arg(salary_period), + sqlc.arg(salary_tax_basis), + sqlc.arg(created_at) +); + +-- name: InsertInvitationEvent :exec +INSERT INTO invitation_events ( + id, + invitation_id, + organization_id, + version, + terms_version, + kind, + actor_id, + changed_fields, + occurred_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(invitation_id), + sqlc.arg(organization_id), + sqlc.arg(version), + sqlc.arg(terms_version), + sqlc.arg(kind), + sqlc.arg(actor_id), + sqlc.arg(changed_fields)::text [], + sqlc.arg(occurred_at) +); + +-- Read one current invitation with its terms snapshot. Both the organization +-- and the invitation scope the row, so another organization's identifier +-- finds nothing. +-- name: ReadInvitation :one +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +WHERE + invitation.organization_id = sqlc.arg(organization_id) + AND invitation.id = sqlc.arg(invitation_id); + +-- Takes the row lock of one invitation. It is a statement of its own, ahead of +-- ReadInvitation, because a locking read that joins the terms table is +-- re-checked against the new row version after a wait and then pairs the +-- updated terms_version with the terms row it fetched before the wait, which +-- finds nothing. Once the lock is held, the following read sees the committed +-- state and no writer can change it. +-- name: LockInvitation :one +SELECT id +FROM invitations +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) +FOR UPDATE; + +-- Read one historical terms version of one invitation of one organization. +-- name: ReadInvitationTermsVersion :one +SELECT terms::text AS terms +FROM invitation_terms_versions +WHERE + organization_id = sqlc.arg(organization_id) + AND invitation_id = sqlc.arg(invitation_id) + AND version = sqlc.arg(version); + +-- One bounded newest-first page. Both the organization scope and the tuple +-- cursor are applied before the limit. +-- name: ListInvitations :many +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +WHERE + invitation.organization_id = sqlc.arg(organization_id) + AND ( + sqlc.narg(after_created_at)::timestamptz IS NULL + OR (invitation.created_at, invitation.id) < ( + sqlc.narg(after_created_at)::timestamptz, + sqlc.narg(after_invitation_id)::uuid + ) + ) +ORDER BY invitation.created_at DESC, invitation.id DESC +LIMIT sqlc.arg(row_limit); + +-- The conditional update is the compare-and-swap of a draft: it applies only +-- to a draft whose version is still the one the caller read, and advances the +-- version by one. No row is returned when it lost a race or the invitation +-- left the draft state. +-- name: AdvanceInvitationDraft :one +UPDATE invitations +SET + need_id = sqlc.narg(need_id), + need_requirements_version = sqlc.narg(need_requirements_version), + response_period_days = sqlc.arg(response_period_days), + policy_version_id = sqlc.arg(policy_version_id), + terms_version = sqlc.arg(terms_version), + version = sqlc.arg(next_version), + updated_at = sqlc.arg(updated_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state = 'draft' + AND version = sqlc.arg(expected_version) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- A requirements version that a need of the organization has had is the +-- version number of a stored snapshot whose own requirements version is that +-- number, so a later edit that only renamed the need is not accepted. +-- name: InvitationNeedVersionExists :one +SELECT EXISTS ( + SELECT 1 + FROM organization_need_versions + WHERE + organization_id = sqlc.arg(organization_id) + AND need_id = sqlc.arg(need_id) + AND version = sqlc.arg(requirements_version)::bigint + AND snapshot ->> 'requirements_version' = sqlc.arg(requirements_version)::bigint::text +) AS found; + +-- name: SaveInvitationCreationResult :exec +INSERT INTO invitation_creation_results (scope_hash, snapshot) +VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)::jsonb) +ON CONFLICT (scope_hash) DO UPDATE +SET snapshot = excluded.snapshot; + +-- name: GetInvitationCreationResult :one +SELECT snapshot::text AS snapshot +FROM invitation_creation_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/integration_test/invitation_http_test.go b/backend/integration_test/invitation_http_test.go new file mode 100644 index 0000000..3e43fef --- /dev/null +++ b/backend/integration_test/invitation_http_test.go @@ -0,0 +1,1109 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + invitationusecase "lincodex/backend/internal/usecase/invitation" + needusecase "lincodex/backend/internal/usecase/need" + "lincodex/backend/internal/usecase/organization" + "lincodex/backend/internal/usecase/policy" +) + +const invitationHTTPTimeout = 10 * time.Minute + +// Private values of the visible candidates. None of them may appear in any +// response, problem, or log of the organization's invitation operations. +const ( + invitationCandidateName = "Hidden Candidate Name" + invitationCandidateContact = "hidden-candidate-contact@example.test" + invitationCandidateMarker = "Hidden Candidate Employer" +) + +type invitationHTTPHarness struct { + *sessionHTTPHarness + + key domain.CandidateViewPseudonymKey +} + +func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *invitationHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + transactor := postgresadapter.NewTransactor(pool) + sessionService, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, + Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, + AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{Transactor: transactor, Keyring: keyring, Clock: clock.Now}) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + needService, err := needusecase.NewService(needusecase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: clock.Now}) + if err != nil { + t.Fatalf("need.NewService() error = %v", err) + } + quota := companyquota.NewService(clock.Now) + views, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: transactor, Projector: anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(pool), key, clock.Now), + PseudonymKey: key, Clock: clock.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + invitationService, err := invitationusecase.NewService(invitationusecase.Dependencies{ + Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, Clock: clock.Now, + }) + if err != nil { + t.Fatalf("invitation.NewService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessionService), v1.WithPublicOrigin(env.Config.AppPublicURL)) + organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), + v1.WithNeed(v1.NewNeedHandler(needService)), v1.WithInvitation(v1.NewInvitationHandler(invitationService)), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &invitationHTTPHarness{ + sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}, + key: key, + } +} + +// invitationHTTPBody is the part of the organization's invitation that the +// tests read. Fields that must be absent have no member, so a leak shows up as +// an unknown key in the raw text that the tests also scan. +type invitationHTTPBody struct { + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"organization_id"` + CandidateHandle string `json:"candidate_handle"` + Need *struct { + NeedID uuid.UUID `json:"need_id"` + RequirementsVersion int64 `json:"requirements_version"` + } `json:"need"` + State string `json:"state"` + ExpiryReason *string `json:"expiry_reason"` + Version int64 `json:"version"` + TermsVersion int64 `json:"terms_version"` + Terms json.RawMessage `json:"terms"` + ResponsePeriodDays int `json:"response_period_days"` + ResponseDeadlineAt *string `json:"response_deadline_at"` + SalaryRaiseUsed bool `json:"salary_raise_used"` + SalaryFit string `json:"salary_fit"` + ContactAccess struct { + Status string `json:"status"` + Fields []string `json:"fields"` + } `json:"contact_access"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + DeliveredAt *string `json:"delivered_at"` + ViewedAt *string `json:"viewed_at"` + RespondedAt *string `json:"responded_at"` +} + +type invitationHTTPPage struct { + Items []struct { + ID uuid.UUID `json:"id"` + CandidateHandle string `json:"candidate_handle"` + State string `json:"state"` + Version int64 `json:"version"` + TermsVersion int64 `json:"terms_version"` + RoleTitle string `json:"role_title"` + Salary struct { + SalaryFrom int64 `json:"salary_from"` + SalaryTo int64 `json:"salary_to"` + TaxBasis string `json:"tax_basis"` + } `json:"salary"` + } `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +type invitationHTTPProblem struct { + Code string `json:"code"` + Errors []struct { + In string `json:"in"` + Pointer string `json:"pointer"` + Code string `json:"code"` + } `json:"errors"` +} + +func invitationTermsMap() map[string]any { + return map[string]any{ + "role_title": "Middle Go developer in the payments team", + "specialization": "backend", + "grade": "middle", + "offer_type": "full_time", + "tasks": []any{"Move the payout service to an event model", "Review the changes of the team"}, + "team": "Six engineers and a team lead\nwho work in two-week iterations", + "tech_stack": []any{"Go", "PostgreSQL"}, + "work_formats": []any{"remote"}, + "location": nil, + "communication_method": map[string]any{ + "channel": "email", "details": nil, + }, + "salary": map[string]any{ + "salary_from": 100000, "salary_to": 140000, "currency": "RUB", "period": "month", "tax_basis": "net", + }, + "package": map[string]any{ + "bonus": map[string]any{"status": "provided", "description": "Quarterly bonus up to 20% of the salary"}, + "equipment": map[string]any{"status": "provided", "description": "Laptop of the employee's choice"}, + "training": map[string]any{"status": "not_provided"}, + "health_insurance": map[string]any{"status": "not_provided"}, + }, + } +} + +// invitationCreateJSON builds a create request for the handle and lets the +// caller change the request or its terms before it is encoded. +func invitationCreateJSON(t *testing.T, handle string, change func(body, terms map[string]any)) string { + t.Helper() + terms := invitationTermsMap() + body := map[string]any{"candidate_handle": handle, "terms": terms} + if change != nil { + change(body, terms) + } + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal invitation request: %v", err) + } + return string(encoded) +} + +func invitationSalary(terms map[string]any) map[string]any { return terms["salary"].(map[string]any) } + +func decodeInvitationHTTP(t *testing.T, response *httptest.ResponseRecorder, wantStatus int) invitationHTTPBody { + 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 invitationHTTPBody + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode invitation %s: %v", response.Body.String(), err) + } + return body +} + +func requireInvitationValidation(t *testing.T, response *httptest.ResponseRecorder, wantPointer, wantFieldCode string) { + t.Helper() + if response.Code != http.StatusBadRequest { + t.Fatalf("response = %d %s, want 400 validation_failed at %s", response.Code, response.Body.String(), wantPointer) + } + var body invitationHTTPProblem + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode problem %s: %v", response.Body.String(), err) + } + if body.Code != "validation_failed" { + t.Fatalf("problem code = %q in %s, want validation_failed", body.Code, response.Body.String()) + } + for _, field := range body.Errors { + if field.Pointer == wantPointer && (wantFieldCode == "" || field.Code == wantFieldCode) { + return + } + } + t.Fatalf("problem %s has no error at %s with code %q", response.Body.String(), wantPointer, wantFieldCode) +} + +func invitationCount(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, table string) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM "+table).Scan(&count); err != nil { + t.Fatalf("count %s: %v", table, err) + } + return count +} + +type invitationStoredCounts struct{ invitations, termsVersions, events, results int } + +func readInvitationCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness) invitationStoredCounts { + t.Helper() + return invitationStoredCounts{ + invitations: invitationCount(ctx, t, harness, "invitations"), + termsVersions: invitationCount(ctx, t, harness, "invitation_terms_versions"), + events: invitationCount(ctx, t, harness, "invitation_events"), + results: invitationCount(ctx, t, harness, "invitation_creation_results"), + } +} + +func TestOrganizationInvitationDraftsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolated := *env + isolated.Config.DatabaseURL = databaseURL + setupPool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + harness := newInvitationHTTPHarness(ctx, t, &isolated) + // The policy takes effect when it is stored, after the clock of the + // harness was first read. + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) + origin := env.Config.AppPublicURL + now := harness.clock.Now() + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + account := func(email string, scenario domain.Scenario) domain.User { + return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) + } + ownerA, ownerB, ownerC := account("invite-owner-a@example.test", domain.ScenarioEmployer), + account("invite-owner-b@example.test", domain.ScenarioEmployer), account("invite-owner-c@example.test", domain.ScenarioEmployer) + recruiter := account("invite-recruiter@example.test", domain.ScenarioEmployer) + candidateAccount := account("invite-candidate-account@example.test", domain.ScenarioCandidate) + sessionA, sessionB, sessionC := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()), + loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()), loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerC.Email.Address()) + sessionRecruiter := loginOrganizationHTTP(t, harness.sessionHTTPHarness, recruiter.Email.Address()) + sessionCandidate := loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidateAccount.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionA, "invite-company-a") + orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionB, "invite-company-b") + orgC := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionC, "invite-company-c") + insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA, recruiter.ID, "recruiter", "active", now) + + // The candidates of the cards. Seven identical published candidates form + // the visible cohort; the hiding and the revocation below remove them from + // one organization at a time. + 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} + newVisibleCandidate := func(email string, publish bool) domain.User { + candidate := privacy.candidate(t, email) + verifyPrivacyCohortCandidate(t, privacy, candidate) + consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now) + if publish { + 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) + } + return candidate + } + cohort := make([]domain.User, 0, 7) + for index := range 7 { + cohort = append(cohort, newVisibleCandidate(fmt.Sprintf("invite-visible-%d@example.test", index), true)) + } + unpublished := newVisibleCandidate("invite-unpublished@example.test", false) + revoked := newVisibleCandidate("invite-revoked@example.test", true) + privacy.revokeC2(t, revoked.ID, now.Add(time.Minute)) + hiddenFromA, hiddenFromB := cohort[0], cohort[1] + privacy.hide(t, hiddenFromA.ID, orgA, now) + privacy.hide(t, hiddenFromB.ID, orgB, now) + for _, candidate := range cohort[2:5] { + privacy.hide(t, candidate.ID, orgC, now) + } + 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 + } + // Organization C sees four candidates, below the minimum cohort of five, + // so none of its cards exists. + suppressedForC := alias(orgC, cohort[5]) + // A usable candidate of organization A, and the same person as B sees them. + target := cohort[3] + handleA, handleB := alias(orgA, target), alias(orgB, target) + if handleA == handleB { + t.Fatal("the same candidate has one handle in two organizations") + } + + createPath := func(organizationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID) + } + itemPath := func(organizationID, invitationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID) + } + 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-http-key-%d", keySequence) + } + createDraft := func(organizationID uuid.UUID, session organizationHTTPSession, handle string, change func(body, terms map[string]any)) *httptest.ResponseRecorder { + t.Helper() + return request(http.MethodPost, createPath(organizationID), invitationCreateJSON(t, handle, change), session, nextKey()) + } + mustCreate := func(change func(body, terms map[string]any)) invitationHTTPBody { + t.Helper() + return decodeInvitationHTTP(t, createDraft(orgA, sessionA, handleA, change), http.StatusCreated) + } + candidateMarkers := []string{ + invitationCandidateName, invitationCandidateContact, invitationCandidateMarker, + target.ID.String(), unpublished.ID.String(), revoked.ID.String(), hiddenFromA.ID.String(), + } + requireNoCandidateData := func(label string, text string) { + t.Helper() + for _, marker := range candidateMarkers { + if strings.Contains(text, marker) { + t.Errorf("%s contains the private marker %q: %s", label, marker, text) + } + } + for _, field := range []string{"candidate_id", "email", "phone", "telegram", "full_name", "salary_minimum", "minimum"} { + if strings.Contains(text, `"`+field+`":`) { + t.Errorf("%s contains the key %q: %s", label, field, text) + } + } + } + + t.Run("stores a complete draft with its first terms version and audit", func(t *testing.T) { + response := createDraft(orgA, sessionA, handleA, nil) + created := decodeInvitationHTTP(t, response, http.StatusCreated) + if created.ID == uuid.Nil || created.OrganizationID != orgA || created.State != "draft" || created.Version != 1 || created.TermsVersion != 1 || + created.ResponsePeriodDays != 7 || created.ResponseDeadlineAt != nil || created.DeliveredAt != nil || created.ViewedAt != nil || + created.RespondedAt != nil || created.ExpiryReason != nil || created.Need != nil || created.SalaryRaiseUsed { + t.Fatalf("created draft = %+v, want an unsent version 1 with the default period", created) + } + if created.CandidateHandle != handleA || created.SalaryFit != "not_available" || + created.ContactAccess.Status != "not_granted" || len(created.ContactAccess.Fields) != 0 { + t.Fatalf("created draft names %q, fit %q, access %+v; want the card handle, no indicator, and no access", created.CandidateHandle, created.SalaryFit, created.ContactAccess) + } + requireNoCandidateData("created draft", response.Body.String()) + + var candidateID uuid.UUID + var state string + var version, termsVersion int64 + if err := harness.pool.QueryRow(ctx, `SELECT candidate_id, state, version, terms_version FROM invitations WHERE id = $1`, created.ID). + Scan(&candidateID, &state, &version, &termsVersion); err != nil { + t.Fatalf("read the stored draft: %v", err) + } + if candidateID != target.ID || state != "draft" || version != 1 || termsVersion != 1 { + t.Fatalf("stored draft = candidate %s state %s version %d/%d, want the resolved candidate in a version 1 draft", candidateID, state, version, termsVersion) + } + var from, to int64 + var currency, period, basis string + if err := harness.pool.QueryRow(ctx, `SELECT salary_from, salary_to, salary_currency, salary_period, salary_tax_basis + FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, created.ID).Scan(&from, &to, ¤cy, &period, &basis); err != nil { + t.Fatalf("read the stored terms version: %v", err) + } + if from != 100000 || to != 140000 || currency != "RUB" || period != "month" || basis != "net" { + t.Fatalf("stored money = %d-%d %s %s %s, want whole rubles with their base", from, to, currency, period, basis) + } + var kind string + var eventVersion, eventTerms int64 + var actor uuid.UUID + var changed []string + if err := harness.pool.QueryRow(ctx, `SELECT kind, version, terms_version, actor_id, changed_fields FROM invitation_events WHERE invitation_id = $1`, created.ID). + Scan(&kind, &eventVersion, &eventTerms, &actor, &changed); err != nil { + t.Fatalf("read the audit event: %v", err) + } + if kind != "draft_created" || eventVersion != 1 || eventTerms != 1 || actor != ownerA.ID || len(changed) != 0 { + t.Fatalf("audit event = %s %d/%d by %s changed %v, want a creation by the owner", kind, eventVersion, eventTerms, actor, changed) + } + + read := request(http.MethodGet, itemPath(orgA, created.ID), "", sessionA, "") + reread := decodeInvitationHTTP(t, read, http.StatusOK) + requireNoCandidateData("read draft", read.Body.String()) + if string(reread.Terms) != string(created.Terms) || reread.Version != 1 || reread.CandidateHandle != handleA { + t.Fatalf("read draft differs from the created one: %s", read.Body.String()) + } + }) + + t.Run("accepts an explicit package of conditions that are not provided and refuses a left-out condition", func(t *testing.T) { + none := func(body, terms map[string]any) { + terms["package"] = map[string]any{ + "bonus": map[string]any{"status": "not_provided"}, "equipment": map[string]any{"status": "not_provided"}, + "training": map[string]any{"status": "not_provided"}, "health_insurance": map[string]any{"status": "not_provided"}, + } + } + created := mustCreate(none) + if !strings.Contains(string(created.Terms), `"training":{"status":"not_provided"}`) { + t.Fatalf("stored package = %s, want the explicit choice back", created.Terms) + } + before := readInvitationCounts(ctx, t, harness) + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + delete(terms["package"].(map[string]any), "training") + }), "/terms/package/training", "required") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["package"].(map[string]any)["bonus"] = map[string]any{"status": "provided"} + }), "/terms/package/bonus/description", "required") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["package"].(map[string]any)["equipment"] = map[string]any{"status": "not_provided", "description": "Laptop"} + }), "/terms/package/equipment", "invalid") + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused packages stored rows: %+v -> %+v", before, after) + } + }) + + t.Run("requires the base, the currency, whole thousands, and a width of 10 to 40 percent", func(t *testing.T) { + before := readInvitationCounts(ctx, t, harness) + cases := []struct { + name string + change func(terms map[string]any) + pointer string + }{ + {"no tax basis", func(terms map[string]any) { delete(invitationSalary(terms), "tax_basis") }, "/terms/salary/tax_basis"}, + {"unknown tax basis", func(terms map[string]any) { invitationSalary(terms)["tax_basis"] = "before_tax" }, "/terms/salary/tax_basis"}, + {"zero lower bound", func(terms map[string]any) { invitationSalary(terms)["salary_from"] = 0 }, "/terms/salary/salary_from"}, + {"lower bound off the step", func(terms map[string]any) { invitationSalary(terms)["salary_from"] = 100500 }, "/terms/salary/salary_from"}, + {"upper bound off the step", func(terms map[string]any) { invitationSalary(terms)["salary_to"] = 140500 }, "/terms/salary/salary_to"}, + {"fractional bound", func(terms map[string]any) { invitationSalary(terms)["salary_from"] = 100000.5 }, "/terms/salary/salary_from"}, + {"foreign currency", func(terms map[string]any) { invitationSalary(terms)["currency"] = "USD" }, "/terms/salary/currency"}, + {"yearly period", func(terms map[string]any) { invitationSalary(terms)["period"] = "year" }, "/terms/salary/period"}, + {"equal bounds", func(terms map[string]any) { invitationSalary(terms)["salary_to"] = 100000 }, "/terms/salary/salary_to"}, + {"reversed bounds", func(terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 140000, 100000 + }, "/terms/salary/salary_to"}, + {"just below 10 percent", func(terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 95000, 104000 + }, "/terms/salary/salary_to"}, + {"just above 40 percent", func(terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 80000, 121000 + }, "/terms/salary/salary_to"}, + {"far too wide", func(terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 1000, 100000000 + }, "/terms/salary/salary_to"}, + } + for _, test := range cases { + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { test.change(terms) }), test.pointer, "") + } + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused ranges stored rows: %+v -> %+v", before, after) + } + + // The exact boundaries are accepted and stored without rounding. + for _, boundary := range []struct{ from, to int }{{95000, 105000}, {80000, 120000}, {100000, 140000}} { + created := mustCreate(func(body, terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = boundary.from, boundary.to + }) + var from, to int64 + if err := harness.pool.QueryRow(ctx, `SELECT salary_from, salary_to FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, created.ID).Scan(&from, &to); err != nil { + t.Fatalf("read the stored range: %v", err) + } + if from != int64(boundary.from) || to != int64(boundary.to) { + t.Fatalf("stored range = %d-%d, want %d-%d", from, to, boundary.from, boundary.to) + } + } + // The gross base is as valid as the net base and is kept as chosen. + gross := mustCreate(func(body, terms map[string]any) { invitationSalary(terms)["tax_basis"] = "gross" }) + if !strings.Contains(string(gross.Terms), `"tax_basis":"gross"`) { + t.Fatalf("gross draft terms = %s", gross.Terms) + } + }) + + t.Run("applies the other rules of the terms with the pointer of the field", func(t *testing.T) { + before := readInvitationCounts(ctx, t, harness) + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["work_formats"] = []any{"remote", "office"} + }), "/terms/location", "") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["tech_stack"] = []any{"Go", "PostgreSQL", "GO"} + }), "/terms/tech_stack/2", "") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["role_title"] = "Bad\u0000title" + }), "/terms/role_title", "") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + delete(terms, "communication_method") + }), "/terms/communication_method", "required") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + body["response_period_days"] = 5 + }), "/response_period_days", "") + // A request cannot name the candidate by anything but the handle, set + // the state, a version, an indicator, or the candidate's minimum. + for _, field := range []string{"candidate_email", "state", "version", "salary_fit", "salary_minimum", "candidate_id"} { + response := createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { body[field] = "x" }) + if response.Code != http.StatusBadRequest { + t.Errorf("a request with %s = %d %s, want 400", field, response.Code, response.Body.String()) + } + } + withLocation := mustCreate(func(body, terms map[string]any) { + terms["work_formats"] = []any{"remote", "hybrid"} + terms["location"] = "Kazan" + body["response_period_days"] = 14 + }) + if withLocation.ResponsePeriodDays != 14 || !strings.Contains(string(withLocation.Terms), `"location":"Kazan"`) { + t.Fatalf("draft with a place of work = %+v", withLocation) + } + if after := readInvitationCounts(ctx, t, harness); after.invitations != before.invitations+1 { + t.Fatalf("rules stored %d invitations, want only the valid one", after.invitations-before.invitations) + } + }) + + t.Run("resolves the handle through the visibility barrier and shows nothing of a refused card", func(t *testing.T) { + before := readInvitationCounts(ctx, t, harness) + refused := map[string]string{ + "a handle of another organization": handleB, + "a candidate hidden from the company": alias(orgA, hiddenFromA), + "a candidate who revoked C2": alias(orgA, revoked), + "a candidate who never published": alias(orgA, unpublished), + "an unknown handle": "cv1_" + strings.Repeat("Z", 43), + } + var shapes []string + for name, handle := range refused { + response := createDraft(orgA, sessionA, handle, nil) + requireInvitationValidation(t, response, "/candidate_handle", "") + requireNoCandidateData(name, response.Body.String()) + var body invitationHTTPProblem + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode refusal: %v", err) + } + shapes = append(shapes, fmt.Sprint(body)) + } + // Every refusal looks the same, so the answer does not tell which case + // applied. + for _, shape := range shapes[1:] { + if shape != shapes[0] { + t.Fatalf("refusals differ: %s and %s", shapes[0], shape) + } + } + // The cohort of organization C is below the minimum, so no card of it + // exists and its handles are refused. + requireInvitationValidation(t, createDraft(orgC, sessionC, suppressedForC, nil), "/candidate_handle", "") + // A malformed handle is refused by the schema. + if response := createDraft(orgA, sessionA, "not-a-handle", nil); response.Code != http.StatusBadRequest { + t.Fatalf("malformed handle = %d %s, want 400", response.Code, response.Body.String()) + } + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused handles stored rows: %+v -> %+v", before, after) + } + // The organization that owns the handle can use it, for its own + // invitation only. + own := decodeInvitationHTTP(t, createDraft(orgB, sessionB, handleB, nil), http.StatusCreated) + if own.OrganizationID != orgB || own.CandidateHandle != handleB { + t.Fatalf("organization B draft = %+v, want its own handle", own) + } + // The same person is a different pseudonym for each organization. + if own.CandidateHandle == handleA { + t.Fatal("two organizations share a handle") + } + }) + + t.Run("replays an idempotent create and refuses a reused key", func(t *testing.T) { + before := readInvitationCounts(ctx, t, harness) + path := createPath(orgA) + body := invitationCreateJSON(t, handleA, func(body, terms map[string]any) { terms["role_title"] = "Idempotent role" }) + responses := parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, path, body, origin, sessionA, "invitation-replay-key", 2) + if responses[0].Code != http.StatusCreated || responses[1].Code != http.StatusCreated || + responses[0].Body.String() != responses[1].Body.String() { + t.Fatalf("concurrent creates = %d %s and %d %s, want one identical 201", responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) + } + original := responses[0].Body.String() + created := decodeInvitationHTTP(t, responses[0], http.StatusCreated) + after := readInvitationCounts(ctx, t, harness) + if after.invitations != before.invitations+1 || after.events != before.events+1 || after.results != before.results+1 { + t.Fatalf("two creates with one key stored %+v -> %+v, want one draft", before, after) + } + + // A change of the draft does not change the replayed response. + update := `{"expected_version":1,"response_period_days":3}` + decodeInvitationHTTP(t, request(http.MethodPatch, itemPath(orgA, created.ID), update, sessionA, ""), http.StatusOK) + replay := request(http.MethodPost, path, body, sessionA, "invitation-replay-key") + if replay.Code != http.StatusCreated || replay.Body.String() != original { + t.Fatalf("replay = %d %s, want the original 201", replay.Code, replay.Body.String()) + } + // The candidate stops being visible: the stored response is replayed, + // while a new key is refused. + privacy.hide(t, target.ID, orgA, now) + defer func() { + if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1 AND organization_id = $2`, target.ID, orgA); err != nil { + t.Errorf("lift the hiding: %v", err) + } + }() + if replay := request(http.MethodPost, path, body, sessionA, "invitation-replay-key"); replay.Code != http.StatusCreated || replay.Body.String() != original { + t.Fatalf("replay after hiding = %d %s, want the original 201", replay.Code, replay.Body.String()) + } + requireInvitationValidation(t, request(http.MethodPost, path, body, sessionA, "invitation-after-hiding"), "/candidate_handle", "") + + changed := invitationCreateJSON(t, handleA, func(body, terms map[string]any) { terms["role_title"] = "Another role" }) + requireSessionProblem(t, request(http.MethodPost, path, changed, sessionA, "invitation-replay-key"), http.StatusUnprocessableEntity, "idempotency_key_reused") + if final := readInvitationCounts(ctx, t, harness); final.invitations != after.invitations { + t.Fatalf("replays and refusals stored %d invitations", final.invitations-after.invitations) + } + // The key is scoped by organization: the same key in B is a new request. + fromB := createDraft(orgB, sessionB, handleB, nil) + if fromB.Code != http.StatusCreated { + t.Fatalf("organization B create = %d %s", fromB.Code, fromB.Body.String()) + } + missingKey := request(http.MethodPost, path, body, sessionA, "") + requireInvitationValidation(t, missingKey, "/Idempotency-Key", "") + }) + + t.Run("answers every unauthorized caller without revealing an invitation", func(t *testing.T) { + created := mustCreate(nil) + own := itemPath(orgA, created.ID) + before := readInvitationCounts(ctx, t, harness) + + requireSessionProblem(t, request(http.MethodGet, own, "", organizationHTTPSession{}, ""), http.StatusUnauthorized, "unauthenticated") + requireSessionProblem(t, request(http.MethodGet, own, "", sessionCandidate, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodGet, own, "", sessionRecruiter, ""), http.StatusForbidden, "forbidden") + // The owner of another organization and an unknown invitation both + // answer 404 not_found with the same body shape. + foreignRead := request(http.MethodGet, own, "", sessionB, "") + requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") + unknownRead := request(http.MethodGet, itemPath(orgA, uuid.New()), "", sessionA, "") + requireSessionProblem(t, unknownRead, http.StatusNotFound, "not_found") + // An invitation of organization A is not readable through organization + // B's own path either. + requireSessionProblem(t, request(http.MethodGet, itemPath(orgB, created.ID), "", sessionB, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodGet, createPath(orgA), "", sessionB, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodGet, createPath(orgA), "", sessionCandidate, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodGet, createPath(orgA), "", sessionRecruiter, ""), http.StatusForbidden, "forbidden") + if foreignRead.Code != unknownRead.Code { + t.Fatalf("foreign and unknown invitations answer %d and %d", foreignRead.Code, unknownRead.Code) + } + if response := request(http.MethodGet, itemPath(orgA, uuid.Nil), "", sessionA, ""); response.Code != http.StatusNotFound { + t.Fatalf("nil invitation identifier = %d %s, want 404", response.Code, response.Body.String()) + } + if response := request(http.MethodGet, createPath(orgA)+"/not-a-uuid", "", sessionA, ""); response.Code != http.StatusBadRequest { + t.Fatalf("malformed invitation identifier = %d %s, want 400", response.Code, response.Body.String()) + } + + // Commands: the CSRF token and the origin are required, and a role that + // does not own the organization changes nothing. + body := invitationCreateJSON(t, handleA, nil) + noCSRF := organizationHTTPSession{cookie: sessionA.cookie} + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, noCSRF, nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, createPath(orgA), body, + "https://attacker.example", sessionA, nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, sessionRecruiter, nextKey()), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, sessionCandidate, nextKey()), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, sessionB, nextKey()), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, organizationHTTPSession{}, nextKey()), http.StatusUnauthorized, "unauthenticated") + patch := `{"expected_version":1,"response_period_days":3}` + requireSessionProblem(t, request(http.MethodPatch, own, patch, noCSRF, ""), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, request(http.MethodPatch, own, patch, sessionRecruiter, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPatch, own, patch, sessionCandidate, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPatch, own, patch, sessionB, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodPatch, itemPath(orgA, uuid.New()), patch, sessionA, ""), http.StatusNotFound, "not_found") + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("unauthorized calls stored rows: %+v -> %+v", before, after) + } + current := decodeInvitationHTTP(t, request(http.MethodGet, own, "", sessionA, ""), http.StatusOK) + if current.Version != 1 || current.ResponsePeriodDays != 7 { + t.Fatalf("an unauthorized patch changed the draft: %+v", current) + } + }) + + t.Run("lists the invitations of the organization newest first with a bound cursor", func(t *testing.T) { + list := func(organizationID uuid.UUID, session organizationHTTPSession, query string) (*httptest.ResponseRecorder, invitationHTTPPage) { + t.Helper() + response := request(http.MethodGet, createPath(organizationID)+query, "", session, "") + var page invitationHTTPPage + if response.Code == http.StatusOK { + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode page %s: %v", response.Body.String(), err) + } + } + return response, page + } + total := invitationCount(ctx, t, harness, "invitations WHERE organization_id = '"+orgA.String()+"'") + seen := map[uuid.UUID]bool{} + var previous time.Time + query := "?limit=3" + for { + response, page := list(orgA, sessionA, query) + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || len(page.Items) == 0 { + t.Fatalf("list = %d %s", response.Code, response.Body.String()) + } + requireNoCandidateData("list", response.Body.String()) + for _, item := range page.Items { + if seen[item.ID] || !strings.HasPrefix(item.CandidateHandle, "cv1_") || item.State != "draft" || item.RoleTitle == "" || item.Salary.TaxBasis == "" { + t.Fatalf("listed item %+v is repeated or incomplete", item) + } + var createdAt time.Time + if err := harness.pool.QueryRow(ctx, `SELECT created_at FROM invitations WHERE id = $1 AND organization_id = $2`, item.ID, orgA).Scan(&createdAt); err != nil { + t.Fatalf("listed item %s is not an invitation of the organization: %v", item.ID, err) + } + if !previous.IsZero() && createdAt.After(previous) { + t.Fatalf("list is not newest first: %s after %s", createdAt, previous) + } + previous = createdAt + seen[item.ID] = true + } + if !page.Page.HasMore { + break + } + if page.Page.NextCursor == nil { + t.Fatal("a page with more items has no cursor") + } + query = "?limit=3&cursor=" + url.QueryEscape(*page.Page.NextCursor) + } + if len(seen) != total { + t.Fatalf("pages listed %d invitations, want %d", len(seen), total) + } + // A cursor belongs to its reader and organization. + _, first := list(orgA, sessionA, "?limit=1") + if first.Page.NextCursor == nil { + t.Fatal("no cursor to test") + } + for name, response := range map[string]*httptest.ResponseRecorder{ + "another organization": request(http.MethodGet, createPath(orgB)+"?cursor="+url.QueryEscape(*first.Page.NextCursor), "", sessionB, ""), + "a forged cursor": request(http.MethodGet, createPath(orgA)+"?cursor="+url.QueryEscape(*first.Page.NextCursor+"AA"), "", sessionA, ""), + } { + if response.Code != http.StatusBadRequest { + t.Errorf("%s: list = %d %s, want 400", name, response.Code, response.Body.String()) + } + } + if response, _ := list(orgA, sessionA, "?limit=0"); response.Code != http.StatusBadRequest { + t.Errorf("limit 0 = %d, want 400", response.Code) + } + // Organization B sees only its own invitations. + _, others := list(orgB, sessionB, "") + for _, item := range others.Items { + if seen[item.ID] { + t.Fatalf("organization B lists the invitation %s of organization A", item.ID) + } + } + }) + + t.Run("updates a draft with versions, immutable terms versions, and a no-op rule", func(t *testing.T) { + draft := mustCreate(func(body, terms map[string]any) { terms["role_title"] = "Versioned role" }) + path := itemPath(orgA, draft.ID) + harness.clock.Advance(time.Minute) + + newTerms := invitationTermsMap() + newTerms["role_title"] = "Versioned role, second terms" + invitationSalary(newTerms)["salary_to"] = 150000 + body, err := json.Marshal(map[string]any{"expected_version": 1, "terms": newTerms}) + if err != nil { + t.Fatalf("marshal update: %v", err) + } + updated := decodeInvitationHTTP(t, request(http.MethodPatch, path, string(body), sessionA, ""), http.StatusOK) + if updated.Version != 2 || updated.TermsVersion != 2 || !strings.Contains(string(updated.Terms), "second terms") || !updated.UpdatedAt.After(draft.UpdatedAt) { + t.Fatalf("updated draft = %+v, want version 2 with terms version 2", updated) + } + + // Both terms versions are stored; the first is the original text. + var firstRole, secondRole string + var firstTo, secondTo int64 + for version, target := range map[int]struct { + role *string + to *int64 + }{1: {&firstRole, &firstTo}, 2: {&secondRole, &secondTo}} { + if err := harness.pool.QueryRow(ctx, `SELECT terms ->> 'role_title', salary_to FROM invitation_terms_versions WHERE invitation_id = $1 AND version = $2`, + draft.ID, version).Scan(target.role, target.to); err != nil { + t.Fatalf("read terms version %d: %v", version, err) + } + } + if firstRole != "Versioned role" || firstTo != 140000 || secondRole != "Versioned role, second terms" || secondTo != 150000 { + t.Fatalf("terms versions = (%q, %d) and (%q, %d), want the original and the new terms", firstRole, firstTo, secondRole, secondTo) + } + var kind string + var changed []string + var termsOfEvent int64 + if err := harness.pool.QueryRow(ctx, `SELECT kind, changed_fields, terms_version FROM invitation_events WHERE invitation_id = $1 AND version = 2`, draft.ID). + Scan(&kind, &changed, &termsOfEvent); err != nil { + t.Fatalf("read the update event: %v", err) + } + if kind != "draft_updated" || !slices.Equal(changed, []string{"terms"}) || termsOfEvent != 2 { + t.Fatalf("update event = %s %v terms %d, want draft_updated for the terms", kind, changed, termsOfEvent) + } + + // A body that changes nothing answers 200 with the current draft, even + // with a stale version, and creates no version. + before := readInvitationCounts(ctx, t, harness) + for _, stale := range []int{1, 2} { + noop, err := json.Marshal(map[string]any{"expected_version": stale, "terms": newTerms}) + if err != nil { + t.Fatalf("marshal no-op: %v", err) + } + repeated := decodeInvitationHTTP(t, request(http.MethodPatch, path, string(noop), sessionA, ""), http.StatusOK) + if repeated.Version != 2 || repeated.TermsVersion != 2 { + t.Fatalf("no-op with version %d = %+v, want the current version 2", stale, repeated) + } + } + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("no-op updates stored rows: %+v -> %+v", before, after) + } + + // A stale version is a 412 and nothing is changed or stored. + stale, err := json.Marshal(map[string]any{"expected_version": 1, "response_period_days": 3}) + if err != nil { + t.Fatalf("marshal stale update: %v", err) + } + requireSessionProblem(t, request(http.MethodPatch, path, string(stale), sessionA, ""), http.StatusPreconditionFailed, "version_conflict") + // A stale version beats a rule violation. + invalidTerms := invitationTermsMap() + invitationSalary(invalidTerms)["salary_to"] = 500000 + staleInvalid, _ := json.Marshal(map[string]any{"expected_version": 1, "terms": invalidTerms}) + requireSessionProblem(t, request(http.MethodPatch, path, string(staleInvalid), sessionA, ""), http.StatusPreconditionFailed, "version_conflict") + // A current version with a rule violation is a field error. + currentInvalid, _ := json.Marshal(map[string]any{"expected_version": 2, "terms": invalidTerms}) + requireInvitationValidation(t, request(http.MethodPatch, path, string(currentInvalid), sessionA, ""), "/terms/salary/salary_to", "") + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused updates stored rows: %+v -> %+v", before, after) + } + + // A change of the period or the need keeps the terms version. + period, _ := json.Marshal(map[string]any{"expected_version": 2, "response_period_days": 14}) + withPeriod := decodeInvitationHTTP(t, request(http.MethodPatch, path, string(period), sessionA, ""), http.StatusOK) + if withPeriod.Version != 3 || withPeriod.TermsVersion != 2 || withPeriod.ResponsePeriodDays != 14 { + t.Fatalf("period update = %+v, want version 3 with terms version 2", withPeriod) + } + if got := invitationCount(ctx, t, harness, "invitation_terms_versions WHERE invitation_id = '"+draft.ID.String()+"'"); got != 2 { + t.Fatalf("stored %d terms versions, want 2", got) + } + // The candidate and the other fixed fields cannot be changed. + for _, field := range []string{"candidate_handle", "state", "salary_fit", "organization_id"} { + response := request(http.MethodPatch, path, fmt.Sprintf(`{"expected_version":3,%q:"x"}`, field), sessionA, "") + if response.Code != http.StatusBadRequest { + t.Errorf("update with %s = %d %s, want 400", field, response.Code, response.Body.String()) + } + } + if response := request(http.MethodPatch, path, `{"response_period_days":3}`, sessionA, ""); response.Code != http.StatusBadRequest { + t.Errorf("update without expected_version = %d, want 400", response.Code) + } + }) + + t.Run("links a draft only to a need of the organization that has had the requirements version", func(t *testing.T) { + needA := createNeedForInvitation(t, harness.sessionHTTPHarness, origin, sessionA, orgA, "Invitation need A") + needB := createNeedForInvitation(t, harness.sessionHTTPHarness, origin, sessionB, orgB, "Invitation need B") + linked := mustCreate(func(body, terms map[string]any) { + body["need"] = map[string]any{"need_id": needA.ID, "requirements_version": needA.RequirementsVersion} + }) + if linked.Need == nil || linked.Need.NeedID != needA.ID || linked.Need.RequirementsVersion != needA.RequirementsVersion { + t.Fatalf("linked draft = %+v, want the need reference back", linked.Need) + } + // Renaming the need makes version 2 without a new requirements version, + // so version 2 is not a requirements version the need has had. + renamed := request(http.MethodPatch, fmt.Sprintf("/api/v1/organizations/%s/needs/%s", orgA, needA.ID), `{"expected_version":1,"title":"Renamed invitation need A"}`, sessionA, "") + var renamedNeed struct { + Version int64 `json:"version"` + RequirementsVersion int64 `json:"requirements_version"` + } + if err := json.Unmarshal(renamed.Body.Bytes(), &renamedNeed); err != nil || renamed.Code != http.StatusOK || + renamedNeed.Version != 2 || renamedNeed.RequirementsVersion != needA.RequirementsVersion { + t.Fatalf("rename need = %d %s, want version 2 with the same requirements version", renamed.Code, renamed.Body.String()) + } + before := readInvitationCounts(ctx, t, harness) + for name, ref := range map[string]map[string]any{ + "a version that only renamed the need": {"need_id": needA.ID, "requirements_version": 2}, + "a need of another organization": {"need_id": needB.ID, "requirements_version": needB.RequirementsVersion}, + "an unknown need": {"need_id": uuid.New(), "requirements_version": 1}, + "a version the need never had": {"need_id": needA.ID, "requirements_version": needA.RequirementsVersion + 5}, + } { + response := createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { body["need"] = ref }) + if response.Code != http.StatusBadRequest { + t.Errorf("link to %s = %d %s, want 400", name, response.Code, response.Body.String()) + continue + } + requireInvitationValidation(t, response, "/need", "") + } + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused links stored rows: %+v -> %+v", before, after) + } + // The link is informational and can be removed or changed in the draft. + path := itemPath(orgA, linked.ID) + unlink := decodeInvitationHTTP(t, request(http.MethodPatch, path, `{"expected_version":1,"need":null}`, sessionA, ""), http.StatusOK) + if unlink.Need != nil || unlink.Version != 2 || unlink.TermsVersion != 1 { + t.Fatalf("unlinked draft = %+v, want version 2 without a need and the same terms version", unlink) + } + relink := fmt.Sprintf(`{"expected_version":2,"need":{"need_id":%q,"requirements_version":%d}}`, needA.ID, needA.RequirementsVersion) + if relinked := decodeInvitationHTTP(t, request(http.MethodPatch, path, relink, sessionA, ""), http.StatusOK); relinked.Need == nil || relinked.Version != 3 { + t.Fatalf("relinked draft = %+v", relinked) + } + foreign := fmt.Sprintf(`{"expected_version":3,"need":{"need_id":%q,"requirements_version":%d}}`, needB.ID, needB.RequirementsVersion) + requireInvitationValidation(t, request(http.MethodPatch, path, foreign, sessionA, ""), "/need", "") + }) + + t.Run("refuses to change an invitation that is no longer a draft", func(t *testing.T) { + draft := mustCreate(nil) + if _, err := harness.pool.Exec(ctx, `UPDATE invitations SET state = 'withdrawn', version = version + 1, updated_at = updated_at WHERE id = $1`, draft.ID); err != nil { + t.Fatalf("withdraw the draft: %v", err) + } + changed, _ := json.Marshal(map[string]any{"expected_version": 2, "response_period_days": 14}) + requireSessionProblem(t, request(http.MethodPatch, itemPath(orgA, draft.ID), string(changed), sessionA, ""), http.StatusConflict, "state_conflict") + // The stale version is compared before the state. + stale, _ := json.Marshal(map[string]any{"expected_version": 1, "response_period_days": 14}) + requireSessionProblem(t, request(http.MethodPatch, itemPath(orgA, draft.ID), string(stale), sessionA, ""), http.StatusPreconditionFailed, "version_conflict") + read := decodeInvitationHTTP(t, request(http.MethodGet, itemPath(orgA, draft.ID), "", sessionA, ""), http.StatusOK) + if read.State != "withdrawn" || read.Version != 2 || read.ResponsePeriodDays != 7 { + t.Fatalf("withdrawn invitation = %+v, want it unchanged", read) + } + }) + + t.Run("lets only one of two concurrent updates from the same version win", func(t *testing.T) { + draft := mustCreate(nil) + path := itemPath(orgA, draft.ID) + first, second := invitationTermsMap(), invitationTermsMap() + first["role_title"], second["role_title"] = "Concurrent role one", "Concurrent role two" + bodies := make([]string, 0, 2) + for _, terms := range []map[string]any{first, second} { + encoded, _ := json.Marshal(map[string]any{"expected_version": 1, "terms": terms}) + bodies = append(bodies, string(encoded)) + } + responses := parallelNeedRequestsWithBodies(t, harness.sessionHTTPHarness, http.MethodPatch, path, bodies, origin, sessionA) + statuses := []int{responses[0].Code, responses[1].Code} + slices.Sort(statuses) + if !slices.Equal(statuses, []int{http.StatusOK, http.StatusPreconditionFailed}) { + t.Fatalf("concurrent updates answered %d %s and %d %s, want one 200 and one 412", + responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) + } + if got := invitationCount(ctx, t, harness, "invitation_terms_versions WHERE invitation_id = '"+draft.ID.String()+"'"); got != 2 { + t.Fatalf("stored %d terms versions, want 2", got) + } + if got := invitationCount(ctx, t, harness, "invitation_events WHERE invitation_id = '"+draft.ID.String()+"'"); got != 2 { + t.Fatalf("stored %d events, want 2", got) + } + }) + + t.Run("queues concurrent creates and updates of one organization without a deadlock", func(t *testing.T) { + // Creates lock the organization, the membership, and the visible cohort; + // updates lock the organization, the membership, and the invitation. Both + // take the organization lock first, so mixing them never deadlocks + // (SQLSTATE 40P01 would surface as a 500). + const pairs = 4 + drafts := make([]invitationHTTPBody, 0, pairs) + for range pairs { + drafts = append(drafts, mustCreate(nil)) + } + before := readInvitationCounts(ctx, t, harness) + responses := make([]*httptest.ResponseRecorder, 2*pairs) + var group sync.WaitGroup + start := make(chan struct{}) + for index, draft := range drafts { + createBody := invitationCreateJSON(t, handleA, nil) + createKey := nextKey() + updateTerms := invitationTermsMap() + updateTerms["role_title"] = fmt.Sprintf("Concurrent update %d", index) + updateBody, err := json.Marshal(map[string]any{"expected_version": 1, "terms": updateTerms}) + if err != nil { + t.Fatalf("marshal update: %v", err) + } + group.Go(func() { + <-start + responses[2*index] = request(http.MethodPost, createPath(orgA), createBody, sessionA, createKey) + }) + group.Go(func() { + <-start + responses[2*index+1] = request(http.MethodPatch, itemPath(orgA, draft.ID), string(updateBody), sessionA, "") + }) + } + close(start) + group.Wait() + for index, response := range responses { + want := http.StatusCreated + if index%2 == 1 { + want = http.StatusOK + } + if response.Code != want { + t.Fatalf("concurrent command %d = %d %s, want %d", index, response.Code, response.Body.String(), want) + } + } + after := readInvitationCounts(ctx, t, harness) + if after.invitations != before.invitations+pairs || after.events != before.events+2*pairs { + t.Fatalf("concurrent commands stored %+v -> %+v, want %d drafts and %d events", before, after, pairs, 2*pairs) + } + }) + + t.Run("keeps every candidate value out of responses and logs", func(t *testing.T) { + requireNoCandidateData("server log", harness.logs.String()) + var stored string + if err := harness.pool.QueryRow(ctx, `SELECT coalesce(string_agg(terms::text, ' '), '') || ' ' || coalesce((SELECT string_agg(snapshot::text, ' ') FROM invitation_creation_results), '') + FROM invitation_terms_versions`).Scan(&stored); err != nil { + t.Fatalf("read stored terms: %v", err) + } + requireNoCandidateData("stored terms and replay responses", stored) + }) +} + +type invitationNeedBody struct { + ID uuid.UUID `json:"id"` + RequirementsVersion int64 `json:"requirements_version"` +} + +func createNeedForInvitation(t *testing.T, harness *sessionHTTPHarness, origin string, session organizationHTTPSession, organizationID uuid.UUID, title string) invitationNeedBody { + t.Helper() + response := organizationHTTPRequest(t, harness, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/needs", organizationID), + fmt.Sprintf(`{"title":%q}`, title), origin, session, "need-for-"+strings.ReplaceAll(strings.ToLower(title), " ", "-")) + if response.Code != http.StatusCreated { + t.Fatalf("create need = %d %s, want 201", response.Code, response.Body.String()) + } + var need invitationNeedBody + if err := json.Unmarshal(response.Body.Bytes(), &need); err != nil || need.ID == uuid.Nil { + t.Fatalf("decode need %s: %v", response.Body.String(), err) + } + return need +} diff --git a/backend/integration_test/invitation_storage_test.go b/backend/integration_test/invitation_storage_test.go new file mode 100644 index 0000000..7359f39 --- /dev/null +++ b/backend/integration_test/invitation_storage_test.go @@ -0,0 +1,338 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "strconv" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" +) + +const ( + // invitationMigrationVersion creates the invitation tables. + invitationMigrationVersion = 37 + invitationRetainedState = "invitations_retained" +) + +type invitationStorageFixture struct { + ctx context.Context + transactor *postgresadapter.Transactor + organization domain.Organization + owner domain.User + candidate domain.User + policyID domain.PolicyVersionID + now time.Time +} + +func invitationStorageTerms() domain.InvitationTerms { + none := domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided} + return domain.InvitationTerms{ + RoleTitle: "Storage role", Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, + OfferType: domain.InvitationOfferFullTime, Tasks: []string{"Store the draft"}, Team: "Storage team", + TechStack: []string{"Go"}, WorkFormats: []domain.NeedWorkFormat{domain.NeedWorkFormatRemote}, + CommunicationMethod: domain.InvitationCommunicationMethod{Channel: domain.InvitationChannelEmail}, + Salary: domain.SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "RUB", Period: "month", TaxBasis: "net"}, + Package: domain.InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none}, + } +} + +func newInvitationStorageFixture(ctx context.Context, t *testing.T, databaseURL string) (invitationStorageFixture, *pgxpool.Pool) { + t.Helper() + pool := newPoolFor(ctx, t, databaseURL) + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + organizations := organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now} + owner := organizations.employer(t, "storage-owner@example.test") + organization := organizations.create(t, owner, organizations.completeProfile(t, "Invitation storage company"), now) + candidate := identity.createUser(t, "storage-candidate@example.test", domain.ScenarioCandidate, now.Add(-time.Hour)) + seeded, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx) + if err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + return invitationStorageFixture{ + ctx: ctx, transactor: postgresadapter.NewTransactor(pool), organization: organization, owner: owner, + candidate: candidate, policyID: seeded.Version.ID(), now: now, + }, pool +} + +// draft stores a new draft through the repository in its own transaction. +func (fixture invitationStorageFixture) draft(t *testing.T) domain.Invitation { + t.Helper() + invitationID, err := uuid.NewV7() + if err != nil { + t.Fatalf("NewV7() error = %v", err) + } + draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{ + ID: invitationID, OrganizationID: fixture.organization.ID(), CandidateID: fixture.candidate.ID, ActorID: fixture.owner.ID, + PolicyVersionID: fixture.policyID, At: fixture.now, + Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationStorageTerms()}, + }) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + event, err := draft.DraftEvent(fixture.owner.ID, nil) + if err != nil { + t.Fatalf("DraftEvent() error = %v", err) + } + if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Create(ctx, draft, event) + }); err != nil { + t.Fatalf("store the draft: %v", err) + } + return draft +} + +func TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + fixture, _ := newInvitationStorageFixture(ctx, t, databaseURL) + draft := fixture.draft(t) + + read := func(work func(unit outbound.UnitOfWork) error) error { + return fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return work(unit) }) + } + var stored domain.Invitation + if err := read(func(unit outbound.UnitOfWork) error { + var err error + stored, err = unit.Invitations().Get(ctx, fixture.organization.ID(), draft.ID()) + return err + }); err != nil { + t.Fatalf("Get() error = %v", err) + } + if got, want := stored.Snapshot(), draft.Snapshot(); got.Version != want.Version || !got.Terms.Equal(want.Terms) || !got.CreatedAt.Equal(want.CreatedAt) || + stored.CandidateID() != fixture.candidate.ID || stored.PolicyVersionID() != fixture.policyID { + t.Fatalf("stored draft = %+v, want the one that was saved", got) + } + // Another organization finds nothing. + err := read(func(unit outbound.UnitOfWork) error { + _, err := unit.Invitations().Get(ctx, uuid.New(), draft.ID()) + return err + }) + if !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Fatalf("Get(another organization) error = %v, want ErrInvitationNotFound", err) + } + + content := draft.DraftContent() + content.Terms.Salary.SalaryTo = 150_000 + revised, changed, err := draft.ReviseDraft(content, fixture.policyID, fixture.now.Add(time.Minute)) + if err != nil { + t.Fatalf("ReviseDraft() error = %v", err) + } + event, err := revised.DraftEvent(fixture.owner.ID, changed) + if err != nil { + t.Fatalf("DraftEvent() error = %v", err) + } + // A save from a version that is not current is refused and stores nothing. + err = read(func(unit outbound.UnitOfWork) error { + return unit.Invitations().SaveDraft(ctx, 7, revised, true, event) + }) + if err == nil { + t.Fatal("SaveDraft(from version 7) succeeded") + } + if err := read(func(unit outbound.UnitOfWork) error { + return unit.Invitations().SaveDraft(ctx, draft.Version(), revised, true, event) + }); err != nil { + t.Fatalf("SaveDraft() error = %v", err) + } + // The same save again lost the race: the stored draft moved on. + err = read(func(unit outbound.UnitOfWork) error { + return unit.Invitations().SaveDraft(ctx, draft.Version(), revised, true, event) + }) + if !errors.Is(err, outbound.ErrInvitationVersionConflict) { + t.Fatalf("second SaveDraft() error = %v, want ErrInvitationVersionConflict", err) + } + + if err := read(func(unit outbound.UnitOfWork) error { + first, err := unit.Invitations().GetTermsVersion(ctx, fixture.organization.ID(), draft.ID(), 1) + if err != nil { + return err + } + second, err := unit.Invitations().GetTermsVersion(ctx, fixture.organization.ID(), draft.ID(), 2) + if err != nil { + return err + } + if first.Salary.SalaryTo != 140_000 || second.Salary.SalaryTo != 150_000 { + t.Errorf("terms versions end at %d and %d, want 140000 and 150000", first.Salary.SalaryTo, second.Salary.SalaryTo) + } + if _, err := unit.Invitations().GetTermsVersion(ctx, fixture.organization.ID(), draft.ID(), 3); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Errorf("GetTermsVersion(3) error = %v, want ErrInvitationNotFound", err) + } + if _, err := unit.Invitations().GetTermsVersion(ctx, uuid.New(), draft.ID(), 1); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Errorf("GetTermsVersion(another organization) error = %v, want ErrInvitationNotFound", err) + } + return nil + }); err != nil { + t.Fatalf("read terms versions: %v", err) + } +} + +func TestInvitationTablesRefuseMoneyAndHistoryViolations(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + draft := fixture.draft(t) + id := draft.ID() + snapshot := func(from, to int64, basis string) string { + return `{"role_title":"x","specialization":"backend","grade":"middle","offer_type":"full_time","tasks":["x"],"team":"x",` + + `"tech_stack":["Go"],"work_formats":["remote"],"location":null,"communication_method":{"channel":"email","details":null},` + + `"salary":{"salary_from":` + strconv.FormatInt(from, 10) + `,"salary_to":` + strconv.FormatInt(to, 10) + `,"currency":"RUB","period":"month","tax_basis":"` + basis + `"},` + + `"package":{"bonus":{"status":"not_provided"},"equipment":{"status":"not_provided"},"training":{"status":"not_provided"},"health_insurance":{"status":"not_provided"}}}` + } + insertTerms := func(version int64, from, to int64, currency, period, basis string, terms string) error { + _, err := pool.Exec(ctx, `INSERT INTO invitation_terms_versions ( + invitation_id, organization_id, version, terms, salary_from, salary_to, salary_currency, salary_period, salary_tax_basis, created_at + ) VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8, $9, now())`, + id, fixture.organization.ID(), version, terms, from, to, currency, period, basis) + return err + } + + // The money rules hold in the database for any writer. + assertPgError(t, "A equal to B", insertTerms(2, 100000, 100000, "RUB", "month", "net", snapshot(100000, 100000, "net")), checkViolation, "invitation_terms_versions_salary_bounds") + assertPgError(t, "A off the step", insertTerms(2, 100500, 140000, "RUB", "month", "net", snapshot(100500, 140000, "net")), checkViolation, "invitation_terms_versions_salary_bounds") + assertPgError(t, "A of zero", insertTerms(2, 0, 100000, "RUB", "month", "net", snapshot(0, 100000, "net")), checkViolation, "invitation_terms_versions_salary_bounds") + assertPgError(t, "width below 10 percent", insertTerms(2, 95000, 104000, "RUB", "month", "net", snapshot(95000, 104000, "net")), checkViolation, "invitation_terms_versions_salary_width") + assertPgError(t, "width above 40 percent", insertTerms(2, 80000, 121000, "RUB", "month", "net", snapshot(80000, 121000, "net")), checkViolation, "invitation_terms_versions_salary_width") + assertPgError(t, "foreign currency", insertTerms(2, 100000, 140000, "USD", "month", "net", snapshot(100000, 140000, "net")), checkViolation, "invitation_terms_versions_salary_basis") + assertPgError(t, "unknown base", insertTerms(2, 100000, 140000, "RUB", "month", "pre-tax", snapshot(100000, 140000, "pre-tax")), checkViolation, "invitation_terms_versions_salary_basis") + assertPgError(t, "snapshot that disagrees with the columns", insertTerms(2, 100000, 140000, "RUB", "month", "net", snapshot(100000, 150000, "net")), checkViolation, "invitation_terms_versions_snapshot_shape") + assertPgError(t, "snapshot without a term", insertTerms(2, 100000, 140000, "RUB", "month", "net", `{"salary":{"salary_from":100000,"salary_to":140000,"currency":"RUB","period":"month","tax_basis":"net"}}`), checkViolation, "invitation_terms_versions_snapshot_shape") + // The exact boundaries are accepted by the same rules, as new versions of + // the same invitation. + if err := insertTerms(2, 95000, 105000, "RUB", "month", "gross", snapshot(95000, 105000, "gross")); err != nil { + t.Fatalf("insert the 10 percent range: %v", err) + } + if err := insertTerms(3, 80000, 120000, "RUB", "month", "gross", snapshot(80000, 120000, "gross")); err != nil { + t.Fatalf("insert the 40 percent range: %v", err) + } + _, err := pool.Exec(ctx, `DELETE FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 2`, id) + assertPgError(t, "delete of a terms version", err, privacyIntegrityViolation, "invitation_terms_versions_immutable") + + // Terms versions and audit events are append-only. + _, err = pool.Exec(ctx, `UPDATE invitation_terms_versions SET salary_to = 150000 WHERE invitation_id = $1 AND version = 1`, id) + assertPgError(t, "update of a terms version", err, privacyIntegrityViolation, "invitation_terms_versions_immutable") + _, err = pool.Exec(ctx, `UPDATE invitation_events SET kind = 'draft_updated' WHERE invitation_id = $1`, id) + assertPgError(t, "update of an audit event", err, privacyIntegrityViolation, "invitation_events_immutable") + _, err = pool.Exec(ctx, `DELETE FROM invitation_events WHERE invitation_id = $1`, id) + assertPgError(t, "delete of an audit event", err, privacyIntegrityViolation, "invitation_events_immutable") + + // The invitation keeps its identity, steps its version by one, and is + // never deleted. + _, err = pool.Exec(ctx, `UPDATE invitations SET candidate_id = $2, version = version + 1 WHERE id = $1`, id, fixture.owner.ID) + assertPgError(t, "change of the candidate", err, privacyIntegrityViolation, "invitations_identity_immutable") + _, err = pool.Exec(ctx, `UPDATE invitations SET version = version + 2 WHERE id = $1`, id) + assertPgError(t, "version that skips a step", err, privacyIntegrityViolation, "invitations_version_step") + _, err = pool.Exec(ctx, `UPDATE invitations SET terms_version = 3, version = version + 1 WHERE id = $1`, id) + assertPgError(t, "terms version that skips a step", err, privacyIntegrityViolation, "invitations_version_step") + _, err = pool.Exec(ctx, `UPDATE invitations SET response_period_days = 5, version = version + 1 WHERE id = $1`, id) + assertPgError(t, "response period outside the policy options", err, checkViolation, "invitations_response_period") + _, err = pool.Exec(ctx, `UPDATE invitations SET delivered_at = now(), version = version + 1 WHERE id = $1`, id) + assertPgError(t, "delivery without a deadline", err, checkViolation, "invitations_deadline_with_delivery") + _, err = pool.Exec(ctx, `UPDATE invitations SET delivered_at = now(), response_deadline_at = now() + interval '7 days', version = version + 1 WHERE id = $1`, id) + assertPgError(t, "delivery of a draft", err, checkViolation, "invitations_draft_is_unsent") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'expired', version = version + 1 WHERE id = $1`, id) + assertPgError(t, "expiry without a reason", err, checkViolation, "invitations_expiry_reason") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'sent', version = version + 1 WHERE id = $1`, id) + assertPgError(t, "the internal sending step as a state", err, checkViolation, "invitations_state_known") + _, err = pool.Exec(ctx, `DELETE FROM invitations WHERE id = $1`, id) + assertPgError(t, "delete of an invitation", err, privacyIntegrityViolation, "invitations_immutable") + + // A delivered invitation keeps its deadline. + if _, err := pool.Exec(ctx, `UPDATE invitations SET state = 'delivered', delivered_at = '2026-10-09T10:00:00Z', + response_deadline_at = '2026-10-16T10:00:00Z', version = version + 1 WHERE id = $1`, id); err != nil { + t.Fatalf("deliver the invitation: %v", err) + } + _, err = pool.Exec(ctx, `UPDATE invitations SET response_deadline_at = '2026-10-30T10:00:00Z', version = version + 1 WHERE id = $1`, id) + assertPgError(t, "move of the deadline", err, privacyIntegrityViolation, "invitations_history_immutable") + _, err = pool.Exec(ctx, `UPDATE invitations SET response_period_days = 14, version = version + 1 WHERE id = $1`, id) + assertPgError(t, "change of the period after delivery", err, privacyIntegrityViolation, "invitations_history_immutable") + if _, err := pool.Exec(ctx, `UPDATE invitations SET salary_raise_used = true, version = version + 1 WHERE id = $1`, id); err != nil { + t.Fatalf("record the raise: %v", err) + } + _, err = pool.Exec(ctx, `UPDATE invitations SET salary_raise_used = false, version = version + 1 WHERE id = $1`, id) + assertPgError(t, "undoing the raise", err, privacyIntegrityViolation, "invitations_history_immutable") + + // An invitation links only to a need of its own organization, and its + // current terms version must exist when the transaction commits. + foreignOrganization := organizationFixture{ctx: ctx, pool: pool, identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: fixture.now}, + transactor: fixture.transactor, now: fixture.now} + otherOwner := foreignOrganization.employer(t, "storage-other-owner@example.test") + other := foreignOrganization.create(t, otherOwner, foreignOrganization.completeProfile(t, "Other storage company"), fixture.now) + needID := uuid.New() + _, err = pool.Exec(ctx, `INSERT INTO invitations (id, organization_id, candidate_id, need_id, need_requirements_version, state, version, terms_version, + response_period_days, policy_version_id, created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, 1, 'draft', 1, 1, 7, $5, $6, now(), now())`, + uuid.New(), other.ID(), fixture.candidate.ID, needID, fixture.policyID, otherOwner.ID) + assertPgError(t, "link to an unknown need", err, privacyForeignKeyViolation, "invitations_need_fkey") + _, err = pool.Exec(ctx, `INSERT INTO invitations (id, organization_id, candidate_id, need_id, state, version, terms_version, + response_period_days, policy_version_id, created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, 'draft', 1, 1, 7, $5, $6, now(), now())`, + uuid.New(), other.ID(), fixture.candidate.ID, needID, fixture.policyID, otherOwner.ID) + assertPgError(t, "need without a requirements version", err, checkViolation, "invitations_need_pair") + _, err = pool.Exec(ctx, `INSERT INTO invitations (id, organization_id, candidate_id, state, version, terms_version, + response_period_days, policy_version_id, created_by, created_at, updated_at) + VALUES ($1, $2, $3, 'draft', 1, 1, 7, $4, $5, now(), now())`, + uuid.New(), other.ID(), fixture.candidate.ID, fixture.policyID, otherOwner.ID) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != privacyForeignKeyViolation || pgError.ConstraintName != "invitations_current_terms_fkey" { + t.Fatalf("invitation without its first terms version error = %v, want a deferred violation of invitations_current_terms_fkey", err) + } +} + +func TestInvitationMigrationRollbackKeepsStoredInvitations(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, invitationMigrationVersion) + fixture.draft(t) + + _, err := migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a stored invitation", err, privacyIntegrityViolation, invitationRetainedState) + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() error = %v", err) + } + for _, status := range statuses { + if status.Version == invitationMigrationVersion && !status.Applied { + t.Fatal("the invitation migration was rolled back despite a stored invitation") + } + } + + // Once the rows are gone the rollback succeeds and the tables disappear. + if _, err := pool.Exec(ctx, `TRUNCATE 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 != invitationMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationMigrationVersion) + } + var remaining int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name LIKE 'invitation%'`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("invitation 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 9e95df2..56c736d 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -40,6 +40,7 @@ var ( // users and organizations. Creation snapshots reference idempotency records. organizationTables = []pgx.Identifier{ {"candidate_card_access_events"}, + {"invitation_creation_results"}, {"invitation_events"}, {"invitation_terms_versions"}, {"invitations"}, {"organization_need_versions"}, {"organization_needs"}, {"organization_need_creation_results"}, {"company_invitation_quota_usage"}, {"company_card_view_quota_usage"}, diff --git a/backend/integration_test/policy_test.go b/backend/integration_test/policy_test.go index 196a777..62be8f6 100644 --- a/backend/integration_test/policy_test.go +++ b/backend/integration_test/policy_test.go @@ -251,7 +251,8 @@ func TestPolicyVersions(t *testing.T) { assessment_signal_events, assessment_signal_batches, assessment_attempt_results, assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks, assessment_synthetic_category_reviews, candidate_assessment_categories, - skill_evidence_facts, skill_evidence_skills`}, + skill_evidence_facts, skill_evidence_skills, + invitations, invitation_terms_versions, invitation_events`}, } for _, statement := range statements { _, err := fixture.pool.Exec(ctx, statement.sql, statement.args...) diff --git a/backend/internal/adapter/primary/http/v1/api.go b/backend/internal/adapter/primary/http/v1/api.go index 0e5d903..15b98ec 100644 --- a/backend/internal/adapter/primary/http/v1/api.go +++ b/backend/internal/adapter/primary/http/v1/api.go @@ -25,6 +25,7 @@ type Handler struct { catalog *CatalogHandler organization *OrganizationHandler need *NeedHandler + invitation *InvitationHandler support *SupportHandler assessment *AssessmentHandler assessmentSignals *AssessmentSignalHandler @@ -75,6 +76,11 @@ func WithNeed(need *NeedHandler) HandlerOption { return func(handler *Handler) { handler.need = need } } +// WithInvitation serves the organization side of invitation drafts. +func WithInvitation(invitation *InvitationHandler) HandlerOption { + return func(handler *Handler) { handler.invitation = invitation } +} + // WithSupport serves account-owned support cases. func WithSupport(support *SupportHandler) HandlerOption { return func(handler *Handler) { handler.support = support } diff --git a/backend/internal/adapter/primary/http/v1/invitation.go b/backend/internal/adapter/primary/http/v1/invitation.go new file mode 100644 index 0000000..47dc9b2 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/invitation.go @@ -0,0 +1,495 @@ +package v1 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + invitationusecase "lincodex/backend/internal/usecase/invitation" +) + +const defaultInvitationLimit = 20 + +// InvitationOperations are the owner-scoped invitation draft reads and +// commands served by HTTP. +type InvitationOperations interface { + Create(ctx context.Context, command invitationusecase.CreateCommand) (domain.OrganizationInvitationView, error) + Get(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.OrganizationInvitationView, error) + List(ctx context.Context, command invitationusecase.ListCommand) (invitationusecase.Page, error) + Update(ctx context.Context, command invitationusecase.UpdateCommand) (domain.OrganizationInvitationView, error) +} + +// InvitationHandler serves the organization side of invitation drafts. The +// organization comes from the path and the server-side membership, never from +// a body, and the candidate is only ever named by the opaque card handle. +type InvitationHandler struct { + operations InvitationOperations +} + +func NewInvitationHandler(operations InvitationOperations) *InvitationHandler { + if operations == nil { + panic("v1.NewInvitationHandler - invitation operations must not be nil") + } + return &InvitationHandler{operations: operations} +} + +func (handler *Handler) ListOrganizationInvitations(ctx context.Context, params api.ListOrganizationInvitationsParams) (api.ListOrganizationInvitationsRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.ListOrganizationInvitations(ctx, params) + } + return handler.invitation.ListOrganizationInvitations(ctx, params) +} + +func (handler *Handler) CreateOrganizationInvitation(ctx context.Context, request *api.OrganizationInvitationCreate, params api.CreateOrganizationInvitationParams) (api.CreateOrganizationInvitationRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.CreateOrganizationInvitation(ctx, request, params) + } + return handler.invitation.CreateOrganizationInvitation(ctx, request, params) +} + +func (handler *Handler) GetOrganizationInvitation(ctx context.Context, params api.GetOrganizationInvitationParams) (api.GetOrganizationInvitationRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.GetOrganizationInvitation(ctx, params) + } + return handler.invitation.GetOrganizationInvitation(ctx, params) +} + +func (handler *Handler) UpdateOrganizationInvitation(ctx context.Context, request *api.OrganizationInvitationUpdate, params api.UpdateOrganizationInvitationParams) (api.UpdateOrganizationInvitationRes, error) { + if handler.invitation == nil { + return handler.UnimplementedHandler.UpdateOrganizationInvitation(ctx, request, params) + } + return handler.invitation.UpdateOrganizationInvitation(ctx, request, params) +} + +func (handler *InvitationHandler) CreateOrganizationInvitation( + ctx context.Context, + request *api.OrganizationInvitationCreate, + params api.CreateOrganizationInvitationParams, +) (api.CreateOrganizationInvitationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.CreateOrganizationInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if request == nil { + return (*api.CreateOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil + } + canonical, err := json.Marshal(request) + if err != nil { + return nil, errors.New("InvitationHandler.CreateOrganizationInvitation - encode canonical request") + } + command := invitationusecase.CreateCommand{ + ActorID: principal.UserID, OrganizationID: params.OrgID, IdempotencyKey: params.IdempotencyKey, + CanonicalBody: canonical, CandidateHandle: string(request.CandidateHandle), + Terms: invitationTermsFromRequest(request.Terms), + } + if need, set := request.Need.Get(); set { + command.Need = &domain.InvitationNeedRef{NeedID: need.NeedID, RequirementsVersion: int64(need.RequirementsVersion)} + } + if period, set := request.ResponsePeriodDays.Get(); set { + days := int32(period) + command.ResponsePeriodDays = &days + } + view, err := handler.operations.Create(ctx, command) + if err != nil { + return invitationCreateFailure(ctx, err) + } + return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil +} + +func (handler *InvitationHandler) GetOrganizationInvitation( + ctx context.Context, + params api.GetOrganizationInvitationParams, +) (api.GetOrganizationInvitationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.GetOrganizationInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + view, err := handler.operations.Get(ctx, principal.UserID, params.OrgID, params.InvitationID) + if err != nil { + return invitationReadFailure(ctx, err) + } + return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil +} + +func (handler *InvitationHandler) ListOrganizationInvitations( + ctx context.Context, + params api.ListOrganizationInvitationsParams, +) (api.ListOrganizationInvitationsRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.ListOrganizationInvitationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + command, pointer := invitationListCommand(principal.UserID, params) + if pointer != "" { + return (*api.ListOrganizationInvitationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil + } + page, err := handler.operations.List(ctx, command) + if err != nil { + switch { + case errors.Is(err, invitationusecase.ErrForbidden), errors.Is(err, invitationusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired): + return (*api.ListOrganizationInvitationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, outbound.ErrOrganizationNotFound): + return (*api.ListOrganizationInvitationsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + default: + return nil, err + } + } + items := make([]api.OrganizationInvitationSummary, 0, len(page.Items)) + for _, item := range page.Items { + items = append(items, organizationInvitationSummary(item)) + } + next := api.NilString{} + next.SetToNull() + if page.HasMore && len(page.Items) > 0 { + last := page.Items[len(page.Items)-1] + cursor, err := encodeInvitationCursor(principal.UserID, params.OrgID, outbound.InvitationListPosition{ + CreatedAt: last.CreatedAt, InvitationID: last.ID, + }) + if err != nil { + return nil, fmt.Errorf("InvitationHandler.ListOrganizationInvitations - encode cursor: %w", err) + } + next.SetTo(cursor) + } + return &api.OrganizationInvitationListHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: api.OrganizationInvitationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}}, + }, nil +} + +func (handler *InvitationHandler) UpdateOrganizationInvitation( + ctx context.Context, + request *api.OrganizationInvitationUpdate, + params api.UpdateOrganizationInvitationParams, +) (api.UpdateOrganizationInvitationRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.UpdateOrganizationInvitationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if request == nil { + return (*api.UpdateOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil + } + command := invitationusecase.UpdateCommand{ + ActorID: principal.UserID, OrganizationID: params.OrgID, InvitationID: params.InvitationID, + ExpectedVersion: int64(request.ExpectedVersion), + } + if request.Need.Set { + command.Need = invitationusecase.Field[domain.InvitationNeedRef]{Set: true, Null: request.Need.Null} + if !request.Need.Null { + command.Need.Value = domain.InvitationNeedRef{ + NeedID: request.Need.Value.NeedID, RequirementsVersion: int64(request.Need.Value.RequirementsVersion), + } + } + } + if period, set := request.ResponsePeriodDays.Get(); set { + days := int32(period) + command.ResponsePeriodDays = &days + } + if terms, set := request.Terms.Get(); set { + converted := invitationTermsFromRequest(terms) + command.Terms = &converted + } + view, err := handler.operations.Update(ctx, command) + if err != nil { + return invitationUpdateFailure(ctx, err) + } + return &api.OrganizationInvitationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: organizationInvitationResponse(view)}, nil +} + +// invitationFailure is the public classification of a usecase error. Every +// kind has one fixed problem, so a response never depends on which of two +// indistinguishable causes happened. +type invitationFailure int + +const ( + invitationFailureOther invitationFailure = iota + invitationFailureForbidden + invitationFailureNotFound + invitationFailureKeyReused + invitationFailureBadKey + invitationFailureInvalid + invitationFailureVersionConflict + invitationFailureStateConflict +) + +func classifyInvitationError(err error) invitationFailure { + switch { + case errors.Is(err, invitationusecase.ErrForbidden), errors.Is(err, invitationusecase.ErrEmailNotVerified), + errors.Is(err, outbound.ErrOrganizationManagerRequired): + return invitationFailureForbidden + case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrInvitationNotFound): + return invitationFailureNotFound + case errors.Is(err, invitationusecase.ErrIdempotencyKeyReused): + return invitationFailureKeyReused + case errors.Is(err, invitationusecase.ErrInvalidIdempotencyKey): + return invitationFailureBadKey + case errors.Is(err, domain.ErrInvitationVersionConflict), errors.Is(err, outbound.ErrInvitationVersionConflict): + return invitationFailureVersionConflict + case errors.Is(err, domain.ErrInvitationNotDraft): + return invitationFailureStateConflict + case errors.Is(err, domain.ErrInvalidInvitation), errors.Is(err, domain.ErrInvalidSalaryRange): + if _, ok := errors.AsType[*domain.InvitationFieldError](err); ok { + return invitationFailureInvalid + } + return invitationFailureOther + default: + return invitationFailureOther + } +} + +func invitationValidationProblem(ctx context.Context, err error) *api.Problem { + field, ok := errors.AsType[*domain.InvitationFieldError](err) + if !ok { + return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response + } + return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer).Response +} + +func invitationCreateFailure(ctx context.Context, err error) (api.CreateOrganizationInvitationRes, error) { + switch classifyInvitationError(err) { + case invitationFailureForbidden: + return (*api.CreateOrganizationInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case invitationFailureNotFound: + return (*api.CreateOrganizationInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case invitationFailureKeyReused: + return (*api.CreateOrganizationInvitationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil + case invitationFailureBadKey: + return (*api.CreateOrganizationInvitationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil + case invitationFailureInvalid: + return (*api.CreateOrganizationInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil + case invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther: + return nil, err + } + return nil, err +} + +func invitationReadFailure(ctx context.Context, err error) (api.GetOrganizationInvitationRes, error) { + switch classifyInvitationError(err) { + case invitationFailureForbidden: + return (*api.GetOrganizationInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case invitationFailureNotFound: + return (*api.GetOrganizationInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureInvalid, + invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther: + return nil, err + } + return nil, err +} + +func invitationUpdateFailure(ctx context.Context, err error) (api.UpdateOrganizationInvitationRes, error) { + switch classifyInvitationError(err) { + case invitationFailureForbidden: + return (*api.UpdateOrganizationInvitationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case invitationFailureNotFound: + return (*api.UpdateOrganizationInvitationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil + case invitationFailureVersionConflict: + return (*api.UpdateOrganizationInvitationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil + case invitationFailureStateConflict: + return (*api.UpdateOrganizationInvitationConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil + case invitationFailureInvalid: + return (*api.UpdateOrganizationInvitationBadRequest)(invitationValidationProblem(ctx, err)), nil + case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureOther: + return nil, err + } + return nil, err +} + +func invitationListCommand(actorID uuid.UUID, params api.ListOrganizationInvitationsParams) (invitationusecase.ListCommand, string) { + limit, ok := params.Limit.Get() + if !ok { + limit = defaultInvitationLimit + } + if limit < 1 || limit > outbound.MaxInvitationPageSize { + return invitationusecase.ListCommand{}, "limit" + } + command := invitationusecase.ListCommand{ActorID: actorID, OrganizationID: params.OrgID, Limit: limit} + if cursor, ok := params.Cursor.Get(); ok { + position, err := decodeInvitationCursor(cursor, actorID, params.OrgID) + if err != nil { + return invitationusecase.ListCommand{}, "cursor" + } + command.After = &position + } + return command, "" +} + +// invitationTermsFromRequest copies the request terms into the domain value. +// It validates nothing: the schema has already run, and the domain rules run +// in the usecase in the order of the contract. +func invitationTermsFromRequest(terms api.InvitationTerms) domain.InvitationTerms { + converted := domain.InvitationTerms{ + RoleTitle: string(terms.RoleTitle), Specialization: domain.SpecializationCode(terms.Specialization), + Grade: domain.GradeCode(terms.Grade), OfferType: domain.InvitationOfferType(terms.OfferType), + Team: string(terms.Team), + CommunicationMethod: domain.InvitationCommunicationMethod{ + Channel: domain.InvitationCommunicationChannel(terms.CommunicationMethod.Channel), + }, + Salary: domain.SalaryRange{ + SalaryFrom: int64(terms.Salary.SalaryFrom), SalaryTo: int64(terms.Salary.SalaryTo), + Currency: string(terms.Salary.Currency), Period: string(terms.Salary.Period), TaxBasis: string(terms.Salary.TaxBasis), + }, + Package: domain.InvitationPackage{ + Bonus: packageItemFromRequest(terms.Package.Bonus), Equipment: packageItemFromRequest(terms.Package.Equipment), + Training: packageItemFromRequest(terms.Package.Training), HealthInsurance: packageItemFromRequest(terms.Package.HealthInsurance), + }, + } + converted.Tasks = make([]string, 0, len(terms.Tasks)) + for _, task := range terms.Tasks { + converted.Tasks = append(converted.Tasks, string(task)) + } + converted.TechStack = make([]string, 0, len(terms.TechStack)) + for _, name := range terms.TechStack { + converted.TechStack = append(converted.TechStack, string(name)) + } + converted.WorkFormats = make([]domain.NeedWorkFormat, 0, len(terms.WorkFormats)) + for _, format := range terms.WorkFormats { + converted.WorkFormats = append(converted.WorkFormats, domain.NeedWorkFormat(format)) + } + if !terms.Location.Null { + location := string(terms.Location.Value) + converted.Location = &location + } + if !terms.CommunicationMethod.Details.Null { + details := string(terms.CommunicationMethod.Details.Value) + converted.CommunicationMethod.Details = &details + } + return converted +} + +func packageItemFromRequest(item api.InvitationPackageItem) domain.InvitationPackageItem { + switch item.Type { + case api.InvitationPackageItemProvidedInvitationPackageItem: + description := string(item.InvitationPackageItemProvided.Description) + return domain.InvitationPackageItem{Status: domain.InvitationPackageProvided, Description: &description} + case api.InvitationPackageItemNotProvidedInvitationPackageItem: + return domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided} + } + // The schema admits only the two variants; anything else is left without a + // status, which the domain validation refuses with the pointer of the item. + return domain.InvitationPackageItem{} +} + +func packageItemResponse(item domain.InvitationPackageItem) api.InvitationPackageItem { + if item.Status == domain.InvitationPackageProvided && item.Description != nil { + return api.NewInvitationPackageItemProvidedInvitationPackageItem(api.InvitationPackageItemProvided{ + Status: api.InvitationPackageItemProvidedStatusProvided, + Description: api.InvitationPackageItemText(*item.Description), + }) + } + return api.NewInvitationPackageItemNotProvidedInvitationPackageItem(api.InvitationPackageItemNotProvided{ + Status: api.InvitationPackageItemNotProvidedStatusNotProvided, + }) +} + +func invitationTermsResponse(terms domain.InvitationTerms) api.InvitationTerms { + response := api.InvitationTerms{ + RoleTitle: api.InvitationRoleTitle(terms.RoleTitle), Specialization: api.SpecializationCode(terms.Specialization), + Grade: api.GradeCode(terms.Grade), OfferType: api.InvitationOfferType(terms.OfferType), + Team: api.InvitationTeamDescription(terms.Team), + CommunicationMethod: api.InvitationCommunicationMethod{Channel: api.InvitationCommunicationChannel(terms.CommunicationMethod.Channel)}, + Salary: salaryRangeResponse(terms.Salary), + Package: api.InvitationPackage{ + Bonus: packageItemResponse(terms.Package.Bonus), Equipment: packageItemResponse(terms.Package.Equipment), + Training: packageItemResponse(terms.Package.Training), HealthInsurance: packageItemResponse(terms.Package.HealthInsurance), + }, + } + response.Tasks = make([]api.NeedTaskText, 0, len(terms.Tasks)) + for _, task := range terms.Tasks { + response.Tasks = append(response.Tasks, api.NeedTaskText(task)) + } + response.TechStack = make([]api.SkillName, 0, len(terms.TechStack)) + for _, name := range terms.TechStack { + response.TechStack = append(response.TechStack, api.SkillName(name)) + } + response.WorkFormats = make([]api.WorkFormat, 0, len(terms.WorkFormats)) + for _, format := range terms.WorkFormats { + response.WorkFormats = append(response.WorkFormats, api.WorkFormat(format)) + } + if terms.Location == nil { + response.Location.SetToNull() + } else { + response.Location.SetTo(api.NeedLocationName(*terms.Location)) + } + if terms.CommunicationMethod.Details == nil { + response.CommunicationMethod.Details.SetToNull() + } else { + response.CommunicationMethod.Details.SetTo(api.InvitationCommunicationNote(*terms.CommunicationMethod.Details)) + } + return response +} + +func salaryRangeResponse(salary domain.SalaryRange) api.SalaryRange { + return api.SalaryRange{ + SalaryFrom: api.RubAmount(salary.SalaryFrom), SalaryTo: api.RubAmount(salary.SalaryTo), + Currency: api.CurrencyCode(salary.Currency), Period: api.SalaryPeriod(salary.Period), TaxBasis: api.SalaryTaxBasis(salary.TaxBasis), + } +} + +func invitationNeedResponse(need *domain.InvitationNeedRef) api.NilInvitationNeedReference { + var response api.NilInvitationNeedReference + if need == nil { + response.SetToNull() + return response + } + response.SetTo(api.InvitationNeedReference{NeedID: need.NeedID, RequirementsVersion: api.NeedVersion(need.RequirementsVersion)}) + return response +} + +func invitationExpiryResponse(reason *domain.InvitationExpiryReason) api.NilInvitationExpiryReason { + var response api.NilInvitationExpiryReason + if reason == nil { + response.SetToNull() + return response + } + response.SetTo(api.InvitationExpiryReason(*reason)) + return response +} + +func nullableTimestamp(value *time.Time) api.NilTimestamp { + var response api.NilTimestamp + if value == nil { + response.SetToNull() + return response + } + response.SetTo(api.Timestamp(*value)) + return response +} + +func invitationContactAccessResponse(access domain.InvitationContactAccess) api.InvitationContactAccess { + // No contact grant exists before an acceptance, so no kind of contact is + // listed and no contact value is ever part of this response. + return api.InvitationContactAccess{Status: api.InvitationContactAccessState(access), Fields: []api.ContactFieldKind{}} +} + +func organizationInvitationResponse(view domain.OrganizationInvitationView) api.OrganizationInvitation { + return api.OrganizationInvitation{ + ID: view.ID, OrganizationID: view.OrganizationID, CandidateHandle: api.CandidateHandle(view.CandidateHandle), + Need: invitationNeedResponse(view.Need), State: api.InvitationState(view.State), + ExpiryReason: invitationExpiryResponse(view.ExpiryReason), Version: api.InvitationVersion(view.Version), + TermsVersion: api.InvitationTermsVersion(view.TermsVersion), Terms: invitationTermsResponse(view.Terms), + ResponsePeriodDays: api.InvitationResponsePeriod(view.ResponsePeriodDays), + ResponseDeadlineAt: nullableTimestamp(view.ResponseDeadlineAt), SalaryRaiseUsed: view.SalaryRaiseUsed, + SalaryFit: api.InvitationSalaryFit(view.SalaryFit), ContactAccess: invitationContactAccessResponse(view.ContactAccess), + CreatedAt: api.Timestamp(view.CreatedAt), UpdatedAt: api.Timestamp(view.UpdatedAt), + DeliveredAt: nullableTimestamp(view.DeliveredAt), ViewedAt: nullableTimestamp(view.ViewedAt), + RespondedAt: nullableTimestamp(view.RespondedAt), + } +} + +func organizationInvitationSummary(view domain.OrganizationInvitationView) api.OrganizationInvitationSummary { + return api.OrganizationInvitationSummary{ + ID: view.ID, CandidateHandle: api.CandidateHandle(view.CandidateHandle), Need: invitationNeedResponse(view.Need), + State: api.InvitationState(view.State), ExpiryReason: invitationExpiryResponse(view.ExpiryReason), + Version: api.InvitationVersion(view.Version), TermsVersion: api.InvitationTermsVersion(view.TermsVersion), + RoleTitle: api.InvitationRoleTitle(view.Terms.RoleTitle), Salary: salaryRangeResponse(view.Terms.Salary), + ResponseDeadlineAt: nullableTimestamp(view.ResponseDeadlineAt), ContactAccess: invitationContactAccessResponse(view.ContactAccess), + CreatedAt: api.Timestamp(view.CreatedAt), UpdatedAt: api.Timestamp(view.UpdatedAt), + } +} diff --git a/backend/internal/adapter/primary/http/v1/invitation_cursor.go b/backend/internal/adapter/primary/http/v1/invitation_cursor.go new file mode 100644 index 0000000..e2869b0 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/invitation_cursor.go @@ -0,0 +1,55 @@ +package v1 + +import ( + "encoding/base64" + "encoding/binary" + "errors" + "math" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/port/outbound" +) + +const ( + invitationCursorVersion = 1 + invitationCursorBytes = 61 + maxInvitationCursorTime = uint64(253402300799) +) + +// encodeInvitationCursor binds the position to the account and the +// organization that read the page, so a cursor of another reader or tenant is +// refused instead of continuing a foreign listing. +func encodeInvitationCursor(actorID, organizationID uuid.UUID, position outbound.InvitationListPosition) (string, error) { + seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond() + if actorID == uuid.Nil || organizationID == uuid.Nil || position.InvitationID == uuid.Nil || position.CreatedAt.IsZero() || + position.CreatedAt.Year() < 1 || position.CreatedAt.Year() > 9999 || seconds < 0 || uint64(seconds) > maxInvitationCursorTime || + nanos < 0 || nanos >= 1_000_000_000 || nanos%int(time.Microsecond) != 0 { + return "", errors.New("invitation cursor requires an actor, organization, and valid page position") + } + var value [invitationCursorBytes]byte + value[0] = invitationCursorVersion + copy(value[1:17], actorID[:]) + copy(value[17:33], organizationID[:]) + binary.BigEndian.PutUint64(value[33:41], uint64(seconds)) + binary.BigEndian.PutUint32(value[41:45], uint32(nanos)) + copy(value[45:61], position.InvitationID[:]) + return base64.RawURLEncoding.EncodeToString(value[:]), nil +} + +func decodeInvitationCursor(cursor string, actorID, organizationID uuid.UUID) (outbound.InvitationListPosition, error) { + value, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil || len(value) != invitationCursorBytes || actorID == uuid.Nil || organizationID == uuid.Nil || + base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != invitationCursorVersion || + uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != organizationID { + return outbound.InvitationListPosition{}, errors.New("invitation cursor is invalid") + } + seconds := binary.BigEndian.Uint64(value[33:41]) + nanos := binary.BigEndian.Uint32(value[41:45]) + invitationID := uuid.UUID(value[45:61]) + if seconds > uint64(math.MaxInt64) || seconds > maxInvitationCursorTime || nanos >= 1_000_000_000 || nanos%1_000 != 0 || invitationID == uuid.Nil { + return outbound.InvitationListPosition{}, errors.New("invitation cursor position is invalid") + } + return outbound.InvitationListPosition{CreatedAt: time.Unix(int64(seconds), int64(nanos)).UTC(), InvitationID: invitationID}, nil +} diff --git a/backend/internal/adapter/primary/http/v1/invitation_test.go b/backend/internal/adapter/primary/http/v1/invitation_test.go new file mode 100644 index 0000000..66c88e1 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/invitation_test.go @@ -0,0 +1,193 @@ +package v1 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + invitationusecase "lincodex/backend/internal/usecase/invitation" +) + +func invitationTestTerms() api.InvitationTerms { + provided := api.NewInvitationPackageItemProvidedInvitationPackageItem(api.InvitationPackageItemProvided{ + Status: api.InvitationPackageItemProvidedStatusProvided, Description: "Quarterly bonus", + }) + notProvided := api.NewInvitationPackageItemNotProvidedInvitationPackageItem(api.InvitationPackageItemNotProvided{ + Status: api.InvitationPackageItemNotProvidedStatusNotProvided, + }) + terms := api.InvitationTerms{ + RoleTitle: "Middle Go developer", Specialization: "backend", Grade: "middle", OfferType: api.InvitationOfferTypeFullTime, + Tasks: []api.NeedTaskText{"Build the payout service"}, Team: "Six engineers", TechStack: []api.SkillName{"Go"}, + WorkFormats: []api.WorkFormat{api.WorkFormatRemote}, + CommunicationMethod: api.InvitationCommunicationMethod{Channel: api.InvitationCommunicationChannelEmail}, + Salary: api.SalaryRange{SalaryFrom: 100000, SalaryTo: 140000, Currency: api.CurrencyCodeRUB, Period: api.SalaryPeriodMonth, TaxBasis: api.SalaryTaxBasisNet}, + Package: api.InvitationPackage{Bonus: provided, Equipment: notProvided, Training: notProvided, HealthInsurance: notProvided}, + } + terms.Location.SetToNull() + terms.CommunicationMethod.Details.SetToNull() + return terms +} + +// The request terms and the response terms are the same value: a response can +// be sent back unchanged, and a nullable term keeps its meaning both ways. +func TestInvitationTermsSurviveTheRequestResponseRoundTrip(t *testing.T) { + request := invitationTestTerms() + converted := invitationTermsFromRequest(request) + if err := converted.Validate(); err != nil { + t.Fatalf("converted terms are invalid: %v", err) + } + if converted.Location != nil || converted.CommunicationMethod.Details != nil { + t.Fatalf("null terms were mapped to values: %+v", converted) + } + if converted.Package.Bonus.Status != domain.InvitationPackageProvided || converted.Package.Bonus.Description == nil || + converted.Package.Equipment.Status != domain.InvitationPackageNotProvided || converted.Package.Equipment.Description != nil { + t.Fatalf("package mapped wrongly: %+v", converted.Package) + } + encodedRequest, err := json.Marshal(request) + if err != nil { + t.Fatalf("marshal request terms: %v", err) + } + encodedResponse, err := json.Marshal(invitationTermsResponse(converted)) + if err != nil { + t.Fatalf("marshal response terms: %v", err) + } + if string(encodedRequest) != string(encodedResponse) { + t.Fatalf("response terms differ from the request terms:\n%s\n%s", encodedRequest, encodedResponse) + } +} + +func TestInvitationResponseNeverCarriesACandidateIdentifierOrAContact(t *testing.T) { + candidateID := uuid.Must(uuid.NewV7()) + organizationID := 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) + } + view := domain.OrganizationInvitationView{ + InvitationSnapshot: draft.Snapshot(), CandidateHandle: "cv1_" + strings.Repeat("A", 43), + SalaryFit: domain.InvitationSalaryNotAvailable, ContactAccess: domain.InvitationContactAccessNone, + } + for name, response := range map[string]any{ + "invitation": organizationInvitationResponse(view), + "summary": organizationInvitationSummary(view), + } { + encoded, err := json.Marshal(response) + if err != nil { + t.Fatalf("marshal %s: %v", name, err) + } + text := string(encoded) + if strings.Contains(text, candidateID.String()) { + t.Errorf("%s carries the candidate identifier: %s", name, text) + } + for _, field := range []string{"email", "phone", "telegram", "full_name", "salary_minimum", "candidate_id"} { + if strings.Contains(text, `"`+field+`":`) { + t.Errorf("%s carries the field %s: %s", name, field, text) + } + } + if !strings.Contains(text, `"candidate_handle":"cv1_`) { + t.Errorf("%s does not name the candidate by the card handle: %s", name, text) + } + } + encoded, _ := json.Marshal(organizationInvitationResponse(view)) + for _, want := range []string{`"state":"draft"`, `"version":1`, `"terms_version":1`, `"response_deadline_at":null`, `"salary_fit":"not_available"`, `"contact_access":{"status":"not_granted","fields":[]}`, `"need":null`} { + if !strings.Contains(string(encoded), want) { + t.Errorf("draft response lacks %s: %s", want, encoded) + } + } +} + +func TestInvitationFailuresMapToTheContractStatuses(t *testing.T) { + ctx := context.Background() + field := &domain.InvitationFieldError{Pointer: "/terms/salary/salary_to", Reason: "x"} + create := func(err error) any { + response, unexpected := invitationCreateFailure(ctx, err) + if unexpected != nil { + return unexpected + } + return fmt.Sprintf("%T", response) + } + update := func(err error) any { + response, unexpected := invitationUpdateFailure(ctx, err) + if unexpected != nil { + return unexpected + } + return fmt.Sprintf("%T", response) + } + tests := []struct { + name string + err error + wantCreate string + wantUpdate string + }{ + {"forbidden", invitationusecase.ErrForbidden, "*api.CreateOrganizationInvitationForbidden", "*api.UpdateOrganizationInvitationForbidden"}, + {"not an owner", fmt.Errorf("wrapped: %w", outbound.ErrOrganizationManagerRequired), "*api.CreateOrganizationInvitationForbidden", "*api.UpdateOrganizationInvitationForbidden"}, + {"unknown organization", outbound.ErrOrganizationNotFound, "*api.CreateOrganizationInvitationNotFound", "*api.UpdateOrganizationInvitationNotFound"}, + {"unknown invitation", outbound.ErrInvitationNotFound, "*api.CreateOrganizationInvitationNotFound", "*api.UpdateOrganizationInvitationNotFound"}, + {"field error", fmt.Errorf("wrapped: %w", field), "*api.CreateOrganizationInvitationBadRequest", "*api.UpdateOrganizationInvitationBadRequest"}, + {"stale version", domain.ErrInvitationVersionConflict, "", "*api.UpdateOrganizationInvitationPreconditionFailed"}, + {"not a draft", domain.ErrInvitationNotDraft, "", "*api.UpdateOrganizationInvitationConflict"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if test.wantCreate != "" { + if got := create(test.err); got != test.wantCreate { + t.Errorf("create failure = %v, want %s", got, test.wantCreate) + } + } + if got := update(test.err); got != test.wantUpdate { + t.Errorf("update failure = %v, want %s", got, test.wantUpdate) + } + }) + } + if got := create(invitationusecase.ErrIdempotencyKeyReused); got != "*api.CreateOrganizationInvitationUnprocessableEntity" { + t.Errorf("reused key = %v, want 422", got) + } + // An error without a public meaning is left to the responder, which logs + // it and answers with a fixed 500. + if _, passedOn := create(errors.New("storage failed")).(error); !passedOn { + t.Error("an unknown failure produced a public response instead of reaching the responder") + } +} + +func TestInvitationCursorIsBoundToActorAndOrganization(t *testing.T) { + actorID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + position := outbound.InvitationListPosition{ + CreatedAt: time.Date(2026, time.October, 9, 10, 0, 0, 123456000, time.UTC), InvitationID: uuid.Must(uuid.NewV7()), + } + cursor, err := encodeInvitationCursor(actorID, organizationID, position) + if err != nil { + t.Fatalf("encodeInvitationCursor() error = %v", err) + } + decoded, err := decodeInvitationCursor(cursor, actorID, organizationID) + if err != nil || !decoded.CreatedAt.Equal(position.CreatedAt) || decoded.InvitationID != position.InvitationID { + t.Fatalf("decodeInvitationCursor() = %+v, %v; want the same position", decoded, err) + } + for name, test := range map[string]struct{ actor, organization uuid.UUID }{ + "another actor": {uuid.Must(uuid.NewV7()), organizationID}, "another organization": {actorID, uuid.Must(uuid.NewV7())}, + } { + if _, err := decodeInvitationCursor(cursor, test.actor, test.organization); err == nil { + t.Errorf("a cursor of %s was accepted", name) + } + } + if _, err := decodeInvitationCursor(cursor+"A", actorID, organizationID); err == nil { + t.Error("a cursor with trailing data was accepted") + } +} diff --git a/backend/internal/adapter/secondary/postgres/invitations.go b/backend/internal/adapter/secondary/postgres/invitations.go new file mode 100644 index 0000000..7f7e228 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/invitations.go @@ -0,0 +1,443 @@ +package postgres + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "math" + "slices" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ( + _ outbound.InvitationRepository = invitationRepository{} + _ outbound.InvitationCreationResultRepository = invitationRepository{} +) + +// maxInvitationCreationResultBytes bounds the stored original response of a +// create: the terms plus the alias and the fixed fields. +const maxInvitationCreationResultBytes = 163840 + +func (unit *UnitOfWork) Invitations() outbound.InvitationRepository { + return invitationRepository{queries: unit.queries} +} + +func (unit *UnitOfWork) InvitationCreationResults() outbound.InvitationCreationResultRepository { + return invitationRepository{queries: unit.queries} +} + +type invitationRepository struct { + queries *sqlc.Queries +} + +func (repository invitationRepository) Create( + ctx context.Context, + invitation domain.Invitation, + event domain.InvitationEvent, +) error { + const location = "invitationRepository.Create" + stored := invitation.Stored() + if stored.State != string(domain.InvitationDraft) || stored.Version != 1 || stored.TermsVersion != 1 { + return fmt.Errorf("%s - creation must store a draft at version 1: %w", location, domain.ErrInvalidInvitation) + } + if err := repository.insertEventPrerequisites(location, invitation, event, 1); err != nil { + return err + } + period, err := invitationResponsePeriodParam(location, stored.ResponsePeriodDays) + if err != nil { + return err + } + if err := repository.queries.InsertInvitation(ctx, sqlc.InsertInvitationParams{ + ID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), CandidateID: pgUUID(stored.CandidateID), + NeedID: invitationNeedID(stored.Need), NeedRequirementsVersion: invitationNeedVersion(stored.Need), + State: stored.State, Version: stored.Version, TermsVersion: stored.TermsVersion, + ResponsePeriodDays: period, PolicyVersionID: pgUUID(stored.PolicyVersionID.UUID()), + CreatedBy: pgUUID(stored.CreatedBy), CreatedAt: pgTime(stored.CreatedAt), UpdatedAt: pgTime(stored.UpdatedAt), + }); err != nil { + return fmt.Errorf("%s - insert invitation: %w", location, mapInvitationError(err)) + } + if err := repository.insertTermsVersion(ctx, location, stored, stored.TermsVersion, stored.UpdatedAt); err != nil { + return err + } + return repository.insertEvent(ctx, location, event) +} + +func (repository invitationRepository) Get( + ctx context.Context, + organizationID, invitationID uuid.UUID, +) (domain.Invitation, error) { + const location = "invitationRepository.Get" + if organizationID == uuid.Nil || invitationID == uuid.Nil { + return domain.Invitation{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation) + } + row, err := repository.queries.ReadInvitation(ctx, sqlc.ReadInvitationParams{ + OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), + }) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - read invitation: %w", location, mapInvitationNoRows(err)) + } + return restoreInvitationRow(location, sqlc.ListInvitationsRow(row), organizationID) +} + +func (repository invitationRepository) GetForUpdate( + ctx context.Context, + organizationID, invitationID uuid.UUID, +) (domain.Invitation, error) { + const location = "invitationRepository.GetForUpdate" + if organizationID == uuid.Nil || invitationID == uuid.Nil { + return domain.Invitation{}, fmt.Errorf("%s - organization and invitation IDs must be set: %w", location, domain.ErrInvalidInvitation) + } + if _, err := repository.queries.LockInvitation(ctx, sqlc.LockInvitationParams{ + OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), + }); err != nil { + return domain.Invitation{}, fmt.Errorf("%s - lock invitation: %w", location, mapInvitationNoRows(err)) + } + invitation, err := repository.Get(ctx, organizationID, invitationID) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - read locked invitation: %w", location, err) + } + return invitation, nil +} + +func (repository invitationRepository) GetTermsVersion( + ctx context.Context, + organizationID, invitationID uuid.UUID, + version int64, +) (domain.InvitationTerms, error) { + const location = "invitationRepository.GetTermsVersion" + if organizationID == uuid.Nil || invitationID == uuid.Nil || version < 1 { + return domain.InvitationTerms{}, fmt.Errorf("%s - scope and version must be set: %w", location, domain.ErrInvalidInvitation) + } + encoded, err := repository.queries.ReadInvitationTermsVersion(ctx, sqlc.ReadInvitationTermsVersionParams{ + OrganizationID: pgUUID(organizationID), InvitationID: pgUUID(invitationID), Version: version, + }) + if err != nil { + return domain.InvitationTerms{}, fmt.Errorf("%s - read terms version: %w", location, mapInvitationNoRows(err)) + } + terms, err := domain.DecodeInvitationTerms([]byte(encoded)) + if err != nil { + return domain.InvitationTerms{}, fmt.Errorf("%s - restore terms: %w", location, err) + } + return terms, nil +} + +func (repository invitationRepository) List( + ctx context.Context, + query outbound.InvitationListQuery, +) (outbound.InvitationPage, error) { + const location = "invitationRepository.List" + if query.OrganizationID == uuid.Nil { + return outbound.InvitationPage{}, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidInvitation) + } + if query.Limit < 1 || query.Limit > outbound.MaxInvitationPageSize { + return outbound.InvitationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxInvitationPageSize, domain.ErrInvalidInvitation) + } + params := sqlc.ListInvitationsParams{OrganizationID: pgUUID(query.OrganizationID), RowLimit: query.Limit + 1} + if query.After != nil { + after := *query.After + if after.InvitationID == uuid.Nil || !validStoredInvitationTime(after.CreatedAt) { + return outbound.InvitationPage{}, fmt.Errorf("%s - pagination position is invalid: %w", location, domain.ErrInvalidInvitation) + } + params.AfterCreatedAt = pgTime(after.CreatedAt) + params.AfterInvitationID = pgUUID(after.InvitationID) + } + rows, err := repository.queries.ListInvitations(ctx, params) + if err != nil { + return outbound.InvitationPage{}, fmt.Errorf("%s - select invitations: %w", location, mapInvitationError(err)) + } + page := outbound.InvitationPage{HasMore: len(rows) > int(query.Limit)} + if page.HasMore { + rows = rows[:query.Limit] + } + page.Items = make([]domain.Invitation, 0, len(rows)) + for _, row := range rows { + invitation, err := restoreInvitationRow(location, row, query.OrganizationID) + if err != nil { + return outbound.InvitationPage{}, err + } + page.Items = append(page.Items, invitation) + } + return page, nil +} + +func (repository invitationRepository) SaveDraft( + ctx context.Context, + expectedVersion int64, + next domain.Invitation, + termsChanged bool, + event domain.InvitationEvent, +) error { + const location = "invitationRepository.SaveDraft" + stored := next.Stored() + if expectedVersion < 1 || stored.Version != expectedVersion+1 { + return fmt.Errorf("%s - the next version must follow the expected one: %w", location, domain.ErrInvalidInvitation) + } + if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil { + return err + } + period, err := invitationResponsePeriodParam(location, stored.ResponsePeriodDays) + if err != nil { + return err + } + _, err = repository.queries.AdvanceInvitationDraft(ctx, sqlc.AdvanceInvitationDraftParams{ + NeedID: invitationNeedID(stored.Need), NeedRequirementsVersion: invitationNeedVersion(stored.Need), + ResponsePeriodDays: period, PolicyVersionID: pgUUID(stored.PolicyVersionID.UUID()), + TermsVersion: stored.TermsVersion, NextVersion: stored.Version, UpdatedAt: pgTime(stored.UpdatedAt), + OrganizationID: pgUUID(stored.OrganizationID), InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion, + }) + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("%s - advance draft: %w", location, outbound.ErrInvitationVersionConflict) + } + if err != nil { + return fmt.Errorf("%s - advance draft: %w", location, mapInvitationError(err)) + } + if termsChanged { + if err := repository.insertTermsVersion(ctx, location, stored, stored.TermsVersion, stored.UpdatedAt); err != nil { + return err + } + } + return repository.insertEvent(ctx, location, event) +} + +func (repository invitationRepository) NeedVersionExists( + ctx context.Context, + organizationID, needID uuid.UUID, + requirementsVersion int64, +) (bool, error) { + const location = "invitationRepository.NeedVersionExists" + if organizationID == uuid.Nil || needID == uuid.Nil || requirementsVersion < 1 { + return false, fmt.Errorf("%s - scope and version must be set: %w", location, domain.ErrInvalidInvitation) + } + found, err := repository.queries.InvitationNeedVersionExists(ctx, sqlc.InvitationNeedVersionExistsParams{ + OrganizationID: pgUUID(organizationID), NeedID: pgUUID(needID), RequirementsVersion: requirementsVersion, + }) + if err != nil { + return false, fmt.Errorf("%s - look up need version: %w", location, mapInvitationError(err)) + } + return found, nil +} + +func (repository invitationRepository) SaveCreationResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, + result domain.OrganizationInvitationView, +) error { + const location = "invitationRepository.SaveCreationResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) { + return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) + } + encoded, err := encodeInvitationCreationResult(result) + if err != nil { + return fmt.Errorf("%s - encode response: %w", location, err) + } + if err := repository.queries.SaveInvitationCreationResult(ctx, sqlc.SaveInvitationCreationResultParams{ + ScopeHash: scope[:], Snapshot: encoded, + }); err != nil { + return fmt.Errorf("%s - store response: %w", location, mapInvitationError(err)) + } + return nil +} + +func (repository invitationRepository) GetCreationResult( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, +) (domain.OrganizationInvitationView, error) { + const location = "invitationRepository.GetCreationResult" + if scope == ([outbound.IdempotencyDigestSize]byte{}) { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidInvitation) + } + encoded, err := repository.queries.GetInvitationCreationResult(ctx, scope[:]) + if errors.Is(err, pgx.ErrNoRows) { + return domain.OrganizationInvitationView{}, outbound.ErrInvitationCreationResultNotFound + } + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - read response: %w", location, mapInvitationError(err)) + } + return decodeInvitationCreationResult(location, []byte(encoded)) +} + +// insertEventPrerequisites checks that the audit event describes the version +// that the caller is about to store. +func (repository invitationRepository) insertEventPrerequisites( + location string, + invitation domain.Invitation, + event domain.InvitationEvent, + version int64, +) error { + if event.ID == uuid.Nil || event.InvitationID != invitation.ID() || event.OrganizationID != invitation.OrganizationID() || + event.Version != version || event.TermsVersion != invitation.TermsVersion() || event.ActorID == uuid.Nil || + !validStoredInvitationTime(event.OccurredAt) { + return fmt.Errorf("%s - the audit event does not describe the stored version: %w", location, domain.ErrInvalidInvitation) + } + return nil +} + +func (repository invitationRepository) insertTermsVersion( + ctx context.Context, + location string, + stored domain.StoredInvitation, + version int64, + at time.Time, +) error { + encoded, err := domain.EncodeInvitationTerms(stored.Terms) + if err != nil { + return fmt.Errorf("%s - encode terms: %w", location, err) + } + if err := repository.queries.InsertInvitationTermsVersion(ctx, sqlc.InsertInvitationTermsVersionParams{ + InvitationID: pgUUID(stored.ID), OrganizationID: pgUUID(stored.OrganizationID), Version: version, + Terms: encoded, SalaryFrom: stored.Terms.Salary.SalaryFrom, SalaryTo: stored.Terms.Salary.SalaryTo, + SalaryCurrency: stored.Terms.Salary.Currency, SalaryPeriod: stored.Terms.Salary.Period, + SalaryTaxBasis: stored.Terms.Salary.TaxBasis, CreatedAt: pgTime(at), + }); err != nil { + return fmt.Errorf("%s - append terms version: %w", location, mapInvitationError(err)) + } + return nil +} + +func (repository invitationRepository) insertEvent(ctx context.Context, location string, event domain.InvitationEvent) error { + fields := make([]string, 0, len(event.ChangedFields)) + for _, field := range event.ChangedFields { + fields = append(fields, string(field)) + } + slices.Sort(fields) + if err := repository.queries.InsertInvitationEvent(ctx, sqlc.InsertInvitationEventParams{ + ID: pgUUID(event.ID), InvitationID: pgUUID(event.InvitationID), OrganizationID: pgUUID(event.OrganizationID), + Version: event.Version, TermsVersion: event.TermsVersion, Kind: string(event.Kind), ActorID: pgUUID(event.ActorID), + ChangedFields: fields, OccurredAt: pgTime(event.OccurredAt), + }); err != nil { + return fmt.Errorf("%s - record audit event: %w", location, mapInvitationError(err)) + } + return nil +} + +func restoreInvitationRow(location string, row sqlc.ListInvitationsRow, organizationID uuid.UUID) (domain.Invitation, error) { + if !row.ID.Valid || !row.OrganizationID.Valid || !row.CandidateID.Valid || !row.CreatedBy.Valid || !row.PolicyVersionID.Valid || + !row.CreatedAt.Valid || !row.UpdatedAt.Valid || uuid.UUID(row.OrganizationID.Bytes) != organizationID { + return domain.Invitation{}, fmt.Errorf("%s - invitation row has invalid scope or metadata: %w", location, domain.ErrInvalidInvitation) + } + terms, err := domain.DecodeInvitationTerms([]byte(row.Terms)) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - restore terms: %w", location, err) + } + stored := domain.StoredInvitation{ + ID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes), + CandidateID: uuid.UUID(row.CandidateID.Bytes), State: row.State, Version: row.Version, + TermsVersion: row.TermsVersion, Terms: terms, ResponsePeriodDays: int32(row.ResponsePeriodDays), + PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes), SalaryRaiseUsed: row.SalaryRaiseUsed, + CreatedBy: uuid.UUID(row.CreatedBy.Bytes), CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time, + ResponseDeadlineAt: optionalTime(row.ResponseDeadlineAt), DeliveredAt: optionalTime(row.DeliveredAt), + ViewedAt: optionalTime(row.ViewedAt), RespondedAt: optionalTime(row.RespondedAt), + } + if row.ExpiryReason.Valid { + reason := row.ExpiryReason.String + stored.ExpiryReason = &reason + } + if row.NeedID.Valid != row.NeedRequirementsVersion.Valid { + return domain.Invitation{}, fmt.Errorf("%s - need link is incomplete: %w", location, domain.ErrInvalidInvitation) + } + if row.NeedID.Valid { + stored.Need = &domain.InvitationNeedRef{NeedID: uuid.UUID(row.NeedID.Bytes), RequirementsVersion: row.NeedRequirementsVersion.Int64} + } + invitation, err := domain.RestoreInvitation(stored) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - restore invitation: %w", location, err) + } + return invitation, nil +} + +func encodeInvitationCreationResult(result domain.OrganizationInvitationView) ([]byte, error) { + if err := validateInvitationCreationResult(result); err != nil { + return nil, err + } + encoded, err := json.Marshal(result) + if err != nil { + return nil, fmt.Errorf("postgres.encodeInvitationCreationResult - marshal: %w", err) + } + if len(encoded) > maxInvitationCreationResultBytes { + return nil, fmt.Errorf("postgres.encodeInvitationCreationResult - response exceeds %d bytes: %w", maxInvitationCreationResultBytes, domain.ErrInvalidInvitation) + } + return encoded, nil +} + +func decodeInvitationCreationResult(location string, encoded []byte) (domain.OrganizationInvitationView, error) { + var result domain.OrganizationInvitationView + decoder := json.NewDecoder(bytes.NewReader(encoded)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&result); err != nil || decoder.More() { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - stored response has an unexpected shape: %w", location, domain.ErrInvalidInvitation) + } + if err := validateInvitationCreationResult(result); err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate stored response: %w", location, err) + } + return result, nil +} + +func validateInvitationCreationResult(result domain.OrganizationInvitationView) error { + if result.ID == uuid.Nil || result.OrganizationID == uuid.Nil || !domain.IsCandidateViewPseudonym(result.CandidateHandle) { + return fmt.Errorf("postgres.validateInvitationCreationResult - identity is incomplete: %w", domain.ErrInvalidInvitation) + } + if err := result.Terms.Validate(); err != nil { + return fmt.Errorf("postgres.validateInvitationCreationResult - validate terms: %w", err) + } + return nil +} + +func invitationNeedID(need *domain.InvitationNeedRef) pgtype.UUID { + if need == nil { + return pgtype.UUID{} + } + return pgUUID(need.NeedID) +} + +func invitationNeedVersion(need *domain.InvitationNeedRef) pgtype.Int8 { + if need == nil { + return pgtype.Int8{} + } + return pgtype.Int8{Int64: need.RequirementsVersion, Valid: true} +} + +func validStoredInvitationTime(value time.Time) bool { + return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 && value.Unix() >= 0 +} + +func mapInvitationNoRows(err error) error { + if errors.Is(err, pgx.ErrNoRows) { + return outbound.ErrInvitationNotFound + } + return mapInvitationError(err) +} + +func mapInvitationError(err error) error { + var pgError *pgconn.PgError + if !errors.As(err, &pgError) { + return sanitizeConnectError(err) + } + if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitations_organization_fkey" { + return fmt.Errorf("postgres.mapInvitationError - organization no longer exists: %w", outbound.ErrOrganizationNotFound) + } + if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "invitation_creation_results_idempotency_fkey" { + return fmt.Errorf("postgres.mapInvitationError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound) + } + return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}) +} + +// invitationResponsePeriodParam converts the period to its smallint column. +// The domain allows only the periods of the product policy, so a value out of +// range is an invalid invitation, never a silently truncated one. +func invitationResponsePeriodParam(location string, days int32) (int16, error) { + if days < 1 || days > math.MaxInt16 { + return 0, fmt.Errorf("%s - response period is out of range: %w", location, domain.ErrInvalidInvitation) + } + return int16(days), nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/invitations.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/invitations.sql.go new file mode 100644 index 0000000..7bc63ab --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/invitations.sql.go @@ -0,0 +1,557 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: invitations.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const advanceInvitationDraft = `-- name: AdvanceInvitationDraft :one +UPDATE invitations +SET + need_id = $1, + need_requirements_version = $2, + response_period_days = $3, + policy_version_id = $4, + terms_version = $5, + version = $6, + updated_at = $7 +WHERE + organization_id = $8 + AND id = $9 + AND state = 'draft' + AND version = $10 + AND $6::bigint = $10::bigint + 1 +RETURNING id +` + +type AdvanceInvitationDraftParams struct { + NeedID pgtype.UUID + NeedRequirementsVersion pgtype.Int8 + ResponsePeriodDays int16 + PolicyVersionID pgtype.UUID + TermsVersion int64 + NextVersion int64 + UpdatedAt pgtype.Timestamptz + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + ExpectedVersion int64 +} + +// The conditional update is the compare-and-swap of a draft: it applies only +// to a draft whose version is still the one the caller read, and advances the +// version by one. No row is returned when it lost a race or the invitation +// left the draft state. +func (q *Queries) AdvanceInvitationDraft(ctx context.Context, arg AdvanceInvitationDraftParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, advanceInvitationDraft, + arg.NeedID, + arg.NeedRequirementsVersion, + arg.ResponsePeriodDays, + arg.PolicyVersionID, + arg.TermsVersion, + arg.NextVersion, + arg.UpdatedAt, + arg.OrganizationID, + arg.InvitationID, + arg.ExpectedVersion, + ) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + +const getInvitationCreationResult = `-- name: GetInvitationCreationResult :one +SELECT snapshot::text AS snapshot +FROM invitation_creation_results +WHERE scope_hash = $1 +` + +func (q *Queries) GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error) { + row := q.db.QueryRow(ctx, getInvitationCreationResult, scopeHash) + var snapshot string + err := row.Scan(&snapshot) + return snapshot, err +} + +const insertInvitation = `-- name: InsertInvitation :exec +INSERT INTO invitations ( + id, + organization_id, + candidate_id, + need_id, + need_requirements_version, + state, + version, + terms_version, + response_period_days, + policy_version_id, + created_by, + created_at, + updated_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + $9, + $10, + $11, + $12, + $13 +) +` + +type InsertInvitationParams struct { + ID pgtype.UUID + OrganizationID pgtype.UUID + CandidateID pgtype.UUID + NeedID pgtype.UUID + NeedRequirementsVersion pgtype.Int8 + State string + Version int64 + TermsVersion int64 + ResponsePeriodDays int16 + PolicyVersionID pgtype.UUID + CreatedBy pgtype.UUID + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + +// The invitation row, its first terms version, and its first audit event are +// inserted in one caller-owned transaction. The deferred reference to the +// current terms version is checked when the transaction commits. +func (q *Queries) InsertInvitation(ctx context.Context, arg InsertInvitationParams) error { + _, err := q.db.Exec(ctx, insertInvitation, + arg.ID, + arg.OrganizationID, + arg.CandidateID, + arg.NeedID, + arg.NeedRequirementsVersion, + arg.State, + arg.Version, + arg.TermsVersion, + arg.ResponsePeriodDays, + arg.PolicyVersionID, + arg.CreatedBy, + arg.CreatedAt, + arg.UpdatedAt, + ) + return err +} + +const insertInvitationEvent = `-- name: InsertInvitationEvent :exec +INSERT INTO invitation_events ( + id, + invitation_id, + organization_id, + version, + terms_version, + kind, + actor_id, + changed_fields, + occurred_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8::text [], + $9 +) +` + +type InsertInvitationEventParams struct { + ID pgtype.UUID + InvitationID pgtype.UUID + OrganizationID pgtype.UUID + Version int64 + TermsVersion int64 + Kind string + ActorID pgtype.UUID + ChangedFields []string + OccurredAt pgtype.Timestamptz +} + +func (q *Queries) InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error { + _, err := q.db.Exec(ctx, insertInvitationEvent, + arg.ID, + arg.InvitationID, + arg.OrganizationID, + arg.Version, + arg.TermsVersion, + arg.Kind, + arg.ActorID, + arg.ChangedFields, + arg.OccurredAt, + ) + return err +} + +const insertInvitationTermsVersion = `-- name: InsertInvitationTermsVersion :exec +INSERT INTO invitation_terms_versions ( + invitation_id, + organization_id, + version, + terms, + salary_from, + salary_to, + salary_currency, + salary_period, + salary_tax_basis, + created_at +) VALUES ( + $1, + $2, + $3, + $4::jsonb, + $5, + $6, + $7, + $8, + $9, + $10 +) +` + +type InsertInvitationTermsVersionParams struct { + InvitationID pgtype.UUID + OrganizationID pgtype.UUID + Version int64 + Terms []byte + SalaryFrom int64 + SalaryTo int64 + SalaryCurrency string + SalaryPeriod string + SalaryTaxBasis string + CreatedAt pgtype.Timestamptz +} + +func (q *Queries) InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error { + _, err := q.db.Exec(ctx, insertInvitationTermsVersion, + arg.InvitationID, + arg.OrganizationID, + arg.Version, + arg.Terms, + arg.SalaryFrom, + arg.SalaryTo, + arg.SalaryCurrency, + arg.SalaryPeriod, + arg.SalaryTaxBasis, + arg.CreatedAt, + ) + return err +} + +const invitationNeedVersionExists = `-- name: InvitationNeedVersionExists :one +SELECT EXISTS ( + SELECT 1 + FROM organization_need_versions + WHERE + organization_id = $1 + AND need_id = $2 + AND version = $3::bigint + AND snapshot ->> 'requirements_version' = $3::bigint::text +) AS found +` + +type InvitationNeedVersionExistsParams struct { + OrganizationID pgtype.UUID + NeedID pgtype.UUID + RequirementsVersion int64 +} + +// A requirements version that a need of the organization has had is the +// version number of a stored snapshot whose own requirements version is that +// number, so a later edit that only renamed the need is not accepted. +func (q *Queries) InvitationNeedVersionExists(ctx context.Context, arg InvitationNeedVersionExistsParams) (bool, error) { + row := q.db.QueryRow(ctx, invitationNeedVersionExists, arg.OrganizationID, arg.NeedID, arg.RequirementsVersion) + var found bool + err := row.Scan(&found) + return found, err +} + +const listInvitations = `-- name: ListInvitations :many +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +WHERE + invitation.organization_id = $1 + AND ( + $2::timestamptz IS NULL + OR (invitation.created_at, invitation.id) < ( + $2::timestamptz, + $3::uuid + ) + ) +ORDER BY invitation.created_at DESC, invitation.id DESC +LIMIT $4 +` + +type ListInvitationsParams struct { + OrganizationID pgtype.UUID + AfterCreatedAt pgtype.Timestamptz + AfterInvitationID pgtype.UUID + RowLimit int32 +} + +type ListInvitationsRow 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 +} + +// One bounded newest-first page. Both the organization scope and the tuple +// cursor are applied before the limit. +func (q *Queries) ListInvitations(ctx context.Context, arg ListInvitationsParams) ([]ListInvitationsRow, error) { + rows, err := q.db.Query(ctx, listInvitations, + arg.OrganizationID, + arg.AfterCreatedAt, + arg.AfterInvitationID, + arg.RowLimit, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListInvitationsRow + for rows.Next() { + var i ListInvitationsRow + if err := rows.Scan( + &i.ID, + &i.OrganizationID, + &i.CandidateID, + &i.NeedID, + &i.NeedRequirementsVersion, + &i.State, + &i.ExpiryReason, + &i.Version, + &i.TermsVersion, + &i.ResponsePeriodDays, + &i.PolicyVersionID, + &i.ResponseDeadlineAt, + &i.SalaryRaiseUsed, + &i.CreatedBy, + &i.CreatedAt, + &i.UpdatedAt, + &i.DeliveredAt, + &i.ViewedAt, + &i.RespondedAt, + &i.Terms, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const lockInvitation = `-- name: LockInvitation :one +SELECT id +FROM invitations +WHERE + organization_id = $1 + AND id = $2 +FOR UPDATE +` + +type LockInvitationParams struct { + OrganizationID pgtype.UUID + InvitationID pgtype.UUID +} + +// Takes the row lock of one invitation. It is a statement of its own, ahead of +// ReadInvitation, because a locking read that joins the terms table is +// re-checked against the new row version after a wait and then pairs the +// updated terms_version with the terms row it fetched before the wait, which +// finds nothing. Once the lock is held, the following read sees the committed +// state and no writer can change it. +func (q *Queries) LockInvitation(ctx context.Context, arg LockInvitationParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, lockInvitation, arg.OrganizationID, arg.InvitationID) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + +const readInvitation = `-- name: ReadInvitation :one +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +WHERE + invitation.organization_id = $1 + AND invitation.id = $2 +` + +type ReadInvitationParams struct { + OrganizationID pgtype.UUID + InvitationID pgtype.UUID +} + +type ReadInvitationRow struct { + ID pgtype.UUID + OrganizationID pgtype.UUID + CandidateID pgtype.UUID + NeedID pgtype.UUID + NeedRequirementsVersion pgtype.Int8 + State string + ExpiryReason pgtype.Text + Version int64 + TermsVersion int64 + ResponsePeriodDays int16 + PolicyVersionID pgtype.UUID + ResponseDeadlineAt pgtype.Timestamptz + SalaryRaiseUsed bool + CreatedBy pgtype.UUID + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + DeliveredAt pgtype.Timestamptz + ViewedAt pgtype.Timestamptz + RespondedAt pgtype.Timestamptz + Terms string +} + +// Read one current invitation with its terms snapshot. Both the organization +// and the invitation scope the row, so another organization's identifier +// finds nothing. +func (q *Queries) ReadInvitation(ctx context.Context, arg ReadInvitationParams) (ReadInvitationRow, error) { + row := q.db.QueryRow(ctx, readInvitation, arg.OrganizationID, arg.InvitationID) + var i ReadInvitationRow + err := row.Scan( + &i.ID, + &i.OrganizationID, + &i.CandidateID, + &i.NeedID, + &i.NeedRequirementsVersion, + &i.State, + &i.ExpiryReason, + &i.Version, + &i.TermsVersion, + &i.ResponsePeriodDays, + &i.PolicyVersionID, + &i.ResponseDeadlineAt, + &i.SalaryRaiseUsed, + &i.CreatedBy, + &i.CreatedAt, + &i.UpdatedAt, + &i.DeliveredAt, + &i.ViewedAt, + &i.RespondedAt, + &i.Terms, + ) + return i, err +} + +const readInvitationTermsVersion = `-- name: ReadInvitationTermsVersion :one +SELECT terms::text AS terms +FROM invitation_terms_versions +WHERE + organization_id = $1 + AND invitation_id = $2 + AND version = $3 +` + +type ReadInvitationTermsVersionParams struct { + OrganizationID pgtype.UUID + InvitationID pgtype.UUID + Version int64 +} + +// Read one historical terms version of one invitation of one organization. +func (q *Queries) ReadInvitationTermsVersion(ctx context.Context, arg ReadInvitationTermsVersionParams) (string, error) { + row := q.db.QueryRow(ctx, readInvitationTermsVersion, arg.OrganizationID, arg.InvitationID, arg.Version) + var terms string + err := row.Scan(&terms) + return terms, err +} + +const saveInvitationCreationResult = `-- name: SaveInvitationCreationResult :exec +INSERT INTO invitation_creation_results (scope_hash, snapshot) +VALUES ($1, $2::jsonb) +ON CONFLICT (scope_hash) DO UPDATE +SET snapshot = excluded.snapshot +` + +type SaveInvitationCreationResultParams struct { + ScopeHash []byte + Snapshot []byte +} + +func (q *Queries) SaveInvitationCreationResult(ctx context.Context, arg SaveInvitationCreationResultParams) error { + _, err := q.db.Exec(ctx, saveInvitationCreationResult, arg.ScopeHash, arg.Snapshot) + return err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 4ed2f62..919f467 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -570,6 +570,58 @@ type IdempotencyRecord struct { ExpiresAt pgtype.Timestamptz } +type Invitation 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 +} + +type InvitationCreationResult struct { + ScopeHash []byte + Snapshot []byte +} + +type InvitationEvent struct { + ID pgtype.UUID + InvitationID pgtype.UUID + OrganizationID pgtype.UUID + Version int64 + TermsVersion int64 + Kind string + ActorID pgtype.UUID + ChangedFields []string + OccurredAt pgtype.Timestamptz +} + +type InvitationTermsVersion struct { + InvitationID pgtype.UUID + OrganizationID pgtype.UUID + Version int64 + Terms []byte + SalaryFrom int64 + SalaryTo int64 + SalaryCurrency string + SalaryPeriod string + SalaryTaxBasis string + CreatedAt pgtype.Timestamptz +} + type MailQuotaReservation struct { ID pgtype.UUID DeliveryID pgtype.UUID diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index b7edd35..cd65cc4 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -30,6 +30,11 @@ type Querier interface { // Advances an existing questionnaire only at the version read by the caller. // The row lock serializes saves for one user; a stale writer returns no row. AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error) + // The conditional update is the compare-and-swap of a draft: it applies only + // to a draft whose version is still the one the caller read, and advances the + // version by one. No row is returned when it lost a race or the invitation + // left the draft state. + AdvanceInvitationDraft(ctx context.Context, arg AdvanceInvitationDraftParams) (pgtype.UUID, error) // The conditional parent update is the compare-and-swap. Appending the // snapshot is part of the same SQL statement, so a failed insert leaves the // parent pointer unchanged even before the surrounding transaction rolls @@ -291,6 +296,7 @@ type Querier interface { GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error) // Explains why ConsumeEmailToken matched no row. GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) + GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error) // The caller holds the attempt row lock, so the last mark is stable. GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error) GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error) @@ -461,6 +467,12 @@ type Querier interface { // for it. InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error + // The invitation row, its first terms version, and its first audit event are + // inserted in one caller-owned transaction. The deferred reference to the + // current terms version is checked when the transaction commits. + InsertInvitation(ctx context.Context, arg InsertInvitationParams) error + InsertInvitationEvent(ctx context.Context, arg InsertInvitationEventParams) error + InsertInvitationTermsVersion(ctx context.Context, arg InsertInvitationTermsVersionParams) error InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error InsertMembership(ctx context.Context, arg InsertMembershipParams) error @@ -518,6 +530,10 @@ type Querier interface { InsertSyntheticCategoryReview(ctx context.Context, arg InsertSyntheticCategoryReviewParams) (int64, error) InsertUser(ctx context.Context, arg InsertUserParams) error InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) + // A requirements version that a need of the organization has had is the + // version number of a stored snapshot whose own requirements version is that + // number, so a later edit that only renamed the need is not accepted. + InvitationNeedVersionExists(ctx context.Context, arg InvitationNeedVersionExistsParams) (bool, error) // Read the latest serialized event so a temporarily regressing application // clock cannot make the next request fall before an event already counted. LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error) @@ -607,6 +623,9 @@ type Querier interface { // fingerprint; stale bindings are omitted fail-closed. ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error) ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error) + // One bounded newest-first page. Both the organization scope and the tuple + // cursor are applied before the limit. + ListInvitations(ctx context.Context, arg ListInvitationsParams) ([]ListInvitationsRow, error) // List only the authenticated recipient's rows, optionally narrowed to one // organization context. The caller resolves current source visibility before // returning content. @@ -730,6 +749,13 @@ type Querier interface { // Keeps the current C3 grant stable through a real assessment transaction. // Revocation updates this row and therefore waits until the caller commits. LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error) + // Takes the row lock of one invitation. It is a statement of its own, ahead of + // ReadInvitation, because a locking read that joins the terms table is + // re-checked against the new row version after a wait and then pairs the + // updated terms_version with the terms row it fetched before the wait, which + // finds nothing. Once the lock is held, the following read sees the committed + // state and no writer can change it. + LockInvitation(ctx context.Context, arg LockInvitationParams) (pgtype.UUID, error) // Locks the listed window rows until the transaction ends, in // (period_kind, period_start) order, the same order for every caller, and // returns their usage. Under READ COMMITTED a waiting caller reads the usage @@ -843,6 +869,12 @@ type Querier interface { ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error) // Read one current version with its organization-scoped parent metadata. ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error) + // Read one current invitation with its terms snapshot. Both the organization + // and the invitation scope the row, so another organization's identifier + // finds nothing. + ReadInvitation(ctx context.Context, arg ReadInvitationParams) (ReadInvitationRow, 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. ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error) // Reads a full owner-scoped record. Object values are identifiers only. @@ -937,6 +969,7 @@ type Querier interface { // compares it with the policy captured in the assigned result. SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error) SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error + SaveInvitationCreationResult(ctx context.Context, arg SaveInvitationCreationResultParams) error // Stores the immutable domain snapshot of a successful create command. The // generic idempotency row and this result are committed with the organization // and owner membership. A reused expired scope replaces the snapshot in the diff --git a/backend/internal/bootstrap/identity.go b/backend/internal/bootstrap/identity.go index 9928a44..b7ea153 100644 --- a/backend/internal/bootstrap/identity.go +++ b/backend/internal/bootstrap/identity.go @@ -41,6 +41,7 @@ func newAPIHandler( catalogHandler *v1.CatalogHandler, organizationHandler *v1.OrganizationHandler, needHandler *v1.NeedHandler, + invitationHandler *v1.InvitationHandler, supportHandler *v1.SupportHandler, assessmentHandler *v1.AssessmentHandler, assessmentSignalHandler *v1.AssessmentSignalHandler, @@ -57,6 +58,7 @@ func newAPIHandler( v1.WithCatalog(catalogHandler), v1.WithOrganization(organizationHandler), v1.WithNeed(needHandler), + v1.WithInvitation(invitationHandler), v1.WithSupport(supportHandler), v1.WithAssessment(assessmentHandler), v1.WithAssessmentSignals(assessmentSignalHandler), diff --git a/backend/internal/bootstrap/invitation.go b/backend/internal/bootstrap/invitation.go new file mode 100644 index 0000000..64be4b6 --- /dev/null +++ b/backend/internal/bootstrap/invitation.go @@ -0,0 +1,56 @@ +package bootstrap + +import ( + "context" + "fmt" + "log/slog" + "time" + + "lincodex/backend/config" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/invitation" +) + +const invitationPoolMaxConns = 4 + +// newInvitationHandler builds the invitation draft operations. They resolve a +// card handle through the same visibility service as the card read and the +// search, so the pseudonym key and the cohort rules are the ones of the cards. +func newInvitationHandler( + ctx context.Context, + settings config.Config, + logger *slog.Logger, + keyring *identity.Keyring, +) (*v1.InvitationHandler, func(), error) { + if settings.DatabaseURL == "" { + logger.Warn("invitation operations are not served because DATABASE_URL is not set") + return nil, func() {}, nil + } + if keyring == nil { + return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - identity keyring must be set") + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - derive projection key: %w", err) + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, invitationPoolMaxConns) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create pool: %w", err) + } + transactor := postgres.NewTransactor(pool) + views, err := newCandidateViewService(pool, transactor, key) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create view service: %w", err) + } + service, err := invitation.NewService(invitation.Dependencies{ + Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, Clock: time.Now, + }) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newInvitationHandler - create service: %w", err) + } + return v1.NewInvitationHandler(service), pool.Close, nil +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 50c200e..7894d04 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -53,6 +53,7 @@ func initialize( newCatalogHandler, newOrganizationHandler, newNeedHandler, + newInvitationHandler, newSupportHandler, newAssessmentHandler, newAssessmentSignalHandler, diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index d2101b5..caf29f2 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -122,7 +122,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - supportHandler, cleanup11, err := newSupportHandler(ctx, config2, logger, keyring) + invitationHandler, cleanup11, err := newInvitationHandler(ctx, config2, logger, keyring) if err != nil { cleanup10() cleanup9() @@ -136,7 +136,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - assessmentHandler, cleanup12, err := newAssessmentHandler(ctx, config2, logger, keyring) + supportHandler, cleanup12, err := newSupportHandler(ctx, config2, logger, keyring) if err != nil { cleanup11() cleanup10() @@ -151,7 +151,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - assessmentSignalHandler, cleanup13, err := newAssessmentSignalHandler(ctx, config2, logger, keyring) + assessmentHandler, cleanup13, err := newAssessmentHandler(ctx, config2, logger, keyring) if err != nil { cleanup12() cleanup11() @@ -167,7 +167,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - privacyHandler, cleanup14, err := newPrivacyHandler(ctx, config2, logger, keyring) + assessmentSignalHandler, cleanup14, err := newAssessmentSignalHandler(ctx, config2, logger, keyring) if err != nil { cleanup13() cleanup12() @@ -184,7 +184,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - evidenceHandler, cleanup15, err := newEvidenceHandler(ctx, config2, logger, keyring) + privacyHandler, cleanup15, err := newPrivacyHandler(ctx, config2, logger, keyring) if err != nil { cleanup14() cleanup13() @@ -202,7 +202,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - notificationHandler, cleanup16, err := newNotificationHandler(ctx, config2, logger) + evidenceHandler, cleanup16, err := newEvidenceHandler(ctx, config2, logger, keyring) if err != nil { cleanup15() cleanup14() @@ -221,7 +221,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - matchHandler, cleanup17, err := newMatchHandler(ctx, config2, logger, keyring) + notificationHandler, cleanup17, err := newNotificationHandler(ctx, config2, logger) if err != nil { cleanup16() cleanup15() @@ -241,52 +241,31 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler) + matchHandler, cleanup18, err := newMatchHandler(ctx, config2, logger, keyring) + if err != nil { + cleanup17() + cleanup16() + cleanup15() + cleanup14() + cleanup13() + cleanup12() + cleanup11() + cleanup10() + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, invitationHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler, notificationHandler, matchHandler) sessionSecurity := newSessionSecurity(identityHandler) v := newTrustedProxies(config2) httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler) - if err != nil { - cleanup17() - cleanup16() - cleanup15() - cleanup14() - cleanup13() - cleanup12() - cleanup11() - cleanup10() - cleanup9() - cleanup8() - cleanup7() - cleanup6() - cleanup5() - cleanup4() - cleanup3() - cleanup2() - cleanup() - return nil, nil, err - } - relay, cleanup18, err := newOutboxRelay(ctx, config2, logger, metrics) - if err != nil { - cleanup17() - cleanup16() - cleanup15() - cleanup14() - cleanup13() - cleanup12() - cleanup11() - cleanup10() - cleanup9() - cleanup8() - cleanup7() - cleanup6() - cleanup5() - cleanup4() - cleanup3() - cleanup2() - cleanup() - return nil, nil, err - } - bootstrapEventConsumers, cleanup19, err := newEventConsumers(ctx, config2, logger, metrics) if err != nil { cleanup18() cleanup17() @@ -308,7 +287,29 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - worker, cleanup20, err := newJobWorker(ctx, config2, logger, metrics) + relay, cleanup19, err := newOutboxRelay(ctx, config2, logger, metrics) + if err != nil { + cleanup18() + cleanup17() + cleanup16() + cleanup15() + cleanup14() + cleanup13() + cleanup12() + cleanup11() + cleanup10() + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + bootstrapEventConsumers, cleanup20, err := newEventConsumers(ctx, config2, logger, metrics) if err != nil { cleanup19() cleanup18() @@ -331,7 +332,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - mailsenderWorker, cleanup21, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) + worker, cleanup21, err := newJobWorker(ctx, config2, logger, metrics) if err != nil { cleanup20() cleanup19() @@ -355,7 +356,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - sampler, cleanup22, err := newDeliveryMetrics(ctx, config2, logger, metrics) + mailsenderWorker, cleanup22, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) if err != nil { cleanup21() cleanup20() @@ -380,8 +381,35 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } + sampler, cleanup23, err := newDeliveryMetrics(ctx, config2, logger, metrics) + if err != nil { + cleanup22() + cleanup21() + cleanup20() + cleanup19() + cleanup18() + cleanup17() + cleanup16() + cleanup15() + cleanup14() + cleanup13() + cleanup12() + cleanup11() + cleanup10() + cleanup9() + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler) return application, func() { + cleanup23() cleanup22() cleanup21() cleanup20() diff --git a/backend/internal/domain/invitation.go b/backend/internal/domain/invitation.go new file mode 100644 index 0000000..54d61cb --- /dev/null +++ b/backend/internal/domain/invitation.go @@ -0,0 +1,521 @@ +package domain + +import ( + "errors" + "fmt" + "log/slog" + "slices" + "time" + + "github.com/google/uuid" +) + +var ( + // ErrInvitationNotDraft reports a change of the terms, the need link, or + // the response period of an invitation that is no longer a draft. + ErrInvitationNotDraft = errors.New("invitation is not a draft") + + // ErrInvitationVersionConflict reports that an invitation changed after the + // caller read it. The API maps it to 412. + ErrInvitationVersionConflict = errors.New("invitation changed concurrently") +) + +const redactedInvitation = "[redacted invitation]" + +// InvitationState is the lifecycle state of an invitation (PRD FR12). The +// internal sending step is never a stored or visible state. +type InvitationState string + +const ( + InvitationDraft InvitationState = "draft" + InvitationDelivered InvitationState = "delivered" + InvitationViewed InvitationState = "viewed" + InvitationCounter InvitationState = "counter" + InvitationAccepted InvitationState = "accepted" + InvitationInterviewScheduled InvitationState = "interview_scheduled" + InvitationInterviewed InvitationState = "interviewed" + InvitationNegotiation InvitationState = "negotiation" + InvitationTermsAgreed InvitationState = "terms_agreed" + InvitationNoDeal InvitationState = "no_deal" + InvitationDeclined InvitationState = "declined" + InvitationExpired InvitationState = "expired" + InvitationWithdrawn InvitationState = "withdrawn" + InvitationCancelledByCandidate InvitationState = "cancelled_by_candidate" +) + +// invitationFirstVersion is the version of a new draft and of its terms. +const invitationFirstVersion = int64(1) + +func (state InvitationState) IsKnown() bool { + switch state { + case InvitationDraft, InvitationDelivered, InvitationViewed, InvitationCounter, InvitationAccepted, + InvitationInterviewScheduled, InvitationInterviewed, InvitationNegotiation, InvitationTermsAgreed, + InvitationNoDeal, InvitationDeclined, InvitationExpired, InvitationWithdrawn, InvitationCancelledByCandidate: + return true + default: + return false + } +} + +// InvitationExpiryReason says why an invitation expired. +type InvitationExpiryReason string + +const ( + InvitationExpiryTimeout InvitationExpiryReason = "invitation_timeout" + InvitationExpiryNegotiationTimeout InvitationExpiryReason = "negotiation_timeout" +) + +func (reason InvitationExpiryReason) IsKnown() bool { + return reason == InvitationExpiryTimeout || reason == InvitationExpiryNegotiationTimeout +} + +// InvitationNeedRef links an invitation to the need it was built from. The +// link is informational: the invitation keeps its own terms. +type InvitationNeedRef struct { + NeedID uuid.UUID `json:"need_id"` + RequirementsVersion int64 `json:"requirements_version"` +} + +func (ref InvitationNeedRef) valid() bool { + return ref.NeedID != uuid.Nil && ref.RequirementsVersion >= 1 +} + +// ResolveResponsePeriod returns the period the draft stores. An absent +// request takes the default of the policy, and a requested period must be one +// of its options. +func (policy InvitationPolicy) ResolveResponsePeriod(requested *CalendarDays) (CalendarDays, error) { + if requested == nil { + return policy.DefaultResponseDeadline, nil + } + if !slices.Contains(policy.ResponseDeadlineOptions, *requested) { + return 0, invalidInvitationField("/response_period_days", "must be one of the response periods of the product policy") + } + return *requested, nil +} + +// InvitationDraftContent is what the organization edits in a draft: the terms, +// the optional link to a need, and the response period. The candidate is not +// part of it, because a draft for another candidate is a new draft. +type InvitationDraftContent struct { + Need *InvitationNeedRef + ResponsePeriod CalendarDays + Terms InvitationTerms +} + +// InvitationChangedField names a part of a draft that a change touched. +type InvitationChangedField string + +const ( + InvitationChangedTerms InvitationChangedField = "terms" + InvitationChangedNeed InvitationChangedField = "need" + InvitationChangedResponsePeriod InvitationChangedField = "response_period_days" +) + +// ChangedFields lists, in a fixed order, the parts of other that differ from +// content. The terms are compared as stored, without validation. +func (content InvitationDraftContent) ChangedFields(other InvitationDraftContent) []InvitationChangedField { + changed := make([]InvitationChangedField, 0, 3) + if !content.Terms.Equal(other.Terms) { + changed = append(changed, InvitationChangedTerms) + } + if !equalNeedRef(content.Need, other.Need) { + changed = append(changed, InvitationChangedNeed) + } + if content.ResponsePeriod != other.ResponsePeriod { + changed = append(changed, InvitationChangedResponsePeriod) + } + return changed +} + +func equalNeedRef(left, right *InvitationNeedRef) bool { + if left == nil || right == nil { + return left == right + } + return *left == *right +} + +// Validate applies the rules of a draft that need no storage: the terms and +// the shape of the need link. Whether the need exists is checked by the +// usecase against storage. +func (content InvitationDraftContent) Validate() error { + if content.Need != nil && !content.Need.valid() { + return invalidInvitationField("/need", "must name a need and a requirements version") + } + if content.ResponsePeriod < 1 { + return invalidInvitationField("/response_period_days", "must be positive") + } + return content.Terms.Validate() +} + +// StoredInvitation is the persisted form of an invitation. Only +// RestoreInvitation turns it into an Invitation. +type StoredInvitation struct { + ID uuid.UUID + OrganizationID uuid.UUID + CandidateID uuid.UUID + Need *InvitationNeedRef + State string + ExpiryReason *string + Version int64 + TermsVersion int64 + Terms InvitationTerms + ResponsePeriodDays int32 + PolicyVersionID PolicyVersionID + ResponseDeadlineAt *time.Time + SalaryRaiseUsed bool + CreatedBy uuid.UUID + CreatedAt time.Time + UpdatedAt time.Time + DeliveredAt *time.Time + ViewedAt *time.Time + RespondedAt *time.Time +} + +// Invitation is an offer of one organization to one candidate. The candidate +// identifier is internal: it is never serialized, logged, or printed. +type Invitation struct { + record StoredInvitation +} + +// NewInvitationDraftInput describes a draft that the organization creates. +type NewInvitationDraftInput struct { + ID uuid.UUID + OrganizationID uuid.UUID + CandidateID uuid.UUID + ActorID uuid.UUID + PolicyVersionID PolicyVersionID + Content InvitationDraftContent + At time.Time +} + +// NewInvitationDraft builds version 1 of a draft with terms version 1. The +// candidate does not see a draft. +func NewInvitationDraft(input NewInvitationDraftInput) (Invitation, error) { + const location = "domain.NewInvitationDraft" + if input.ID == uuid.Nil || input.OrganizationID == uuid.Nil || input.CandidateID == uuid.Nil || + input.ActorID == uuid.Nil || input.PolicyVersionID.IsZero() || !validInvitationTime(input.At) { + return Invitation{}, fmt.Errorf("%s - identifiers and time must be set: %w", location, ErrInvalidInvitation) + } + if err := input.Content.Validate(); err != nil { + return Invitation{}, fmt.Errorf("%s - validate draft: %w", location, err) + } + content := cloneDraftContent(input.Content) + return RestoreInvitation(StoredInvitation{ + ID: input.ID, OrganizationID: input.OrganizationID, CandidateID: input.CandidateID, + Need: content.Need, State: string(InvitationDraft), Version: invitationFirstVersion, + TermsVersion: invitationFirstVersion, Terms: content.Terms, ResponsePeriodDays: int32(content.ResponsePeriod), + PolicyVersionID: input.PolicyVersionID, CreatedBy: input.ActorID, CreatedAt: input.At.UTC(), UpdatedAt: input.At.UTC(), + }) +} + +func cloneDraftContent(content InvitationDraftContent) InvitationDraftContent { + content.Terms = content.Terms.Clone() + if content.Need != nil { + need := *content.Need + content.Need = &need + } + return content +} + +// RestoreInvitation validates a stored invitation, so a row changed outside +// the application is not served. +func RestoreInvitation(stored StoredInvitation) (Invitation, error) { + const location = "domain.RestoreInvitation" + for _, defect := range []func(StoredInvitation) string{ + storedInvitationIdentityDefect, storedInvitationVersionDefect, storedInvitationLifecycleDefect, + } { + if reason := defect(stored); reason != "" { + return Invitation{}, fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidInvitation) + } + } + if err := stored.Terms.Validate(); err != nil { + return Invitation{}, fmt.Errorf("%s - validate terms: %w", location, err) + } + stored.Terms = stored.Terms.Clone() + stored.CreatedAt, stored.UpdatedAt = stored.CreatedAt.UTC(), stored.UpdatedAt.UTC() + if stored.Need != nil { + need := *stored.Need + stored.Need = &need + } + return Invitation{record: stored}, nil +} + +// storedInvitationIdentityDefect checks the identifiers, the state, and the +// expiry reason. It returns the reason of the first defect or "". +func storedInvitationIdentityDefect(stored StoredInvitation) string { + state := InvitationState(stored.State) + switch { + case stored.ID == uuid.Nil || stored.OrganizationID == uuid.Nil || stored.CandidateID == uuid.Nil || + stored.CreatedBy == uuid.Nil || stored.PolicyVersionID.IsZero(): + return "identifiers must be set" + case !state.IsKnown(): + return "state is unknown" + case (state == InvitationExpired) != (stored.ExpiryReason != nil) || + (stored.ExpiryReason != nil && !InvitationExpiryReason(*stored.ExpiryReason).IsKnown()): + return "expiry reason does not match the state" + } + return "" +} + +// storedInvitationVersionDefect checks the versions, the need link, the +// timestamps, and the response period. +func storedInvitationVersionDefect(stored StoredInvitation) string { + switch { + case stored.Version < invitationFirstVersion || stored.TermsVersion < invitationFirstVersion || stored.TermsVersion > stored.Version: + return "versions are out of range" + case stored.Need != nil && !stored.Need.valid(): + return "need link is invalid" + case !validInvitationTime(stored.CreatedAt) || !validInvitationTime(stored.UpdatedAt) || stored.UpdatedAt.Before(stored.CreatedAt): + return "timestamps are invalid" + case stored.ResponsePeriodDays < 1: + return "response period must be positive" + } + return "" +} + +// storedInvitationLifecycleDefect checks that a draft is unsent and that the +// deadline is set together with the delivery. +func storedInvitationLifecycleDefect(stored StoredInvitation) string { + switch { + case InvitationState(stored.State) == InvitationDraft && (stored.DeliveredAt != nil || stored.ViewedAt != nil || + stored.RespondedAt != nil || stored.ResponseDeadlineAt != nil || stored.SalaryRaiseUsed): + return "a draft has no delivery, view, answer, or raise" + case (stored.ResponseDeadlineAt == nil) != (stored.DeliveredAt == nil): + return "deadline and delivery are set together" + } + return "" +} + +func validInvitationTime(value time.Time) bool { + return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 +} + +func (invitation Invitation) ID() uuid.UUID { return invitation.record.ID } +func (invitation Invitation) OrganizationID() uuid.UUID { return invitation.record.OrganizationID } + +// CandidateID is internal: only the server resolves it, and no response, +// log, or error shows it. +func (invitation Invitation) CandidateID() uuid.UUID { return invitation.record.CandidateID } +func (invitation Invitation) State() InvitationState { return InvitationState(invitation.record.State) } +func (invitation Invitation) Version() int64 { return invitation.record.Version } +func (invitation Invitation) TermsVersion() int64 { return invitation.record.TermsVersion } +func (invitation Invitation) PolicyVersionID() PolicyVersionID { + return invitation.record.PolicyVersionID +} +func (invitation Invitation) CreatedAt() time.Time { return invitation.record.CreatedAt } +func (invitation Invitation) UpdatedAt() time.Time { return invitation.record.UpdatedAt } + +// Stored returns a deep copy of the persisted form. +func (invitation Invitation) Stored() StoredInvitation { + stored := invitation.record + stored.Terms = stored.Terms.Clone() + if stored.Need != nil { + need := *stored.Need + stored.Need = &need + } + stored.ExpiryReason = cloneString(stored.ExpiryReason) + stored.ResponseDeadlineAt = cloneTime(stored.ResponseDeadlineAt) + stored.DeliveredAt = cloneTime(stored.DeliveredAt) + stored.ViewedAt = cloneTime(stored.ViewedAt) + stored.RespondedAt = cloneTime(stored.RespondedAt) + return stored +} + +func cloneTime(value *time.Time) *time.Time { + if value == nil { + return nil + } + copied := *value + return &copied +} + +// DraftContent returns the editable part of the invitation. +func (invitation Invitation) DraftContent() InvitationDraftContent { + stored := invitation.Stored() + return InvitationDraftContent{ + Need: stored.Need, ResponsePeriod: CalendarDays(stored.ResponsePeriodDays), Terms: stored.Terms, + } +} + +// ReviseDraft returns the draft with the new content as the next version. A +// change of the terms also creates the next terms version, an immutable +// snapshot; a change of anything else keeps the terms version. Content that +// changes nothing returns the invitation as it is and no changed fields. Only +// a draft can change. +func (invitation Invitation) ReviseDraft( + content InvitationDraftContent, + policyVersionID PolicyVersionID, + at time.Time, +) (Invitation, []InvitationChangedField, error) { + const location = "Invitation.ReviseDraft" + if invitation.State() != InvitationDraft { + return Invitation{}, nil, fmt.Errorf("%s - only a draft can change: %w", location, ErrInvitationNotDraft) + } + if policyVersionID.IsZero() || !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) { + return Invitation{}, nil, fmt.Errorf("%s - policy version and a non-decreasing time must be set: %w", location, ErrInvalidInvitation) + } + if err := content.Validate(); err != nil { + return Invitation{}, nil, fmt.Errorf("%s - validate draft: %w", location, err) + } + changed := invitation.DraftContent().ChangedFields(content) + if len(changed) == 0 { + return invitation, nil, nil + } + next := invitation.Stored() + content = cloneDraftContent(content) + next.Need, next.Terms, next.ResponsePeriodDays = content.Need, content.Terms, int32(content.ResponsePeriod) + if slices.Contains(changed, InvitationChangedResponsePeriod) { + next.PolicyVersionID = policyVersionID + } + if slices.Contains(changed, InvitationChangedTerms) { + next.TermsVersion++ + } + next.Version++ + next.UpdatedAt = at.UTC() + revised, err := RestoreInvitation(next) + if err != nil { + return Invitation{}, nil, fmt.Errorf("%s - restore revised draft: %w", location, err) + } + return revised, changed, nil +} + +// InvitationEventKind is the kind of an audit event. +type InvitationEventKind string + +const ( + InvitationEventDraftCreated InvitationEventKind = "draft_created" + InvitationEventDraftUpdated InvitationEventKind = "draft_updated" +) + +// InvitationEvent is the audit record of one committed invitation version. It +// names the actor and the parts that changed and holds no content. +type InvitationEvent struct { + ID uuid.UUID + InvitationID uuid.UUID + OrganizationID uuid.UUID + Version int64 + TermsVersion int64 + Kind InvitationEventKind + ActorID uuid.UUID + ChangedFields []InvitationChangedField + OccurredAt time.Time +} + +// DraftEvent builds the audit event of the version this invitation has just +// reached through a draft change by actor. A creation event has version 1. +func (invitation Invitation) DraftEvent(actorID uuid.UUID, changed []InvitationChangedField) (InvitationEvent, error) { + const location = "Invitation.DraftEvent" + id, err := uuid.NewV7() + if err != nil { + return InvitationEvent{}, fmt.Errorf("%s - generate event ID: %w", location, err) + } + if actorID == uuid.Nil { + return InvitationEvent{}, fmt.Errorf("%s - actor must be set: %w", location, ErrInvalidInvitation) + } + kind := InvitationEventDraftUpdated + if invitation.record.Version == invitationFirstVersion { + kind = InvitationEventDraftCreated + changed = []InvitationChangedField{} + } + 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: slices.Clone(changed), OccurredAt: invitation.record.UpdatedAt, + }, nil +} + +// InvitationSalaryFit is the coarse indicator of the salary range against the +// candidate's hidden minimum (PRD FR13). +type InvitationSalaryFit string + +const ( + InvitationSalaryWithinRange InvitationSalaryFit = "within_range" + InvitationSalaryUpToTenPercent InvitationSalaryFit = "up_to_10_percent_above" + InvitationSalaryAbove InvitationSalaryFit = "above" + InvitationSalaryWithheld InvitationSalaryFit = "withheld" + InvitationSalaryNotAvailable InvitationSalaryFit = "not_available" +) + +// InvitationContactAccess says whether the organization may read contacts +// through the invitation now. +type InvitationContactAccess string + +const ( + InvitationContactAccessNone InvitationContactAccess = "not_granted" + InvitationContactAccessAvailable InvitationContactAccess = "available" + InvitationContactAccessClosed InvitationContactAccess = "closed" +) + +// InvitationSnapshot is the serializable part of an invitation that an +// organization may read. It has no candidate identifier, so it cannot reveal +// who the invitation is for. +type InvitationSnapshot struct { + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"organization_id"` + Need *InvitationNeedRef `json:"need"` + State InvitationState `json:"state"` + ExpiryReason *InvitationExpiryReason `json:"expiry_reason"` + Version int64 `json:"version"` + TermsVersion int64 `json:"terms_version"` + Terms InvitationTerms `json:"terms"` + ResponsePeriodDays int32 `json:"response_period_days"` + ResponseDeadlineAt *time.Time `json:"response_deadline_at"` + SalaryRaiseUsed bool `json:"salary_raise_used"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + DeliveredAt *time.Time `json:"delivered_at"` + ViewedAt *time.Time `json:"viewed_at"` + RespondedAt *time.Time `json:"responded_at"` +} + +// Snapshot returns the organization-facing part of the invitation. +func (invitation Invitation) Snapshot() InvitationSnapshot { + stored := invitation.Stored() + var reason *InvitationExpiryReason + if stored.ExpiryReason != nil { + value := InvitationExpiryReason(*stored.ExpiryReason) + reason = &value + } + return InvitationSnapshot{ + ID: stored.ID, OrganizationID: stored.OrganizationID, Need: stored.Need, State: InvitationState(stored.State), + ExpiryReason: reason, Version: stored.Version, TermsVersion: stored.TermsVersion, Terms: stored.Terms, + ResponsePeriodDays: stored.ResponsePeriodDays, ResponseDeadlineAt: stored.ResponseDeadlineAt, + SalaryRaiseUsed: stored.SalaryRaiseUsed, CreatedAt: stored.CreatedAt, UpdatedAt: stored.UpdatedAt, + DeliveredAt: stored.DeliveredAt, ViewedAt: stored.ViewedAt, RespondedAt: stored.RespondedAt, + } +} + +// OrganizationInvitationView is an invitation as its organization reads it: +// the snapshot, the organization-scoped alias of the candidate, the coarse +// salary indicator, and the state of the contact access without any contact +// value. It also serves as the stored original response of an idempotent +// create. +type OrganizationInvitationView struct { + InvitationSnapshot + + CandidateHandle string `json:"candidate_handle"` + SalaryFit InvitationSalaryFit `json:"salary_fit"` + ContactAccess InvitationContactAccess `json:"contact_access"` +} + +func (invitation Invitation) String() string { return redactedInvitation } +func (invitation Invitation) GoString() string { return redactedInvitation } +func (invitation Invitation) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedInvitation) +} +func (invitation Invitation) LogValue() slog.Value { return slog.StringValue(redactedInvitation) } + +func (view OrganizationInvitationView) String() string { return redactedInvitation } +func (view OrganizationInvitationView) GoString() string { return redactedInvitation } +func (view OrganizationInvitationView) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedInvitation) +} +func (view OrganizationInvitationView) LogValue() slog.Value { + return slog.StringValue(redactedInvitation) +} + +func (snapshot InvitationSnapshot) String() string { return redactedInvitation } +func (snapshot InvitationSnapshot) GoString() string { return redactedInvitation } +func (snapshot InvitationSnapshot) Format(state fmt.State, _ rune) { + writeRedacted(state, redactedInvitation) +} diff --git a/backend/internal/domain/invitation_terms.go b/backend/internal/domain/invitation_terms.go new file mode 100644 index 0000000..c792830 --- /dev/null +++ b/backend/internal/domain/invitation_terms.go @@ -0,0 +1,418 @@ +package domain + +import ( + "encoding/json" + "errors" + "fmt" + "reflect" + "slices" + "strconv" + "strings" + "unicode" + "unicode/utf8" +) + +// ErrInvalidInvitation reports an invitation value that breaks the public +// contract or cannot be restored from storage. +var ErrInvalidInvitation = errors.New("invalid invitation") + +// InvitationFieldError names the field of an invitation request that failed. +// Pointer is a JSON Pointer into the request body, such as +// /terms/salary/salary_to. The error carries the reason only, never a value: +// terms are employer text, and a rejected value is not echoed. +type InvitationFieldError struct { + Pointer string + Reason string +} + +func (err *InvitationFieldError) Error() string { + return fmt.Sprintf("invitation field %s: %s", err.Pointer, err.Reason) +} + +func (err *InvitationFieldError) Unwrap() error { return ErrInvalidInvitation } + +func invalidInvitationField(pointer, reason string) error { + return &InvitationFieldError{Pointer: pointer, Reason: reason} +} + +const ( + maxInvitationRoleTitleRunes = 200 + maxInvitationTaskRunes = 300 + maxInvitationTeamRunes = 1000 + maxInvitationTechnologyRunes = 100 + maxInvitationLocationRunes = 100 + maxInvitationNoteRunes = 300 + maxInvitationPackageTextRunes = 300 + maxInvitationTasks = 20 + maxInvitationTechnologies = 30 + maxInvitationWorkFormats = 3 + // MaxInvitationTermsBytes bounds the encoded terms of one version. The + // longest text fields fit with room even when every character takes four + // bytes; the database repeats the bound with a margin for jsonb spacing. + MaxInvitationTermsBytes = 98304 +) + +// InvitationOfferType is the type of the offer. +type InvitationOfferType string + +const ( + InvitationOfferFullTime InvitationOfferType = "full_time" + InvitationOfferPartTime InvitationOfferType = "part_time" + InvitationOfferContract InvitationOfferType = "contract" + InvitationOfferInternship InvitationOfferType = "internship" +) + +func (offer InvitationOfferType) IsKnown() bool { + switch offer { + case InvitationOfferFullTime, InvitationOfferPartTime, InvitationOfferContract, InvitationOfferInternship: + return true + default: + return false + } +} + +// InvitationCommunicationChannel is how the organization plans to reach the +// candidate after an acceptance. It never selects a contact field. +type InvitationCommunicationChannel string + +const ( + InvitationChannelEmail InvitationCommunicationChannel = "email" + InvitationChannelPhone InvitationCommunicationChannel = "phone" + InvitationChannelTelegram InvitationCommunicationChannel = "telegram" + InvitationChannelVideoCall InvitationCommunicationChannel = "video_call" +) + +func (channel InvitationCommunicationChannel) IsKnown() bool { + switch channel { + case InvitationChannelEmail, InvitationChannelPhone, InvitationChannelTelegram, InvitationChannelVideoCall: + return true + default: + return false + } +} + +// InvitationCommunicationMethod is part of the terms: a draft without it +// cannot exist. +type InvitationCommunicationMethod struct { + Channel InvitationCommunicationChannel `json:"channel"` + Details *string `json:"details"` +} + +// InvitationPackageStatus says whether a package condition is offered. +type InvitationPackageStatus string + +const ( + InvitationPackageProvided InvitationPackageStatus = "provided" + InvitationPackageNotProvided InvitationPackageStatus = "not_provided" +) + +// InvitationPackageItem is one required package condition. "Not provided" is +// an explicit choice with no description; a missing condition is not the same +// thing and fails validation. +type InvitationPackageItem struct { + Status InvitationPackageStatus `json:"status"` + Description *string `json:"description,omitempty"` +} + +// InvitationPackage is the required section of the package (PRD FR12). The +// work format is the separate required term WorkFormats. +type InvitationPackage struct { + Bonus InvitationPackageItem `json:"bonus"` + Equipment InvitationPackageItem `json:"equipment"` + Training InvitationPackageItem `json:"training"` + HealthInsurance InvitationPackageItem `json:"health_insurance"` +} + +// InvitationTerms is everything a candidate sees before deciding. The same +// value is the request field of a draft and the stored snapshot of a terms +// version. It holds no data of the candidate. +type InvitationTerms struct { + RoleTitle string `json:"role_title"` + Specialization SpecializationCode `json:"specialization"` + Grade GradeCode `json:"grade"` + OfferType InvitationOfferType `json:"offer_type"` + Tasks []string `json:"tasks"` + Team string `json:"team"` + TechStack []string `json:"tech_stack"` + WorkFormats []NeedWorkFormat `json:"work_formats"` + Location *string `json:"location"` + CommunicationMethod InvitationCommunicationMethod `json:"communication_method"` + Salary SalaryRange `json:"salary"` + Package InvitationPackage `json:"package"` +} + +// Validate applies the rules the schema cannot express and repeats the +// schema rules a stored value must also satisfy. The error is an +// *InvitationFieldError with the pointer of the first failing field. +func (terms InvitationTerms) Validate() error { + checks := []func() error{ + func() error { + if !validInvitationLine(terms.RoleTitle, maxInvitationRoleTitleRunes) { + return invalidInvitationField("/terms/role_title", "must be one line of 1 to 200 characters") + } + return nil + }, + func() error { + if !terms.Specialization.IsKnown() { + return invalidInvitationField("/terms/specialization", "must be a known specialization") + } + return nil + }, + func() error { + if !terms.Grade.IsKnown() { + return invalidInvitationField("/terms/grade", "must be a known grade") + } + return nil + }, + func() error { + if !terms.OfferType.IsKnown() { + return invalidInvitationField("/terms/offer_type", "must be a known offer type") + } + return nil + }, + terms.validateTasks, + func() error { + if !validInvitationText(terms.Team, maxInvitationTeamRunes) { + return invalidInvitationField("/terms/team", "must be text of 1 to 1000 characters") + } + return nil + }, + terms.validateTechStack, + terms.validateWorkFormats, + terms.validateLocation, + terms.validateCommunicationMethod, + terms.validateSalary, + terms.Package.validate, + } + for _, check := range checks { + if err := check(); err != nil { + return err + } + } + return nil +} + +func (terms InvitationTerms) validateTasks() error { + if len(terms.Tasks) < 1 || len(terms.Tasks) > maxInvitationTasks { + return invalidInvitationField("/terms/tasks", "must have 1 to 20 tasks") + } + for index, task := range terms.Tasks { + if !validInvitationLine(task, maxInvitationTaskRunes) { + return invalidInvitationField("/terms/tasks/"+strconv.Itoa(index), "must be one line of 1 to 300 characters") + } + } + return nil +} + +// validateTechStack compares names without regard to letter case, so Go and +// GO are one technology. The pointer names the later of two equal items. +func (terms InvitationTerms) validateTechStack() error { + if len(terms.TechStack) < 1 || len(terms.TechStack) > maxInvitationTechnologies { + return invalidInvitationField("/terms/tech_stack", "must have 1 to 30 technologies") + } + seen := make(map[string]struct{}, len(terms.TechStack)) + for index, name := range terms.TechStack { + pointer := "/terms/tech_stack/" + strconv.Itoa(index) + if !validInvitationLine(name, maxInvitationTechnologyRunes) { + return invalidInvitationField(pointer, "must be one line of 1 to 100 characters") + } + folded := strings.ToLower(name) + if _, duplicate := seen[folded]; duplicate { + return invalidInvitationField(pointer, "must not repeat a technology") + } + seen[folded] = struct{}{} + } + return nil +} + +func (terms InvitationTerms) validateWorkFormats() error { + if len(terms.WorkFormats) < 1 || len(terms.WorkFormats) > maxInvitationWorkFormats { + return invalidInvitationField("/terms/work_formats", "must have 1 to 3 work formats") + } + for index, format := range terms.WorkFormats { + pointer := "/terms/work_formats/" + strconv.Itoa(index) + if !format.IsKnown() { + return invalidInvitationField(pointer, "must be a known work format") + } + if slices.Contains(terms.WorkFormats[:index], format) { + return invalidInvitationField(pointer, "must not repeat a work format") + } + } + return nil +} + +// validateLocation requires a place of work whenever the role has an office: +// only a fully remote role may leave it null. +func (terms InvitationTerms) validateLocation() error { + officeFormat := slices.Contains(terms.WorkFormats, NeedWorkFormatOffice) || slices.Contains(terms.WorkFormats, NeedWorkFormatHybrid) + if terms.Location == nil { + if officeFormat { + return invalidInvitationField("/terms/location", "is required for the office or hybrid format") + } + return nil + } + if !validInvitationLine(*terms.Location, maxInvitationLocationRunes) { + return invalidInvitationField("/terms/location", "must be one line of 1 to 100 characters") + } + return nil +} + +func (terms InvitationTerms) validateCommunicationMethod() error { + method := terms.CommunicationMethod + if !method.Channel.IsKnown() { + return invalidInvitationField("/terms/communication_method/channel", "must be a known channel") + } + if method.Details != nil && !validInvitationLine(*method.Details, maxInvitationNoteRunes) { + return invalidInvitationField("/terms/communication_method/details", "must be one line of 1 to 300 characters") + } + return nil +} + +func (terms InvitationTerms) validateSalary() error { + err := terms.Salary.Validate() + if err == nil { + return nil + } + if rangeError, ok := errors.AsType[*SalaryRangeError](err); ok { + return invalidInvitationField("/terms/salary/"+rangeError.Field, rangeError.Reason) + } + return invalidInvitationField("/terms/salary", "must be a valid monthly RUB range") +} + +func (pack InvitationPackage) validate() error { + items := []struct { + name string + item InvitationPackageItem + }{ + {"bonus", pack.Bonus}, {"equipment", pack.Equipment}, + {"training", pack.Training}, {"health_insurance", pack.HealthInsurance}, + } + for _, entry := range items { + if err := entry.item.validate("/terms/package/" + entry.name); err != nil { + return err + } + } + return nil +} + +func (item InvitationPackageItem) validate(pointer string) error { + switch item.Status { + case InvitationPackageProvided: + if item.Description == nil { + return invalidInvitationField(pointer+"/description", "is required for a provided condition") + } + if !validInvitationLine(*item.Description, maxInvitationPackageTextRunes) { + return invalidInvitationField(pointer+"/description", "must be one line of 1 to 300 characters") + } + case InvitationPackageNotProvided: + if item.Description != nil { + return invalidInvitationField(pointer, "a condition that is not provided has no description") + } + default: + return invalidInvitationField(pointer+"/status", "must be provided or not_provided") + } + return nil +} + +// Clone returns a deep copy, so a caller cannot change a stored value. +func (terms InvitationTerms) Clone() InvitationTerms { + cloned := terms + cloned.Tasks = slices.Clone(terms.Tasks) + cloned.TechStack = slices.Clone(terms.TechStack) + cloned.WorkFormats = slices.Clone(terms.WorkFormats) + cloned.Location = cloneString(terms.Location) + cloned.CommunicationMethod.Details = cloneString(terms.CommunicationMethod.Details) + cloned.Package = InvitationPackage{ + Bonus: terms.Package.Bonus.clone(), Equipment: terms.Package.Equipment.clone(), + Training: terms.Package.Training.clone(), HealthInsurance: terms.Package.HealthInsurance.clone(), + } + return cloned +} + +func (item InvitationPackageItem) clone() InvitationPackageItem { + item.Description = cloneString(item.Description) + return item +} + +func cloneString(value *string) *string { + if value == nil { + return nil + } + copied := *value + return &copied +} + +// Equal reports whether two terms hold the same content. A reordered list is +// a different content, because the order of tasks and technologies is shown. +func (terms InvitationTerms) Equal(other InvitationTerms) bool { + return reflect.DeepEqual(terms, other) +} + +// EncodeInvitationTerms returns the canonical JSON of a validated snapshot. +func EncodeInvitationTerms(terms InvitationTerms) ([]byte, error) { + if err := terms.Validate(); err != nil { + return nil, fmt.Errorf("domain.EncodeInvitationTerms - validate terms: %w", err) + } + encoded, err := json.Marshal(terms) + if err != nil { + return nil, fmt.Errorf("domain.EncodeInvitationTerms - encode terms: %w", err) + } + if len(encoded) > MaxInvitationTermsBytes { + return nil, fmt.Errorf("domain.EncodeInvitationTerms - terms exceed %d bytes: %w", MaxInvitationTermsBytes, ErrInvalidInvitation) + } + return encoded, nil +} + +// DecodeInvitationTerms restores a stored snapshot. Unknown fields, trailing +// data, and rule violations fail, so a row changed outside the application is +// not served. +func DecodeInvitationTerms(encoded []byte) (InvitationTerms, error) { + const location = "domain.DecodeInvitationTerms" + if len(encoded) == 0 || len(encoded) > MaxInvitationTermsBytes { + return InvitationTerms{}, fmt.Errorf("%s - stored terms are outside their size bound: %w", location, ErrInvalidInvitation) + } + var terms InvitationTerms + if err := decodeStrictJSON(encoded, &terms); err != nil { + return InvitationTerms{}, fmt.Errorf("%s - decode terms: %w: %w", location, ErrInvalidInvitation, err) + } + if err := terms.Validate(); err != nil { + return InvitationTerms{}, fmt.Errorf("%s - validate terms: %w", location, err) + } + return terms, nil +} + +// validInvitationLine accepts one line of plain text: 1 to maxRunes +// characters, no control character, and no ASCII whitespace at either end. +func validInvitationLine(value string, maxRunes int) bool { + if !validInvitationText(value, maxRunes) { + return false + } + return !strings.ContainsAny(value, "\r\n\t") +} + +// validInvitationText accepts plain text of 1 to maxRunes characters that may +// contain line breaks and tabs but no other control character, and does not +// start or end with ASCII whitespace. +func validInvitationText(value string, maxRunes int) bool { + if value == "" || !utf8.ValidString(value) || utf8.RuneCountInString(value) > maxRunes { + return false + } + if strings.TrimFunc(value, isASCIISpace) != value { + return false + } + for _, character := range value { + if unicode.IsControl(character) && character != '\n' && character != '\r' && character != '\t' { + return false + } + } + return true +} + +func isASCIISpace(character rune) bool { + switch character { + case ' ', '\t', '\n', '\v', '\f', '\r': + return true + default: + return false + } +} diff --git a/backend/internal/domain/invitation_test.go b/backend/internal/domain/invitation_test.go new file mode 100644 index 0000000..e8a040d --- /dev/null +++ b/backend/internal/domain/invitation_test.go @@ -0,0 +1,296 @@ +package domain + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +func invitationTestString(value string) *string { return &value } + +func validInvitationTerms() InvitationTerms { + provided := func(text string) InvitationPackageItem { + return InvitationPackageItem{Status: InvitationPackageProvided, Description: invitationTestString(text)} + } + return InvitationTerms{ + RoleTitle: "Middle Go developer", + Specialization: SpecializationBackend, + Grade: GradeMiddle, + OfferType: InvitationOfferFullTime, + Tasks: []string{"Move the payout service to an event model"}, + Team: "Six engineers\nworking in two-week iterations", + TechStack: []string{"Go", "PostgreSQL"}, + WorkFormats: []NeedWorkFormat{NeedWorkFormatRemote}, + CommunicationMethod: InvitationCommunicationMethod{ + Channel: InvitationChannelEmail, + }, + Salary: SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: SalaryCurrencyRUB, Period: SalaryPeriodMonth, TaxBasis: SalaryTaxNet}, + Package: InvitationPackage{ + Bonus: provided("Quarterly bonus"), + Equipment: provided("Laptop"), + Training: InvitationPackageItem{Status: InvitationPackageNotProvided}, + HealthInsurance: InvitationPackageItem{Status: InvitationPackageNotProvided}, + }, + } +} + +func validInvitationDraftInput() NewInvitationDraftInput { + policyID, _ := NewPolicyVersionID() + return NewInvitationDraftInput{ + ID: uuid.New(), OrganizationID: uuid.New(), CandidateID: uuid.New(), ActorID: uuid.New(), + PolicyVersionID: policyID, + Content: InvitationDraftContent{ResponsePeriod: 7, Terms: validInvitationTerms()}, + At: time.Date(2026, 10, 9, 12, 0, 0, 123456789, time.UTC), + } +} + +func TestNewInvitationDraftStartsAtVersionOne(t *testing.T) { + input := validInvitationDraftInput() + draft, err := NewInvitationDraft(input) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + snapshot := draft.Snapshot() + if snapshot.State != InvitationDraft || snapshot.Version != 1 || snapshot.TermsVersion != 1 || + snapshot.ResponseDeadlineAt != nil || snapshot.DeliveredAt != nil || snapshot.SalaryRaiseUsed || snapshot.ExpiryReason != nil { + t.Fatalf("draft snapshot = %+v, want an unsent version 1", snapshot) + } + event, err := draft.DraftEvent(input.ActorID, []InvitationChangedField{InvitationChangedTerms}) + if err != nil { + t.Fatalf("DraftEvent() error = %v", err) + } + if event.Kind != InvitationEventDraftCreated || event.Version != 1 || len(event.ChangedFields) != 0 { + t.Fatalf("creation event = %+v, want draft_created at version 1 with no changed fields", event) + } +} + +func TestInvitationTermsValidationPointsAtTheFailingField(t *testing.T) { + tests := []struct { + name string + change func(*InvitationTerms) + wantPointer string + }{ + {"role title with a line break", func(t *InvitationTerms) { t.RoleTitle = "Go\ndeveloper" }, "/terms/role_title"}, + {"role title with a NUL", func(t *InvitationTerms) { t.RoleTitle = "Go\x00developer" }, "/terms/role_title"}, + {"role title with edge whitespace", func(t *InvitationTerms) { t.RoleTitle = " Go developer" }, "/terms/role_title"}, + {"unknown specialization", func(t *InvitationTerms) { t.Specialization = "wizard" }, "/terms/specialization"}, + {"unknown grade", func(t *InvitationTerms) { t.Grade = "guru" }, "/terms/grade"}, + {"unknown offer type", func(t *InvitationTerms) { t.OfferType = "volunteer" }, "/terms/offer_type"}, + {"no tasks", func(t *InvitationTerms) { t.Tasks = nil }, "/terms/tasks"}, + {"empty second task", func(t *InvitationTerms) { t.Tasks = []string{"First", ""} }, "/terms/tasks/1"}, + {"empty team", func(t *InvitationTerms) { t.Team = "" }, "/terms/team"}, + {"repeated technology ignoring case", func(t *InvitationTerms) { t.TechStack = []string{"Go", "PostgreSQL", "GO"} }, "/terms/tech_stack/2"}, + {"repeated work format", func(t *InvitationTerms) { + t.WorkFormats = []NeedWorkFormat{NeedWorkFormatRemote, NeedWorkFormatRemote} + t.Location = invitationTestString("Moscow") + }, "/terms/work_formats/1"}, + {"office without a place", func(t *InvitationTerms) { t.WorkFormats = []NeedWorkFormat{NeedWorkFormatOffice} }, "/terms/location"}, + {"hybrid among remote without a place", func(t *InvitationTerms) { + t.WorkFormats = []NeedWorkFormat{NeedWorkFormatRemote, NeedWorkFormatHybrid} + }, "/terms/location"}, + {"unknown channel", func(t *InvitationTerms) { t.CommunicationMethod.Channel = "pigeon" }, "/terms/communication_method/channel"}, + {"empty communication note", func(t *InvitationTerms) { t.CommunicationMethod.Details = invitationTestString("") }, "/terms/communication_method/details"}, + {"reversed salary", func(t *InvitationTerms) { t.Salary.SalaryFrom, t.Salary.SalaryTo = 140_000, 100_000 }, "/terms/salary/salary_to"}, + {"salary without a basis", func(t *InvitationTerms) { t.Salary.TaxBasis = "" }, "/terms/salary/tax_basis"}, + {"zero lower bound", func(t *InvitationTerms) { t.Salary.SalaryFrom = 0 }, "/terms/salary/salary_from"}, + {"lower bound off the step", func(t *InvitationTerms) { t.Salary.SalaryFrom = 100_500 }, "/terms/salary/salary_from"}, + {"bonus left without a status", func(t *InvitationTerms) { t.Package.Bonus = InvitationPackageItem{} }, "/terms/package/bonus/status"}, + {"provided without a description", func(t *InvitationTerms) { + t.Package.Training = InvitationPackageItem{Status: InvitationPackageProvided} + }, "/terms/package/training/description"}, + {"not provided with a description", func(t *InvitationTerms) { + t.Package.HealthInsurance = InvitationPackageItem{Status: InvitationPackageNotProvided, Description: invitationTestString("Premium plan")} + }, "/terms/package/health_insurance"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + terms := validInvitationTerms() + test.change(&terms) + var field *InvitationFieldError + err := terms.Validate() + if !errors.As(err, &field) || field.Pointer != test.wantPointer || !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("Validate() error = %v, want a field error at %s", err, test.wantPointer) + } + }) + } +} + +// Every package condition may explicitly be "not provided"; the explicit +// choice is a complete package. +func TestInvitationPackageMayDeclareEveryConditionNotProvided(t *testing.T) { + terms := validInvitationTerms() + none := InvitationPackageItem{Status: InvitationPackageNotProvided} + terms.Package = InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none} + if err := terms.Validate(); err != nil { + t.Fatalf("Validate() error = %v, want an explicit empty package to be valid", err) + } +} + +func TestInvitationTermsRoundTripThroughTheStoredSnapshot(t *testing.T) { + terms := validInvitationTerms() + terms.Location = invitationTestString("Kazan") + encoded, err := EncodeInvitationTerms(terms) + if err != nil { + t.Fatalf("EncodeInvitationTerms() error = %v", err) + } + decoded, err := DecodeInvitationTerms(encoded) + if err != nil || !decoded.Equal(terms) { + t.Fatalf("DecodeInvitationTerms() = %+v, %v; want the same terms", decoded, err) + } + var generic map[string]any + if err := json.Unmarshal(encoded, &generic); err != nil { + t.Fatalf("decode snapshot: %v", err) + } + salary, _ := generic["salary"].(map[string]any) + if salary["salary_from"] != float64(100000) || salary["currency"] != "RUB" || salary["tax_basis"] != "net" { + t.Fatalf("snapshot salary = %v, want whole rubles with their basis", salary) + } + if _, present := generic["candidate_email"]; present { + t.Fatal("snapshot carries a candidate field") + } + for name, mutate := range map[string]func(string) string{ + "unknown field": func(s string) string { return strings.Replace(s, `"team"`, `"salary_minimum":1,"team"`, 1) }, + "trailing data": func(s string) string { return s + " {}" }, + "salary string": func(s string) string { return strings.Replace(s, `"salary_from":100000`, `"salary_from":"100000"`, 1) }, + } { + if _, err := DecodeInvitationTerms([]byte(mutate(string(encoded)))); err == nil { + t.Errorf("DecodeInvitationTerms(%s) accepted a changed snapshot", name) + } + } +} + +func TestReviseDraftCreatesNextVersionsOnlyWhenContentChanges(t *testing.T) { + input := validInvitationDraftInput() + draft, err := NewInvitationDraft(input) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + later := input.At.Add(time.Minute) + policyID, _ := NewPolicyVersionID() + + same, changed, err := draft.ReviseDraft(draft.DraftContent(), policyID, later) + if err != nil || len(changed) != 0 || same.Version() != 1 || !same.UpdatedAt().Equal(draft.UpdatedAt()) { + t.Fatalf("no-op revision = version %d changed %v err %v, want the draft untouched", same.Version(), changed, err) + } + + content := draft.DraftContent() + content.ResponsePeriod = 14 + revised, changed, err := draft.ReviseDraft(content, policyID, later) + if err != nil { + t.Fatalf("ReviseDraft(period) error = %v", err) + } + if revised.Version() != 2 || revised.TermsVersion() != 1 || len(changed) != 1 || changed[0] != InvitationChangedResponsePeriod || + revised.PolicyVersionID() != policyID { + t.Fatalf("period revision = version %d/%d changed %v, want version 2 with terms version 1", revised.Version(), revised.TermsVersion(), changed) + } + + content = revised.DraftContent() + content.Terms.Salary.SalaryTo = 150_000 + content.Need = &InvitationNeedRef{NeedID: uuid.New(), RequirementsVersion: 2} + third, changed, err := revised.ReviseDraft(content, policyID, later.Add(time.Minute)) + if err != nil { + t.Fatalf("ReviseDraft(terms and need) error = %v", err) + } + if third.Version() != 3 || third.TermsVersion() != 2 || fmt.Sprint(changed) != "[terms need]" { + t.Fatalf("terms revision = version %d/%d changed %v, want 3/2 with terms and need", third.Version(), third.TermsVersion(), changed) + } + event, err := third.DraftEvent(input.ActorID, changed) + if err != nil || event.Kind != InvitationEventDraftUpdated || event.Version != 3 || event.TermsVersion != 2 { + t.Fatalf("update event = %+v, %v; want draft_updated at 3/2", event, err) + } + // The earlier values were not changed in place. + if draft.Snapshot().Terms.Salary.SalaryTo != 140_000 || revised.Snapshot().Terms.Salary.SalaryTo != 140_000 { + t.Fatal("a revision changed an earlier invitation value") + } +} + +func TestReviseDraftRefusesAnInvitationThatIsNotADraft(t *testing.T) { + input := validInvitationDraftInput() + draft, err := NewInvitationDraft(input) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + stored := draft.Stored() + stored.State = string(InvitationWithdrawn) + withdrawn, err := RestoreInvitation(stored) + if err != nil { + t.Fatalf("RestoreInvitation(withdrawn) error = %v", err) + } + content := withdrawn.DraftContent() + content.ResponsePeriod = 14 + if _, _, err := withdrawn.ReviseDraft(content, input.PolicyVersionID, input.At.Add(time.Minute)); !errors.Is(err, ErrInvitationNotDraft) { + t.Fatalf("ReviseDraft(withdrawn) error = %v, want ErrInvitationNotDraft", err) + } +} + +func TestRestoreInvitationRejectsInconsistentRows(t *testing.T) { + input := validInvitationDraftInput() + draft, err := NewInvitationDraft(input) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + now := input.At.Add(time.Hour) + tests := map[string]func(*StoredInvitation){ + "unknown state": func(s *StoredInvitation) { s.State = "sent" }, + "expiry reason without expiry": func(s *StoredInvitation) { s.ExpiryReason = invitationTestString("invitation_timeout") }, + "terms version ahead": func(s *StoredInvitation) { s.TermsVersion = 2 }, + "draft with a delivery": func(s *StoredInvitation) { + s.DeliveredAt, s.ResponseDeadlineAt = &now, &now + }, + "salary range that is too wide": func(s *StoredInvitation) { s.Terms.Salary.SalaryTo = 500_000 }, + "updated before created": func(s *StoredInvitation) { s.UpdatedAt = s.CreatedAt.Add(-time.Second) }, + "no policy version": func(s *StoredInvitation) { s.PolicyVersionID = PolicyVersionID{} }, + } + for name, mutate := range tests { + t.Run(name, func(t *testing.T) { + stored := draft.Stored() + mutate(&stored) + if _, err := RestoreInvitation(stored); !errors.Is(err, ErrInvalidInvitation) { + t.Fatalf("RestoreInvitation() error = %v, want ErrInvalidInvitation", err) + } + }) + } +} + +func TestInvitationHidesTheCandidateAndTheTermsWhenPrinted(t *testing.T) { + input := validInvitationDraftInput() + draft, err := NewInvitationDraft(input) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + view := OrganizationInvitationView{InvitationSnapshot: draft.Snapshot(), CandidateHandle: "cv1_" + strings.Repeat("A", 43)} + for _, printed := range []string{ + fmt.Sprintf("%v %+v %#v %s", draft, draft, draft, draft), + fmt.Sprintf("%v %+v %#v", view, view, view), + fmt.Sprintf("%v", draft.Snapshot()), + } { + if strings.Contains(printed, input.CandidateID.String()) || strings.Contains(printed, "Middle Go developer") { + t.Fatalf("printed invitation leaks a candidate or term: %s", printed) + } + } + encoded, err := json.Marshal(view) + if err != nil || strings.Contains(string(encoded), input.CandidateID.String()) { + t.Fatalf("serialized view = %s, %v; want no candidate identifier", encoded, err) + } +} + +func TestInvitationPolicyResolvesTheResponsePeriod(t *testing.T) { + policy := InvitationPolicy{ResponseDeadlineOptions: []CalendarDays{3, 7, 14}, DefaultResponseDeadline: 7} + if period, err := policy.ResolveResponsePeriod(nil); err != nil || period != 7 { + t.Fatalf("ResolveResponsePeriod(nil) = %d, %v; want the default 7", period, err) + } + three := CalendarDays(3) + if period, err := policy.ResolveResponsePeriod(&three); err != nil || period != 3 { + t.Fatalf("ResolveResponsePeriod(3) = %d, %v; want 3", period, err) + } + five := CalendarDays(5) + var field *InvitationFieldError + if _, err := policy.ResolveResponsePeriod(&five); !errors.As(err, &field) || field.Pointer != "/response_period_days" { + t.Fatalf("ResolveResponsePeriod(5) error = %v, want a field error", err) + } +} diff --git a/backend/internal/domain/need.go b/backend/internal/domain/need.go index 4dd9bc8..13efa0e 100644 --- a/backend/internal/domain/need.go +++ b/backend/internal/domain/need.go @@ -102,14 +102,9 @@ func (format NeedWorkFormat) IsKnown() bool { } } -// NeedSalaryRange is a monthly RUB range with an explicit tax basis. -type NeedSalaryRange struct { - SalaryFrom int64 `json:"salary_from"` - SalaryTo int64 `json:"salary_to"` - Currency string `json:"currency"` - Period string `json:"period"` - TaxBasis string `json:"tax_basis"` -} +// NeedSalaryRange is a monthly RUB range with an explicit tax basis. A need +// and an invitation share the money rules of SalaryRange. +type NeedSalaryRange = SalaryRange // NeedSkill is one ordered required or desired skill. TaxonomyCode is nil // when the platform has no reviewed mapping for the supplied name. @@ -749,15 +744,7 @@ func validNeedWorkFormats(formats []NeedWorkFormat) bool { } func validNeedSalaryRange(value NeedSalaryRange) bool { - if value.SalaryFrom < 1000 || value.SalaryFrom > 100000000 || value.SalaryFrom%1000 != 0 || - value.SalaryTo < 1000 || value.SalaryTo > 100000000 || value.SalaryTo%1000 != 0 || - value.Currency != "RUB" || value.Period != "month" || (value.TaxBasis != "net" && value.TaxBasis != "gross") || - value.SalaryFrom >= value.SalaryTo { - return false - } - width := value.SalaryTo - value.SalaryFrom - sum := value.SalaryTo + value.SalaryFrom - return 20*width >= sum && 5*width <= sum + return value.Validate() == nil } func validNeedTaxonomyCode(value string) bool { diff --git a/backend/internal/domain/salary_range.go b/backend/internal/domain/salary_range.go new file mode 100644 index 0000000..97c0650 --- /dev/null +++ b/backend/internal/domain/salary_range.go @@ -0,0 +1,100 @@ +package domain + +import ( + "errors" + "fmt" +) + +// ErrInvalidSalaryRange reports a salary range that breaks the money rules. +var ErrInvalidSalaryRange = errors.New("invalid salary range") + +const ( + // SalaryCurrencyRUB is the only currency of the MVP. + SalaryCurrencyRUB = "RUB" + // SalaryPeriodMonth is the only pay period of the MVP. + SalaryPeriodMonth = "month" + // SalaryTaxNet is a net ("after personal income tax") amount. + SalaryTaxNet = "net" + // SalaryTaxGross is a gross ("before personal income tax") amount. + SalaryTaxGross = "gross" + + // SalaryStepRubles is the step of every salary bound (PRD FR13). + SalaryStepRubles int64 = 1000 + // MaxSalaryRubles caps a bound, so the integer width test below cannot + // overflow: the largest product is 20 * MaxSalaryRubles. + MaxSalaryRubles int64 = 100_000_000 +) + +// SalaryRange is a monthly range [From; To] in whole rubles with its tax +// basis. Amounts are exact integers; no float takes part in any comparison. +type SalaryRange struct { + SalaryFrom int64 `json:"salary_from"` + SalaryTo int64 `json:"salary_to"` + Currency string `json:"currency"` + Period string `json:"period"` + TaxBasis string `json:"tax_basis"` +} + +// SalaryRangeError names the field of the range that failed. The field is the +// JSON name inside the range, so a caller can build the pointer of its own +// request from it. The error never carries an amount. +type SalaryRangeError struct { + Field string + Reason string +} + +func (err *SalaryRangeError) Error() string { + return fmt.Sprintf("salary range field %s: %s", err.Field, err.Reason) +} + +func (err *SalaryRangeError) Unwrap() error { return ErrInvalidSalaryRange } + +// Validate applies the rules of PRD FR13: +// +// - the currency is RUB, the period is a month, and the base is net or gross; +// - A and B are positive multiples of 1000 (and at most MaxSalaryRubles); +// - A < B; +// - the width 2 * (B - A) / (A + B), the range relative to its midpoint, is +// from 10% to 40% inclusive. +// +// The width test is the integer pair 20 * (B - A) >= A + B and +// 5 * (B - A) <= A + B, which holds exactly at 10% and 40% without a rounding +// error. The first failing field is reported; a reversed or too narrow or wide +// range is attributed to salary_to. +func (salary SalaryRange) Validate() error { + if err := validSalaryBound("salary_from", salary.SalaryFrom); err != nil { + return err + } + if err := validSalaryBound("salary_to", salary.SalaryTo); err != nil { + return err + } + switch { + case salary.Currency != SalaryCurrencyRUB: + return &SalaryRangeError{Field: "currency", Reason: "must be RUB"} + case salary.Period != SalaryPeriodMonth: + return &SalaryRangeError{Field: "period", Reason: "must be month"} + case salary.TaxBasis != SalaryTaxNet && salary.TaxBasis != SalaryTaxGross: + return &SalaryRangeError{Field: "tax_basis", Reason: "must be net or gross"} + case salary.SalaryFrom >= salary.SalaryTo: + return &SalaryRangeError{Field: "salary_to", Reason: "must be above salary_from"} + } + width := salary.SalaryTo - salary.SalaryFrom + sum := salary.SalaryTo + salary.SalaryFrom + if 20*width < sum { + return &SalaryRangeError{Field: "salary_to", Reason: "the range is narrower than 10% of its midpoint"} + } + if 5*width > sum { + return &SalaryRangeError{Field: "salary_to", Reason: "the range is wider than 40% of its midpoint"} + } + return nil +} + +func validSalaryBound(field string, amount int64) error { + if amount < SalaryStepRubles || amount > MaxSalaryRubles { + return &SalaryRangeError{Field: field, Reason: "must be from 1000 to 100000000 rubles"} + } + if amount%SalaryStepRubles != 0 { + return &SalaryRangeError{Field: field, Reason: "must be a multiple of 1000"} + } + return nil +} diff --git a/backend/internal/domain/salary_range_test.go b/backend/internal/domain/salary_range_test.go new file mode 100644 index 0000000..ac9d569 --- /dev/null +++ b/backend/internal/domain/salary_range_test.go @@ -0,0 +1,82 @@ +package domain + +import ( + "errors" + "testing" +) + +func rubRange(from, to int64, basis string) SalaryRange { + return SalaryRange{SalaryFrom: from, SalaryTo: to, Currency: SalaryCurrencyRUB, Period: SalaryPeriodMonth, TaxBasis: basis} +} + +// The width is checked in integers: the exact 10% and 40% ranges pass, and a +// step of 1000 beyond either bound fails. +func TestSalaryRangeWidthIsExactAtTheBoundaries(t *testing.T) { + tests := []struct { + name string + from, to int64 + wantField string + }{ + {name: "exactly 10 percent", from: 95_000, to: 105_000}, + {name: "exactly 40 percent", from: 80_000, to: 120_000}, + {name: "typical range", from: 100_000, to: 140_000}, + {name: "exactly 10 percent at a large scale", from: 76_000_000, to: 84_000_000}, + {name: "just below 10 percent", from: 95_000, to: 104_000, wantField: "salary_to"}, + {name: "just above 40 percent", from: 80_000, to: 121_000, wantField: "salary_to"}, + {name: "narrowest lower neighbour", from: 96_000, to: 105_000, wantField: "salary_to"}, + {name: "equal bounds", from: 100_000, to: 100_000, wantField: "salary_to"}, + {name: "reversed bounds", from: 140_000, to: 100_000, wantField: "salary_to"}, + {name: "far too wide", from: 1_000, to: 100_000_000, wantField: "salary_to"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := rubRange(test.from, test.to, SalaryTaxNet).Validate() + if test.wantField == "" { + if err != nil { + t.Fatalf("Validate() error = %v, want nil", err) + } + return + } + var rangeError *SalaryRangeError + if !errors.As(err, &rangeError) || rangeError.Field != test.wantField || !errors.Is(err, ErrInvalidSalaryRange) { + t.Fatalf("Validate() error = %v, want a range error on %s", err, test.wantField) + } + }) + } +} + +func TestSalaryRangeRejectsBoundsOutsideTheStep(t *testing.T) { + tests := []struct { + name string + salary SalaryRange + wantField string + }{ + {name: "zero lower bound", salary: rubRange(0, 100_000, SalaryTaxNet), wantField: "salary_from"}, + {name: "negative lower bound", salary: rubRange(-100_000, 100_000, SalaryTaxNet), wantField: "salary_from"}, + {name: "lower bound off the step", salary: rubRange(100_500, 140_000, SalaryTaxNet), wantField: "salary_from"}, + {name: "upper bound off the step", salary: rubRange(100_000, 140_500, SalaryTaxNet), wantField: "salary_to"}, + {name: "upper bound over the cap", salary: rubRange(80_000_000, 120_000_000, SalaryTaxNet), wantField: "salary_to"}, + {name: "overflowing bound", salary: rubRange(100_000, 9_223_372_036_854_775_000, SalaryTaxNet), wantField: "salary_to"}, + {name: "no tax basis", salary: rubRange(100_000, 140_000, ""), wantField: "tax_basis"}, + {name: "unknown tax basis", salary: rubRange(100_000, 140_000, "pre-tax"), wantField: "tax_basis"}, + {name: "foreign currency", salary: SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "USD", Period: SalaryPeriodMonth, TaxBasis: SalaryTaxNet}, wantField: "currency"}, + {name: "yearly period", salary: SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: SalaryCurrencyRUB, Period: "year", TaxBasis: SalaryTaxNet}, wantField: "period"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var rangeError *SalaryRangeError + if err := test.salary.Validate(); !errors.As(err, &rangeError) || rangeError.Field != test.wantField { + t.Fatalf("Validate() error = %v, want a range error on %s", err, test.wantField) + } + }) + } +} + +// Both bases are valid; the base is never inferred or converted. +func TestSalaryRangeAcceptsBothTaxBases(t *testing.T) { + for _, basis := range []string{SalaryTaxNet, SalaryTaxGross} { + if err := rubRange(100_000, 140_000, basis).Validate(); err != nil { + t.Errorf("Validate(%s) error = %v", basis, err) + } + } +} diff --git a/backend/internal/port/outbound/invitations.go b/backend/internal/port/outbound/invitations.go new file mode 100644 index 0000000..523e9be --- /dev/null +++ b/backend/internal/port/outbound/invitations.go @@ -0,0 +1,104 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrInvitationNotFound reports that the invitation does not exist in the + // organization. An invitation of another organization is reported the same + // way, so an identifier reveals nothing. + ErrInvitationNotFound = errors.New("organization invitation not found") + + // ErrInvitationVersionConflict reports that the draft is no longer at the + // version the caller read, or is no longer a draft. The surrounding + // transaction stays usable and the caller decides which conflict applies. + ErrInvitationVersionConflict = errors.New("organization invitation changed concurrently") + + // ErrInvitationCreationResultNotFound reports a missing original response + // for a live idempotency record. + ErrInvitationCreationResultNotFound = errors.New("organization invitation creation result not found") +) + +// MaxInvitationPageSize is the largest organization-scoped page in the +// contract. +const MaxInvitationPageSize = 100 + +// InvitationRepositories exposes the invitation storage bound to one +// UnitOfWork transaction. +type InvitationRepositories interface { + Invitations() InvitationRepository + InvitationCreationResults() InvitationCreationResultRepository +} + +// InvitationRepository stores invitations, their immutable terms versions, and +// their audit events. Every read scopes by the organization and the +// invitation, so a foreign identifier finds nothing. +type InvitationRepository interface { + // Create inserts version 1 of a draft, its first terms version, and its + // first audit event in the surrounding transaction. + Create(ctx context.Context, invitation domain.Invitation, event domain.InvitationEvent) error + + // Get returns the current invitation or ErrInvitationNotFound. + Get(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) + + // GetForUpdate returns the current invitation and holds its row lock until + // the surrounding transaction ends. + GetForUpdate(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) + + // GetTermsVersion returns one immutable historical terms version or + // ErrInvitationNotFound. + GetTermsVersion(ctx context.Context, organizationID, invitationID uuid.UUID, version int64) (domain.InvitationTerms, error) + + // List returns one newest-first page of the organization's invitations. + List(ctx context.Context, query InvitationListQuery) (InvitationPage, error) + + // SaveDraft appends the next version of a draft in the surrounding + // transaction: the invitation row moves from expectedVersion to the version + // of next, a changed terms version is appended as a new immutable snapshot, + // and the audit event is recorded. It returns ErrInvitationVersionConflict + // when the stored row is not a draft at expectedVersion. + SaveDraft(ctx context.Context, expectedVersion int64, next domain.Invitation, termsChanged bool, event domain.InvitationEvent) error + + // NeedVersionExists reports whether the need of the organization has had + // the requirements version. + NeedVersionExists(ctx context.Context, organizationID, needID uuid.UUID, requirementsVersion int64) (bool, error) +} + +// InvitationCreationResultRepository stores the original response of a +// successful idempotent create. The scope references the generic idempotency +// record, so the response is removed when that record is purged. +type InvitationCreationResultRepository interface { + SaveCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte, result domain.OrganizationInvitationView) error + GetCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (domain.OrganizationInvitationView, error) +} + +// InvitationListQuery selects one page within a single organization. +type InvitationListQuery struct { + OrganizationID uuid.UUID + After *InvitationListPosition + Limit int32 +} + +// InvitationListPosition is the stable newest-first ordering key. +type InvitationListPosition struct { + CreatedAt time.Time + InvitationID uuid.UUID +} + +// InvitationPage contains one organization-scoped page of invitations. +type InvitationPage struct { + Items []domain.Invitation + HasMore bool +} + +// InvitationCreationPosition returns the pagination key of one invitation. +func InvitationCreationPosition(invitation domain.Invitation) InvitationListPosition { + return InvitationListPosition{CreatedAt: invitation.CreatedAt(), InvitationID: invitation.ID()} +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 69b9da9..60e0b84 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -68,6 +68,7 @@ type UnitOfWork interface { ConsentRevocationEffects() ConsentRevocationEffects OrganizationRepositories NeedRepositories + InvitationRepositories CompanyQuotas() CompanyQuotaRepository AssessmentBankRepositories AssessmentAttemptRepositories diff --git a/backend/internal/usecase/candidateview/service.go b/backend/internal/usecase/candidateview/service.go index 6adca80..58b228a 100644 --- a/backend/internal/usecase/candidateview/service.go +++ b/backend/internal/usecase/candidateview/service.go @@ -314,6 +314,54 @@ func (service *Service) AuthorizeCategoriesSection( return candidateID, slices.Clone(view.Categories), nil } +// ResolveCandidateHandle turns the handle of a card of this organization into +// the candidate it stands for, inside the caller's transaction. It applies the +// checks of a card read under the same locks: the active membership of the +// actor, the effective C2 publication, the hiding of this organization, and +// the minimum cohort, so a handle of another organization, an unknown handle, +// a candidate who revoked the publication or hid the profile from the +// organization, and a card that the cohort rules suppress all answer +// ErrCandidateCardNotFound. The caller cannot tell the cases apart. +// +// It consumes no card-view quota and writes no access history: it returns an +// identifier for the server's own use and shows no card content, and the +// search or the card read that produced the handle was charged when it +// revealed the candidate. The identifier must never leave the server. +// +// The caller's transaction must not hold a share lock of the organization yet, +// so that the exclusive organization lock of the quota writers is taken first. +func (service *Service) ResolveCandidateHandle( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID uuid.UUID, + handle string, +) (uuid.UUID, error) { + const location = "candidateview.Service.ResolveCandidateHandle" + if actorID == uuid.Nil || organizationID == uuid.Nil { + return uuid.Nil, ErrForbidden + } + if !domain.IsCandidateViewPseudonym(handle) { + return uuid.Nil, ErrInvalidCandidateHandle + } + if err := lockOrganizationFirst(ctx, unit, organizationID); err != nil { + return uuid.Nil, err + } + _, _, sources, err := loadCurrentVisibleCohort(ctx, unit, actorID, organizationID, location) + if err != nil { + return uuid.Nil, err + } + candidateID, err := candidateIDForHandle(service, organizationID, sources, handle, location) + if err != nil { + return uuid.Nil, err + } + // A card that the cohort rules suppress is not offered by a search, so its + // handle is not accepted either. + if _, err := projectedViewForHandle(service, organizationID, sources, handle, location); err != nil { + return uuid.Nil, err + } + return candidateID, nil +} + func (service *Service) currentOrganizationCard( ctx context.Context, unit outbound.UnitOfWork, diff --git a/backend/internal/usecase/invitation/draft.go b/backend/internal/usecase/invitation/draft.go new file mode 100644 index 0000000..86f5f82 --- /dev/null +++ b/backend/internal/usecase/invitation/draft.go @@ -0,0 +1,467 @@ +package invitation + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/candidateview" +) + +const ( + createLocation = "invitation.Service.Create" + updateLocation = "invitation.Service.Update" + getLocation = "invitation.Service.Get" + listLocation = "invitation.Service.List" +) + +// CreateCommand binds the authenticated actor and the path organization to +// one validated create request. The candidate is named only by the handle. +type CreateCommand struct { + ActorID uuid.UUID + OrganizationID uuid.UUID + IdempotencyKey string + CanonicalBody []byte + CandidateHandle string + Need *domain.InvitationNeedRef + ResponsePeriodDays *int32 + Terms domain.InvitationTerms +} + +type createRequest struct { + fingerprint [outbound.IdempotencyDigestSize]byte + scope [outbound.IdempotencyDigestSize]byte + record outbound.IdempotencyRecord + now time.Time +} + +// Create stores a new draft addressed to one candidate of the organization's +// visible cards, or replays the original response of the same request within +// the idempotency window. Nothing is stored when any rule fails. +func (service *Service) Create(ctx context.Context, command CreateCommand) (domain.OrganizationInvitationView, error) { + request, err := service.prepareCreate(command) + if err != nil { + return domain.OrganizationInvitationView{}, err + } + var result domain.OrganizationInvitationView + // The visible cohort can change while it is locked. The whole command is + // then repeated, a bounded number of times, and the writes of a failed + // attempt roll back with it. + for range maxCreateAttempts { + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + result, err = service.createInTransaction(ctx, unit, command, request) + return err + }) + if !errors.Is(err, candidateview.ErrConcurrentVisibilityChange) { + break + } + } + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", createLocation, err) + } + return result, nil +} + +func (service *Service) prepareCreate(command CreateCommand) (createRequest, error) { + const location = "invitation.Service.prepareCreate" + switch { + case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil: + return createRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden) + case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize: + return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey) + case len(command.CanonicalBody) == 0 || len(command.CanonicalBody) > maxCanonicalBodySize: + return createRequest{}, fmt.Errorf("%s - canonical request body is outside its bound: %w", location, ErrInvalidRequest) + } + now, err := service.now(location) + if err != nil { + return createRequest{}, err + } + expiresAt := now.Add(outbound.IdempotencyRetention) + principal := command.ActorID.String() + ":" + command.OrganizationID.String() + fingerprint := service.keyring.Fingerprint(command.CanonicalBody) + scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, principal) + return createRequest{ + fingerprint: fingerprint, scope: scope, now: now, + record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt}, + }, nil +} + +func (service *Service) createInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateCommand, + request createRequest, +) (domain.OrganizationInvitationView, error) { + if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, createLocation); err != nil { + return domain.OrganizationInvitationView{}, err + } + if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, createLocation); err != nil { + return domain.OrganizationInvitationView{}, err + } + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err) + } + if !created { + return replayCreation(ctx, unit, request, command.OrganizationID, stored) + } + invitation, err := service.buildDraft(ctx, unit, command, request.now) + if err != nil { + return domain.OrganizationInvitationView{}, err + } + event, err := invitation.DraftEvent(command.ActorID, nil) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - build audit event: %w", createLocation, err) + } + if err := unit.Invitations().Create(ctx, invitation, event); err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - store draft: %w", createLocation, err) + } + view, err := service.view(invitation) + if err != nil { + return domain.OrganizationInvitationView{}, err + } + if err := unit.InvitationCreationResults().SaveCreationResult(ctx, request.scope, view); err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - store original response: %w", createLocation, err) + } + if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err) + } + return view, nil +} + +// buildDraft applies the domain rules in the order of the contract: the +// candidate handle, the need link, then the terms. The handle is resolved +// through the same visibility barrier as a card read, so a draft cannot be +// addressed to a candidate that the organization may not see. +func (service *Service) buildDraft( + ctx context.Context, + unit outbound.UnitOfWork, + command CreateCommand, + now time.Time, +) (domain.Invitation, error) { + policy, policyVersionID, err := effectiveInvitationPolicy(ctx, unit, now, createLocation) + if err != nil { + return domain.Invitation{}, err + } + var requested *domain.CalendarDays + if command.ResponsePeriodDays != nil { + period := domain.CalendarDays(*command.ResponsePeriodDays) + requested = &period + } + period, err := policy.ResolveResponsePeriod(requested) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - resolve response period: %w", createLocation, err) + } + candidateID, err := service.candidates(ctx, unit, command.ActorID, command.OrganizationID, command.CandidateHandle) + if err != nil { + if errors.Is(err, candidateview.ErrCandidateCardNotFound) || errors.Is(err, candidateview.ErrInvalidCandidateHandle) { + return domain.Invitation{}, fmt.Errorf("%s - resolve candidate handle: %w", createLocation, + &domain.InvitationFieldError{Pointer: "/candidate_handle", Reason: "must be a handle of a candidate this organization can see"}) + } + return domain.Invitation{}, fmt.Errorf("%s - resolve candidate handle: %w", createLocation, err) + } + if err := checkNeedLink(ctx, unit, command.OrganizationID, command.Need); err != nil { + return domain.Invitation{}, fmt.Errorf("%s - %w", createLocation, err) + } + draftID, err := uuid.NewV7() + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - generate invitation ID: %w", createLocation, err) + } + invitation, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{ + ID: draftID, OrganizationID: command.OrganizationID, CandidateID: candidateID, ActorID: command.ActorID, + PolicyVersionID: policyVersionID, At: now, + Content: domain.InvitationDraftContent{Need: command.Need, ResponsePeriod: period, Terms: command.Terms}, + }) + if err != nil { + return domain.Invitation{}, fmt.Errorf("%s - build draft: %w", createLocation, err) + } + return invitation, nil +} + +// checkNeedLink requires that a linked need belongs to the organization and +// has had the stated requirements version. Both cases give one pointer, so the +// answer does not tell whether the need exists in another organization. +func checkNeedLink(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID, need *domain.InvitationNeedRef) error { + if need == nil { + return nil + } + exists, err := unit.Invitations().NeedVersionExists(ctx, organizationID, need.NeedID, need.RequirementsVersion) + if err != nil { + return fmt.Errorf("check need link: %w", err) + } + if !exists { + return &domain.InvitationFieldError{Pointer: "/need", Reason: "must be a need of this organization with a requirements version it has had"} + } + return nil +} + +func replayCreation( + ctx context.Context, + unit outbound.UnitOfWork, + request createRequest, + organizationID uuid.UUID, + stored outbound.IdempotencyRecord, +) (domain.OrganizationInvitationView, error) { + if stored.Fingerprint != request.fingerprint { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare request fingerprint: %w", createLocation, ErrIdempotencyKeyReused) + } + original, err := unit.InvitationCreationResults().GetCreationResult(ctx, request.scope) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - read original response: %w", createLocation, err) + } + if original.OrganizationID != organizationID { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate original response: %w", createLocation, domain.ErrInvalidInvitation) + } + return original, nil +} + +// Field distinguishes a property that the request left out from one it set, +// and from one it set to null. +type Field[T any] struct { + Set bool + Null bool + Value T +} + +// UpdateCommand binds one versioned replacement to a trusted actor and path. +// A field that is not set stays unchanged; terms are replaced as a whole. +type UpdateCommand struct { + ActorID uuid.UUID + OrganizationID uuid.UUID + InvitationID uuid.UUID + ExpectedVersion int64 + Need Field[domain.InvitationNeedRef] + ResponsePeriodDays *int32 + Terms *domain.InvitationTerms +} + +// Update replaces the fields the request sets, in the order of the contract: +// a request that changes nothing returns the current invitation, then the +// version is compared, then the state, then the domain rules. Only a draft +// changes. A change appends the next invitation version, and a change of the +// terms appends the next immutable terms version. +func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.OrganizationInvitationView, error) { + if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", updateLocation, ErrForbidden) + } + if command.ExpectedVersion < 1 { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - %w", updateLocation, + &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"}) + } + now, err := service.now(updateLocation) + if err != nil { + return domain.OrganizationInvitationView{}, err + } + var result domain.OrganizationInvitationView + err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + result, err = service.updateInTransaction(ctx, unit, command, now) + return err + }) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", updateLocation, err) + } + return result, nil +} + +func (service *Service) updateInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + command UpdateCommand, + now time.Time, +) (domain.OrganizationInvitationView, error) { + // Every invitation command takes the organization lock before the + // membership share lock and the invitation row lock, in the order of the + // create, the card read, and the search, so a later command that also + // charges the organization (sending, the salary limit) cannot deadlock + // against an update. + if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, updateLocation); err != nil { + return domain.OrganizationInvitationView{}, err + } + if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, updateLocation); err != nil { + return domain.OrganizationInvitationView{}, err + } + // The nil identifier cannot name an invitation. It answers like any + // unknown identifier, after the authorization above. + if command.InvitationID == uuid.Nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - nil invitation: %w", updateLocation, outbound.ErrInvitationNotFound) + } + current, err := unit.Invitations().GetForUpdate(ctx, command.OrganizationID, command.InvitationID) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - lock invitation: %w", updateLocation, err) + } + before := current.DraftContent() + merged := mergeDraft(before, command) + changed := before.ChangedFields(merged) + if len(changed) == 0 { + return service.view(current) + } + if command.ExpectedVersion != current.Version() { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare expected version: %w", updateLocation, domain.ErrInvitationVersionConflict) + } + if current.State() != domain.InvitationDraft { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - require a draft: %w", updateLocation, domain.ErrInvitationNotDraft) + } + policyVersionID, err := service.checkRevision(ctx, unit, current, merged, changed, now) + if err != nil { + return domain.OrganizationInvitationView{}, err + } + // A clock that stepped back must not make the revision older than the + // draft it revises. + at := now + if at.Before(current.UpdatedAt()) { + at = current.UpdatedAt() + } + next, appliedFields, err := current.ReviseDraft(merged, policyVersionID, at) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - revise draft: %w", updateLocation, err) + } + event, err := next.DraftEvent(command.ActorID, appliedFields) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - build audit event: %w", updateLocation, err) + } + termsChanged := next.TermsVersion() != current.TermsVersion() + if err := unit.Invitations().SaveDraft(ctx, current.Version(), next, termsChanged, event); err != nil { + if errors.Is(err, outbound.ErrInvitationVersionConflict) { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, domain.ErrInvitationVersionConflict) + } + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, err) + } + return service.view(next) +} + +// mergeDraft applies the fields the command sets over the current content. +func mergeDraft(current domain.InvitationDraftContent, command UpdateCommand) domain.InvitationDraftContent { + merged := current + if command.Need.Set { + merged.Need = nil + if !command.Need.Null { + need := command.Need.Value + merged.Need = &need + } + } + if command.ResponsePeriodDays != nil { + merged.ResponsePeriod = domain.CalendarDays(*command.ResponsePeriodDays) + } + if command.Terms != nil { + merged.Terms = *command.Terms + } + return merged +} + +// checkRevision runs the rules that need storage or the policy and returns the +// policy version that governs the stored response period. The period is +// checked against the policy in force only when the request changes it. +func (service *Service) checkRevision( + ctx context.Context, + unit outbound.UnitOfWork, + current domain.Invitation, + merged domain.InvitationDraftContent, + changed []domain.InvitationChangedField, + now time.Time, +) (domain.PolicyVersionID, error) { + policyVersionID := current.PolicyVersionID() + for _, field := range changed { + switch field { + case domain.InvitationChangedResponsePeriod: + policy, versionID, err := effectiveInvitationPolicy(ctx, unit, now, updateLocation) + if err != nil { + return domain.PolicyVersionID{}, err + } + if _, err := policy.ResolveResponsePeriod(&merged.ResponsePeriod); err != nil { + return domain.PolicyVersionID{}, fmt.Errorf("%s - resolve response period: %w", updateLocation, err) + } + policyVersionID = versionID + case domain.InvitationChangedNeed: + if err := checkNeedLink(ctx, unit, current.OrganizationID(), merged.Need); err != nil { + return domain.PolicyVersionID{}, fmt.Errorf("%s - %w", updateLocation, err) + } + case domain.InvitationChangedTerms: + // The terms need no storage: the domain validates them when the + // draft is revised, after the need link, as on creation. + } + } + return policyVersionID, nil +} + +// Get reads the current invitation for an active owner. +func (service *Service) Get(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.OrganizationInvitationView, error) { + if actorID == uuid.Nil || organizationID == uuid.Nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", getLocation, ErrForbidden) + } + var result domain.OrganizationInvitationView + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeOwner(ctx, unit, actorID, organizationID, getLocation); err != nil { + return err + } + if invitationID == uuid.Nil { + return fmt.Errorf("%s - nil invitation: %w", getLocation, outbound.ErrInvitationNotFound) + } + current, err := unit.Invitations().Get(ctx, organizationID, invitationID) + if err != nil { + return fmt.Errorf("%s - read invitation: %w", getLocation, err) + } + result, err = service.view(current) + return err + }) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", getLocation, err) + } + return result, nil +} + +// ListCommand selects an owner-scoped page of invitations. +type ListCommand struct { + ActorID uuid.UUID + OrganizationID uuid.UUID + After *outbound.InvitationListPosition + Limit int32 +} + +// Page is one page of invitations, newest first. +type Page struct { + Items []domain.OrganizationInvitationView + HasMore bool +} + +// List reads one page of the organization's invitations of every state after +// checking the current account and owner membership in the same transaction. +func (service *Service) List(ctx context.Context, command ListCommand) (Page, error) { + if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil { + return Page{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", listLocation, ErrForbidden) + } + if command.Limit < 1 || command.Limit > outbound.MaxInvitationPageSize { + return Page{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", listLocation, outbound.MaxInvitationPageSize, ErrInvalidRequest) + } + var result Page + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, listLocation); err != nil { + return err + } + page, err := unit.Invitations().List(ctx, outbound.InvitationListQuery{ + OrganizationID: command.OrganizationID, After: command.After, Limit: command.Limit, + }) + if err != nil { + return fmt.Errorf("%s - list invitations: %w", listLocation, err) + } + result = Page{Items: make([]domain.OrganizationInvitationView, 0, len(page.Items)), HasMore: page.HasMore} + for _, invitation := range page.Items { + item, err := service.view(invitation) + if err != nil { + return err + } + result.Items = append(result.Items, item) + } + return nil + }) + if err != nil { + return Page{}, fmt.Errorf("%s - run transaction: %w", listLocation, err) + } + return result, nil +} diff --git a/backend/internal/usecase/invitation/service.go b/backend/internal/usecase/invitation/service.go new file mode 100644 index 0000000..a8e59c2 --- /dev/null +++ b/backend/internal/usecase/invitation/service.go @@ -0,0 +1,191 @@ +// Package invitation applies the owner-only rules of invitation drafts: the +// terms and their immutable versions, the link to a candidate card of the +// organization, and the idempotent creation. Sending, the candidate's side, and +// the contact grant belong to later operations that build on the same records. +package invitation + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ( + // ErrForbidden reports an account that may not work with the invitations + // of the organization: not an employer, or not its owner in the MVP. + ErrForbidden = errors.New("organization invitation operation forbidden") + // ErrEmailNotVerified reports an employer without a confirmed email. + ErrEmailNotVerified = errors.New("organization invitation requires a confirmed email") + // ErrIdempotencyKeyReused reports a key that was used with another request. + ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request") + // ErrInvalidIdempotencyKey reports a key outside 1 to 255 bytes. + ErrInvalidIdempotencyKey = errors.New("invalid idempotency key") + // ErrInvalidRequest reports a command that is incomplete before storage is + // read, such as a missing identifier or canonical body. + ErrInvalidRequest = errors.New("invalid organization invitation request") + // ErrPolicyUnavailable reports an effective product policy that cannot + // answer the invitation rules. It is a configuration error. + ErrPolicyUnavailable = errors.New("invitation policy is unavailable") +) + +const ( + createOperation = "organization_invitation.create" + maxIdempotencyKeySize = 255 + maxCanonicalBodySize = 1 << 20 + purgeExpiredBatch = 100 + // maxCreateAttempts bounds the repeats of a create after the visible + // cohort changed while it was locked. + maxCreateAttempts = 3 +) + +// Keyring computes scoped idempotency digests. identity.Keyring implements +// this interface, so invitation commands use the existing server secret and +// store. +type Keyring interface { + IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte + Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte +} + +// CandidateResolver turns a card handle of the organization into the candidate +// it stands for, inside the caller's transaction. It applies the same +// visibility barrier as the card read: the effective publication, the hiding +// of the organization, and the cohort rules. It answers +// candidateview.ErrCandidateCardNotFound for every handle the organization may +// not use. The identifier it returns never leaves the server. +type CandidateResolver func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID, handle string) (uuid.UUID, error) + +// Dependencies configure one stateless invitation service. +type Dependencies struct { + Transactor outbound.Transactor + Keyring Keyring + // PseudonymKey derives the organization-scoped alias that responses show + // instead of the candidate. It is the key of the cards and the search, so + // a handle in an invitation is the handle of the card. + PseudonymKey domain.CandidateViewPseudonymKey + Candidates CandidateResolver + Clock func() time.Time +} + +// Service applies organization-scoped invitation draft commands and reads. +type Service struct { + transactor outbound.Transactor + keyring Keyring + pseudonymKey domain.CandidateViewPseudonymKey + candidates CandidateResolver + clock func() time.Time +} + +// NewService fails at startup when a required dependency is missing. +func NewService(deps Dependencies) (*Service, error) { + if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Clock == nil { + return nil, errors.New("invitation.NewService - every dependency must be set") + } + if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil { + return nil, errors.New("invitation.NewService - the pseudonym key must be usable") + } + return &Service{ + transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey, + candidates: deps.Candidates, clock: deps.Clock, + }, nil +} + +// now returns the application time at the precision the database stores. +func (service *Service) now(location string) (time.Time, error) { + now := service.clock().UTC().Truncate(time.Microsecond) + if now.IsZero() || now.Year() < 1 || now.Year() > 9999 { + return time.Time{}, fmt.Errorf("%s - application time must be representable: %w", location, ErrInvalidRequest) + } + return now, nil +} + +// view is the invitation as its organization reads it. The salary indicator +// and the contact access are not derived from the candidate's minimum or from +// a grant yet: the indicator is not_available, the least revealing value, and +// no grant exists before an acceptance. +func (service *Service) view(invitation domain.Invitation) (domain.OrganizationInvitationView, error) { + handle, err := service.pseudonymKey.ForOrganization(invitation.OrganizationID(), invitation.CandidateID()) + if err != nil { + return domain.OrganizationInvitationView{}, fmt.Errorf("invitation.Service.view - derive candidate alias: %w", err) + } + return domain.OrganizationInvitationView{ + InvitationSnapshot: invitation.Snapshot(), + CandidateHandle: handle, + SalaryFit: domain.InvitationSalaryNotAvailable, + ContactAccess: domain.InvitationContactAccessNone, + }, nil +} + +// lockOrganizationFirst takes the exclusive organization lock of the company +// quota port, ahead of the share lock of the membership check and of the +// cohort locks, so two commands of one organization queue instead of +// deadlocking on a lock upgrade. An organization that does not exist answers +// like a missing membership. +func lockOrganizationFirst(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID, location string) error { + if err := unit.CompanyQuotas().LockOrganization(ctx, organizationID); err != nil { + if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) { + return fmt.Errorf("%s - lock organization: %w", location, outbound.ErrOrganizationNotFound) + } + return fmt.Errorf("%s - lock organization: %w", location, err) + } + return nil +} + +// authorizeOwner repeats, inside the transaction, the checks of the HTTP +// boundary: an existing employer with a confirmed email whose membership in +// the organization is active and owner. The MVP milestone grants a membership +// by itself no right over invitations. +func authorizeOwner( + ctx context.Context, + unit outbound.UnitOfWork, + actorID, organizationID uuid.UUID, + location string, +) error { + if actorID == uuid.Nil || organizationID == uuid.Nil { + return fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden) + } + user, err := unit.Users().GetByID(ctx, actorID) + if err != nil { + if errors.Is(err, outbound.ErrUserNotFound) { + return fmt.Errorf("%s - require existing employer account: %w", location, ErrForbidden) + } + return fmt.Errorf("%s - read account: %w", location, err) + } + if user.Scenario != domain.ScenarioEmployer { + return fmt.Errorf("%s - require employer account: %w", location, ErrForbidden) + } + if !user.EmailVerified() { + return fmt.Errorf("%s - require verified email: %w", location, ErrEmailNotVerified) + } + membership, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID) + if err != nil { + if errors.Is(err, outbound.ErrOrganizationNotFound) { + return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound) + } + return fmt.Errorf("%s - lock active membership: %w", location, err) + } + if membership.Role() != domain.OrganizationRoleOwner { + return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired) + } + return nil +} + +// effectiveInvitationPolicy reads the invitation section of the product +// policy in force at the time, with the version that governed the decision. +func effectiveInvitationPolicy( + ctx context.Context, + unit outbound.UnitOfWork, + at time.Time, + location string, +) (domain.InvitationPolicy, domain.PolicyVersionID, error) { + version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, at) + if err != nil { + return domain.InvitationPolicy{}, domain.PolicyVersionID{}, fmt.Errorf("%s - read effective product policy: %w: %w", location, ErrPolicyUnavailable, err) + } + return version.Policy().Invitations, version.ID(), nil +} diff --git a/backend/internal/usecase/invitation/service_test.go b/backend/internal/usecase/invitation/service_test.go new file mode 100644 index 0000000..bfe68ce --- /dev/null +++ b/backend/internal/usecase/invitation/service_test.go @@ -0,0 +1,699 @@ +package invitation + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/candidateview" +) + +type testKeyring struct{} + +func (testKeyring) IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte { + return sha256.Sum256([]byte(operation + "\x00" + key + "\x00" + principal)) +} + +func (testKeyring) Fingerprint(body []byte) [outbound.IdempotencyDigestSize]byte { + return sha256.Sum256(body) +} + +type termsKey struct { + invitationID uuid.UUID + version int64 +} + +type testState struct { + users map[uuid.UUID]domain.User + memberships map[[2]uuid.UUID]domain.Membership + invitations map[uuid.UUID]domain.Invitation + terms map[termsKey]domain.InvitationTerms + events []domain.InvitationEvent + idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord + results map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView + needVersions map[[3]string]bool +} + +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{}, + needVersions: map[[3]string]bool{}, + } +} + +func (state testState) clone() testState { + cloned := newTestState() + for id, user := range state.users { + cloned.users[id] = user + } + for key, membership := range state.memberships { + cloned.memberships[key] = membership + } + for id, invitation := range state.invitations { + cloned.invitations[id] = invitation + } + for key, terms := range state.terms { + cloned.terms[key] = terms.Clone() + } + cloned.events = slices.Clone(state.events) + for scope, record := range state.idempotency { + cloned.idempotency[scope] = record + } + for scope, result := range state.results { + cloned.results[scope] = result + } + for key, found := range state.needVersions { + cloned.needVersions[key] = found + } + return cloned +} + +type testTransactor struct { + mu sync.Mutex + state testState + policy domain.PolicyVersion + failResultSave bool +} + +func (transactor *testTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error { + transactor.mu.Lock() + defer transactor.mu.Unlock() + working := transactor.state.clone() + unit := &testUnit{state: &working, policy: transactor.policy, failResultSave: transactor.failResultSave} + if err := work(ctx, unit); err != nil { + return err + } + transactor.state = working + return nil +} + +func (transactor *testTransactor) snapshot() testState { + transactor.mu.Lock() + defer transactor.mu.Unlock() + return transactor.state.clone() +} + +type testUnit struct { + outbound.UnitOfWork + + state *testState + policy domain.PolicyVersion + failResultSave bool +} + +func (unit *testUnit) Users() outbound.UserRepository { return testUsers{state: unit.state} } +func (unit *testUnit) Organizations() outbound.OrganizationRepository { + return testOrganizations{state: unit.state} +} +func (unit *testUnit) IdempotencyRecords() outbound.IdempotencyRepository { + return testIdempotency{state: unit.state} +} +func (unit *testUnit) CompanyQuotas() outbound.CompanyQuotaRepository { return testQuotas{} } +func (unit *testUnit) Policies() outbound.PolicyRepository { return testPolicies{version: unit.policy} } +func (unit *testUnit) Invitations() outbound.InvitationRepository { + return testInvitations{state: unit.state} +} +func (unit *testUnit) InvitationCreationResults() outbound.InvitationCreationResultRepository { + return testInvitations{state: unit.state, failResultSave: unit.failResultSave} +} + +type testUsers struct { + outbound.UserRepository + + state *testState +} + +func (repository testUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) { + user, ok := repository.state.users[id] + if !ok { + return domain.User{}, outbound.ErrUserNotFound + } + return user, nil +} + +type testOrganizations struct { + outbound.OrganizationRepository + + state *testState +} + +func (repository testOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) { + membership, ok := repository.state.memberships[[2]uuid.UUID{organizationID, userID}] + if !ok || !membership.GrantsAccess() { + return domain.Membership{}, outbound.ErrOrganizationNotFound + } + return membership, nil +} + +type testQuotas struct { + outbound.CompanyQuotaRepository +} + +func (testQuotas) LockOrganization(context.Context, uuid.UUID) error { return nil } + +type testPolicies struct { + outbound.PolicyRepository + + version domain.PolicyVersion +} + +func (policies testPolicies) GetEffective(context.Context, domain.PolicyKey, time.Time) (domain.PolicyVersion, error) { + return policies.version, nil +} + +type testIdempotency struct { + outbound.IdempotencyRepository + + state *testState +} + +func (repository testIdempotency) Reserve(_ context.Context, record outbound.IdempotencyRecord) (outbound.IdempotencyRecord, bool, error) { + if existing, ok := repository.state.idempotency[record.Scope]; ok && existing.ExpiresAt.After(record.CreatedAt) { + return existing, false, nil + } + repository.state.idempotency[record.Scope] = record + return record, true, nil +} + +func (repository testIdempotency) PurgeExpired(_ context.Context, at time.Time, _ int32) (int64, error) { + var deleted int64 + for scope, record := range repository.state.idempotency { + if !record.ExpiresAt.After(at) { + delete(repository.state.idempotency, scope) + delete(repository.state.results, scope) + deleted++ + } + } + return deleted, nil +} + +type testInvitations struct { + state *testState + failResultSave bool +} + +func (repository testInvitations) Create(_ context.Context, invitation domain.Invitation, event domain.InvitationEvent) error { + repository.state.invitations[invitation.ID()] = invitation + repository.state.terms[termsKey{invitation.ID(), 1}] = invitation.Snapshot().Terms + repository.state.events = append(repository.state.events, event) + return nil +} + +func (repository testInvitations) Get(_ context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) { + invitation, ok := repository.state.invitations[invitationID] + if !ok || invitation.OrganizationID() != organizationID { + return domain.Invitation{}, outbound.ErrInvitationNotFound + } + return invitation, nil +} + +func (repository testInvitations) GetForUpdate(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.Invitation, error) { + return repository.Get(ctx, organizationID, invitationID) +} + +func (repository testInvitations) List(_ context.Context, query outbound.InvitationListQuery) (outbound.InvitationPage, error) { + var items []domain.Invitation + for _, invitation := range repository.state.invitations { + if invitation.OrganizationID() == query.OrganizationID { + items = append(items, invitation) + } + } + slices.SortFunc(items, func(left, right domain.Invitation) int { + return strings.Compare(right.ID().String(), left.ID().String()) + }) + page := outbound.InvitationPage{HasMore: len(items) > int(query.Limit)} + if page.HasMore { + items = items[:query.Limit] + } + page.Items = items + return page, nil +} + +func (repository testInvitations) SaveDraft(_ context.Context, expectedVersion int64, next domain.Invitation, termsChanged bool, event domain.InvitationEvent) error { + current, ok := repository.state.invitations[next.ID()] + if !ok || current.Version() != expectedVersion || current.State() != domain.InvitationDraft { + return outbound.ErrInvitationVersionConflict + } + repository.state.invitations[next.ID()] = next + if termsChanged { + repository.state.terms[termsKey{next.ID(), next.TermsVersion()}] = next.Snapshot().Terms + } + repository.state.events = append(repository.state.events, event) + return nil +} + +func (repository testInvitations) NeedVersionExists(_ context.Context, organizationID, needID uuid.UUID, version int64) (bool, error) { + return repository.state.needVersions[[3]string{organizationID.String(), needID.String(), fmt.Sprint(version)}], nil +} + +func (repository testInvitations) SaveCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result domain.OrganizationInvitationView) error { + if repository.failResultSave { + return errors.New("result store failed") + } + repository.state.results[scope] = result + return nil +} + +func (repository testInvitations) GetCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (domain.OrganizationInvitationView, error) { + result, ok := repository.state.results[scope] + if !ok { + return domain.OrganizationInvitationView{}, outbound.ErrInvitationCreationResultNotFound + } + return result, nil +} + +type harness struct { + service *Service + transactor *testTransactor + key domain.CandidateViewPseudonymKey + actorID uuid.UUID + organizationID uuid.UUID + // visible maps a handle of the organization to its candidate. + visible map[string]uuid.UUID + setTime func(time.Time) +} + +func newHarness(t *testing.T) *harness { + t.Helper() + now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC) + current := now + actorID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + verifiedAt := now.Add(-time.Hour) + state := newTestState() + state.users[actorID] = domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt} + owner, err := domain.NewOwnerMembership(organizationID, actorID, now) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + state.memberships[[2]uuid.UUID{organizationID, actorID}] = owner + key, err := domain.NewCandidateViewPseudonymKey([]byte(strings.Repeat("invitation-test-key-", 3))) + if err != nil { + t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err) + } + test := &harness{ + transactor: &testTransactor{state: state, policy: testPolicyVersion(t, now)}, + key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{}, + setTime: func(value time.Time) { current = value }, + } + test.service, err = NewService(Dependencies{ + Transactor: test.transactor, Keyring: testKeyring{}, PseudonymKey: key, Clock: func() time.Time { return current }, + Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) { + candidateID, ok := test.visible[handle] + if !ok || organizationID != test.organizationID { + return uuid.Nil, candidateview.ErrCandidateCardNotFound + } + return candidateID, nil + }, + }) + if err != nil { + t.Fatalf("NewService() error = %v", err) + } + return test +} + +// showCandidate makes a new candidate visible to the organization and returns +// the handle of the card. +func (test *harness) showCandidate(t *testing.T) (string, uuid.UUID) { + t.Helper() + candidateID := uuid.Must(uuid.NewV7()) + handle, err := test.key.ForOrganization(test.organizationID, candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + test.visible[handle] = candidateID + return handle, candidateID +} + +func testPolicyVersion(t *testing.T, at time.Time) domain.PolicyVersion { + t.Helper() + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(), + }) + if err != nil { + t.Fatalf("NewPolicyVersionDraft() error = %v", err) + } + numbered, err := draft.WithVersion(1) + if err != nil { + t.Fatalf("WithVersion() error = %v", err) + } + hash := numbered.DocumentHash() + version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{ + ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()), + Author: string(numbered.Author()), EffectiveAt: at, CreatedAt: at, Document: numbered.Document(), DocumentHash: hash[:], + }) + if err != nil { + t.Fatalf("RestorePolicyVersion() error = %v", err) + } + return version +} + +func testTerms() domain.InvitationTerms { + none := domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided} + return domain.InvitationTerms{ + RoleTitle: "Middle Go developer", Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, + OfferType: domain.InvitationOfferFullTime, Tasks: []string{"Build the payout service"}, Team: "Six engineers", + TechStack: []string{"Go"}, WorkFormats: []domain.NeedWorkFormat{domain.NeedWorkFormatRemote}, + CommunicationMethod: domain.InvitationCommunicationMethod{Channel: domain.InvitationChannelEmail}, + Salary: domain.SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "RUB", Period: "month", TaxBasis: "net"}, + Package: domain.InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none}, + } +} + +func (test *harness) createCommand(handle, key string) CreateCommand { + return CreateCommand{ + ActorID: test.actorID, OrganizationID: test.organizationID, IdempotencyKey: key, + CanonicalBody: []byte(fmt.Sprintf(`{"candidate_handle":%q,"key":%q}`, handle, key)), + CandidateHandle: handle, Terms: testTerms(), + } +} + +func fieldPointer(t *testing.T, err error) string { + t.Helper() + field, ok := errors.AsType[*domain.InvitationFieldError](err) + if !ok { + t.Fatalf("error = %v, want a field error", err) + } + return field.Pointer +} + +func TestCreateStoresADraftForAVisibleCandidateWithTheDefaultPeriod(t *testing.T) { + test := newHarness(t) + handle, candidateID := test.showCandidate(t) + view, err := test.service.Create(t.Context(), test.createCommand(handle, "key-1")) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + if view.State != domain.InvitationDraft || view.Version != 1 || view.TermsVersion != 1 || view.ResponsePeriodDays != 7 || + view.CandidateHandle != handle || view.SalaryFit != domain.InvitationSalaryNotAvailable || + view.ContactAccess != domain.InvitationContactAccessNone || view.ResponseDeadlineAt != nil { + t.Fatalf("created view = %+v, want an unsent version 1 with the default period for the card handle", view.InvitationSnapshot) + } + state := test.transactor.snapshot() + stored := state.invitations[view.ID] + if stored.CandidateID() != candidateID || len(state.events) != 1 || state.events[0].Kind != domain.InvitationEventDraftCreated || + state.events[0].ActorID != test.actorID { + t.Fatalf("stored candidate/events = %v/%+v, want the resolved candidate and one creation event", stored.CandidateID() == candidateID, state.events) + } +} + +func TestCreateRefusesEveryCandidateTheOrganizationCannotUseWithTheSamePointer(t *testing.T) { + test := newHarness(t) + otherOrganization := uuid.Must(uuid.NewV7()) + foreign, err := test.key.ForOrganization(otherOrganization, uuid.Must(uuid.NewV7())) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + unknown := "cv1_" + strings.Repeat("Z", 43) + for name, handle := range map[string]string{"another organization": foreign, "unknown": unknown, "malformed": "not-a-handle"} { + command := test.createCommand(handle, "key-"+name) + _, err := test.service.Create(t.Context(), command) + if pointer := fieldPointer(t, err); pointer != "/candidate_handle" { + t.Errorf("%s: pointer = %s, want /candidate_handle", name, pointer) + } + } + state := test.transactor.snapshot() + if len(state.invitations) != 0 || len(state.events) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 { + t.Fatalf("refused creates left state: %d invitations, %d events, %d keys, %d results", len(state.invitations), len(state.events), len(state.idempotency), len(state.results)) + } +} + +func TestCreateAppliesTheDomainRulesInTheContractOrderAndStoresNothingOnFailure(t *testing.T) { + test := newHarness(t) + handle, _ := test.showCandidate(t) + needID := uuid.Must(uuid.NewV7()) + + command := test.createCommand(handle, "key-need") + command.Need = &domain.InvitationNeedRef{NeedID: needID, RequirementsVersion: 1} + command.Terms.Salary.SalaryTo = 500_000 + _, err := test.service.Create(t.Context(), command) + if pointer := fieldPointer(t, err); pointer != "/need" { + t.Fatalf("pointer = %s, want /need before the terms", pointer) + } + + test.transactor.state.needVersions[[3]string{test.organizationID.String(), needID.String(), "1"}] = true + _, err = test.service.Create(t.Context(), command) + if pointer := fieldPointer(t, err); pointer != "/terms/salary/salary_to" { + t.Fatalf("pointer = %s, want the salary range", pointer) + } + + command = test.createCommand(handle, "key-period") + period := int32(5) + command.ResponsePeriodDays = &period + _, err = test.service.Create(t.Context(), command) + if pointer := fieldPointer(t, err); pointer != "/response_period_days" { + t.Fatalf("pointer = %s, want /response_period_days", pointer) + } + if state := test.transactor.snapshot(); len(state.invitations) != 0 || len(state.idempotency) != 0 { + t.Fatalf("failed creates stored %d invitations and %d keys", len(state.invitations), len(state.idempotency)) + } +} + +func TestCreateReplaysTheOriginalResponseAndRejectsAChangedRequest(t *testing.T) { + test := newHarness(t) + handle, _ := test.showCandidate(t) + command := test.createCommand(handle, "key-replay") + first, err := test.service.Create(t.Context(), command) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + // The candidate stops being visible; the replay still returns the stored + // response and creates nothing. + delete(test.visible, handle) + replay, err := test.service.Create(t.Context(), command) + if err != nil || replay.ID != first.ID || replay.Version != 1 { + t.Fatalf("replay = %v, %v; want the original draft", replay.ID, err) + } + changed := command + changed.CanonicalBody = []byte(`{"different":true}`) + if _, err := test.service.Create(t.Context(), changed); !errors.Is(err, ErrIdempotencyKeyReused) { + t.Fatalf("Create(changed body) error = %v, want ErrIdempotencyKeyReused", err) + } + if state := test.transactor.snapshot(); len(state.invitations) != 1 || len(state.events) != 1 { + t.Fatalf("replay stored %d invitations and %d events, want one each", len(state.invitations), len(state.events)) + } +} + +func TestCreateRollbackLeavesNoDraftWhenTheResponseCannotBeStored(t *testing.T) { + test := newHarness(t) + handle, _ := test.showCandidate(t) + test.transactor.failResultSave = true + if _, err := test.service.Create(t.Context(), test.createCommand(handle, "key-fail")); err == nil { + t.Fatal("Create() succeeded although the response could not be stored") + } + if state := test.transactor.snapshot(); len(state.invitations) != 0 || len(state.events) != 0 || len(state.idempotency) != 0 { + t.Fatalf("failed create left %d invitations, %d events, %d keys", len(state.invitations), len(state.events), len(state.idempotency)) + } +} + +func TestOnlyTheActiveOwnerOfAnEmployerAccountMayWorkWithInvitations(t *testing.T) { + test := newHarness(t) + handle, _ := test.showCandidate(t) + verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC) + addAccount := func(scenario domain.Scenario) uuid.UUID { + id := uuid.Must(uuid.NewV7()) + test.transactor.state.users[id] = domain.User{ID: id, Scenario: scenario, EmailVerifiedAt: &verified} + return id + } + recruiter := addAccount(domain.ScenarioEmployer) + membership, err := domain.NewMembership(domain.MembershipInput{ + OrganizationID: test.organizationID, UserID: recruiter, Role: domain.OrganizationRoleRecruiter, At: verified, + }) + if err != nil { + t.Fatalf("NewMembership() error = %v", err) + } + test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, recruiter}] = membership + unverified := uuid.Must(uuid.NewV7()) + test.transactor.state.users[unverified] = domain.User{ID: unverified, Scenario: domain.ScenarioEmployer} + ownerMembership, _ := domain.NewOwnerMembership(test.organizationID, unverified, verified) + test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, unverified}] = ownerMembership + + tests := []struct { + name string + actor uuid.UUID + want error + }{ + {"recruiter", recruiter, outbound.ErrOrganizationManagerRequired}, + {"candidate account", addAccount(domain.ScenarioCandidate), ErrForbidden}, + {"employer outside the organization", addAccount(domain.ScenarioEmployer), outbound.ErrOrganizationNotFound}, + {"owner without a confirmed email", unverified, ErrEmailNotVerified}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + command := test.createCommand(handle, "key-"+tt.name) + command.ActorID = tt.actor + if _, err := test.service.Create(t.Context(), command); !errors.Is(err, tt.want) { + t.Errorf("Create() error = %v, want %v", err, tt.want) + } + if _, err := test.service.List(t.Context(), ListCommand{ActorID: tt.actor, OrganizationID: test.organizationID, Limit: 10}); !errors.Is(err, tt.want) { + t.Errorf("List() error = %v, want %v", err, tt.want) + } + if _, err := test.service.Get(t.Context(), tt.actor, test.organizationID, uuid.New()); !errors.Is(err, tt.want) { + t.Errorf("Get() error = %v, want %v", err, tt.want) + } + }) + } + if state := test.transactor.snapshot(); len(state.invitations) != 0 { + t.Fatalf("a refused actor created %d invitations", len(state.invitations)) + } +} + +func (test *harness) createDraft(t *testing.T, key string) domain.OrganizationInvitationView { + t.Helper() + handle, _ := test.showCandidate(t) + view, err := test.service.Create(t.Context(), test.createCommand(handle, key)) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + return view +} + +func (test *harness) update(command UpdateCommand) (domain.OrganizationInvitationView, error) { + command.ActorID, command.OrganizationID = test.actorID, test.organizationID + return test.service.Update(context.Background(), command) +} + +func TestUpdateFollowsTheDocumentedOrderOfChecks(t *testing.T) { + test := newHarness(t) + draft := test.createDraft(t, "key-order") + test.setTime(time.Date(2026, time.October, 9, 10, 5, 0, 0, time.UTC)) + + changedTerms := testTerms() + changedTerms.Salary.SalaryTo = 150_000 + updated, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changedTerms}) + if err != nil || updated.Version != 2 || updated.TermsVersion != 2 || updated.Terms.Salary.SalaryTo != 150_000 { + t.Fatalf("Update(terms) = version %d/%d, %v; want 2/2", updated.Version, updated.TermsVersion, err) + } + state := test.transactor.snapshot() + if first := state.terms[termsKey{draft.ID, 1}]; first.Salary.SalaryTo != 140_000 { + t.Fatalf("terms version 1 changed to %d", first.Salary.SalaryTo) + } + if len(state.events) != 2 || state.events[1].Kind != domain.InvitationEventDraftUpdated || + fmt.Sprint(state.events[1].ChangedFields) != "[terms]" { + t.Fatalf("events = %+v, want a draft_updated event for the terms", state.events) + } + + // 1. A body that changes nothing answers with the current invitation even + // when the version it names is stale. + repeated, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changedTerms}) + if err != nil || repeated.Version != 2 { + t.Fatalf("Update(retry) = version %d, %v; want the current version 2", repeated.Version, err) + } + // 2. A stale version beats the domain rules. + invalid := testTerms() + invalid.Salary.SalaryTo = 500_000 + if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &invalid}); !errors.Is(err, domain.ErrInvitationVersionConflict) { + t.Fatalf("Update(stale, invalid) error = %v, want a version conflict", err) + } + // 3. A rule violation of a current version is a field error and changes nothing. + _, err = test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Terms: &invalid}) + if pointer := fieldPointer(t, err); pointer != "/terms/salary/salary_to" { + t.Fatalf("pointer = %s, want the salary range", pointer) + } + // 4. A period outside the policy and an unknown need are field errors. + period := int32(5) + if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, ResponsePeriodDays: &period}); fieldPointer(t, err) != "/response_period_days" { + t.Fatalf("Update(period 5) error = %v", err) + } + need := Field[domain.InvitationNeedRef]{Set: true, Value: domain.InvitationNeedRef{NeedID: uuid.New(), RequirementsVersion: 1}} + if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Need: need}); fieldPointer(t, err) != "/need" { + t.Fatalf("Update(unknown need) error = %v", err) + } + if after := test.transactor.snapshot(); after.invitations[draft.ID].Version() != 2 || len(after.events) != 2 { + t.Fatalf("rejected updates changed the draft: version %d, %d events", after.invitations[draft.ID].Version(), len(after.events)) + } +} + +func TestUpdateKeepsTheTermsVersionWhenOnlyThePeriodOrTheNeedChanges(t *testing.T) { + test := newHarness(t) + draft := test.createDraft(t, "key-parts") + needID := uuid.Must(uuid.NewV7()) + test.transactor.state.needVersions[[3]string{test.organizationID.String(), needID.String(), "2"}] = true + period := int32(14) + linked, err := test.update(UpdateCommand{ + InvitationID: draft.ID, ExpectedVersion: 1, ResponsePeriodDays: &period, + Need: Field[domain.InvitationNeedRef]{Set: true, Value: domain.InvitationNeedRef{NeedID: needID, RequirementsVersion: 2}}, + }) + if err != nil || linked.Version != 2 || linked.TermsVersion != 1 || linked.ResponsePeriodDays != 14 || + linked.Need == nil || linked.Need.NeedID != needID { + t.Fatalf("Update(period, need) = version %d/%d period %d, %v; want 2/1 with the link", linked.Version, linked.TermsVersion, linked.ResponsePeriodDays, err) + } + unlinked, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 2, Need: Field[domain.InvitationNeedRef]{Set: true, Null: true}}) + if err != nil || unlinked.Version != 3 || unlinked.Need != nil || unlinked.TermsVersion != 1 { + t.Fatalf("Update(unlink) = version %d need %v, %v; want version 3 without a need", unlinked.Version, unlinked.Need, err) + } + if state := test.transactor.snapshot(); len(state.terms) != 1 { + t.Fatalf("stored %d terms versions, want only the first", len(state.terms)) + } +} + +func TestUpdateRefusesAnInvitationThatLeftTheDraftState(t *testing.T) { + test := newHarness(t) + draft := test.createDraft(t, "key-state") + stored := test.transactor.state.invitations[draft.ID].Stored() + stored.State = string(domain.InvitationWithdrawn) + withdrawn, err := domain.RestoreInvitation(stored) + if err != nil { + t.Fatalf("RestoreInvitation() error = %v", err) + } + test.transactor.state.invitations[draft.ID] = withdrawn + changed := testTerms() + changed.RoleTitle = "Senior Go developer" + if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 1, Terms: &changed}); !errors.Is(err, domain.ErrInvitationNotDraft) { + t.Fatalf("Update(withdrawn) error = %v, want ErrInvitationNotDraft", err) + } + // A stale version of a withdrawn invitation is still reported as the state. + if _, err := test.update(UpdateCommand{InvitationID: draft.ID, ExpectedVersion: 7, Terms: &changed}); !errors.Is(err, domain.ErrInvitationVersionConflict) { + t.Fatalf("Update(stale, withdrawn) error = %v, want the version comparison first", err) + } +} + +func TestReadsAreScopedToTheOrganizationAndPaged(t *testing.T) { + test := newHarness(t) + first := test.createDraft(t, "key-1") + second := test.createDraft(t, "key-2") + third := test.createDraft(t, "key-3") + + if got, err := test.service.Get(t.Context(), test.actorID, test.organizationID, second.ID); err != nil || got.ID != second.ID { + t.Fatalf("Get() = %v, %v; want the draft", got.ID, err) + } + if _, err := test.service.Get(t.Context(), test.actorID, uuid.Must(uuid.NewV7()), second.ID); !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("Get(other organization) error = %v, want not found", err) + } + if _, err := test.service.Get(t.Context(), test.actorID, test.organizationID, uuid.New()); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Fatalf("Get(unknown) error = %v, want not found", err) + } + page, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 2}) + if err != nil || len(page.Items) != 2 || !page.HasMore { + t.Fatalf("List(2) = %d items more=%t, %v; want a first page of two", len(page.Items), page.HasMore, err) + } + ids := map[uuid.UUID]bool{first.ID: true, second.ID: true, third.ID: true} + for _, item := range page.Items { + if !ids[item.ID] || item.CandidateHandle == "" { + t.Fatalf("listed item %v is unknown or has no alias", item.ID) + } + } + if _, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 0}); !errors.Is(err, ErrInvalidRequest) { + t.Fatalf("List(0) error = %v, want ErrInvalidRequest", err) + } +} + +func (repository testInvitations) GetTermsVersion(_ context.Context, _, invitationID uuid.UUID, version int64) (domain.InvitationTerms, error) { + terms, ok := repository.state.terms[termsKey{invitationID, version}] + if !ok { + return domain.InvitationTerms{}, outbound.ErrInvitationNotFound + } + return terms, nil +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 8ff5fcd..95e6f89 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -6,7 +6,7 @@ This document separates the target product architecture from the technical scaff The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port. -Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks synthetic notices, and no product module produces a real one yet (see [Internal notifications](#internal-notifications)). Other product workflows are not implemented: roles, profiles, assessments, grades, invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. +Registration, email confirmation, login, and basic current-session operations work through the backend API. The frontend implements registration, confirmation, sign-in, and continuation from the server-provided scenario step; local browser E2E covers candidate and employer accounts. Consent settings and organization creation/editing work through the backend API. The internal notification inbox of both cabinets lists and marks synthetic notices, and no product module produces a real one yet (see [Internal notifications](#internal-notifications)). The organization side of the invitation draft (list, create, read, and update with versioned terms) works through the backend API; sending and the candidate side are not implemented (see [Invitation drafts](#invitation-drafts)). Other product workflows are not implemented: roles, profiles, assessments, grades, sending and answering invitations, resume processing, PDF generation, and FSP integration. The deterministic basic match search of the organization-visible bank works through the backend API without ML, competition data, snapshots, or invitations (see [Matching and explanations](#matching-and-explanations)). ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage. @@ -609,7 +609,7 @@ Candidate flow: verify email -> complete profile and consent -> answer questionn Employer flow: verify email -> create company profile -> describe need -> confirm extracted skills -> choose filters -> review an explainable result set -> send a salary offer -> candidate accepts -> only that company can access contacts. -An invitation includes the employer, description, contact channel, both salary bounds, and RUB currency. Both salary values are required whole rubles in multiples of 1000 and must satisfy 0 < salary_from < salary_to, with a width (salary_to - salary_from) / ((salary_from + salary_to) / 2) from 10% to 40% inclusive (PRD FR13); the same rule applies to the salary range of a need. Show the pay period and tax basis (net or gross). vacancy_id is optional. Main transitions are draft -> delivered -> viewed -> accepted or declined; the internal sending step is never visible, a send answers with delivered, and direct acceptance from delivered is allowed. The candidate records viewed with an explicit view command; reading an invitation has no side effect. withdrawn (by the organization), expired (a server deadline), and cancelled_by_candidate are terminal states. Retries are idempotent, and transactions protect concurrent state changes. +An invitation includes the employer, description, contact channel, both salary bounds, and RUB currency. Both salary values are required whole rubles in multiples of 1000 and must satisfy 0 < salary_from < salary_to, with a width (salary_to - salary_from) / ((salary_from + salary_to) / 2) from 10% to 40% inclusive (PRD FR13); the same rule applies to the salary range of a need. Show the pay period and tax basis (net or gross). vacancy_id is optional. Main transitions are draft -> delivered -> viewed -> accepted or declined; the internal sending step is never visible, a send answers with delivered, and direct acceptance from delivered is allowed. The candidate records viewed with an explicit view command; reading an invitation has no side effect. withdrawn (by the organization), expired (a server deadline), and cancelled_by_candidate are terminal states. Retries are idempotent, and transactions protect concurrent state changes. The draft part of this flow is implemented; see [Invitation drafts](#invitation-drafts). A contact grant belongs to one candidate-company pair and is created after an accepted invitation or a candidate's own application. The server checks the user, company membership, grant, and current visibility on each read. Before a grant, employers receive no contacts, original PDF, messaging links, or contact fragments from resumes or ML. @@ -699,7 +699,7 @@ Implemented as a deterministic search without ML: `POST /api/v1/organizations/{o - Accepted residual risks. `truncated` is one bit about the size of the visible bank (it says that more than the limit or the allowance exists) and the response time grows with the bank, so both leak a coarse size to the owner. The bit is bounded by the group limit and no count is returned; the risk is accepted for the demonstration and is listed with the owner questions. - Checks. `internal/usecase/matching` unit tests (formulas with hand-computed values, ties and ordering, filters, explanation, the cut and the charge of the output), `internal/domain/policy_matching_test.go` (document round trip, strictness, validation), `v1/matches_test.go` (mapping and problems), and the integration test `TestMatchSearchOverHTTP` against PostgreSQL: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, Backend confirmed and Networks unconfirmed for one handle, a profile published without a grade through the real profile, consent, and publication operations and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the batch evidence read, two concurrent searches under one allowance, the demo group limit, the policy taxonomy, the denials, and the policy without the section. -Not implemented: the percentile and a real T (they need the theta of a comparable real cohort of at least 30 people); the competition value V and the FSP data; the domain of a candidate; freshness and responsiveness histories; semantic similarity and the ML fallback flag beyond the neutral value; the stored `search_run` snapshots, refinement, comparison, and the shortlist; paging beyond the group limit; and the use of the grade of a need as a filter. The invitation from a search result is not implemented either, so the revocation of C2 after an invitation is not checked here. +Not implemented: the percentile and a real T (they need the theta of a comparable real cohort of at least 30 people); the competition value V and the FSP data; the domain of a candidate; freshness and responsiveness histories; semantic similarity and the ML fallback flag beyond the neutral value; the stored `search_run` snapshots, refinement, comparison, and the shortlist; paging beyond the group limit; and the use of the grade of a need as a filter. Sending an invitation from a search result is not implemented either, so the revocation of C2 after an invitation is not checked here; the draft of an invitation resolves a handle of the search result through the same visibility barrier (see [Invitation drafts](#invitation-drafts)). Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. This is the first model, not an optimized or measured ranking: the plan compares keyword search, the verified-skill baseline, and an ML variant, adds a semantic signal only after an experiment, and never treats its score as a probability of hiring success. @@ -869,7 +869,7 @@ Decisions: - Verification level. `verification_level` is `e0` to `e3` with `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), and one CHECK ties each level to its own bases. The columns are separate from the profile: `UpdateOrganizationProfile` never names them, `domain.NewOrganization` cannot choose a level and starts every organization at `e0` on `confirmed_email`, `Organization.ApplyProfile` keeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; the planned verification flow adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process. `OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the quota tiers of the product policy and has none for `e3`, which the PRD gives a separate policy (quota enforcement reads the tier and must fail closed on an `e3` organization: no quota granted, the action refused, never a fallback to another tier). - An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management, not of this constraint, which would otherwise block a platform decision about an abusive organization. - Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management, which changes a membership and the organization together, and the tenant repository must take the locks in that order, or two transactions can deadlock. -- Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the consent ledger tests to create real organizations, and the same migration has to add the `invitation_id` key, which needs the invitation table; both arrive with the migration that creates the invitation records, together with the keys of needs. All of them are `ON DELETE RESTRICT`, so an organization with consent history, needs, or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3). +- Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the consent ledger tests to create real organizations, and the `invitation_id` key needs real invitations; both arrive with the acceptance of an invitation, the first writer of C4 rows that name a real invitation. The invitation tables (migration 00037) and the needs reference organizations, accounts, and policy versions with `ON DELETE RESTRICT`, so an organization with needs or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3). - Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and remove it through bounded opportunistic cleanup after the replay window; physical deletion may happen later when create traffic resumes; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (organization creation and quota enforcement need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations). What the ports guarantee (`outbound.OrganizationRepositories`, available on `UnitOfWork` only, because a write needs the transaction): @@ -939,6 +939,35 @@ Content of the card (hard requirements for its builder): The anonymous card for organizations is not built here: `AnonymousCardContent` is the closed set of properties that a published card can hold (confirmed categories, stack, total months of experience, soft skills, location, relocation), with no name, contact, employer, salary, or identifier, and a contract test walks the references of the card and the preview and fails on any profile, contact, consent, or organization schema. The card of an organization's search result must reuse it. `GetMyCardPreview` and `ListMyCardAccessHistory` are contract-only: the preview needs the profile, the confirmed categories, and the publication read together, and the access records are written by the search and contact-read tasks, so the table for them comes with those tasks. +### Invitation drafts + +Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox row, no event, and no quota charge. Sending, withdrawal, the salary raise, the contact read, and every candidate operation of the invitation tag still answer 501 after the common checks. Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`. + +Tables: + +- `invitations`: UUIDv7 `id`, `organization_id`, the internal `candidate_id` (never serialized, logged, or printed), the optional need link (`need_id` with `need_requirements_version`, bound by composite foreign keys to a stored version of a need of the same organization), `state` (all fourteen states of the contract, so the later operations need no constraint change), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7, or 14), `policy_version_id` (the product policy version that allowed the period), `response_deadline_at`, `salary_raise_used`, `created_by`, and `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. CHECK constraints tie the deadline to the delivery (both set or both null), keep a draft free of delivery, view, answer, and raise, and tie the expiry reason to the state. A trigger keeps the identity columns, makes every UPDATE advance `version` by exactly one and `terms_version` by at most one, and refuses to undo a raise or to move the delivery, the deadline, or the period after a delivery. A second trigger refuses DELETE. The foreign keys to organizations, accounts, and policy versions are `ON DELETE RESTRICT`, so an account with invitations is undeletable until a deletion procedure settles them. +- `invitation_terms_versions`: `(invitation_id, version)`, the terms as a JSONB snapshot, and the salary again in typed columns (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Constraints repeat the money rules in integers: both bounds from 1000 to 100 000 000 rubles in steps of 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B` (a width of 10% to 40% of the midpoint), RUB, month, and `net` or `gross`. The snapshot must hold all twelve terms and its salary must equal the typed columns. A trigger refuses UPDATE and DELETE: a version of the terms is immutable, and a change appends the next version. The invitation points at its current version by a deferred composite foreign key, so the first version is inserted in the same transaction. +- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created` or `draft_updated`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only. +- `invitation_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: + +- Money. Amounts are whole rubles in `bigint`, as in the contract: there are no minor units and no floating-point column or comparison. `domain.SalaryRange.Validate` is the single implementation of the rule for needs and invitations; it checks the bounds, the step, the currency, the period, the base, `A < B`, and the width with the integer pair above. A violation of the order or the width is attributed to `salary_to`. The database repeats the rule, so another writer cannot store a range the API would refuse. +- Terms are complete from the first draft. `InvitationTerms.Validate` repeats the schema rules a stored value must also satisfy and adds the cross-field rules: a place of work for the `office` or `hybrid` format, a technology that is not repeated ignoring letter case, and a package in which every condition is either provided with a description or explicitly not provided. Text fields reject control characters, including NUL, which JSONB cannot store. A stored snapshot is decoded strictly and validated again on every read. +- The candidate. A draft names the candidate only by the card handle. `candidateview.Service.ResolveCandidateHandle` resolves it in the create transaction with the checks of a card read: the active membership, the effective C2 publication, the hiding of this organization, the locks of the visible cohort, and the minimum cohort of five. An unknown handle, a handle of another organization, a candidate who revoked C2 or hid the profile from the organization, and a card that the cohort rules suppress all fail with the same 400 at `/candidate_handle`. The resolution charges no card-view quota and writes no access history, because it returns an identifier to the server only and shows no card content. Responses derive the alias again with the key of the cards, so the handle of an invitation is the handle of the card; the same candidate has another alias in every organization. +- Owner only. The HTTP boundary lists the operations in `ownerCompanyOperations`, and the usecase repeats the check in its transaction: a verified employer account with an active `owner` membership. Another role gets 403; an outsider, an unknown organization, an unknown invitation, and an invitation of another organization get the same 404. A membership alone grants nothing. +- Idempotent create. The scope of `Idempotency-Key` is the operation, the key, the account, and the organization; the fingerprint is that of the canonical request body. The original 201 is stored in `invitation_creation_results` and replayed for 24 hours, even after the draft changed or the candidate stopped being visible. A different body under the same key gives 422 `idempotency_key_reused`. Every failure rolls the whole transaction back, so a 400 is never stored. +- Update. The body replaces the fields it sets, and `terms` is always replaced as a whole. The order is the one of the contract: a body that changes nothing returns the current invitation with 200 even when the version is stale, then the version (412 `version_conflict`), then the state (409 `state_conflict`, only a draft changes), then the rules (400 with a pointer). A change of the terms appends the next terms version; a change of the period or the need keeps it. A new period is checked against the policy in force and records its version. +- Response period. The options and the default come from the `invitations` section of the effective product policy (3, 7, 14; default 7), and the draft stores the version it used. +- Locks. A create and an update both take the exclusive organization lock first (`CompanyQuotaRepository.LockOrganization`), like a card read and a search, and only then the share lock of the membership check, the cohort locks of a create, or the invitation row lock of an update, so commands of one organization queue instead of deadlocking on a lock upgrade, and a later command that also charges the organization, such as sending, keeps the same order. An update locks the invitation row with a statement of its own (`LockInvitation`) and reads it afterwards: a locking read joined to the terms table would, after waiting for a concurrent commit, pair the new `terms_version` with the terms row it fetched before the wait and find nothing. A create repeats a bounded number of times when the visible cohort changed while it was locked. +- The indicator. `salary_fit` is always `not_available` and `contact_access` is `not_granted` with no fields. The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet. + +How the later operations plug in: sending must resolve the candidate through the same visibility barrier again, because a draft keeps its candidate after a C2 revocation or a hiding, and then moves the draft to `delivered` by one UPDATE of `state`, `delivered_at`, `response_deadline_at`, and `version`, appends an audit event for that version, and writes the `invitation.delivered` outbox event whose inbox resolver for the source `invitation` is the existing plug-in point of [Internal notifications](#internal-notifications); the candidate's inbox reads `invitations` by `candidate_id` and `delivered_at`, and the pair rules read the index on the organization and the candidate. The contact grant, the C4 key to `invitations`, and the keys of the consent ledger to `organizations` and `invitations` arrive with the acceptance, the first writer of C4 rows that name a real invitation. + +Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the quota charge and the limit of pending invitations per need, the sending, the raise, the withdrawal, the candidate side, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned. + +Tests: `domain/salary_range_test.go` and `domain/invitation_test.go` (exact width at 10% and 40%, steps, caps, terms rules with pointers, versions, immutability of earlier values, redaction), `usecase/invitation/service_test.go` (owner policy, handle refusals, order of checks, replay, rollback, versions), `adapter/primary/http/v1/invitation_test.go` (mapping, no candidate field, failure statuses, cursor), and the integration tests `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations`, and `TestInvitationMigrationRollbackKeepsStoredInvitations` against a real PostgreSQL. + ## 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 f9eaff7..f6f540d 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -6,7 +6,7 @@ Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту. -Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Внутренний inbox уведомлений в обоих кабинетах показывает и отмечает синтетические уведомления, а настоящие пока не создает ни один продуктовый модуль (см. [Внутренние уведомления](#внутренние-уведомления)). Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований, снимков и приглашений (см. [Подбор и объяснение](#подбор-и-объяснение)). ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. +Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Во frontend реализованы регистрация, подтверждение, вход и продолжение по серверному шагу сценария; локальный браузерный E2E проверяет кандидата и работодателя. Настройки согласий и создание/редактирование организаций работают через backend API. Внутренний inbox уведомлений в обоих кабинетах показывает и отмечает синтетические уведомления, а настоящие пока не создает ни один продуктовый модуль (см. [Внутренние уведомления](#внутренние-уведомления)). Сторона организации в черновике приглашения (список, создание, чтение и изменение с версиями условий) работает через backend API; отправка и сторона кандидата не реализованы (см. [Черновики приглашений](#черновики-приглашений)). Остальные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, отправка приглашений и ответ на них, загрузка и анализ резюме, PDF и интеграция с ФСП. Детерминированный базовый подбор по банку, видимому организации, работает через backend API без ML, данных соревнований, снимков и приглашений (см. [Подбор и объяснение](#подбор-и-объяснение)). ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md). @@ -609,7 +609,7 @@ backend/ Целевой сценарий работодателя: подтверждение email -> профиль компании -> описание потребности -> выбор или подтверждение извлеченных навыков -> фильтры и объяснимая подборка -> предложение с диапазоном зарплаты -> принятие кандидатом -> контактный доступ только этой компании. -Приглашение содержит работодателя, описание, способ связи, обе границы зарплаты и валюту RUB. Обе границы - целые рубли, кратные 1000, 0 < salary_from < salary_to, ширина (salary_to - salary_from) / ((salary_from + salary_to) / 2) от 10% до 40% включительно (FR13 в PRD); то же правило действует для вилки потребности. Период и база налога (net или gross) показываются явно. vacancy_id необязателен. Базовые переходы: draft -> delivered -> viewed -> accepted или declined; внутренний этап отправки не виден, отправка отвечает delivered, принять можно и прямо из delivered. Состояние viewed кандидат фиксирует явной командой просмотра; чтение приглашения побочных эффектов не имеет. withdrawn (отзыв организацией), expired (серверный срок) и cancelled_by_candidate - терминальные состояния. Повторные операции идемпотентны, конкурирующие переходы защищены транзакцией и текущей версией. +Приглашение содержит работодателя, описание, способ связи, обе границы зарплаты и валюту RUB. Обе границы - целые рубли, кратные 1000, 0 < salary_from < salary_to, ширина (salary_to - salary_from) / ((salary_from + salary_to) / 2) от 10% до 40% включительно (FR13 в PRD); то же правило действует для вилки потребности. Период и база налога (net или gross) показываются явно. vacancy_id необязателен. Базовые переходы: draft -> delivered -> viewed -> accepted или declined; внутренний этап отправки не виден, отправка отвечает delivered, принять можно и прямо из delivered. Состояние viewed кандидат фиксирует явной командой просмотра; чтение приглашения побочных эффектов не имеет. withdrawn (отзыв организацией), expired (серверный срок) и cancelled_by_candidate - терминальные состояния. Повторные операции идемпотентны, конкурирующие переходы защищены транзакцией и текущей версией. Часть этого пути с черновиком реализована, см. [Черновики приглашений](#черновики-приглашений). contact_grant относится к паре кандидат-компания и создается после принятого приглашения или собственного отклика кандидата. Сервер проверяет пользователя, компанию, grant и актуальную видимость при каждом чтении. До grant работодатель не получает контакты, оригинальный PDF, мессенджеры или контактные фрагменты из резюме и ML. @@ -699,7 +699,7 @@ contact_grant относится к паре кандидат-компания - Принятые остаточные риски. `truncated` - один бит о размере видимого банка (он говорит, что существует больше, чем предел или лимит), а время ответа растет с банком, поэтому оба раскрывают владельцу грубый размер. Бит ограничен пределом группы, число не возвращается; риск принят для демонстрации и внесен в вопросы владельцу. - Проверки. Модульные тесты `internal/usecase/matching` (формулы с рассчитанными вручную значениями, равенства и порядок, фильтры, объяснение, обрезка и оплата вывода), `internal/domain/policy_matching_test.go` (круговой проход документа, строгость, проверка значений), `v1/matches_test.go` (отображение и ошибки) и интеграционный тест `TestMatchSearchOverHTTP` на PostgreSQL: скрытые кандидаты и две организации, потребность и ее измененные требования, повторные одинаковые ответы, Backend подтвержден и сети не подтверждены для одного handle, профиль без грейда, опубликованный настоящими операциями профиля, согласия и публикации и убранный отзывом C2, кандидат один в своей когорте, отсутствие контактов и идентификаторов в теле, оплата и история доступа за поиск, организация с лимитом меньше ее банка, предел группы, пакетное чтение доказательств, два одновременных поиска под одним лимитом, демонстрационный предел группы, таксономия политики, отказы доступа и политика без раздела. -Не реализовано: перцентиль и настоящий T (нужны theta сопоставимой реальной когорты не менее 30 человек); соревновательное значение V и данные ФСП; домен кандидата; истории свежести и своевременности; семантическая близость и признак недоступности ML сверх нейтрального значения; сохраняемые снимки `search_run`, уточнение, сравнение и шортлист; продолжение выдачи сверх предела группы; использование грейда потребности как фильтра. Приглашение из результата поиска тоже не реализовано, поэтому отзыв C2 после приглашения здесь не проверяется. +Не реализовано: перцентиль и настоящий T (нужны theta сопоставимой реальной когорты не менее 30 человек); соревновательное значение V и данные ФСП; домен кандидата; истории свежести и своевременности; семантическая близость и признак недоступности ML сверх нейтрального значения; сохраняемые снимки `search_run`, уточнение, сравнение и шортлист; продолжение выдачи сверх предела группы; использование грейда потребности как фильтра. Отправка приглашения из результата поиска тоже не реализована, поэтому отзыв C2 после приглашения здесь не проверяется; черновик приглашения разрешает handle из результата поиска через тот же барьер видимости (см. [Черновики приглашений](#черновики-приглашений)). До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия. Это первая модель, а не оптимальное или измеренное ранжирование: планируется сравнить ключевые слова, baseline подтвержденных навыков и ML-вариант, семантический сигнал добавлять только после эксперимента и не считать его балл вероятностью успешного найма. @@ -869,7 +869,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове - Уровень проверки. `verification_level` - от `e0` до `e3` с `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), а один CHECK связывает каждый уровень с его основаниями. Столбцы отделены от профиля: `UpdateOrganizationProfile` никогда их не называет, `domain.NewOrganization` не может выбрать уровень и начинает каждую организацию с `e0` на основании `confirmed_email`, `Organization.ApplyProfile` сохраняет проверку, а в контракте нет операции или поля запроса, которые ее задают. Тест обновляет профиль после того, как процесс сдвинул уровень, и проверяет, что он остается. E1-E3 задаются процессами проверки, которых еще нет; запланированный процесс проверки добавляет E0/E1 с доказательствами, областью действия и историей только на добавление и будет обновлять эти столбцы вместе со строкой истории, а сначала обязан записать историю из текущей строки каждой существующей организации (уровень, основание и время как сохранены), чтобы в истории не было разрыва до первого процесса. `OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням квот продуктовой политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику (механизм квот читает ступень и обязан отказывать по умолчанию для организации с `e3`: квота не выдается, действие отклоняется, возврата на другую ступень нет). - У организации есть владелец. Отложенный constraint trigger (`organizations_owner_required`, SQLSTATE 23514) при фиксации отказывает организации без членства `owner` в состоянии `active`, поэтому создание организации без владельца падает, каким бы кодом ее ни вставили, а `CreateWithOwner` сохраняет организацию, представителей и владельца в одной транзакции. Удаление или понижение последнего владельца позже - правило управления участниками, а не этого ограничения, которое иначе блокировало бы решение платформы о недобросовестной организации. - Обновление. `UpdateProfile` - один оператор, который применяется только когда сохраненная версия равна версии, прочитанной вызывающим, и увеличивает ее на единицу. Тот же оператор требует активного членства исполнителя с управляющей ролью (роли берутся из `domain.ManagerRoles`, а не из SQL), поэтому членство, закончившееся после чтения вызывающего, все равно останавливает запись. Если оператор ничего не нашел, адаптер читает членство и отвечает `ErrOrganizationNotFound` (неизвестная организация или нет активного членства), `ErrOrganizationManagerRequired` или `ErrOrganizationVersionConflict` в этом порядке, поэтому устаревшая версия ничего не сообщает постороннему. Затем список представителей заменяется в той же транзакции под блокировкой строки обновления. Оператор блокирует строку организации (`FOR UPDATE`), а затем строку членства исполнителя `FOR SHARE`, поэтому отзыв, зафиксированный, пока оператор ждет блокировку членства, проверяется заново и останавливает запись (интеграционный тест держит отзыв открытым, ставит обновление за ним в очередь и фиксирует отзыв). Порядок блокировок у каждого писателя: сначала организации, затем членства; управление участниками, которое меняет членство и организацию вместе, и tenant-репозиторий обязаны брать блокировки в этом порядке, иначе две транзакции могут взаимно заблокироваться. -- Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала согласий создавать настоящие организации, а та же миграция должна добавить ключ `invitation_id`, которому нужна таблица приглашений; оба появятся с миграцией, создающей записи приглашений, вместе с ключами потребностей. Все они `ON DELETE RESTRICT`, поэтому организацию с историей согласий, потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD). +- Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала согласий создавать настоящие организации, а ключу `invitation_id` нужны настоящие приглашения; оба появятся с принятием приглашения, первым писателем строк C4 с настоящим приглашением. Таблицы приглашений (миграция 00037) и потребности ссылаются на организации, аккаунты и версии политики с `ON DELETE RESTRICT`, поэтому организацию с потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD). - Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять ограниченной очисткой после окна повтора; физическое удаление может произойти позже при возобновлении создания организаций; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (для создания организаций и применения квот нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации). Что гарантируют порты (`outbound.OrganizationRepositories`, доступны только через `UnitOfWork`, потому что запись требует транзакции): @@ -939,6 +939,35 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове Анонимная карточка для организаций здесь не строится: `AnonymousCardContent` - закрытый набор свойств, которые может содержать опубликованная карточка (подтвержденные категории, стек, суммарный опыт в месяцах, софт-скиллы, место, переезд), без имени, контакта, работодателя, зарплаты и идентификатора, а контрактный тест обходит ссылки карточки и предпросмотра и падает на любой схеме профиля, контакта, согласия или организации. Карточку результата поиска организации нужно строить на ней. `GetMyCardPreview` и `ListMyCardAccessHistory` только в контракте: предпросмотру нужно читать профиль, подтвержденные категории и публикацию вместе, а записи обращений пишут задачи поиска и чтения контактов, поэтому таблица для них придет с этими задачами. +### Черновики приглашений + +Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет. Отправка, отзыв, повышение вилки, чтение контактов и все операции кандидата тега invitation после общих проверок по-прежнему отвечают 501. Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`. + +Таблицы: + +- `invitations`: UUIDv7 `id`, `organization_id`, внутренний `candidate_id` (его не сериализуют, не логируют и не печатают), необязательная связь с потребностью (`need_id` с `need_requirements_version`, привязанные составными внешними ключами к сохраненной версии потребности той же организации), `state` (все четырнадцать состояний контракта, поэтому последующим операциям не нужно менять ограничение), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7 или 14), `policy_version_id` (версия продуктовой политики, разрешившая срок), `response_deadline_at`, `salary_raise_used`, `created_by`, а также `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. Ограничения CHECK связывают дедлайн с доставкой (оба заданы или оба null), оставляют черновик без доставки, просмотра, ответа и повышения и связывают причину истечения с состоянием. Триггер хранит неизменными столбцы идентичности, требует, чтобы каждый UPDATE увеличивал `version` ровно на единицу, а `terms_version` не более чем на единицу, и не дает отменить повышение или сдвинуть доставку, дедлайн и срок после доставки. Второй триггер запрещает DELETE. Внешние ключи на организации, аккаунты и версии политики - `ON DELETE RESTRICT`, поэтому аккаунт с приглашениями нельзя удалить, пока процедура удаления их не закроет. +- `invitation_terms_versions`: `(invitation_id, version)`, условия в виде снимка JSONB и вилка еще раз в типизированных столбцах (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Ограничения повторяют денежные правила в целых числах: обе границы от 1000 до 100 000 000 рублей с шагом 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` и `5 * (B - A) <= A + B` (ширина 10-40% от середины), RUB, месяц и `net` или `gross`. Снимок обязан содержать все двенадцать условий, а его вилка - совпадать с типизированными столбцами. Триггер запрещает UPDATE и DELETE: версия условий неизменяема, изменение добавляет следующую версию. Приглашение указывает на текущую версию отложенным составным внешним ключом, поэтому первая версия вставляется в той же транзакции. +- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created` или `draft_updated`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются. +- `invitation_creation_results`: исходный ответ идемпотентного создания, привязанный к общей записи идемпотентности и удаляемый вместе с ней. В нем условия, псевдоним и нет идентификатора кандидата. + +Решения: + +- Деньги. Суммы - целые рубли в `bigint`, как в контракте: копеек, столбцов и сравнений с плавающей точкой нет. `domain.SalaryRange.Validate` - единственная реализация правила для потребностей и приглашений: она проверяет границы, шаг, валюту, период, базу, `A < B` и ширину парой целых неравенств выше. Нарушение порядка или ширины относится к `salary_to`. База данных повторяет правило, поэтому другой писатель не сохранит вилку, которую отклонил бы API. +- Условия полны с первого черновика. `InvitationTerms.Validate` повторяет правила схемы, которые должно выполнять и сохраненное значение, и добавляет межполевые правила: место работы для формата `office` или `hybrid`, неповторяющаяся без учета регистра технология и пакет, где каждое условие либо предоставлено с описанием, либо явно не предусмотрено. Текстовые поля отклоняют управляющие символы, включая NUL, который JSONB хранить не умеет. Сохраненный снимок читается строго и проверяется при каждом чтении. +- Кандидат. Черновик называет кандидата только handle карточки. `candidateview.Service.ResolveCandidateHandle` разрешает его в транзакции создания проверками чтения карточки: активное членство, действующая публикация C2, скрытие этой организации, блокировки видимой когорты и минимальная когорта из пяти. Неизвестный handle, handle другой организации, кандидат, отозвавший C2 или скрывший профиль от организации, и карточка, подавленная правилами когорты, дают один и тот же 400 на `/candidate_handle`. Разрешение не списывает квоту просмотров и не пишет историю доступа: оно возвращает идентификатор только серверу и не показывает содержимое карточки. Ответы снова выводят псевдоним ключом карточек, поэтому handle приглашения - это handle карточки; у одного кандидата в каждой организации свой псевдоним. +- Только владелец. HTTP-граница перечисляет операции в `ownerCompanyOperations`, а usecase повторяет проверку в своей транзакции: подтвержденный аккаунт работодателя с активным членством `owner`. Другая роль получает 403; посторонний, неизвестная организация, неизвестное приглашение и приглашение другой организации получают один и тот же 404. Само членство ничего не дает. +- Идемпотентное создание. Область `Idempotency-Key` - операция, ключ, аккаунт и организация, отпечаток - отпечаток канонического тела запроса. Исходный 201 хранится в `invitation_creation_results` и повторяется 24 часа, даже после изменения черновика или когда кандидат перестал быть видимым. Другое тело с тем же ключом дает 422 `idempotency_key_reused`. Любой отказ откатывает всю транзакцию, поэтому 400 не сохраняется. +- Изменение. Тело заменяет заданные поля, а `terms` всегда заменяются целиком. Порядок как в контракте: тело, которое ничего не меняет, возвращает текущее приглашение с 200 даже при устаревшей версии, затем версия (412 `version_conflict`), затем состояние (409 `state_conflict`, меняется только черновик), затем правила (400 с pointer). Изменение условий добавляет следующую версию условий, изменение срока или потребности ее сохраняет. Новый срок проверяется по действующей политике и записывает ее версию. +- Срок ответа. Варианты и значение по умолчанию берутся из раздела `invitations` действующей продуктовой политики (3, 7, 14; по умолчанию 7), а черновик хранит версию, которой воспользовался. +- Блокировки. Создание и изменение сначала берут исключительную блокировку организации (`CompanyQuotaRepository.LockOrganization`), как чтение карточки и поиск, и только потом разделяемую блокировку проверки членства, блокировки когорты при создании или блокировку строки приглашения при изменении. Поэтому команды одной организации встают в очередь, а не блокируют друг друга при повышении блокировки, и следующая команда, которая тоже списывает ресурсы организации, например отправка, сохраняет тот же порядок. Изменение блокирует строку приглашения отдельным запросом (`LockInvitation`) и читает ее после: блокирующее чтение с соединением таблицы условий после ожидания чужой фиксации сопоставило бы новый `terms_version` со строкой условий, взятой до ожидания, и ничего не нашло бы. Создание повторяется ограниченное число раз, если видимая когорта изменилась во время блокировки. +- Индикатор. `salary_fit` всегда `not_available`, а `contact_access` - `not_granted` без полей. Индикатору нужен минимум кандидата, а его вычисление до появления лимита из трех установок в день и семидневного отключения позволило бы организации подбирать минимум правками черновика, поэтому пока не считается и не применяется ни то ни другое. + +Как подключаются следующие операции: отправка должна снова проверить кандидата тем же барьером видимости, потому что черновик сохраняет кандидата после отзыва C2 или скрытия, и затем переводит черновик в `delivered` одним UPDATE `state`, `delivered_at`, `response_deadline_at` и `version`, добавляет событие аудита этой версии и пишет событие outbox `invitation.delivered`, а преобразователь входящей записи для источника `invitation` - уже существующая точка подключения [Внутренних уведомлений](#внутренние-уведомления); входящие кандидата читают `invitations` по `candidate_id` и `delivered_at`, а правила пары читают индекс по организации и кандидату. Контактное разрешение, ключ C4 на `invitations` и ключи журнала согласий на `organizations` и `invitations` появятся вместе с принятием, первым писателем строк C4 с настоящим приглашением. + +Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, списание квоты и предел ожидающих приглашений на потребность, отправка, повышение, отзыв, сторона кандидата, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована. + +Тесты: `domain/salary_range_test.go` и `domain/invitation_test.go` (точная ширина на 10% и 40%, шаг, пределы, правила условий с pointer, версии, неизменность прежних значений, скрытие при печати), `usecase/invitation/service_test.go` (политика владельца, отказы по handle, порядок проверок, повтор, откат, версии), `adapter/primary/http/v1/invitation_test.go` (преобразование, отсутствие полей кандидата, статусы отказов, курсор) и интеграционные `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations` и `TestInvitationMigrationRollbackKeepsStoredInvitations` на настоящем PostgreSQL. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.