feat(invitations): check contact grants on every read, cap pending invitations, and expire them at the deadline

This commit is contained in:
shira committed 2026-10-09 19:06:50 +03:00
1 parent 676b3c6e24
commit 12a7213d4a
67 files changed
+4255 -149

No files matched your search

+54 -14
View File
@@ -174,7 +174,7 @@ The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts fini
### Scheduled jobs
Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. One product handler is registered in `jobHandlers()` (`backend/internal/bootstrap/jobs.go`): `assessment.signal_review`, which computes the [assessment review band](#assessment-signals-and-the-review-band). The tests also use a test-only kind. The first planned deadline kind is the invitation response deadline. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs).
Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. Two product handlers are registered in `jobHandlers()` (`backend/internal/bootstrap/jobs.go`): `assessment.signal_review`, which computes the [assessment review band](#assessment-signals-and-the-review-band), and `invitation.response_deadline`, which moves an invitation to `expired` when its response deadline passes ([Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry)). The tests also use a test-only kind. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs).
Scheduling. A usecase calls `unit.ScheduledJobs().Schedule(ctx, job)` in its business transaction, so the job exists exactly when the change that needs it committed, and `Cancel(ctx, kind, key)` stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. `(kind, key)` is unique and the first schedule wins: a repeat inserts nothing (`INSERT ... ON CONFLICT DO NOTHING`) and reports `false`, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example `<id>:<version>`.
@@ -184,7 +184,7 @@ Claim and lease. The worker claims up to `JOBS_BATCH_SIZE` jobs in one statement
Run and completion. Each job runs in its own READ COMMITTED transaction: it sets `statement_timeout` and `idle_in_transaction_session_timeout` to the lease duration, locks the job row with a guard on `status = running`, the lease owner, and the attempt number, calls the handler with an `outbound.UnitOfWork` of the same transaction, marks the job `done` with the same guard, and commits. The handler effect and the completion therefore commit together: for an effect that stays in PostgreSQL a job is applied exactly once even when workers race, restart, or a lease expires. While the handler runs the row is locked, so another worker's claim skips it even after the lease expired by the clock; when the guard fails because the job was canceled or reclaimed, the handler is not called and nothing commits (`lease_lost`). A handler may cancel its own job through the unit, for example an expiry that also cancels the deadline job it stands for: the completion then finds the job `cancelled` in its own transaction, treats it as finished, and commits the effect, and the job stays `cancelled`. Any other change of its own job by the handler rolls back and makes the job `dead` with `completion_conflict`, because it would repeat on every attempt. A handler whose effect leaves the database, such as a call to another service, can repeat after a crash between that call and the commit and must be idempotent itself. The handler context ends with the renewed lease. A handler decides by `job.DueAt`, the deadline the job stands for, which a retry keeps, not by when it happens to run.
Lock order. The handler holds the job row lock and may then lock product rows. A business transaction that cancels a job, such as accepting an invitation at its deadline, should call `Cancel` before it locks those product rows. `Cancel` waits for a handler transaction in progress: after its commit the job is done and `Cancel` reports `false`, so the caller sees the expiry; otherwise the job is canceled and the worker finds its lease gone. The opposite order can deadlock, which PostgreSQL resolves by aborting one side with `ErrTransactionConflict`; the job side counts a failed attempt and retries.
Lock order. The handler holds the job row lock and may then lock product rows. A business transaction that cancels a job should call `Cancel` before it locks those product rows. A candidate's answer does not cancel the response deadline job: the run finds the answered invitation and changes nothing ([Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry)). `Cancel` waits for a handler transaction in progress: after its commit the job is done and `Cancel` reports `false`, so the caller sees the finished job; otherwise the job is canceled and the worker finds its lease gone. The opposite order can deadlock, which PostgreSQL resolves by aborting one side with `ErrTransactionConflict`; the job side counts a failed attempt and retries.
Failures. A failed attempt rolls back its effect; a second statement, guarded the same way, records it. A handler error, a lease timeout, a deadlock or serialization failure (`conflict`), or a commit that PostgreSQL refuses (`effect_rejected`, for a handler that ignored a failed statement or a deferred constraint) moves the job to `failed` with `available_at = now + backoff`, where the backoff is the shared `worker/retry` delay from `JOBS_BACKOFF_INITIAL`, doubling up to `JOBS_BACKOFF_MAX`, with jitter. `inbound.ErrJobRejected`, a handler panic, and `completion_conflict` are final, also when they happen during shutdown. After the last allowed attempt (the job's own limit or `JOBS_MAX_ATTEMPTS`) the job is `dead`: it is logged at error level and counted as `dead`, and it needs an operator. `last_error_class` stores only a bounded class; a sanitized reason appears only in the log. A database failure outside the handler is not the job's fault: the worker releases its unfinished jobs without counting the attempt and backs off before the next claim, so an outage causes no hot loop. When the failure record itself cannot be written, the job keeps its started lease; a later claim then counts it as `lease_expired`, which on the last attempt makes it dead.
@@ -805,7 +805,7 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo
- `ConsentTexts().Get` and `Current` read published texts and verify the stored hash on every read.
- `ConsentLedger().Grant` and `GrantContact` return the new record with `created` true or the existing one with `created` false. An unknown subject returns `ErrUserNotFound`, an unknown version `ErrConsentTextNotFound`, a version published later `ErrConsentTextNotPublished`, and a hash that does not match the published text (for C4 with the stored name) `ErrConsentTextMismatch`; these come from the database and abort a surrounding transaction. A duplicate does not. A grant whose conflicting record was revoked between its two statements returns `ErrTransactionConflict`.
- `Revoke` returns the rows it stamped. `Current` returns the newest unrevoked C1-C3 or C5 record or `ErrConsentNotFound`; `CurrentContact` returns the unrevoked C4 records of one organization. `List` pages the subject's ledger newest first, optionally by state.
- `ConsentRevocationEffects.Apply` runs in the same `UnitOfWork` transaction as the ledger revocation. It closes the current publication's effective C2 access only when that publication references one of the revoked records, appends its privacy-history event once, and writes bounded outbox intents from the exact revoked records. A future C2/C4 grant adapter must bind each downstream grant to its source consent-record ID and synchronously close that old grant in this transaction; a later grant may open only a new record-bound grant, never reopen an old one. C5 readers and importers must check the current ledger and fail closed; an outbox message alone does not authorize access or prove that an external system deleted data.
- `ConsentRevocationEffects.Apply` runs in the same `UnitOfWork` transaction as the ledger revocation. It closes the current publication's effective C2 access only when that publication references one of the revoked records, appends its privacy-history event once, and writes bounded outbox intents from the exact revoked records. The contact grants of the revoked records are closed in this transaction (C4 by record, C2 for every grant of the candidate; see [Contact reads and revocation](#contact-reads-and-revocation)); a later grant may open only a new record-bound grant, never reopen an old one. C5 readers and importers must check the current ledger and fail closed; an outbox message alone does not authorize access or prove that an external system deleted data.
### Consent usecase
@@ -922,7 +922,7 @@ Decisions:
- The lapse of `looking` comes from the versioned policy and only narrows. The 30 days are `search_status.searching_confirmation_interval_days` of the effective `product` policy version (demo version 1: 30), so the owner changes them by publishing a new policy version, not by a constant or configuration. A confirmation fixes `lapses_at` and stores `policy_version_id`, so a later policy change moves no stored time and every row names the policy it was made under, as the policy section requires. The lapse itself is computed (`SearchStatus.Effective(now)` is `looking` only while `now` is before `lapses_at`) and never written: no process, job, or clock skew can turn an expired status into anything more public, the stored row keeps what the candidate said, and the read model shows `value` `not_looking` with `lapsed` true. The candidate confirms again with `looking`, which replaces `confirmed_at`. A reminder before the lapse is a planned notification, not part of this task.
- Versions. Each setting has its own `version` (0 is the absence of a row), checked in the statement like the profile: `UpdateCandidatePublication` and `UpdateCandidateSearchStatus` change a row only when the stored version equals the one the caller read, and no row returns for a stale one (412 `version_conflict`). The domain order is the contract's: a version above the current one is a conflict, an unchanged effective setting is a success even over a stale version, any other change over a stale version is a conflict, and a publication needs an active C2. Because the settings are independent, a change of one never makes another stale.
- Hidden organizations belong to the candidate and are safe against enumeration. The record is the candidate's: no organization-visible query selects it, and an organization cannot tell a hidden candidate from an unpublished one. Hiding by identifier must not become a way to ask whether an organization exists. The foreign key refuses an unknown organization (SQLSTATE 23503), and the usecase must answer that exactly like an organization the candidate cannot see: the same 404 `not_found` with the same body, without a different timing or code. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned, an open question), so a hiding reveals nothing the candidate could not already read. Lifting a hiding is a DELETE that answers 204 for any well-formed identifier, so it reveals nothing at all, and its history event is written only when a row was deleted. The identifiers are random UUIDv7 values, and the general rate limit covers the probing that remains.
- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke the grant with the reason `visibility_closed` in the same transaction as the change (the invitation contract fixes the reason). That belongs to the usecases that do not exist yet; this task stores the settings and defines the contract. The search status never closes a grant.
- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke the grant with the reason `visibility_closed` in the same transaction as the change (the invitation contract fixes the reason). The closing is implemented; see [Contact reads and revocation](#contact-reads-and-revocation). The search status never closes a grant.
- History instead of a field scope. The C2 record proves the consent to the publication text, and `candidate_privacy_events` keeps what the consent ledger note asked for: the published field set and its changes with their times and the C2 record behind each. A revocation of C2 and a lapse are computed, not events. Whether C2 needs its own field scope as a consent under article 10.1 of 152-FZ is still a legal question (see the consent ledger).
- Privacy. The tables hold identifiers, card field codes, and times; no profile value, name, contact, or file (a test lists the columns). `Publication`, `SearchStatus`, `HiddenOrganization`, and `PrivacyEvent` log only identifiers, versions, and kinds. No query selects another account's row: every statement is scoped by `user_id`. The adapter must report only the SQLSTATE and the constraint name, as the others do.
@@ -962,11 +962,11 @@ Decisions:
- 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.
- The indicator. `salary_fit` is always `not_available`; `contact_access` is derived from the grant ([Contact reads and revocation](#contact-reads-and-revocation)). The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet.
How the later operations plug in: the pair rules read the index on the organization and the candidate. The contact grant arrives with the acceptance ([Candidate acceptance](#candidate-acceptance)). The C4 columns of the consent ledger still have no foreign keys to `organizations` and `invitations`; that is a follow-up.
Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the limit of pending invitations per need, the raise, the withdrawal, the candidate side beyond the list of invitations, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned.
Not implemented: the salary limit and the withheld counter, the indicator against the candidate's minimum, the raise, the withdrawal, the candidate side beyond the list of invitations, the card of the organization for the candidate, the reading of earlier terms versions, and the handling of invitations when an account is deleted. The role and assignment matrix beyond the owner is planned.
Tests: `domain/salary_range_test.go` and `domain/invitation_test.go` (exact width at 10% and 40%, steps, caps, terms rules with pointers, versions, immutability of earlier values, redaction), `usecase/invitation/service_test.go` (owner policy, handle refusals, order of checks, replay, rollback, versions), `adapter/primary/http/v1/invitation_test.go` (mapping, no candidate field, failure statuses, cursor), and the integration tests `TestOrganizationInvitationDraftsOverHTTP`, `TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates`, `TestInvitationTablesRefuseMoneyAndHistoryViolations`, and `TestInvitationMigrationRollbackKeepsStoredInvitations` against a real PostgreSQL.
@@ -984,7 +984,7 @@ Implemented: `SendOrganizationInvitation` and the candidate's list of invitation
- Access. Owner only, as for drafts: `ownerCompanyOperations` at the HTTP boundary and the same check in the transaction; no other role may send. The candidate's list requires a verified candidate account, and an employer gets 403.
- Order of checks after the boundary: the owner, the key (422 or a replay), the invitation (404), a completed send (200), the version (412), the state and the visibility (409), then the quota (429).
Not implemented: the pending limit per need and the pause after a decline or a no deal (both planned in the contract), the acceptance and the cancellation (the read, the view, and the decline are in [Candidate view and decline](#candidate-view-and-decline)), the expiry at the deadline, the sending of notification email, the shared E0 pool of a holding in the quota port, and the role and assignment matrix beyond the owner.
Not implemented: the pause after a no deal (no operation produces the `no_deal` state yet), the cancellation (the view, the decline, and the acceptance are in [Candidate view and decline](#candidate-view-and-decline) and [Candidate acceptance](#candidate-acceptance)), the sending of notification email, the shared E0 pool of a holding in the quota port, and the role and assignment matrix beyond the owner. The pending limit and the pause after a decline are in [Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry).
Tests: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, `usecase/notification/inbox_test.go` (the invitation notice), `adapter/primary/http/v1/invitation_test.go` (statuses, `Retry-After`, the candidate cursor), and the integration tests `TestOrganizationInvitationSendOverHTTP` (the inbox before any email, repeats with one row of each kind and one charge, a 3-day deadline with the mail stopped and its job retried, visibility, a stale version, owner only, the quota, paging) and `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage`.
@@ -992,20 +992,20 @@ Tests: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`,
Implemented: `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_answer.go`, `usecase/invitation/view.go` and `decline.go`, the HTTP handler `adapter/primary/http/v1/invitation_candidate.go`, the adapter `adapter/secondary/postgres/invitation_answer.go` with `db/queries/invitation_answers.sql`, and migration `00039_answer_invitations.sql`.
- Read without a side effect. `GetMyInvitation` reads a delivered invitation by the candidate of the session and the invitation, with the current terms and the current name of the sending organization; it records nothing. The view is the explicit command `ViewMyInvitation`, as the contract requires, so a prefetch, a retry, or a cache refresh never changes what the organization sees. A draft, an invitation of another candidate, and an unknown identifier answer the same 404; an employer account answers 403.
- View. In `delivered` before the deadline the command moves the invitation to `viewed` with one conditional UPDATE (`state`, `version` plus one, `viewed_at`, `updated_at`), keeps `response_deadline_at`, and appends the audit event `viewed`. In every other state, and at the deadline or later, it changes nothing and answers 200 with the invitation as it is. It takes neither a key nor a version; concurrent views queue on the row lock, and the first one wins.
- Read without a side effect. `GetMyInvitation` reads a delivered invitation by the candidate of the session and the invitation, with the current terms and the current name of the sending organization, and it records no view. The one change a read can cause is the expiry: a read at the deadline or later first moves the invitation to `expired` ([Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry)). The view is the explicit command `ViewMyInvitation`, as the contract requires, so a prefetch, a retry, or a cache refresh never changes what the organization sees. A draft, an invitation of another candidate, and an unknown identifier answer the same 404; an employer account answers 403.
- View. In `delivered` before the deadline the command moves the invitation to `viewed` with one conditional UPDATE (`state`, `version` plus one, `viewed_at`, `updated_at`), keeps `response_deadline_at`, and appends the audit event `viewed`. At the deadline or later the due expiry is applied first, and the 200 answer shows `expired` with no view recorded; in every other state the command changes nothing and answers 200 with the invitation as it is. It takes neither a key nor a version; concurrent views queue on the row lock, and the first one wins.
- Decline. Allowed from `delivered`, `viewed`, and the planned `counter` before the deadline. One transaction moves the invitation to the terminal `declined` (`responded_at`, `version` plus one), stores the reason and the optional comment in `invitation_declines`, appends the audit event `declined`, and keeps the outcome under the key. It writes no consent, no contact grant, and no outbox event. The comment follows the schema rule with the Unicode notion of white space and refuses control characters other than a line break or a tab, because PostgreSQL text cannot hold NUL (400 at `/comment`).
- Responsiveness. The `declined` event (`kind`, `version`, the candidate as `actor_id`, `occurred_at`) is the candidate's answer that the planned responsiveness metrics of the organization count. It is always in time, since a late decline is refused, and it is never a consent or a hire. It holds neither the reason nor the comment.
- Privacy of the decline. The organization reads only `declined` and `responded_at`: none of its operations reads `invitation_declines`, and the audit event names no reason. The comment is never logged, notified, or copied into the stored outcome; the candidate reads both back in `decline`.
- Order of checks after the boundary: the candidate (403), the key (422 or a replay), the invitation (404, stored), the same decline of a declined invitation (200 with a new key or an older version), another reason or comment on a declined invitation, any other terminal state, or a passed deadline (409 whatever the version, stored), the version (412, not stored), then a state without an open answer (409, stored). `invitation_decline_results` keeps only the outcome and the invitation: a declined invitation and its decline never change, so a replay rebuilds the same answer and the comment is stored once.
- Deadline. Expiry is not implemented yet, so no read or command applies the transition to `expired`. A view at the deadline or later changes nothing, and a decline at the deadline or later answers 409 `state_conflict`, as the contract requires for a late command; the invitation stays `delivered` or `viewed` with its passed deadline until the expiry arrives. The conditional UPDATEs repeat the deadline, so a command cannot cross it between the check and the write.
- Deadline. A command at the deadline or later first applies the due expiry: the invitation moves to `expired` with the reason `invitation_timeout`, and only then are the state and the version checked. A decline at the deadline or later answers 409 `state_conflict`, as the contract requires for a late command. The conditional UPDATEs repeat the deadline, so a command cannot cross it between the check and the write. The lock order and the expiry rules are in [Pending limit, cooldown, and expiry](#pending-limit-cooldown-and-expiry).
- Consent and grant. A decline creates neither a consent nor a grant, so `contact_consent` and `contact_grant` are null after it. The acceptance is described in [Candidate acceptance](#candidate-acceptance).
- Hiding. The candidate's read shows the sending organization even after the candidate hid the profile from it: the hiding keeps the organization from seeing the candidate, while the candidate must know who sent the offer to answer it. The pushed content follows the hiding instead: the inbox notice of the invitation loses its content (`ResolveInvitationNotice`).
- Locks. A candidate command locks only the invitation row (`LockCandidateInvitation`) after the candidate's own idempotency record, never the organization. An organization command takes the organization lock first and the invitation row afterwards, so the two orders never cross: a candidate command does not wait for an organization lock while it holds the row.
- Locks. A candidate command locks the invitation row (`LockCandidateInvitation`) after the candidate's own idempotency record. A decline also takes the organization lock before the row, because it changes the pause of the pair; it never takes that lock after the row. An organization command takes the organization lock first and the invitation row afterwards, so the orders never cross. A view and an acceptance do not lock the organization.
- Database rules of migration 00039: the event kinds `viewed` and `declined` without changed fields; `invitations_answer_matches_state` (a delivered invitation has no view or answer, a viewed one has its view, a declined one its answer, and neither precedes the delivery); the trigger `invitations_guard_answer`, which refuses to move or undo a view or an answer and to leave `declined`; `invitation_declines` with the known reasons, the comment bound, a trigger that ties the row to a declined invitation answered at the same moment, and a refusal of UPDATE and DELETE; and the deferred constraint trigger `invitations_require_decline`, so a declined invitation without its decline cannot commit. The down migration refuses while a view, a decline, or a stored outcome exists.
- Notification. The contract has no notification kind for an answer, so the organization gets no inbox entry for a view or a decline yet; it sees the state in its invitation list. A notice of the answer is planned as a contract change.
Not implemented: the expiry at the deadline and its application on a read, the cancellation, the counter offer that would produce `counter`, the decline aggregates with a minimum group size, the responsiveness metrics, the 30-day pause after a decline, and a notification of the organization about an answer.
Not implemented: the cancellation, the counter offer that would produce `counter`, the decline aggregates with a minimum group size, the responsiveness metrics, and a notification of the organization about an answer.
Tests: `domain/invitation_answer_test.go` (the view only from `delivered` before the deadline, the decline from `delivered`, `viewed`, and `counter`, the refusal of terminal and late invitations, the comment rules, the stored answer rules, redaction), `usecase/invitation/answer_test.go` (no side effect of a read, the deadline kept, repeats, order of checks, foreign callers, invalid comments), `adapter/primary/http/v1/invitation_candidate_test.go` (statuses and a response without candidate data), and the integration tests `TestCandidateInvitationViewAndDeclineOverHTTP` (the read and the view with the same deadline, concurrent views with one event, a decline with `other` and no comment without a C4 consent, the stored answer event, replays and conflicts, the comment kept from the organization and the audit, foreign candidates and employers, CSRF and Origin, the hiding, a stale version, a late command) and `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`.
@@ -1018,15 +1018,55 @@ Implemented: `AcceptMyInvitation` ([contract](../../api/README.en.md#invitations
- Repeats. An accepted invitation whose grant has the same terms version and the same set of fields answers 200 with the same invitation, under the same key or a new one and with an older `expected_version`, and records nothing. Another terms version or set of fields answers 409 `state_conflict`, stored under the key. The outcomes under a key are `accepted`, `not_found`, and `state_conflict`; a stale version and a consent refusal are not stored.
- The grant. `contact_grants` holds the organization, the candidate, the source invitation (one grant per invitation), the consent record (one per grant), the canonical field set, the terms version, the consent text version, the grant time, and the revocation stamp (`revoked_at` and `revocation_reason`). This change never sets the stamp; the revocation is a later operation. Composite foreign keys tie the grant to its invitation of the same organization and candidate, and to its C4 record of the same subject, organization, invitation, and terms version. A trigger checks that the fields, the text version, and the grant time equal those of the record; a second trigger refuses DELETE and every change other than the one stamp. A deferred constraint trigger refuses to commit an accepted invitation without its grant. The grant holds kinds only, never contact values.
- The candidate's view. While an acceptance is possible, `contact_consent` holds the rendered C4 text and the kinds that the profile holds, in the order of the contract, with nothing preselected; it is null when the profile holds no confirmed kind. After the acceptance, `contact_grant` holds the selected kinds, the status, the terms version, the consent text version, and `readable`. `readable` is true only while the organization may read the profile: the publication is effective and the candidate has not hidden the organization. Otherwise `blocked_by` is `visibility`. A declined invitation keeps both fields null.
- Visibility decision. The acceptance is allowed while the profile is hidden from the organization or not published, as the contract's example of a blocked grant shows. It never publishes the profile, never changes the publication, and never lifts or adds a hiding. The grant stays stored and becomes readable when the candidate publishes the profile or unhides the organization; `readable` is recomputed on every read, so the grant itself never changes. The contact read through the grant is a later operation, so the organization still sees `contact_access` as not granted.
- Visibility decision. The acceptance is allowed while the profile is hidden from the organization or not published, as the contract's example of a blocked grant shows. It never publishes the profile, never changes the publication, and never lifts or adds a hiding. The grant stays stored and becomes readable when the candidate publishes the profile or unhides the organization; `readable` is recomputed on every read, so the grant itself never changes. The organization sees `contact_access` as `closed` while the grant is blocked, and as `available` once it becomes readable (see [Contact reads and revocation](#contact-reads-and-revocation)).
- Concurrency. The candidate command never takes the organization lock. Two concurrent acceptances of one version make one transition: the second waits for the row and then answers as a repeat, which is 200 with the same answer for identical terms and fields and 409 for another field set.
- Clocks. The answer time comes from the invitation service and the grant time from the consent service. In production both read the process clock, so they can differ by microseconds; the grant keeps the consent time. A replay of a stored acceptance rebuilds the response from the invitation and the grant. The outcome table keeps no copy of the response, so a later state change would show in a replay, as it would for a decline.
- Ledger keys. The C4 columns of the consent ledger still have no foreign keys to `organizations` and `invitations`: the ledger tests write C4 records with synthetic identifiers. The composite keys of the grant keep an acceptance consistent without that change; the ledger keys need fixtures with real invitations and are a follow-up.
Not implemented: the contact read through a grant, the revocation of a grant (after the publication is closed, after the hiding, after the consent is revoked, or after the participation is cancelled), the counter offer, the expiry at the deadline, and the cancellation.
Not implemented: the counter offer and the cancellation, including the revocation of a grant after the participation is cancelled (the other revocations are in [Contact reads and revocation](#contact-reads-and-revocation)).
Tests: `domain/contact_grant_test.go` (the grant from its record, the scope and revocation rules, the visibility view, the offer rendering, and `Accept`), `usecase/invitation/accept_test.go` (the order of checks, repeats, stale terms, late commands, consent pointers, visibility without a change of the publication), `adapter/primary/http/v1/invitation_candidate_test.go` (failure statuses), and the integration tests `TestCandidateInvitationAcceptOverHTTP` (an email-only grant, repeats and conflicts, a stale terms version and the raised terms, concurrent acceptances, a hidden profile, a late acceptance, consent and kind checks, the server log) and `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` against a real PostgreSQL.
### Pending limit, cooldown, and expiry
Implemented: the limit of invitations that wait for an answer per need, the pause of the organization and candidate pair after a decline, and the expiry of an invitation at its response deadline. Code: `usecase/invitation/pending_limit.go` (the send checks), `usecase/invitation/expire.go` (the handler of the job `invitation.response_deadline`, the shared expiry function, and the scheduling at delivery), `domain/invitation_expiry.go` (`Expire` and `ExpiryEvent`), `usecase/invitation/send.go`, `decline.go`, `accept.go`, and `view.go` (the expiry before a candidate answer), the adapter `adapter/secondary/postgres/invitation_expiry.go` with `db/queries/invitation_pending.sql`, `invitation_cooldowns.sql`, and `invitation_expiry.sql`, the registration in `jobHandlers()` (`bootstrap/jobs.go`), and migration `00043_expire_invitations.sql`.
- Limit. A send counts the invitations of the need that wait for an answer (`delivered`, `viewed`, `counter`) and answers 409 `state_conflict` when there are already `max_pending_per_need` of them in the effective policy (20 in the demo policy). The count is exact: the send takes the organization lock before anything else, and only a send can move an invitation into the waiting states. An invitation without a need has no need limit; the quota bounds it. Leaving the waiting states (a decline, an expiry, an acceptance) frees the place but never returns the weekly quota: the quota is charged at the send and does not change.
- Pause. A send answers 409 `state_conflict` until `repeat_after_decline_days` (30 days) have passed since the latest decline of the candidate by this organization. The pause belongs to the pair of the organization and the candidate, not to a need and not to a member: another need or another owner of the same organization gets the same refusal. The pause after a no deal does not apply yet: no operation produces the `no_deal` state.
- Lock order. A candidate's decline takes the organization lock before the invitation row, like every command that can change the pause of a pair. The decline and a send of the same pair are therefore ordered: a send never misses a decline that committed before its check. The order is the same as in [sending](#sending-invitations): the organization, then the invitation rows.
- Deadline. A send schedules the job `invitation.response_deadline` in the same transaction as the delivery: the key is the invitation identifier, the due time is `response_deadline_at`, and the payload holds only the identifier. The handler `ResponseDeadlineJob` runs in a transaction that locks the invitation row. If the invitation still waits for an answer, it moves to `expired` with the reason `invitation_timeout`; otherwise the handler changes nothing. A repeat of the job is safe: a second run finds no invitation that waits for an answer.
- Candidate commands at or after the deadline. The view, the decline, and the acceptance lock the row and read the time while they hold the lock; the read (`GetMyInvitation`) locks the row only when the deadline has passed. In both cases, when the deadline has passed, the expiry is applied first with the same conditional UPDATE and the same audit event. The read and the view then answer with the invitation in the state `expired`, with no view recorded; the decline and the acceptance answer 409 `state_conflict` and keep the outcome under the key. The list of the candidate's inbox and the organization's reads do not apply the expiry: they show the stored state until the job or the next candidate command applies it.
- What the expiry writes. The transition writes only the audit event `expired` with its version, no field, and no actor (`actor_id` is empty, because the server made the change). No consent C4, contact grant, decline record, or quota change is created or changed. The deadline and the terms are kept. The constraint `invitation_events_system_actor` allows an empty actor only for `expired`, the trigger `invitations_guard_expiry` allows the transition only from `delivered` or `viewed` and not before the deadline, and `invitations_expiry_reason` requires the reason.
- Race with the acceptance. An acceptance at or after the deadline always refuses: the acceptance and the job both decide by a time that is known while the row is held. Whichever path takes the row first, the outcome is one: an `expired` invitation with no grant. An acceptance before the deadline that commits before the job leaves the job without effect. The tests `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres` (the race) and `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres` (the job first) check it.
- Clock. The deadline and the limits are decided by the application clock, injected into the usecases and into the job handler; the database clock decides nothing. A handler whose clock has not reached the deadline returns an error, so the job is retried with backoff instead of completing without the expiry.
- Running. The worker that runs the job is the one enabled by `JOBS_ENABLED`; without it the job waits in the database. The candidate commands apply the expiry without the worker, so the candidate's answer stays correct.
- Migration 00043. The new event kind `expired`; the constraints `invitation_events_expiry_changes_no_field` and `invitation_events_system_actor`; the trigger `invitations_guard_expiry`; the partial indexes `invitations_pending_need_idx` (the waiting invitations of a need) and `invitations_declined_pair_idx` (the declines of a pair); and the backfill of the expiry jobs for invitations delivered before the migration, keyed by the identifier with `ON CONFLICT DO NOTHING`. The rollback refuses while expired invitations exist and removes the jobs of this kind.
Not implemented: the pause after a no deal (it needs an operation that moves an invitation to `no_deal` and sets the end of the pause), the expiry of the `counter` state (no operation produces it yet), the reason `negotiation_timeout`, and a limit for invitations without a need, should one be introduced.
Tests: `domain/invitation_expiry_test.go` (the expiry of a waiting invitation only after its deadline, the kept deadline and terms, and the event without an actor); `usecase/invitation/pending_limit_test.go` (the limit at 20 waiting and the 21st, two concurrent sends at 19, the freed place without a quota return, the pause at day 29 and day 30 for another owner and another need, and no pause for another candidate or an expired invitation); `usecase/invitation/expire_test.go` (the expiry by a read, a view, an acceptance, and a decline at the deadline, the job and its repeat, and the job refusal of a payload that names no invitation); the integration tests `TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres`, `TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres`, `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres`, `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres`, and `TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries` in `integration_test/invitation_expiry_test.go`.
### Contact reads and revocation
Implemented: `GetOrganizationInvitationContacts` ([contract](../../api/README.en.md#invitations-and-contact-grants)) in `usecase/invitation/contacts.go` and `adapter/primary/http/v1/contacts.go`; the disclosure type in `domain/contact_disclosure.go`; the grant lock `ContactGrantRepository.LockForRead` in `adapter/secondary/postgres/invitation_accept.go`; the closings in `consent_revocation.go` (`ConsentRevocationEffects.Apply`), `privacy_view.go` (`CloseForVisibility`), and `contact_grant_closure.go`; the queries in `db/queries/contact_grants.sql`; and migration `00042_index_contact_grants_by_candidate.sql`, which adds the candidate-wide index that the candidate-wide closings use. The organization's `contact_access` is derived in `usecase/invitation/contact_access.go`, through the same `readableContactGrant` check that the read uses (`usecase/invitation/contacts.go`).
- Access. The company middleware checks the session, the active owner membership, and the path before the handler. A non-owner member answers 403, an account without a membership answers 404, and a candidate account answers 403. The usecase repeats the owner check inside its transaction. In the MVP no other role reads contacts.
- Lock order. The read takes, in this order: the organization and the membership (`LockActiveMembership`, share locks), the candidate account, the newest active C2 record, the publication with its C2 record (which also applies the organization's hiding), the C4 record of the grant, and the grant itself. The unlocked grant read before the locks only names the candidate, which a grant never changes. A C4 revocation locks the record and then the grant in the same order, so the two cannot wait for each other in opposite orders. The visibility locks come first, so a hiding or a C2 revocation that commits first is seen, and one that waits runs after the read commits.
- Decision. The read answers 200 only when the grant is active, its C4 record is unrevoked, and the organization may read the publication now. Every other case answers 404 `not_found` and does not say which one applies: no grant of this invitation for this organization, a revoked grant or C4 record, or a profile that is closed or hidden from the organization. A kind returns its value only when the profile holds it as a confirmed claim; any other kind is null, and a suggestion that nobody confirmed is never disclosed. The response has `Cache-Control: no-store`.
- Closings. Each closing runs in the transaction of the change, stamps the revocation time and its reason, and never reopens a grant:
- Revoking C4 for an organization (`consent_revoked`) closes the grants that name the revoked records. The grants of other organizations and of other invitations stay open.
- Revoking C2 (`visibility_closed`) closes every active grant of the candidate, including when the candidate has no publication row to close.
- Closing the publication (`visibility_closed`) closes every active grant of the candidate.
- Hiding an organization (`visibility_closed`) closes the active grants of that organization, including on a repeated hide. Unhiding and publishing again close nothing and reopen nothing: a closed grant keeps its first stamp, which the guard trigger allows once.
- A grant stored while the profile is not readable is not closed by that state. It stays active and blocked by visibility, becomes readable when the candidate publishes or unhides, and the next closing event closes it.
- Withdrawing an invitation by the organization changes no grant. Cancellation of the participation by the candidate (`participation_cancelled`) is not implemented. A C1 revocation closes no grant, because the contract names no reason for it.
- Organization view. Each organization response that carries `contact_access` derives it from the grant of the invitation, in the transaction of the request: `GetOrganizationInvitation`, `ListOrganizationInvitations`, and the responses of the draft create, update, and send. No grant answers `not_granted`, and a revoked grant answers `closed`. An active grant runs the read's visibility locks and checks, then its C4 record and the grant, so the view says `available` exactly when a read would succeed at that moment, and `closed` otherwise. The view lists the granted kinds only while it is `available`; `closed` carries no reason, and no contact value is ever part of the view. The derivation reads the grant of every state, so a withdrawn invitation keeps the state of its grant, as the contract requires. A declined or expired invitation has no grant and answers `not_granted`. The idempotent replays of a create and of a send return the stored original response, so their `contact_access` is the state at the first answer. The derivation costs one grant lookup per invitation, and it takes the share locks only for an invitation with a grant.
- Quota and audit. A successful read writes one `contact_read` row to `candidate_card_access_events` in the same transaction, with the granted kinds and never a value. It does not consume the card-view quota, because the contract does not count contact reads against it. The candidate's own history read stays a contract-only operation.
- Not implemented: the candidate's cancellation, and the organization's withdrawal. `CurrentContactFields` in `usecase/candidateview` stays closed, because the card-handle read has no contract operation.
Tests: `domain/contact_disclosure_test.go` (confirmed values only, refused revoked grants, redacted formatting), `usecase/invitation/contacts_test.go` (owner and role checks, visibility, revoked grant and C4 record, unknown invitations), `usecase/invitation/contact_access_test.go` (the organization's states, their agreement with the read in each closing state, a blocked grant that opens once it is visible, and a revoked grant that never reopens), and the integration test `TestOrganizationContactReadsAndRevocationOverHTTP` over the real router and PostgreSQL. It covers the email-only read, the repeated read, the refusals of another organization, a recruiter, and a candidate, C4 revocation with an independent organization, hiding and unhiding without reopening, C2 revocation with republication, closing the publication, and the index. It also checks `contact_access` of the single read and of the list after each change, a declined invitation, and an expired one, which runs last because it moves the clock.
## 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.
+1 -1
View File
@@ -1,6 +1,6 @@
# Company quotas
Company quota reservations are implemented in the domain, `companyquota` usecase, and PostgreSQL adapter. They provide a transaction-bound storage port for invitation and candidate-card usage. The product invitation and delivery workflow is still pending; these reservations do not mean that an invitation has been sent.
Company quota reservations are implemented in the domain, `companyquota` usecase, and PostgreSQL adapter. They provide a transaction-bound storage port for invitation and candidate-card usage. An invitation spends one place of the weekly quota when it is sent (`SendOrganizationInvitation`): a draft spends nothing, and a repeat of the send of the same invitation does not spend a second place. An invitation that leaves the waiting state (a decline, an expiry, an acceptance) frees its place in the per-need pending limit, but never returns the weekly quota; see [Pending limit, cooldown, and expiry](ARCHITECTURE.md#pending-limit-cooldown-and-expiry).
## Policy and trusted organization level