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
+54 -14
View File
@@ -174,7 +174,7 @@ Offsets и партиции. Каждый обработчик - один уча
### Задания по сроку
Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. В `jobHandlers()` (`backend/internal/bootstrap/jobs.go`) зарегистрирован один продуктовый обработчик: `assessment.signal_review`, который считает [полосу проверки оценки](#серверные-сигналы-оценки-и-полоса-проверки). Тесты используют и вид задания, который есть только в тестах. Первый запланированный вид по сроку - срок ответа на приглашение. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку).
Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. В `jobHandlers()` (`backend/internal/bootstrap/jobs.go`) зарегистрированы два продуктовых обработчика: `assessment.signal_review`, который считает [полосу проверки оценки](#серверные-сигналы-оценки-и-полоса-проверки), и `invitation.response_deadline`, который переводит приглашение в `expired` при истечении срока ответа ([Предел ожидающих, пауза и истечение](#предел-ожидающих-пауза-и-истечение)). Тесты используют и вид задания, который есть только в тестах. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку).
Планирование. Usecase вызывает `unit.ScheduledJobs().Schedule(ctx, job)` в своей бизнес-транзакции, поэтому задание существует ровно тогда, когда зафиксировано изменение, которому оно нужно; `Cancel(ctx, kind, key)` останавливает незавершенное задание. У задания есть вид (имя обработчика, строчное имя с точками), ключ логического задания внутри вида (например, ID агрегата), срок по часам приложения, необязательный лимит попыток и payload: плоский JSON-объект из идентификаторов не больше 2 КиБ. Ни ключ, ни payload не должны содержать персональные данные; остальное обработчик читает из исходных таблиц в момент выполнения. Пара `(kind, key)` уникальна, и побеждает первое планирование: повтор ничего не вставляет (`INSERT ... ON CONFLICT DO NOTHING`) и возвращает `false`, в том числе после выполнения или отмены задания. Это намеренно insert-or-ignore, а не upsert: повторная команда не может сдвинуть срок, который нельзя сбрасывать, а устаревший писатель не может оживить завершенное задание. Для нового повторения нужен новый ключ, например `<id>:<version>`.
@@ -184,7 +184,7 @@ Offsets и партиции. Каждый обработчик - один уча
Выполнение и завершение. Каждое задание выполняется в собственной транзакции READ COMMITTED: она ставит `statement_timeout` и `idle_in_transaction_session_timeout` равными длительности lease, блокирует строку задания с проверкой `status = running`, владельца lease и номера попытки, вызывает обработчик с `outbound.UnitOfWork` той же транзакции, отмечает задание `done` с той же проверкой и фиксирует транзакцию. Эффект обработчика и завершение фиксируются вместе: для эффекта, который остается в PostgreSQL, задание применяется ровно один раз, даже когда workers конкурируют, перезапускаются или lease истекает. Пока обработчик работает, строка заблокирована, поэтому захват другого worker пропускает ее даже после истечения lease по часам; если проверка не прошла, потому что задание отменили или захватили заново, обработчик не вызывается и ничего не фиксируется (`lease_lost`). Обработчик может отменить собственное задание через unit, например истечение, которое заодно отменяет задание срока, которое оно представляет: тогда завершение находит задание `cancelled` в своей же транзакции, считает его выполненным и фиксирует эффект, а задание остается `cancelled`. Любое другое изменение собственного задания обработчиком откатывается и переводит задание в `dead` с классом `completion_conflict`, потому что оно повторялось бы на каждой попытке. Обработчик, эффект которого выходит за пределы базы данных, например вызов другого сервиса, может повториться после сбоя между этим вызовом и фиксацией и должен быть идемпотентным сам. Context обработчика заканчивается вместе с продленным lease. Обработчик принимает решение по `job.DueAt`, то есть по сроку, который задание представляет и который повтор сохраняет, а не по моменту, когда оно случайно выполнилось.
Порядок блокировок. Обработчик держит блокировку строки задания и затем может блокировать продуктовые строки. Бизнес-транзакция, которая отменяет задание, например принятие приглашения в момент срока, должна вызывать `Cancel` до блокировки этих продуктовых строк. `Cancel` ждет транзакцию обработчика, если она идет: после ее фиксации задание уже `done`, и `Cancel` возвращает `false`, поэтому вызывающий видит истечение; иначе задание отменяется, а worker обнаруживает, что его lease больше не действует. Обратный порядок может привести к deadlock, который PostgreSQL разрешает, прерывая одну сторону с `ErrTransactionConflict`; сторона задания засчитывает неудачную попытку и повторяет ее.
Порядок блокировок. Обработчик держит блокировку строки задания и затем может блокировать продуктовые строки. Бизнес-транзакция, которая отменяет задание, должна вызывать `Cancel` до блокировки этих продуктовых строк. Ответ кандидата задание срока ответа не отменяет: выполнение находит ответивший приглашение и ничего не меняет ([Предел ожидающих, пауза и истечение](#предел-ожидающих-пауза-и-истечение)). `Cancel` ждет транзакцию обработчика, если она идет: после ее фиксации задание уже `done`, и `Cancel` возвращает `false`, поэтому вызывающий видит результат выполнения; иначе задание отменяется, а worker обнаруживает, что его lease больше не действует. Обратный порядок может привести к deadlock, который PostgreSQL разрешает, прерывая одну сторону с `ErrTransactionConflict`; сторона задания засчитывает неудачную попытку и повторяет ее.
Сбои. Неудачная попытка откатывает свой эффект; второй оператор с той же проверкой записывает ее. Ошибка обработчика, истечение lease, deadlock или serialization failure (`conflict`) и фиксация, которую отверг PostgreSQL (`effect_rejected`, для обработчика, который проигнорировал упавший оператор, или для отложенного ограничения), переводят задание в `failed` с `available_at = now + backoff`, где backoff - общая задержка `worker/retry`: от `JOBS_BACKOFF_INITIAL`, удваивается до `JOBS_BACKOFF_MAX`, со случайным разбросом. `inbound.ErrJobRejected`, panic обработчика и `completion_conflict` финальны, в том числе во время остановки. После последней разрешенной попытки (собственный лимит задания или `JOBS_MAX_ATTEMPTS`) задание становится `dead`: это пишется в журнал на уровне error и считается как `dead`, такому заданию нужен оператор. `last_error_class` хранит только ограниченный класс; очищенная причина есть только в журнале. Сбой базы данных вне обработчика - не вина задания: worker освобождает незавершенные задания без учета попытки и ждет backoff перед следующим захватом, поэтому сбой не создает горячего цикла. Если не удалось записать сам сбой, задание сохраняет начатый lease; следующий захват учтет его как `lease_expired`, а на последней попытке это делает задание dead.
@@ -798,7 +798,7 @@ contact_grant относится к паре кандидат-компания
- `ConsentTexts().Get` и `Current` читают опубликованные тексты и при каждом чтении проверяют сохраненный хэш.
- `ConsentLedger().Grant` и `GrantContact` возвращают новую запись с `created` true или существующую с `created` false. Неизвестный субъект возвращает `ErrUserNotFound`, неизвестная версия - `ErrConsentTextNotFound`, версия, опубликованная позже, - `ErrConsentTextNotPublished`, хэш, не совпадающий с опубликованным текстом (для C4 - с сохраненным названием), - `ErrConsentTextMismatch`; эти ошибки приходят из базы и прерывают внешнюю транзакцию. Дубликат ее не прерывает. Выдача, чья конфликтующая запись была отозвана между двумя ее запросами, возвращает `ErrTransactionConflict`.
- `Revoke` возвращает строки, на которые поставил отметку. `Current` возвращает новейшую неотозванную запись C1-C3 или C5 либо `ErrConsentNotFound`; `CurrentContact` возвращает неотозванные записи C4 одной организации. `List` выдает журнал субъекта страницами от новых к старым, при необходимости по состоянию.
- `ConsentRevocationEffects.Apply` выполняется в той же транзакции `UnitOfWork`, что и отзыв в журнале. Он закрывает эффективный доступ C2 только когда текущая публикация ссылается на одну из отозванных записей, один раз добавляет событие истории приватности и записывает ограниченные по размеру outbox-intents на основе точных отозванных записей. Будущий адаптер выдачи для C2/C4 должен привязывать grant к ID исходной записи согласия и синхронно закрывать старый grant в этой транзакции; новая выдача может создать только новый grant, но не открыть старый. Читатели и импортеры C5 должны проверять актуальный журнал и отказывать по умолчанию; outbox-сообщение само по себе не дает доступ и не доказывает удаление данных во внешней системе.
- `ConsentRevocationEffects.Apply` выполняется в той же транзакции `UnitOfWork`, что и отзыв в журнале. Он закрывает эффективный доступ C2 только когда текущая публикация ссылается на одну из отозванных записей, один раз добавляет событие истории приватности и записывает ограниченные по размеру outbox-intents на основе точных отозванных записей. Разрешения, которые дали отозванные записи, закрываются в этой транзакции (C4 по записи, C2 для всех разрешений кандидата; см. [Чтение контактов и отзыв](#чтение-контактов-и-отзыв)); новая выдача может создать только новый grant, но не открыть старый. Читатели и импортеры C5 должны проверять актуальный журнал и отказывать по умолчанию; outbox-сообщение само по себе не дает доступ и не доказывает удаление данных во внешней системе.
### Usecase согласий
@@ -922,7 +922,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
- Истечение `looking` берется из версионированной политики и только сужает видимость. 30 дней - это `search_status.searching_confirmation_interval_days` действующей версии политики `product` (демо-версия 1: 30), поэтому владелец меняет срок публикацией новой версии политики, а не константой или конфигурацией. Подтверждение фиксирует `lapses_at` и сохраняет `policy_version_id`, поэтому последующее изменение политики не сдвигает сохраненные времена, а каждая строка называет политику, по которой создана, как требует раздел политик. Само истечение вычисляется (`SearchStatus.Effective(now)` дает `looking`, только пока `now` раньше `lapses_at`) и нигде не записывается: ни процесс, ни задача, ни расхождение часов не превратит истекший статус во что-то более публичное, сохраненная строка хранит слова кандидата, а ответ показывает `value` `not_looking` и `lapsed` true. Кандидат подтверждает снова значением `looking`, которое заменяет `confirmed_at`. Напоминание до истечения - запланированное уведомление, не часть этой задачи.
- Версии. У каждой настройки своя `version` (0 - отсутствие строки), она проверяется в самом операторе, как у профиля: `UpdateCandidatePublication` и `UpdateCandidateSearchStatus` меняют строку только если сохраненная версия равна прочитанной вызывающим, а для устаревшей строка не возвращается (412 `version_conflict`). Порядок в домене совпадает с контрактом: версия выше текущей - конфликт, неизмененная действующая настройка - успех даже при устаревшей версии, любое другое изменение по устаревшей версии - конфликт, а публикации нужна действующая C2. Поскольку настройки независимы, изменение одной никогда не делает устаревшей другую.
- Скрытые организации принадлежат кандидату и защищены от перебора. Запись принадлежит кандидату: ни один запрос стороны организации ее не выбирает, а организация не отличает скрывшего кандидата от неопубликованного. Скрытие по идентификатору не должно стать способом спросить, существует ли организация. Внешний ключ отклоняет неизвестную организацию (SQLSTATE 23503), а юзкейс обязан ответить на это так же, как на организацию, которую кандидат не видит: тот же 404 `not_found` с тем же телом, без другого времени ответа или кода. Кандидат видит организацию, приславшую ему приглашение, и организации, которые покажет поиск организаций для кандидата (запланирован, открытый вопрос), поэтому скрытие не раскрывает того, что кандидат не мог прочитать раньше. Снятие скрытия - DELETE, который отвечает 204 на любой корректный идентификатор и потому ничего не раскрывает; событие истории пишется, только если строка была удалена. Идентификаторы - случайные UUIDv7, а оставшийся перебор покрывает общий лимит запросов.
- Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (причину задает контракт приглашений). Это относится к юзкейсам, которых еще нет; эта задача хранит настройки и задает контракт. Статус поиска разрешение никогда не закрывает.
- Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (причину задает контракт приглашений). Закрытие реализовано, см. [Чтение контактов и отзыв](#чтение-контактов-и-отзыв). Статус поиска разрешение никогда не закрывает.
- История вместо области полей. Запись C2 доказывает согласие с текстом публикации, а `candidate_privacy_events` хранит то, о чем просила заметка журнала согласий: набор опубликованных полей и его изменения с временами и записью C2 за каждым. Отзыв C2 и истечение статуса вычисляются и не являются событиями. Нужна ли C2 собственная область полей как согласию по статье 10.1 152-ФЗ - по-прежнему юридический вопрос (см. журнал согласий).
- Приватность. Таблицы хранят идентификаторы, коды полей карточки и времена; значений профиля, имен, контактов и файлов нет (тест перечисляет столбцы). `Publication`, `SearchStatus`, `HiddenOrganization` и `PrivacyEvent` пишут в журналы только идентификаторы, версии и виды. Ни один запрос не выбирает строку чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер должен сообщать только SQLSTATE и имя ограничения, как остальные.
@@ -962,11 +962,11 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
- Изменение. Тело заменяет заданные поля, а `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` без полей. Индикатору нужен минимум кандидата, а его вычисление до появления лимита из трех установок в день и семидневного отключения позволило бы организации подбирать минимум правками черновика, поэтому пока не считается и не применяется ни то ни другое.
- Индикатор. `salary_fit` всегда `not_available`; `contact_access` выводится из разрешения ([Чтение контактов и отзыв](#чтение-контактов-и-отзыв)). Индикатору нужен минимум кандидата, а его вычисление до появления лимита из трех установок в день и семидневного отключения позволило бы организации подбирать минимум правками черновика, поэтому пока не считается и не применяется ни то ни другое.
Как подключаются следующие операции: правила пары читают индекс по организации и кандидату. Контактное разрешение появляется с принятием ([Принятие кандидатом](#принятие-кандидатом)). Колонки C4 журнала согласий пока не имеют внешних ключей на `organizations` и `invitations`; это последующая задача.
Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, предел ожидающих приглашений на потребность, повышение, отзыв, сторона кандидата сверх списка приглашений, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована.
Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, повышение, отзыв, сторона кандидата сверх списка приглашений, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована.
Тесты: `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.
@@ -984,7 +984,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
- Доступ. Только владелец, как для черновиков: `ownerCompanyOperations` на HTTP-границе и та же проверка в транзакции; другие роли отправлять не могут. Список кандидата требует подтвержденный аккаунт кандидата, работодатель получает 403.
- Порядок проверок после границы: владелец, ключ (422 или повтор), приглашение (404), завершенная отправка (200), версия (412), состояние и видимость (409), затем квота (429).
Не реализовано: предел ожидающих приглашений на потребность и пауза после отказа или "сделки нет" (оба запланированы в контракте), принятие и отмена участия (чтение, просмотр и отказ описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата)), истечение по сроку, отправка писем-уведомлений, общий пул E0 холдинга в порте квоты и матрица ролей и назначений сверх владельца.
Не реализовано: пауза после "сделки нет" (состояние `no_deal` пока не создает ни одна операция), отмена участия (чтение, просмотр, отказ и принятие описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата) и [Принятии кандидатом](#принятие-кандидатом)), отправка писем-уведомлений, общий пул E0 холдинга в порте квоты и матрица ролей и назначений сверх владельца. Предел ожидающих и паузу после отказа см. в [Пределе ожидающих, паузе и истечении](#предел-ожидающих-пауза-и-истечение).
Тесты: `domain/invitation_delivery_test.go`, `usecase/invitation/send_test.go`, `usecase/notification/inbox_test.go` (уведомление о приглашении), `adapter/primary/http/v1/invitation_test.go` (статусы, `Retry-After`, курсор кандидата) и интеграционные `TestOrganizationInvitationSendOverHTTP` (входящие до любого письма, повторы с одной строкой каждого вида и одним списанием, срок 3 дня при остановленной почте и повторе ее задания, видимость, устаревшая версия, только владелец, квота, страницы) и `TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage`.
@@ -992,20 +992,20 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
Реализовано: `GetMyInvitation`, `ViewMyInvitation` и `DeclineMyInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Код: `domain/invitation_answer.go`, `usecase/invitation/view.go` и `decline.go`, HTTP-обработчик `adapter/primary/http/v1/invitation_candidate.go`, адаптер `adapter/secondary/postgres/invitation_answer.go` с `db/queries/invitation_answers.sql` и миграция `00039_answer_invitations.sql`.
- Чтение без побочного эффекта. `GetMyInvitation` читает доставленное приглашение по кандидату из сессии и приглашению, с текущими условиями и текущим названием организации-отправителя, и ничего не записывает. Просмотр - явная команда `ViewMyInvitation`, как требует контракт, поэтому предзагрузка, повтор или обновление кэша не меняют то, что видит организация. Черновик, приглашение другого кандидата и неизвестный идентификатор дают одинаковый 404; аккаунт работодателя получает 403.
- Просмотр. В `delivered` до срока команда переводит приглашение в `viewed` одним условным UPDATE (`state`, `version` плюс один, `viewed_at`, `updated_at`), сохраняет `response_deadline_at` и добавляет событие аудита `viewed`. В любом другом состоянии, а также в момент срока и позже, она ничего не меняет и отвечает 200 с приглашением как есть. Ключа и версии она не принимает; одновременные просмотры встают в очередь на блокировке строки, побеждает первый.
- Чтение без побочного эффекта. `GetMyInvitation` читает доставленное приглашение по кандидату из сессии и приглашению, с текущими условиями и текущим названием организации-отправителя, и не записывает просмотр. Единственное, что чтение может изменить, - истечение срока: чтение в срок или позже сначала переводит приглашение в `expired` ([Предел ожидающих, пауза и истечение](#предел-ожидающих-пауза-и-истечение)). Просмотр - явная команда `ViewMyInvitation`, как требует контракт, поэтому предзагрузка, повтор или обновление кэша не меняют то, что видит организация. Черновик, приглашение другого кандидата и неизвестный идентификатор дают одинаковый 404; аккаунт работодателя получает 403.
- Просмотр. В `delivered` до срока команда переводит приглашение в `viewed` одним условным UPDATE (`state`, `version` плюс один, `viewed_at`, `updated_at`), сохраняет `response_deadline_at` и добавляет событие аудита `viewed`. В момент срока и позже сначала применяется истечение, и ответ 200 показывает `expired` без записи просмотра; в любом другом состоянии команда ничего не меняет и отвечает 200 с приглашением как есть. Ключа и версии она не принимает; одновременные просмотры встают в очередь на блокировке строки, побеждает первый.
- Отказ. Разрешен из `delivered`, `viewed` и запланированного `counter` до срока. Одна транзакция переводит приглашение в терминальное `declined` (`responded_at`, `version` плюс один), сохраняет причину и необязательный комментарий в `invitation_declines`, добавляет событие аудита `declined` и хранит исход под ключом. Согласия, контактного разрешения и события outbox она не пишет. Комментарий проверяется по правилу схемы с юникодным понятием пробела и не принимает управляющие символы, кроме перевода строки и табуляции, потому что текст PostgreSQL не хранит NUL (400 по `/comment`).
- Отзывчивость. Событие `declined` (`kind`, `version`, кандидат в `actor_id`, `occurred_at`) - ответ кандидата, который будут считать запланированные метрики отзывчивости организации. Оно всегда своевременно, потому что опоздавший отказ отклоняется, и никогда не означает согласие или найм. Ни причины, ни комментария в нем нет.
- Приватность отказа. Организация читает только `declined` и `responded_at`: ни одна ее операция не читает `invitation_declines`, а событие аудита не называет причину. Комментарий не логируется, не попадает в уведомления и не копируется в сохраненный исход; кандидат читает причину и комментарий обратно в `decline`.
- Порядок проверок после границы: кандидат (403), ключ (422 или повтор), приглашение (404, сохраняется), тот же отказ на отклоненном приглашении (200 с новым ключом или старой версией), другая причина или комментарий на отклоненном приглашении, иное терминальное состояние или прошедший срок (409 при любой версии, сохраняется), версия (412, не сохраняется), затем состояние без открытого ответа (409, сохраняется). `invitation_decline_results` хранит только исход и приглашение: отклоненное приглашение и его отказ не меняются, поэтому повтор собирает тот же ответ, а комментарий хранится в одном месте.
- Срок. Истечение пока не реализовано, поэтому ни чтение, ни команда не выполняют переход в `expired`. Просмотр в момент срока и позже ничего не меняет, а отказ в момент срока и позже отвечает 409 `state_conflict`, как контракт требует для опоздавшей команды; приглашение остается `delivered` или `viewed` с прошедшим сроком, пока не появится истечение. Условные UPDATE повторяют проверку срока, поэтому команда не пересечет его между проверкой и записью.
- Срок. Команда в срок или позже сначала применяет истечение: приглашение переходит в `expired` с причиной `invitation_timeout`, и только после этого проверяются состояние и версия. Отказ в момент срока и позже отвечает 409 `state_conflict`, как контракт требует для опоздавшей команды. Условные UPDATE повторяют проверку срока, поэтому команда не пересечет его между проверкой и записью. Порядок блокировок и правила истечения описаны в [Пределе ожидающих, паузе и истечении](#предел-ожидающих-пауза-и-истечение).
- Согласие и разрешение. Отказ не создает ни согласия, ни разрешения, поэтому после отказа `contact_consent` и `contact_grant` равны null. Принятие описано в [Принятии кандидатом](#принятие-кандидатом).
- Скрытие. Чтение кандидата показывает организацию-отправителя и после того, как кандидат скрыл от нее профиль: скрытие не дает организации видеть кандидата, а кандидату нужно знать, кто прислал предложение, чтобы ответить. Исходящее содержимое, наоборот, следует скрытию: уведомление о приглашении во входящих теряет содержимое (`ResolveInvitationNotice`).
- Блокировки. Команда кандидата блокирует только строку приглашения (`LockCandidateInvitation`) после собственной записи идемпотентности кандидата и никогда не блокирует организацию. Команда организации берет сначала блокировку организации, а потом строку приглашения, поэтому порядки не пересекаются: команда кандидата не ждет блокировку организации, удерживая строку.
- Блокировки. Команда кандидата блокирует строку приглашения (`LockCandidateInvitation`) после собственной записи идемпотентности кандидата. Отказ дополнительно берет блокировку организации до строки, потому что меняет паузу пары; он никогда не берет ее после строки. Команда организации берет сначала блокировку организации, а потом строку приглашения, поэтому порядки не пересекаются. Просмотр и принятие организацию не блокируют.
- Правила базы миграции 00039: виды событий `viewed` и `declined` без измененных полей; `invitations_answer_matches_state` (у доставленного приглашения нет просмотра и ответа, у просмотренного есть просмотр, у отклоненного есть ответ, и ни то ни другое не раньше доставки); триггер `invitations_guard_answer`, который не дает сдвинуть или отменить просмотр или ответ и выйти из `declined`; `invitation_declines` с известными причинами, границей комментария, триггером, который привязывает строку к отклоненному приглашению с тем же моментом ответа, и запретом UPDATE и DELETE; отложенный ограничивающий триггер `invitations_require_decline`, чтобы отклоненное приглашение без записи отказа не зафиксировалось. Откат миграции отказывает, пока есть просмотр, отказ или сохраненный исход.
- Уведомление. В контракте нет вида уведомления об ответе, поэтому организация пока не получает записи во входящих о просмотре или отказе; состояние она видит в своем списке приглашений. Уведомление об ответе запланировано как изменение контракта.
Не реализовано: истечение по сроку и его применение при чтении, отмена участия, встречное предложение, которое дало бы `counter`, агрегаты причин отказа с минимальным размером группы, метрики отзывчивости, 30-дневная пауза после отказа и уведомление организации об ответе.
Не реализовано: отмена участия, встречное предложение, которое дало бы `counter`, агрегаты причин отказа с минимальным размером группы, метрики отзывчивости и уведомление организации об ответе.
Тесты: `domain/invitation_answer_test.go` (просмотр только из `delivered` до срока, отказ из `delivered`, `viewed` и `counter`, отклонение терминальных и опоздавших приглашений, правила комментария, правила сохраненного ответа, маскирование), `usecase/invitation/answer_test.go` (чтение без побочного эффекта, сохранение срока, повторы, порядок проверок, чужие вызывающие, неверные комментарии), `adapter/primary/http/v1/invitation_candidate_test.go` (статусы и ответ без данных кандидата) и интеграционные `TestCandidateInvitationViewAndDeclineOverHTTP` (чтение и просмотр с тем же сроком, одновременные просмотры с одним событием, отказ с `other` без комментария и без согласия C4, сохраненное событие ответа, повторы и конфликты, комментарий скрыт от организации и аудита, чужие кандидаты и работодатели, CSRF и Origin, скрытие, устаревшая версия, опоздавшая команда) и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`.
@@ -1018,15 +1018,55 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
- Повторы. Принятое приглашение, у которого разрешение имеет ту же версию условий и тот же набор полей, отвечает 200 тем же приглашением под тем же или новым ключом и при более старом `expected_version`, и ничего не записывает. Другая версия условий или другой набор полей отвечают 409 `state_conflict` и сохраняются под ключом. Исходы под ключом: `accepted`, `not_found`, `state_conflict`; устаревшая версия и отказ по согласию не сохраняются.
- Разрешение. `contact_grants` хранит организацию, кандидата, исходное приглашение (одно разрешение на приглашение), запись согласия (одну на разрешение), канонический набор полей, версию условий, версию текста согласия, время выдачи и отметку отзыва (`revoked_at` и `revocation_reason`). Эта задача отметку не ставит; отзыв - отдельная операция. Составные внешние ключи связывают разрешение с приглашением той же организации и того же кандидата и с записью C4 того же субъекта, организации, приглашения и версии условий. Триггер проверяет, что поля, версия текста и время выдачи совпадают с записью; второй триггер запрещает DELETE и любое изменение, кроме одной отметки отзыва. Отложенный триггер ограничения не дает зафиксировать принятое приглашение без разрешения. Разрешение хранит виды контактов, но не их значения.
- Вид кандидата. Пока принятие возможно, `contact_consent` содержит отрисованный текст C4 и виды, которые есть в профиле, в порядке контракта; ничего не выбрано заранее. Поле равно null, если в профиле нет подтвержденного вида. После принятия `contact_grant` содержит выбранные виды, статус, версию условий, версию текста согласия и `readable`. `readable` истинно только тогда, когда организация может читать профиль сейчас: публикация действует и кандидат не скрыл организацию. Иначе `blocked_by` равно `visibility`. У отказанного приглашения оба поля равны null.
- Решение о видимости. Принятие разрешено, пока профиль скрыт от организации или не опубликован, как показывает пример контракта с заблокированным разрешением. Принятие не публикует профиль, не меняет публикацию и не снимает и не добавляет скрытие. Разрешение остается сохраненным и станет читаемым, когда кандидат опубликует профиль или уберет скрытие организации: `readable` пересчитывается при каждом чтении, поэтому само разрешение не меняется. Чтение контактов через разрешение - отдельная операция; организация по-прежнему видит `contact_access` как не выданный.
- Решение о видимости. Принятие разрешено, пока профиль скрыт от организации или не опубликован, как показывает пример контракта с заблокированным разрешением. Принятие не публикует профиль, не меняет публикацию и не снимает и не добавляет скрытие. Разрешение остается сохраненным и станет читаемым, когда кандидат опубликует профиль или уберет скрытие организации: `readable` пересчитывается при каждом чтении, поэтому само разрешение не меняется. Организация видит `contact_access` как `closed`, пока разрешение заблокировано, и как `available`, когда оно становится читаемым (см. [Чтение контактов и отзыв](#чтение-контактов-и-отзыв)).
- Конкурентность. Командой кандидата блокировка организации не берется. Два конкурентных принятия одной версии дают один переход: второе ждет строку и затем отвечает как повтор - 200 тем же ответом при тех же условиях и полях и 409 при другом наборе полей.
- Часы. Время ответа берется у сервиса приглашений, время выдачи разрешения - у сервиса согласий. В продакшене оба читают часы процесса, поэтому могут расходиться на микросекунды; разрешение сохраняет время согласия. Повтор сохраненного принятия восстанавливает ответ из приглашения и разрешения. Таблица исходов не хранит копию ответа, поэтому позднее изменение состояния было бы видно в повторе, как и для отказа.
- Ключи журнала. Колонки C4 в журнале согласий пока не имеют внешних ключей на `organizations` и `invitations`: тесты журнала пишут записи C4 с синтетическими идентификаторами. Составные ключи разрешения сохраняют согласованность принятия без этой правки; ключи журнала требуют фикстур с настоящими приглашениями и остаются последующей задачей.
Не реализовано: чтение контактов через разрешение, отзыв разрешения (после закрытия публикации, скрытия, отзыва согласия или отмены участия), встречное предложение, истечение по сроку и отмена участия.
Не реализовано: встречное предложение, отмена участия, включая отзыв разрешения при отмене участия (остальные отзывы описаны в [Чтение контактов и отзыв](#чтение-контактов-и-отзыв)).
Тесты: `domain/contact_grant_test.go` (разрешение из записи согласия, правила области и отзыва, вид видимости, отрисовка предложения и `Accept`), `usecase/invitation/accept_test.go` (порядок проверок, повторы, устаревшие условия, поздние команды, указатели согласия, видимость без изменения публикации), `adapter/primary/http/v1/invitation_candidate_test.go` (коды отказов) и интеграционные `TestCandidateInvitationAcceptOverHTTP` (разрешение только на email, повторы и конфликты, устаревшие и поднятые условия, конкурентные принятия, скрытый профиль, поздний ответ, проверки согласия и видов, журнал сервера) и `TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback` на настоящем PostgreSQL.
### Предел ожидающих, пауза и истечение
Реализовано: предел ожидающих приглашений на потребность, пауза пары организации и кандидата после отказа и истечение приглашения в срок ответа. Код: `usecase/invitation/pending_limit.go` (проверки отправки), `usecase/invitation/expire.go` (обработчик задания `invitation.response_deadline`, общая функция истечения и постановка задания при доставке), `domain/invitation_expiry.go` (`Expire` и `ExpiryEvent`), `usecase/invitation/send.go`, `decline.go`, `accept.go` и `view.go` (истечение перед ответом кандидата), адаптер `adapter/secondary/postgres/invitation_expiry.go` с `db/queries/invitation_pending.sql`, `invitation_cooldowns.sql` и `invitation_expiry.sql`, регистрация в `jobHandlers()` (`bootstrap/jobs.go`) и миграция `00043_expire_invitations.sql`.
- Предел. Отправка считает приглашения потребности, которые ждут ответа (`delivered`, `viewed`, `counter`), и отказывает с 409 `state_conflict`, когда их уже `max_pending_per_need` из эффективной политики (20 в демо-политике). Счет точный: отправка берет блокировку организации раньше всего, а перевести приглашение в ожидание может только отправка. Приглашение без потребности предела не имеет, его ограничивает квота. Уход из ожидания (отказ, истечение, принятие) освобождает место, но не возвращает недельную квоту: квота списана при отправке и не меняется.
- Пауза. Отправка отказывает с 409 `state_conflict`, пока с последнего отказа кандидата этой организации не прошло `repeat_after_decline_days` (30 дней). Пауза относится к паре организации и кандидата, а не к потребности и не к сотруднику: другая потребность или другой владелец той же организации получает тот же отказ. Пауза после "сделки нет" пока не действует: состояние `no_deal` ни одна операция не создает.
- Порядок блокировок. Отказ кандидата берет блокировку организации до строки приглашения, как все команды, которые могут менять паузу пары. Так отказ и отправка одной пары упорядочены: отправка не пропускает отказ, закоммиченный раньше ее проверки. Порядок тот же, что в [отправке](#отправка-приглашений): организация, затем строки приглашений.
- Срок. Отправка ставит задание `invitation.response_deadline` в той же транзакции, что и доставка: ключ - идентификатор приглашения, срок исполнения - `response_deadline_at`, payload - только идентификатор. Обработчик `ResponseDeadlineJob` выполняется в транзакции, которая блокирует строку приглашения. Если приглашение все еще ждет ответа, оно переходит в `expired` с причиной `invitation_timeout`; иначе обработчик ничего не меняет. Повтор задания безопасен: второе выполнение не находит приглашения, которое ждет ответа.
- Команды кандидата в срок или позже. Просмотр, отказ и принятие блокируют строку и читают время уже при удерживаемой блокировке; чтение (`GetMyInvitation`) блокирует строку, только если срок прошел. В обоих случаях при прошедшем сроке сначала применяется истечение тем же условным UPDATE и той же записью аудита. Чтение и просмотр затем отвечают приглашением в состоянии `expired` без записи просмотра; отказ и принятие отвечают 409 `state_conflict` и сохраняют исход под ключом. Список входящих и чтение организации истечение не применяют: они показывают сохраненное состояние, пока задание или следующая команда кандидата его не применили.
- Что создает истечение. Переход пишет только событие аудита `expired` с версией, без полей и без актора (`actor_id` пуст, потому что переход сделал сервер). Согласие C4, контактное разрешение, запись отказа и квота не создаются и не меняются. Срок и условия сохраняются. Ограничение `invitation_events_system_actor` допускает пустого актора только у `expired`, триггер `invitations_guard_expiry` разрешает переход только из `delivered` или `viewed` и не раньше срока, а `invitations_expiry_reason` требует причину.
- Гонка с принятием. Принятие в срок или позже всегда отказывает: и принятие, и задание решают по времени, известному при удерживаемой строке. Из двух путей, которые берут строку первыми, итог один: приглашение `expired` без гранта. Принятие до срока, закоммиченное раньше задания, оставляет задание без действия. Проверяют `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres` (гонка) и `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres` (задание первым).
- Часы. Срок и лимиты решаются по часам приложения, которые внедряются в usecase и в обработчик задания; часы базы не решают. Обработчик, которому часы еще не показали срок, возвращает ошибку, и задание повторяется по backoff, а не завершается без истечения.
- Запуск. Истечение по заданию выполняет воркер, который включает `JOBS_ENABLED`; без него задание ждет в базе. Команды кандидата применяют истечение и без воркера, поэтому ответ кандидата остается верным.
- Миграция 00043. Новый вид события `expired`; ограничения `invitation_events_expiry_changes_no_field` и `invitation_events_system_actor`; триггер `invitations_guard_expiry`; частичные индексы `invitations_pending_need_idx` (ожидающие приглашения потребности) и `invitations_declined_pair_idx` (отказы пары); перенос заданий истечения для приглашений, доставленных до миграции, с ключом по идентификатору и `ON CONFLICT DO NOTHING`. Откат отказывает, пока есть истекшие приглашения, и удаляет задания этого вида.
Не реализовано: пауза после "сделки нет" (нужна операция, которая переводит приглашение в `no_deal` и задает время выхода из паузы), истечение состояния `counter` (его пока не создает ни одна операция), причина `negotiation_timeout` и предел для приглашений без потребности, если его решат ввести.
Тесты: `domain/invitation_expiry_test.go` (истечение только ожидающего приглашения после срока, сохранение срока и условий, событие без актора); `usecase/invitation/pending_limit_test.go` (предел при 20 ожидающих и 21-м, два конкурентных отправления при 19, освобождение места без возврата квоты, пауза на 29 и 30 день для другого владельца и другой потребности, пауза не действует на другого кандидата и на истекшее приглашение); `usecase/invitation/expire_test.go` (истечение чтением, просмотром, принятием и отказом в срок, задание и его повтор, отказ задания с неверным payload); интеграционные `TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres`, `TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres`, `TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres`, `TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres` и `TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries` в `integration_test/invitation_expiry_test.go`.
### Чтение контактов и отзыв
Реализовано: `GetOrganizationInvitationContacts` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)) в `usecase/invitation/contacts.go` и `adapter/primary/http/v1/contacts.go`; тип раскрытия в `domain/contact_disclosure.go`; блокировка разрешения `ContactGrantRepository.LockForRead` в `adapter/secondary/postgres/invitation_accept.go`; закрытия в `consent_revocation.go` (`ConsentRevocationEffects.Apply`), `privacy_view.go` (`CloseForVisibility`) и `contact_grant_closure.go`; запросы в `db/queries/contact_grants.sql`; миграция `00042_index_contact_grants_by_candidate.sql`, которая добавляет индекс по кандидату для закрытий на уровне всего кандидата. `contact_access` организации выводится в `usecase/invitation/contact_access.go` той же проверкой `readableContactGrant`, которой пользуется чтение (`usecase/invitation/contacts.go`).
- Доступ. Middleware компании до обработчика проверяет сессию, активное членство владельца и путь. Участник без роли владельца получает 403, аккаунт без членства получает 404, а аккаунт кандидата получает 403. Юзкейс повторяет проверку владельца внутри своей транзакции. В MVP контакты не читает никакая другая роль.
- Порядок блокировок. Чтение берет по порядку: организацию и членство (`LockActiveMembership`, общие блокировки), аккаунт кандидата, самую новую действующую запись C2, публикацию вместе с записью C2 (это же применяет скрытие организации), запись C4 разрешения и само разрешение. Непроверенное чтение разрешения до блокировок только называет кандидата, который у разрешения не меняется. Отзыв C4 блокирует запись, затем разрешение в том же порядке, поэтому две операции не ждут друг друга в обратном порядке. Блокировки видимости идут первыми: скрытие или отзыв C2, зафиксированные раньше, видны чтению, а те, что ждут, выполняются после фиксации чтения.
- Решение. Чтение отвечает 200, только если разрешение активно, его запись C4 не отозвана и организация сейчас может читать публикацию. Любой другой случай отвечает 404 `not_found` и не говорит, какой именно: нет разрешения этого приглашения для этой организации, разрешение или запись C4 отозваны, профиль закрыт или скрыт от организации. Вид возвращает значение, только если профиль держит его как подтвержденное утверждение; любой другой вид равен null, а предложение, которое никто не подтвердил, не раскрывается. Ответ имеет `Cache-Control: no-store`.
- Закрытия. Каждое закрытие выполняется в транзакции изменения, ставит время отзыва и его причину и никогда не открывает разрешение заново:
- Отзыв C4 для организации (`consent_revoked`) закрывает разрешения, которые ссылаются на отозванные записи. Разрешения других организаций и других приглашений остаются открытыми.
- Отзыв C2 (`visibility_closed`) закрывает все действующие разрешения кандидата, даже если строки публикации, которую надо закрыть, нет.
- Закрытие публикации (`visibility_closed`) закрывает все действующие разрешения кандидата.
- Скрытие организации (`visibility_closed`) закрывает действующие разрешения этой организации, в том числе при повторном скрытии. Снятие скрытия и повторная публикация ничего не закрывают и ничего не открывают: закрытое разрешение сохраняет первую отметку, которую охранный триггер допускает один раз.
- Разрешение, сохраненное, пока профиль нельзя читать, этим состоянием не закрывается. Оно остается действующим и заблокированным видимостью, становится читаемым, когда кандидат публикует профиль или снимает скрытие, а закрывает его следующее закрывающее событие.
- Отзыв приглашения организацией не меняет разрешение. Отмена участия кандидатом (`participation_cancelled`) не реализована. Отзыв C1 разрешение не закрывает: контракт не называет для него причины.
- Вид организации. Каждый ответ организации с `contact_access` выводит его из разрешения приглашения в транзакции запроса: `GetOrganizationInvitation`, `ListOrganizationInvitations` и ответы создания черновика, изменения и отправки. Без разрешения ответ `not_granted`, отозванное разрешение дает `closed`. Действующее разрешение проходит те же блокировки видимости и проверки, что и чтение: сначала видимость, затем запись C4 и само разрешение. Поэтому вид говорит `available` именно тогда, когда чтение в этот момент бы прошло, и `closed` в остальных случаях. Вид перечисляет выданные виды только при `available`; `closed` не несет причины, а значение контакта никогда не входит в вид. Вывод читает разрешение любого состояния, поэтому отозванное приглашение сохраняет состояние своего разрешения, как требует контракт. У отклоненного и истекшего приглашения разрешения нет, и они отвечают `not_granted`. Идемпотентные повторы создания и отправки возвращают сохраненный исходный ответ, поэтому их `contact_access` - состояние на момент первого ответа. Вывод делает один поиск разрешения на приглашение, а блокировки общего доступа берет только для приглашения с разрешением.
- Квота и аудит. Успешное чтение записывает одну строку `contact_read` в `candidate_card_access_events` в той же транзакции, с выданными видами и никогда без значения. Чтение не расходует квоту просмотров карточек, потому что контракт не засчитывает чтение контактов в эту квоту. Собственное чтение истории кандидатом остается операцией только контракта.
- Не реализовано: отмена кандидатом и отзыв приглашения организацией. `CurrentContactFields` в `usecase/candidateview` остается закрытым, потому что чтение по дескриптору карточки не имеет операции контракта.
Тесты: `domain/contact_disclosure_test.go` (значения только подтвержденных видов, отказ для отозванного разрешения, редактирование при выводе), `usecase/invitation/contacts_test.go` (проверки владельца и роли, видимость, отозванное разрешение и запись C4, неизвестные приглашения) `usecase/invitation/contact_access_test.go` (состояния разрешения для организации, их согласие с чтением в каждом закрывающем состоянии, заблокированное разрешение, которое открывается, когда становится видимым, и отозванное разрешение, которое никогда не открывается заново) и интеграционный тест `TestOrganizationContactReadsAndRevocationOverHTTP` через настоящий роутер и PostgreSQL. Он покрывает чтение только email, повторное чтение, отказы для другой организации, участника и кандидата, отзыв C4 при независимой организации, скрытие и снятие скрытия без повторного открытия, отзыв C2 с повторной публикацией, закрытие публикации и индекс. Он также проверяет `contact_access` в одиночном чтении и в списке после каждого изменения, отклоненное приглашение и истекшее; истекшее идет последним, потому что переводит часы.
## Frontend
Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.
+1 -1
View File
@@ -1,6 +1,6 @@
# Квоты компании
Резервирование квот компании реализовано в домене, usecase `companyquota` и адаптере PostgreSQL. Для резервирования приглашений и просмотров карточек кандидатов используется порт, связанный с транзакцией. Рабочий процесс создания и отправки приглашений пока не реализован; резервирование квоты не означает, что приглашение отправлено.
Резервирование квот компании реализовано в домене, usecase `companyquota` и адаптере PostgreSQL. Для резервирования приглашений и просмотров карточек кандидатов используется порт, связанный с транзакцией. Приглашение тратит одно место недельной квоты при отправке (`SendOrganizationInvitation`): черновик квоту не тратит, а повтор отправки того же приглашения не тратит второе место. Уход приглашения из ожидания ответа (отказ, истечение, принятие) освобождает место в пределе ожидающих приглашений на потребность, но не возвращает недельную квоту; см. [Предел ожидающих, пауза и истечение](ARCHITECTURE.md#предел-ожидающих-пауза-и-истечение).
## Политика и доверенный уровень компании