feat(invitations): accept invitations with C4 consent and contact grants; share the E0 quota across holdings
This commit is contained in:
1 parent
a5990d3fc6
commit
676b3c6e24
59 files changed
+4926
-194
No files matched your search
+29
-9
@@ -467,7 +467,7 @@ Demo and calibrated policy: `domain.DemoProductPolicyV1()` is the accepted initi
|
||||
| Section | Values |
|
||||
| --- | --- |
|
||||
| `invitations` | response deadline options 3, 7, and 14 days, default 7; at most 20 pending invitations per need; repeat after a decline in 30 days; interview proposal within 5 business days; 30-day pause after no deal |
|
||||
| `organization_quotas` | rolling windows of 7 days for invitations and 24 hours for distinct card views; E0 10 invitations and 50 views, E1 40 and 150, E2 100 and 400; E2 is inactive until the organization verification that grants it exists |
|
||||
| `organization_quotas` | rolling windows of 7 days for invitations and 24 hours for distinct card views; E0 10 invitations and 50 views, E1 40 and 150, E2 100 and 400; E2 is inactive until the organization verification that grants it exists; the E0 companies of one holding share one pool, and E1 and above count separately (see [Company quotas](COMPANY_QUOTAS.md#holding-pool)) |
|
||||
| `assessment`, uncalibrated initial | same-grade retry after 30 days; at most 3 attempts per 180 days; at most one promotion per 90 days; confirmation at P_G >= 0.80, high strength from 0.90; after at least 8 scored items stop at P_G >= 0.90 or <= 0.10 or SE <= 0.25; at most 23 scored items plus 2 seed items; practice is mandatory |
|
||||
| `identity` | verification token 24 hours; unverified account deleted 7 days after the latest registration; session idle timeout 24 hours, absolute lifetime 7 days |
|
||||
| `search_status` | the "searching" status is confirmed every 30 days |
|
||||
@@ -695,7 +695,7 @@ Implemented as a deterministic search without ML: `POST /api/v1/organizations/{o
|
||||
- Order and rounding. Scores are integers in micro units (six decimals), the shares are basis points, and the products are exact integers, so the same data and policy give the same order on every platform. `main` and `near` sort by S, then Cov (both descending), then the internal candidate identifier ascending (then the specialization code, which only separates two entries of one candidate); `unconfirmed` sorts by Fit, then Cov, then the identifier. The identifier never leaves the server, and the groups are not merged on one scale.
|
||||
- Explanation. The summary and the flags are built from the same computed contributions: per skill group `supports` (every skill carried by a measurement at or above the threshold), `declared_only` (only stated tags), `partial` (a mix, or measurements below the threshold), or `gap` (nothing), plus the confirmed category, the declared grade, the work-format match against the need or the filter, and the salary compatibility. It uses bounded codes only, never free text, a contact, a candidate location, a salary value or minimum, a failed attempt, or a reason for withheld data. An unknown component appears only in `unknown_flags`.
|
||||
- Policy. The search reads the effective `product` policy at the application time and its `matching` section. A policy without the section fails closed with an internal error (the ProblemCode enum has no code for a temporarily unavailable dependency, and none is added); the error log says that the effective product policy has no matching section and names the `policy-publish` operator command, the backend logs a warning at startup while the section is missing, and [DEPLOY.md](DEPLOY.md#match-search-policy-on-a-stand) describes the command. The response does not name the policy version, and no search is stored.
|
||||
- Concurrency. The reservations take the exclusive organization lock of the company quota port. A membership check before them holds only a share lock on the same row, and two searches of one organization would deadlock on the upgrade, so the search takes the organization lock first (`CompanyQuotaRepository.LockOrganization`, the documented order; it is FOR NO KEY UPDATE, so readers queue behind each other but the foreign-key lock of a candidate's own hide, which holds the candidate row and then needs the organization row, is not blocked, and the reservation itself still takes FOR UPDATE in the same transaction) and the charges of one organization are serialized. A change of the visible cohort while it is being locked (`ErrConcurrentVisibilityChange`) repeats the whole search up to three times, and its writes roll back with the failed attempt. The card read (`GetOrganizationCard`) and the evidence section (`AuthorizeCategoriesSection`) take the same exclusive lock first, before any share lock, for the same reason: before this order two simultaneous card reads of one organization deadlocked (SQLSTATE 40P01). `TestMatchSearchOverHTTP` runs concurrent card reads, evidence reads, and searches of one organization and checks for no deadlock and one quota row for each candidate.
|
||||
- Concurrency. The reservations take the exclusive organization lock of the company quota port. A membership check before them holds only a share lock on the same row, and two searches of one organization would deadlock on the upgrade, so the search takes the organization lock first (`CompanyQuotaRepository.LockOrganization`, the documented order; it is FOR NO KEY UPDATE, so readers queue behind each other but the foreign-key lock of a candidate's own hide, which holds the candidate row and then needs the organization row, is not blocked, and the reservation itself still takes FOR UPDATE in the same transaction) and the charges of one organization are serialized. A change of the visible cohort while it is being locked (`ErrConcurrentVisibilityChange`) repeats the whole search up to three times, and its writes roll back with the failed attempt. The card read (`GetOrganizationCard`) and the evidence section (`AuthorizeCategoriesSection`) take the same exclusive lock first, before any share lock, for the same reason: before this order two simultaneous card reads of one organization deadlocked (SQLSTATE 40P01). For an E0 company, `LockOrganization` takes the lock of its holding right after the organization row (the shared E0 pool is described in [Company quotas](COMPANY_QUOTAS.md#holding-pool)), so the order stays the same: the organization, then the holding, and no holding is taken before its organization. `TestMatchSearchOverHTTP` runs concurrent card reads, evidence reads, and searches of one organization and checks for no deadlock and one quota row for each candidate.
|
||||
- Accepted residual risks. `truncated` is one bit about the size of the visible bank (it says that more than the limit or the allowance exists) and the response time grows with the bank, so both leak a coarse size to the owner. The bit is bounded by the group limit and no count is returned; the risk is accepted for the demonstration and is listed with the owner questions.
|
||||
- Checks. `internal/usecase/matching` unit tests (formulas with hand-computed values, ties and ordering, filters, explanation, the cut and the charge of the output), `internal/domain/policy_matching_test.go` (document round trip, strictness, validation), `v1/matches_test.go` (mapping and problems), and the integration test `TestMatchSearchOverHTTP` against PostgreSQL: hidden candidates and two organizations, a need and its edited requirements, repeated identical responses, Backend confirmed and Networks unconfirmed for one handle, a profile published without a grade through the real profile, consent, and publication operations and removed by a C2 revocation, a candidate alone in its cohort, no contact or identifier in the body, the charge and the access history of a search, an organization with an allowance smaller than its bank, the group limit, the batch evidence read, two concurrent searches under one allowance, the demo group limit, the policy taxonomy, the denials, and the policy without the section.
|
||||
|
||||
@@ -861,20 +861,22 @@ Tables:
|
||||
- `organizations`: UUIDv7 `id` (the `org_id` of every organization path), `name` (1-200 characters, the bound of the consent snapshot), `description`, `sphere` (free text; the PRD has no taxonomy), four public contact columns (`contact_website`, `contact_email`, `contact_phone`, `contact_telegram`), the verification columns `verification_level`, `verification_basis`, and `verification_changed_at`, the profile `version`, and the times. Every text column has a CHECK for the same format and bounds as the contract (no surrounding whitespace, no control characters, `https` website without credentials).
|
||||
- `organization_representatives`: `organization_id`, `ordinal` (0 to 9, so at most ten), `name`, and `job_title`; deleted with the organization row. The list is replaced as a whole with a profile update.
|
||||
- `memberships`: UUIDv7 `id`, `organization_id`, `user_id`, `role`, `state`, and the times. `UNIQUE (user_id, organization_id)` allows one membership per pair in any state, and `UNIQUE (organization_id, id)` is the target of the composite foreign keys that later tables (the assignments of needs) use to bind a membership to its organization. Both foreign keys are `ON DELETE RESTRICT`.
|
||||
- `holdings`: UUIDv7 `id` (internal; the API never shows it), `founder_account_id`, the account that created the first organization of the holding, with `UNIQUE` and a foreign key to `users` with `ON DELETE RESTRICT`, and `created_at`. The column `organizations.holding_id` is required, references the holding with `ON DELETE RESTRICT`, and has an index; migration `00041_create_holdings.sql` fills it from the account of the earliest membership of each organization.
|
||||
|
||||
Decisions:
|
||||
|
||||
- Active context. It is not a server-side session attribute. The organization is the `org_id` in the path, and the server derives the right from the active membership on every request, so a removal, a suspension, or a leave closes the next read with nothing to invalidate. `ListMyOrganizations` is the directory a client picks from; remembering the last choice is a browser convenience. The context comes only from the caller's active memberships, and a terminated membership closes reads at once. A switch clears the client's tenant queries.
|
||||
- Role and state in the membership only. `OrganizationRole` is `owner`, `recruiter`, `hiring_manager`, or `technical_expert` (PRD 2.2, Q3, and the FR07 matrix), and `MembershipState` is `active`, `suspended`, `removed`, or `left`, each a CHECK constraint, not a PostgreSQL enum, so a later value is a constraint change in a migration. There is no `invited` state: PRD 6.4 lists `MemberInvite` as its own entity, an invitation to an email address that may have no account yet, and a membership row appears when its owner accepts it. `organizations` has no role, owner, or member column (an integration test reads the catalog to prove it), and `Organization`, `OrganizationCreate`, and `OrganizationUpdate` have no such field. Only the owner manages the company (`OrganizationRole.CanManageOrganization`); the rest of the matrix is applied by the operations it governs, and in the MVP the other roles grant nothing.
|
||||
- Verification level. `verification_level` is `e0` to `e3` with `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), and one CHECK ties each level to its own bases. The columns are separate from the profile: `UpdateOrganizationProfile` never names them, `domain.NewOrganization` cannot choose a level and starts every organization at `e0` on `confirmed_email`, `Organization.ApplyProfile` keeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; the planned verification flow adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process. `OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the quota tiers of the product policy and has none for `e3`, which the PRD gives a separate policy (quota enforcement reads the tier and must fail closed on an `e3` organization: no quota granted, the action refused, never a fallback to another tier).
|
||||
- Holding. The organizations of one founder account form a holding. `CreateWithOwner` stores the organization in the holding of its owner account in the same transaction, and creates the holding with the first organization of the account (`INSERT ... ON CONFLICT (founder_account_id) DO NOTHING`, then a read), so concurrent creations of one account end in one holding. A holding carries no profile and no right: it only defines the scope of the shared E0 quota pool (invitations and card views). The number of organizations per account is not limited; merging holdings of different owners is not modelled. The pool and lock rules are in [Company quotas](COMPANY_QUOTAS.md#holding-pool).
|
||||
- An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management, not of this constraint, which would otherwise block a platform decision about an abusive organization.
|
||||
- Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management, which changes a membership and the organization together, and the tenant repository must take the locks in that order, or two transactions can deadlock.
|
||||
- Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the consent ledger tests to create real organizations, and the `invitation_id` key needs real invitations; both arrive with the acceptance of an invitation, the first writer of C4 rows that name a real invitation. The invitation tables (migration 00037) and the needs reference organizations, accounts, and policy versions with `ON DELETE RESTRICT`, so an organization with needs or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3).
|
||||
- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and remove it through bounded opportunistic cleanup after the replay window; physical deletion may happen later when create traffic resumes; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (organization creation and quota enforcement need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations).
|
||||
- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and remove it through bounded opportunistic cleanup after the replay window; physical deletion may happen later when create traffic resumes; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the owner's decision on the number of organizations per account (no limit; the E0 quotas of a holding are shared) are in [api/README.en.md](../../api/README.en.md#organizations).
|
||||
|
||||
What the ports guarantee (`outbound.OrganizationRepositories`, available on `UnitOfWork` only, because a write needs the transaction):
|
||||
|
||||
- `Organizations().CreateWithOwner` stores the organization and its owner membership and validates that the owner is the active owner membership of that organization. An unknown account returns `ErrUserNotFound` and aborts the surrounding transaction.
|
||||
- `Organizations().CreateWithOwner` stores the organization and its owner membership and validates that the owner is the active owner membership of that organization. The organization joins the holding of the owner account, and the holding is created in the same transaction when none exists yet. An unknown account returns `ErrUserNotFound` and aborts the surrounding transaction.
|
||||
- `GetForMember` reads the organization, its representatives (aggregated as JSON in the same statement), and the caller's active membership from one snapshot, and returns them or `ErrOrganizationNotFound` for an unknown organization, an account without a membership, and a `suspended`, `removed`, or `left` member alike. `ListForUser` pages the active organizations of one account, newest membership first, with the organization identifier as the tie-breaker. `UpdateProfile` is described above.
|
||||
- `Memberships().Insert` returns `ErrMembershipExists` for a repeated pair in any state, `ErrOrganizationNotFound` for an unknown organization, and `ErrUserNotFound` for an unknown account; `Get` returns the membership in any state or `ErrMembershipNotFound`, and the caller checks `GrantsAccess`. There is no method that changes a role or a state yet.
|
||||
|
||||
@@ -941,13 +943,13 @@ The anonymous card for organizations is not built here: `AnonymousCardContent` i
|
||||
|
||||
### Invitation drafts
|
||||
|
||||
Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in [Sending invitations](#sending-invitations). Withdrawal, the salary raise, the contact read, the acceptance, and the cancellation still answer 501 after the common checks; the candidate's read, view, and decline are described in [Candidate view and decline](#candidate-view-and-decline). Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`.
|
||||
Implemented: the organization side of the invitation draft, that is `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation`, and `UpdateOrganizationInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). A draft is invisible to the candidate and produces no inbox entry, no event, and no quota charge; the send is described in [Sending invitations](#sending-invitations). Withdrawal, the salary raise, the contact read, and the cancellation still answer 501 after the common checks; the candidate's read, view, decline, and acceptance are described in [Candidate view and decline](#candidate-view-and-decline) and [Candidate acceptance](#candidate-acceptance). Code: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, the PostgreSQL adapter `adapter/secondary/postgres/invitations.go` with `db/queries/invitations.sql`, and migration `00037_create_invitations.sql`.
|
||||
|
||||
Tables:
|
||||
|
||||
- `invitations`: UUIDv7 `id`, `organization_id`, the internal `candidate_id` (never serialized, logged, or printed), the optional need link (`need_id` with `need_requirements_version`, bound by composite foreign keys to a stored version of a need of the same organization), `state` (all fourteen states of the contract, so the later operations need no constraint change), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7, or 14), `policy_version_id` (the product policy version that allowed the period), `response_deadline_at`, `salary_raise_used`, `created_by`, and `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. CHECK constraints tie the deadline to the delivery (both set or both null), keep a draft free of delivery, view, answer, and raise, and tie the expiry reason to the state. A trigger keeps the identity columns, makes every UPDATE advance `version` by exactly one and `terms_version` by at most one, and refuses to undo a raise or to move the delivery, the deadline, or the period after a delivery. A second trigger refuses DELETE. The foreign keys to organizations, accounts, and policy versions are `ON DELETE RESTRICT`, so an account with invitations is undeletable until a deletion procedure settles them.
|
||||
- `invitation_terms_versions`: `(invitation_id, version)`, the terms as a JSONB snapshot, and the salary again in typed columns (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Constraints repeat the money rules in integers: both bounds from 1000 to 100 000 000 rubles in steps of 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B` (a width of 10% to 40% of the midpoint), RUB, month, and `net` or `gross`. The snapshot must hold all twelve terms and its salary must equal the typed columns. A trigger refuses UPDATE and DELETE: a version of the terms is immutable, and a change appends the next version. The invitation points at its current version by a deferred composite foreign key, so the first version is inserted in the same transaction.
|
||||
- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created`, `draft_updated`, since migration 00038 `delivered`, and since migration 00039 `viewed` and `declined`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only.
|
||||
- `invitation_events`: one audit event for each committed invitation version (`UNIQUE (invitation_id, version)`) with the kind (`draft_created`, `draft_updated`, since migration 00038 `delivered`, and since migration 00039 `viewed` and `declined`, and since migration 00040 `accepted`), the version and terms version, the actor, the parts that changed (`terms`, `need`, `response_period_days`), and the time. It holds no content and is append-only.
|
||||
- `invitation_creation_results`: the original response of an idempotent create, bound to the generic idempotency record and removed with it. It holds the terms, the alias, and no candidate identifier.
|
||||
|
||||
Decisions:
|
||||
@@ -962,7 +964,7 @@ Decisions:
|
||||
- Locks. A create and an update both take the exclusive organization lock first (`CompanyQuotaRepository.LockOrganization`), like a card read and a search, and only then the share lock of the membership check, the cohort locks of a create, or the invitation row lock of an update, so commands of one organization queue instead of deadlocking on a lock upgrade, and a later command that also charges the organization, such as sending, keeps the same order. An update locks the invitation row with a statement of its own (`LockInvitation`) and reads it afterwards: a locking read joined to the terms table would, after waiting for a concurrent commit, pair the new `terms_version` with the terms row it fetched before the wait and find nothing. A create repeats a bounded number of times when the visible cohort changed while it was locked.
|
||||
- The indicator. `salary_fit` is always `not_available` and `contact_access` is `not_granted` with no fields. The indicator needs the candidate's minimum, and computing it before the limit of three settings a day and the seven-day withholding exist would let an organization probe the minimum by editing a draft, so neither is computed or enforced yet.
|
||||
|
||||
How the later operations plug in: the pair rules read the index on the organization and the candidate. The contact grant, the C4 key to `invitations`, and the keys of the consent ledger to `organizations` and `invitations` arrive with the acceptance, the first writer of C4 rows that name a real invitation.
|
||||
How the later operations plug in: the pair rules read the index on the organization and the candidate. The contact grant 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.
|
||||
|
||||
@@ -997,16 +999,34 @@ Implemented: `GetMyInvitation`, `ViewMyInvitation`, and `DeclineMyInvitation` ([
|
||||
- Privacy of the decline. The organization reads only `declined` and `responded_at`: none of its operations reads `invitation_declines`, and the audit event names no reason. The comment is never logged, notified, or copied into the stored outcome; the candidate reads both back in `decline`.
|
||||
- Order of checks after the boundary: the candidate (403), the key (422 or a replay), the invitation (404, stored), the same decline of a declined invitation (200 with a new key or an older version), another reason or comment on a declined invitation, any other terminal state, or a passed deadline (409 whatever the version, stored), the version (412, not stored), then a state without an open answer (409, stored). `invitation_decline_results` keeps only the outcome and the invitation: a declined invitation and its decline never change, so a replay rebuilds the same answer and the comment is stored once.
|
||||
- Deadline. Expiry is not implemented yet, so no read or command applies the transition to `expired`. A view at the deadline or later changes nothing, and a decline at the deadline or later answers 409 `state_conflict`, as the contract requires for a late command; the invitation stays `delivered` or `viewed` with its passed deadline until the expiry arrives. The conditional UPDATEs repeat the deadline, so a command cannot cross it between the check and the write.
|
||||
- Consent and grant. Acceptance is not implemented, so an acceptance is impossible now and `contact_consent` and `contact_grant` are always null, as the contract requires when no acceptance can be made. Both arrive with `AcceptMyInvitation`.
|
||||
- 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.
|
||||
- Database rules of migration 00039: the event kinds `viewed` and `declined` without changed fields; `invitations_answer_matches_state` (a delivered invitation has no view or answer, a viewed one has its view, a declined one its answer, and neither precedes the delivery); the trigger `invitations_guard_answer`, which refuses to move or undo a view or an answer and to leave `declined`; `invitation_declines` with the known reasons, the comment bound, a trigger that ties the row to a declined invitation answered at the same moment, and a refusal of UPDATE and DELETE; and the deferred constraint trigger `invitations_require_decline`, so a declined invitation without its decline cannot commit. The down migration refuses while a view, a decline, or a stored outcome exists.
|
||||
- Notification. The contract has no notification kind for an answer, so the organization gets no inbox entry for a view or a decline yet; it sees the state in its invitation list. A notice of the answer is planned as a contract change.
|
||||
|
||||
Not implemented: the expiry at the deadline and its application on a read, the acceptance with C4 and the contact grant, the cancellation, the counter offer that would produce `counter`, the decline aggregates with a minimum group size, the responsiveness metrics, the 30-day pause after a decline, and a notification of the organization about an answer.
|
||||
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.
|
||||
|
||||
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`.
|
||||
|
||||
### Candidate acceptance
|
||||
|
||||
Implemented: `AcceptMyInvitation` ([contract](../../api/README.en.md#invitations-and-contact-grants)). Code: `domain/invitation_answer.go` (`Accept`), `domain/contact_grant.go`, `usecase/invitation/accept.go` and `view.go` (the candidate's view with the consent offer and the grant), `usecase/consent` (`GrantContact`, the C4 record), the HTTP handler `adapter/primary/http/v1/invitation_candidate.go`, the adapter `adapter/secondary/postgres/invitation_accept.go` with `db/queries/invitation_answers.sql` and `db/queries/contact_grants.sql`, and migration `00040_accept_invitations.sql`.
|
||||
|
||||
- One transaction. The candidate accepts the current terms with the consent C4 from `delivered` or `viewed`, before the deadline, at the invitation version and the terms version that the candidate read. The transaction takes its own idempotency record, then only the invitation row (`LockCandidateInvitation`), and then, in order: it moves the invitation to `accepted` with one conditional UPDATE (`responded_at` is the answer time, `version` plus one; the deadline and the terms stay), records the consent C4 in the consent ledger through `consent.Service.GrantContact` (the published text, the organization name as it was shown, the selected fields, the invitation, and its terms version), stores the contact grant of exactly those fields, and appends the audit event `accepted`, which names no field. A failure of any step rolls the whole transaction back.
|
||||
- Order of checks. The contract order: the candidate (403), the key (422 or a replay), the invitation (404, stored), a repeat of an accepted invitation (200), a terminal state or a passed deadline (409 `state_conflict`, stored), the versions (412 `version_conflict`, not stored), any state other than `delivered` or `viewed` (409, stored), and the consent rules (400 at `/consent_c4/text_version` for a text that is not the published one, and at `/consent_c4/fields/N` for a kind that the profile does not hold). A kind is held when the profile has it as a confirmed claim; a suggestion that nobody confirmed is never disclosed.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -14,9 +14,9 @@ The quota snapshot captures the policy version and the stored organization verif
|
||||
|
||||
Call `companyquota.Service.ReserveInvitation` or `ReserveCardView` with repositories from the current `outbound.UnitOfWork`. The repository returned by `UnitOfWork.CompanyQuotas()` is transaction-scoped and must not be retained. Make the quota reservation and its eventual business change in the same transaction so rollback removes both. The service is constructed with the application clock and reads the effective policy once per operation.
|
||||
|
||||
Tenant authorization remains the caller's responsibility. Recheck active membership and owner permission inside the same transaction. Writers follow this order: organization, active membership, invitation or visibility record, then quota usage. The quota adapter locks the organization row first; a caller that already holds that row may lock it again in the same transaction. Do not reverse this order.
|
||||
Tenant authorization remains the caller's responsibility. Recheck active membership and owner permission inside the same transaction. Writers follow this order: organization, then for an E0 organization its holding (see [Holding pool](#holding-pool)), active membership, invitation or visibility record, then quota usage. The quota adapter locks the organization row first and, for an E0 organization, the holding row right after it; a caller that already holds those rows may lock them again in the same transaction. Do not reverse this order.
|
||||
|
||||
The organization lock serializes concurrent reservations. The adapter checks existing usage, counts the active window, and inserts or refreshes usage while that lock is held. A decision is either allowed or denied; reuse implies allowed. A denied reservation writes no usage and includes `RetryAt`, the earliest active usage expiry that can free capacity.
|
||||
The organization lock serializes concurrent reservations of one organization, and the holding lock serializes the shared E0 pool. The adapter checks existing usage, counts the active window, and inserts or refreshes usage while those locks are held. A decision is either allowed or denied; reuse implies allowed. A denied reservation writes no usage and includes `RetryAt`, the earliest active usage expiry that can free capacity.
|
||||
|
||||
## Windows and retries
|
||||
|
||||
@@ -24,10 +24,24 @@ An invitation is keyed by `(organization_id, invitation_id)`. Repeating the same
|
||||
|
||||
A card view is keyed by `(organization_id, candidate_id)`, so viewing the same candidate again during the active window does not consume another distinct-view slot. The repeat refreshes `last_seen_at` monotonically: a backdated application clock cannot move the stored time backward.
|
||||
|
||||
The active-window query uses a strict comparison with the cutoff. A row exactly at `now - window` has expired. Invitation usage is counted over seven rolling days; card views are counted over 24 rolling hours. The limits apply across requests and users in the organization.
|
||||
The active-window query uses a strict comparison with the cutoff. A row exactly at `now - window` has expired. Invitation usage is counted over seven rolling days; card views are counted over 24 rolling hours. The limits apply across requests and users of the organization, except that an E0 organization shares its limits with the other E0 organizations of its holding (see [Holding pool](#holding-pool)).
|
||||
|
||||
Expired card-view rows are deleted in batches of at most 100 after a successful allowed reservation. Window expiry is logical; this cleanup does not promise deletion at an exact time. Deleting a candidate account cascades its card-view usage row. Deleting an organization cascades both quota tables. Invitation usage has no invitation foreign key, so future invitation withdrawal cannot erase its idempotency evidence.
|
||||
|
||||
## Holding pool
|
||||
|
||||
A holding groups the organizations that one founder account created; the `holdings` table and the migration `00041_create_holdings.sql` store it. `CreateWithOwner` stores each new organization in the holding of its owner account in the same transaction. The holding of an account is created with its first organization, and concurrent creations of one account end in one holding, because the insert ignores an existing founder key and the transaction then reads the stored holding. A holding carries no profile and no right; its only effect is the shared E0 pool.
|
||||
|
||||
The E0 limits (10 invitations per 7 days and 50 distinct card views per 24 hours in the bundled demo policy) are shared by the E0 organizations of a holding. An E0 reservation counts the usage rows of every organization of its holding whose trust level is E0 when the count runs. Each usage row stays attributed to the organization that consumed it, and usage of an organization that is no longer E0 leaves the shared pool. An organization at E1 or above counts only its own usage and keeps its own pool, so its usage does not count toward the E0 pool.
|
||||
|
||||
Idempotency stays per organization. The same invitation ID, or a repeated view of one candidate by the same organization inside the window, is not charged twice. The same candidate viewed by two organizations of one holding is two charges of the shared pool.
|
||||
|
||||
Locks: for an E0 organization, `CompanyQuotaRepository.LockOrganization` and each reservation take the holding row with `FOR NO KEY UPDATE` right after the organization row. Reservations of one pool therefore run one after another, and the second one counts the usage that the first one committed, because it counts only after the holding lock. Every writer takes the organization lock before the holding lock, and no code takes an organization lock while it holds a holding lock, so the holding lock adds no cycle to the documented order. The cost is that E0 searches, card reads, and invitation drafts or sends of one holding wait for one another while their transactions are open; a search holds the lock for its whole ranking transaction.
|
||||
|
||||
The migration gives each founder one holding: the founder of an organization is the account of its earliest membership, which is the creator's owner membership, and the holding is dated by its first organization. The rollback refuses while a holding groups several organizations, because the schema without holdings could not keep their E0 pool together. Merging holdings of different owners is out of scope.
|
||||
|
||||
## Verification
|
||||
|
||||
`TestHoldings` in `backend/integration_test/holding_test.go` covers the shared E0 pool of two organizations of one account with a verified organization apart, a second account's own holding, usage leaving the pool when its organization is raised, concurrent reservations from two organizations that never exceed the shared limits, concurrent creations ending in one holding, and a refused creation of an unknown founder. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` in `backend/integration_test/holding_migration_test.go` covers the backfill and the guarded rollback.
|
||||
|
||||
`TestCompanyQuota` in `backend/integration_test/company_quota_test.go` exercises the real PostgreSQL adapter in an isolated database. It checks concurrent E0 reservations, E0/E1 boundaries, exact window cutoffs and `RetryAt`, same-ID invitation reuse, cross-request card-view reuse, monotonic refresh, rollback, policy or organization snapshot changes, an allowed reservation with an active E2 policy and stored E2 verification, rejection of a forged E2 snapshot for a stored E0 company, inactive E2 and E3 denial, and candidate-deletion cleanup. It does not test a delivered invitation because that workflow is not implemented.
|
||||
+29
-9
@@ -467,7 +467,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| Раздел | Значения |
|
||||
| --- | --- |
|
||||
| `invitations` | варианты срока ответа 3, 7 и 14 дней, по умолчанию 7; не более 20 ожидающих приглашений на одну потребность; повтор после отказа через 30 дней; предложение интервью в течение 5 рабочих дней; пауза 30 дней после контакта без сделки |
|
||||
| `organization_quotas` | скользящие окна 7 дней для приглашений и 24 часа для просмотров разных карточек; E0 10 приглашений и 50 просмотров, E1 40 и 150, E2 100 и 400; E2 неактивен, пока нет верификации организаций, которая его дает |
|
||||
| `organization_quotas` | скользящие окна 7 дней для приглашений и 24 часа для просмотров разных карточек; E0 10 приглашений и 50 просмотров, E1 40 и 150, E2 100 и 400; E2 неактивен, пока нет верификации организаций, которая его дает; E0-компании одного холдинга делят общий пул, E1 и выше считают отдельно (см. [Квоты компании](COMPANY_QUOTAS.md#пул-холдинга)) |
|
||||
| `assessment`, начальные некалиброванные значения | повтор того же грейда через 30 дней; не более 3 попыток за 180 дней; повышение не чаще одного раза в 90 дней; подтверждение при P_G >= 0.80, высокая уверенность от 0.90; после не менее 8 оцениваемых заданий остановка при P_G >= 0.90 или <= 0.10 или SE <= 0.25; не более 23 оцениваемых заданий плюс 2 seed-задания; практика обязательна |
|
||||
| `identity` | токен подтверждения 24 часа; неподтвержденный аккаунт удаляется через 7 дней после последней регистрации; сессия без активности 24 часа, абсолютный срок 7 дней |
|
||||
| `search_status` | статус "ищу работу" подтверждается каждые 30 дней |
|
||||
@@ -695,7 +695,7 @@ contact_grant относится к паре кандидат-компания
|
||||
- Порядок и округление. Баллы - целые числа в микроединицах (шесть знаков), доли - базисные пункты, произведения точные целые, поэтому одни и те же данные и политика дают один порядок на любой платформе. `main` и `near` сортируются по S, затем Cov (оба по убыванию), затем по внутреннему идентификатору кандидата по возрастанию (затем по коду специализации, который лишь разделяет две записи одного кандидата); `unconfirmed` - по Fit, затем Cov, затем по идентификатору. Идентификатор не покидает сервер, группы не объединяются общей шкалой.
|
||||
- Объяснение. Сводка и признаки строятся из тех же рассчитанных вкладов: для каждой группы навыков `supports` (каждый навык подкреплен измерением не ниже порога), `declared_only` (только заявленные теги), `partial` (смесь или измерения ниже порога) или `gap` (ничего), а также подтвержденная категория, заявленный грейд, совпадение форматов работы с потребностью или фильтром и совместимость зарплаты. Только ограниченные коды, никогда свободный текст, контакт, локация кандидата, значение или минимум зарплаты, проваленная попытка или причина скрытых данных. Неизвестный компонент виден только в `unknown_flags`.
|
||||
- Политика. Поиск читает действующую политику `product` на время приложения и ее раздел `matching`. Политика без раздела дает закрытый отказ с внутренней ошибкой (в перечислении ProblemCode нет кода для временно недоступной зависимости, и новый не добавляется); в логе ошибка говорит, что в действующей политике нет раздела подбора, и называет команду оператора `policy-publish`, при старте backend пишет предупреждение, пока раздела нет, а [DEPLOY.md](DEPLOY.md#политика-подбора-на-стенде) описывает команду. Ответ не называет версию политики, поиск не сохраняется.
|
||||
- Параллельность. Резервирования берут исключительную блокировку организации порта квоты компании. Проверка членства до них держит на той же строке только разделяемую блокировку, и два поиска одной организации взаимно блокировались бы при ее повышении, поэтому поиск сначала берет блокировку организации (`CompanyQuotaRepository.LockOrganization`, документированный порядок; это FOR NO KEY UPDATE, поэтому читатели встают в очередь друг за другом, но блокировка внешнего ключа при собственном скрытии кандидата, которое держит строку кандидата и затем требует строку организации, не блокируется, а само резервирование по-прежнему берет FOR UPDATE в той же транзакции), а оплата одной организации сериализуется. Изменение видимой когорты во время ее блокировки (`ErrConcurrentVisibilityChange`) повторяет весь поиск до трех раз, а записи неудачной попытки откатываются вместе с ней. Чтение карточки (`GetOrganizationCard`) и раздел доказательств (`AuthorizeCategoriesSection`) по той же причине берут эту исключительную блокировку первой, до любой разделяемой: до такого порядка два одновременных чтения карточек одной организации взаимно блокировались (SQLSTATE 40P01). `TestMatchSearchOverHTTP` запускает одновременные чтения карточек, чтения доказательств и поиски одной организации и проверяет отсутствие взаимной блокировки и одну строку квоты на кандидата.
|
||||
- Параллельность. Резервирования берут исключительную блокировку организации порта квоты компании. Проверка членства до них держит на той же строке только разделяемую блокировку, и два поиска одной организации взаимно блокировались бы при ее повышении, поэтому поиск сначала берет блокировку организации (`CompanyQuotaRepository.LockOrganization`, документированный порядок; это FOR NO KEY UPDATE, поэтому читатели встают в очередь друг за другом, но блокировка внешнего ключа при собственном скрытии кандидата, которое держит строку кандидата и затем требует строку организации, не блокируется, а само резервирование по-прежнему берет FOR UPDATE в той же транзакции), а оплата одной организации сериализуется. Изменение видимой когорты во время ее блокировки (`ErrConcurrentVisibilityChange`) повторяет весь поиск до трех раз, а записи неудачной попытки откатываются вместе с ней. Чтение карточки (`GetOrganizationCard`) и раздел доказательств (`AuthorizeCategoriesSection`) по той же причине берут эту исключительную блокировку первой, до любой разделяемой: до такого порядка два одновременных чтения карточек одной организации взаимно блокировались (SQLSTATE 40P01). Для компании на E0 `LockOrganization` сразу после строки организации берет блокировку ее холдинга (общий пул E0 описан в [Квотах компании](COMPANY_QUOTAS.md#пул-холдинга)), поэтому порядок остается прежним: организация, затем холдинг, и холдинг нигде не берется раньше организации. `TestMatchSearchOverHTTP` запускает одновременные чтения карточек, чтения доказательств и поиски одной организации и проверяет отсутствие взаимной блокировки и одну строку квоты на кандидата.
|
||||
- Принятые остаточные риски. `truncated` - один бит о размере видимого банка (он говорит, что существует больше, чем предел или лимит), а время ответа растет с банком, поэтому оба раскрывают владельцу грубый размер. Бит ограничен пределом группы, число не возвращается; риск принят для демонстрации и внесен в вопросы владельцу.
|
||||
- Проверки. Модульные тесты `internal/usecase/matching` (формулы с рассчитанными вручную значениями, равенства и порядок, фильтры, объяснение, обрезка и оплата вывода), `internal/domain/policy_matching_test.go` (круговой проход документа, строгость, проверка значений), `v1/matches_test.go` (отображение и ошибки) и интеграционный тест `TestMatchSearchOverHTTP` на PostgreSQL: скрытые кандидаты и две организации, потребность и ее измененные требования, повторные одинаковые ответы, Backend подтвержден и сети не подтверждены для одного handle, профиль без грейда, опубликованный настоящими операциями профиля, согласия и публикации и убранный отзывом C2, кандидат один в своей когорте, отсутствие контактов и идентификаторов в теле, оплата и история доступа за поиск, организация с лимитом меньше ее банка, предел группы, пакетное чтение доказательств, два одновременных поиска под одним лимитом, демонстрационный предел группы, таксономия политики, отказы доступа и политика без раздела.
|
||||
|
||||
@@ -861,20 +861,22 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
|
||||
- `organizations`: UUIDv7 `id` (это `org_id` каждого пути организации), `name` (1-200 символов, граница снимка в согласии), `description`, `sphere` (свободный текст; таксономии в PRD нет), четыре столбца публичных контактов (`contact_website`, `contact_email`, `contact_phone`, `contact_telegram`), столбцы проверки `verification_level`, `verification_basis` и `verification_changed_at`, `version` профиля и времена. Каждый текстовый столбец имеет CHECK с тем же форматом и границами, что и контракт (без пробелов и управляющих символов по краям, сайт по `https` без учетных данных).
|
||||
- `organization_representatives`: `organization_id`, `ordinal` (от 0 до 9, то есть не более десяти), `name` и `job_title`; удаляется вместе со строкой организации. Список заменяется целиком при обновлении профиля.
|
||||
- `memberships`: UUIDv7 `id`, `organization_id`, `user_id`, `role`, `state` и времена. `UNIQUE (user_id, organization_id)` допускает одно членство на пару в любом состоянии, а `UNIQUE (organization_id, id)` - цель составных внешних ключей, которыми поздние таблицы (назначения потребностей) привязывают членство к его организации. Оба внешних ключа - `ON DELETE RESTRICT`.
|
||||
- `holdings`: UUIDv7 `id` (внутренний, API его не показывает), `founder_account_id` - аккаунт, создавший первую организацию холдинга, с `UNIQUE` и внешним ключом на `users` с `ON DELETE RESTRICT`, и `created_at`. Столбец `organizations.holding_id` обязателен, ссылается на холдинг с `ON DELETE RESTRICT` и имеет индекс; миграция `00041_create_holdings.sql` заполняет его по аккаунту самого раннего членства организации.
|
||||
|
||||
Решения:
|
||||
|
||||
- Активный контекст. Это не атрибут серверной сессии. Организация - это `org_id` в пути, а сервер выводит право из активного членства на каждом запросе, поэтому удаление, приостановка или выход закрывают следующее чтение без чего-либо, что нужно сбрасывать. `ListMyOrganizations` - справочник, из которого клиент выбирает; запоминание последнего выбора - удобство браузера. Контекст берется только из активных членств вызывающего, а прекращенное членство сразу закрывает чтение. Переключение очищает клиентские запросы с областью организации.
|
||||
- Роль и состояние только в членстве. `OrganizationRole` - `owner`, `recruiter`, `hiring_manager` или `technical_expert` (2.2, Q3 и матрица FR07 в PRD), а `MembershipState` - `active`, `suspended`, `removed` или `left`; каждое задано CHECK, а не enum PostgreSQL, поэтому новое значение - изменение ограничения в миграции. Состояния `invited` нет: в 6.4 PRD `MemberInvite` - отдельная сущность, приглашение на email, у которого еще может не быть аккаунта, а строка членства появляется, когда владелец адреса его принимает. В `organizations` нет столбца роли, владельца или участника (интеграционный тест читает каталог, чтобы это доказать), а в `Organization`, `OrganizationCreate` и `OrganizationUpdate` нет такого поля. Компанией управляет только владелец (`OrganizationRole.CanManageOrganization`); остальная матрица применяется операциями, которыми она управляет, а в MVP остальные роли ничего не дают.
|
||||
- Уровень проверки. `verification_level` - от `e0` до `e3` с `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), а один CHECK связывает каждый уровень с его основаниями. Столбцы отделены от профиля: `UpdateOrganizationProfile` никогда их не называет, `domain.NewOrganization` не может выбрать уровень и начинает каждую организацию с `e0` на основании `confirmed_email`, `Organization.ApplyProfile` сохраняет проверку, а в контракте нет операции или поля запроса, которые ее задают. Тест обновляет профиль после того, как процесс сдвинул уровень, и проверяет, что он остается. E1-E3 задаются процессами проверки, которых еще нет; запланированный процесс проверки добавляет E0/E1 с доказательствами, областью действия и историей только на добавление и будет обновлять эти столбцы вместе со строкой истории, а сначала обязан записать историю из текущей строки каждой существующей организации (уровень, основание и время как сохранены), чтобы в истории не было разрыва до первого процесса. `OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням квот продуктовой политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику (механизм квот читает ступень и обязан отказывать по умолчанию для организации с `e3`: квота не выдается, действие отклоняется, возврата на другую ступень нет).
|
||||
- Холдинг. Организации одного аккаунта-основателя образуют холдинг. `CreateWithOwner` в той же транзакции сохраняет организацию в холдинге владельца и создает холдинг при первой организации аккаунта (`INSERT ... ON CONFLICT (founder_account_id) DO NOTHING`, затем чтение), поэтому параллельные создания одного аккаунта дают один холдинг. Холдинг не несет профиля и прав: он задает только область общего пула E0 квот (приглашения и просмотры карточек). Число организаций на аккаунт не ограничено; слияние холдингов разных владельцев не моделируется. Правила пула и блокировок - в [Квотах компании](COMPANY_QUOTAS.md#пул-холдинга).
|
||||
- У организации есть владелец. Отложенный constraint trigger (`organizations_owner_required`, SQLSTATE 23514) при фиксации отказывает организации без членства `owner` в состоянии `active`, поэтому создание организации без владельца падает, каким бы кодом ее ни вставили, а `CreateWithOwner` сохраняет организацию, представителей и владельца в одной транзакции. Удаление или понижение последнего владельца позже - правило управления участниками, а не этого ограничения, которое иначе блокировало бы решение платформы о недобросовестной организации.
|
||||
- Обновление. `UpdateProfile` - один оператор, который применяется только когда сохраненная версия равна версии, прочитанной вызывающим, и увеличивает ее на единицу. Тот же оператор требует активного членства исполнителя с управляющей ролью (роли берутся из `domain.ManagerRoles`, а не из SQL), поэтому членство, закончившееся после чтения вызывающего, все равно останавливает запись. Если оператор ничего не нашел, адаптер читает членство и отвечает `ErrOrganizationNotFound` (неизвестная организация или нет активного членства), `ErrOrganizationManagerRequired` или `ErrOrganizationVersionConflict` в этом порядке, поэтому устаревшая версия ничего не сообщает постороннему. Затем список представителей заменяется в той же транзакции под блокировкой строки обновления. Оператор блокирует строку организации (`FOR UPDATE`), а затем строку членства исполнителя `FOR SHARE`, поэтому отзыв, зафиксированный, пока оператор ждет блокировку членства, проверяется заново и останавливает запись (интеграционный тест держит отзыв открытым, ставит обновление за ним в очередь и фиксирует отзыв). Порядок блокировок у каждого писателя: сначала организации, затем членства; управление участниками, которое меняет членство и организацию вместе, и tenant-репозиторий обязаны брать блокировки в этом порядке, иначе две транзакции могут взаимно заблокироваться.
|
||||
- Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала согласий создавать настоящие организации, а ключу `invitation_id` нужны настоящие приглашения; оба появятся с принятием приглашения, первым писателем строк C4 с настоящим приглашением. Таблицы приглашений (миграция 00037) и потребности ссылаются на организации, аккаунты и версии политики с `ON DELETE RESTRICT`, поэтому организацию с потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD).
|
||||
- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять ограниченной очисткой после окна повтора; физическое удаление может произойти позже при возобновлении создания организаций; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (для создания организаций и применения квот нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации).
|
||||
- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять ограниченной очисткой после окна повтора; физическое удаление может произойти позже при возобновлении создания организаций; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и решение владельца о числе организаций на аккаунт (лимита нет, E0-квоты холдинга общие) описаны в [api/README.md](../../api/README.md#организации).
|
||||
|
||||
Что гарантируют порты (`outbound.OrganizationRepositories`, доступны только через `UnitOfWork`, потому что запись требует транзакции):
|
||||
|
||||
- `Organizations().CreateWithOwner` сохраняет организацию и членство владельца и проверяет, что владелец - активное членство `owner` именно этой организации. Неизвестный аккаунт возвращает `ErrUserNotFound` и прерывает внешнюю транзакцию.
|
||||
- `Organizations().CreateWithOwner` сохраняет организацию и членство владельца и проверяет, что владелец - активное членство `owner` именно этой организации. Организация попадает в холдинг аккаунта владельца; холдинг создается в той же транзакции, если его еще нет. Неизвестный аккаунт возвращает `ErrUserNotFound` и прерывает внешнюю транзакцию.
|
||||
- `GetForMember` читает организацию, ее представителей (собранных в JSON тем же оператором) и активное членство вызывающего из одного снимка и возвращает их либо `ErrOrganizationNotFound` одинаково для неизвестной организации, аккаунта без членства и участника в состоянии `suspended`, `removed` или `left`. `ListForUser` постранично отдает активные организации одного аккаунта от нового членства к старому с идентификатором организации как разрешением ничьей. `UpdateProfile` описан выше.
|
||||
- `Memberships().Insert` возвращает `ErrMembershipExists` для повторной пары в любом состоянии, `ErrOrganizationNotFound` для неизвестной организации и `ErrUserNotFound` для неизвестного аккаунта; `Get` возвращает членство в любом состоянии или `ErrMembershipNotFound`, а вызывающий проверяет `GrantsAccess`. Метода, который меняет роль или состояние, пока нет.
|
||||
|
||||
@@ -941,13 +943,13 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
|
||||
|
||||
### Черновики приглашений
|
||||
|
||||
Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет; отправка описана в [Отправке приглашений](#отправка-приглашений). Отзыв, повышение вилки, чтение контактов, принятие и отмена участия после общих проверок по-прежнему отвечают 501; чтение, просмотр и отказ кандидата описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата). Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`.
|
||||
Реализовано: сторона организации в черновике приглашения, то есть `ListOrganizationInvitations`, `CreateOrganizationInvitation`, `GetOrganizationInvitation` и `UpdateOrganizationInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Кандидат черновик не видит: входящей записи, события и списания квоты нет; отправка описана в [Отправке приглашений](#отправка-приглашений). Отзыв, повышение вилки, чтение контактов и отмена участия после общих проверок по-прежнему отвечают 501; чтение, просмотр, отказ и принятие кандидата описаны в [Просмотре и отказе кандидата](#просмотр-и-отказ-кандидата) и [Принятии кандидатом](#принятие-кандидатом). Код: `domain/salary_range.go`, `domain/invitation_terms.go`, `domain/invitation.go`, `usecase/invitation/`, `adapter/primary/http/v1/invitation.go`, адаптер PostgreSQL `adapter/secondary/postgres/invitations.go` с `db/queries/invitations.sql` и миграция `00037_create_invitations.sql`.
|
||||
|
||||
Таблицы:
|
||||
|
||||
- `invitations`: UUIDv7 `id`, `organization_id`, внутренний `candidate_id` (его не сериализуют, не логируют и не печатают), необязательная связь с потребностью (`need_id` с `need_requirements_version`, привязанные составными внешними ключами к сохраненной версии потребности той же организации), `state` (все четырнадцать состояний контракта, поэтому последующим операциям не нужно менять ограничение), `expiry_reason`, `version`, `terms_version`, `response_period_days` (3, 7 или 14), `policy_version_id` (версия продуктовой политики, разрешившая срок), `response_deadline_at`, `salary_raise_used`, `created_by`, а также `created_at`, `updated_at`, `delivered_at`, `viewed_at`, `responded_at`. Ограничения CHECK связывают дедлайн с доставкой (оба заданы или оба null), оставляют черновик без доставки, просмотра, ответа и повышения и связывают причину истечения с состоянием. Триггер хранит неизменными столбцы идентичности, требует, чтобы каждый UPDATE увеличивал `version` ровно на единицу, а `terms_version` не более чем на единицу, и не дает отменить повышение или сдвинуть доставку, дедлайн и срок после доставки. Второй триггер запрещает DELETE. Внешние ключи на организации, аккаунты и версии политики - `ON DELETE RESTRICT`, поэтому аккаунт с приглашениями нельзя удалить, пока процедура удаления их не закроет.
|
||||
- `invitation_terms_versions`: `(invitation_id, version)`, условия в виде снимка JSONB и вилка еще раз в типизированных столбцах (`salary_from`, `salary_to`, `salary_currency`, `salary_period`, `salary_tax_basis`). Ограничения повторяют денежные правила в целых числах: обе границы от 1000 до 100 000 000 рублей с шагом 1000, `salary_from < salary_to`, `20 * (B - A) >= A + B` и `5 * (B - A) <= A + B` (ширина 10-40% от середины), RUB, месяц и `net` или `gross`. Снимок обязан содержать все двенадцать условий, а его вилка - совпадать с типизированными столбцами. Триггер запрещает UPDATE и DELETE: версия условий неизменяема, изменение добавляет следующую версию. Приглашение указывает на текущую версию отложенным составным внешним ключом, поэтому первая версия вставляется в той же транзакции.
|
||||
- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created`, `draft_updated`, с миграции 00038 `delivered`, с миграции 00039 `viewed` и `declined`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются.
|
||||
- `invitation_events`: одно событие аудита на каждую зафиксированную версию приглашения (`UNIQUE (invitation_id, version)`) с видом (`draft_created`, `draft_updated`, с миграции 00038 `delivered`, с миграции 00039 `viewed` и `declined`, с миграции 00040 `accepted`), версией и версией условий, исполнителем, изменившимися частями (`terms`, `need`, `response_period_days`) и временем. Содержимого в нем нет, записи только добавляются.
|
||||
- `invitation_creation_results`: исходный ответ идемпотентного создания, привязанный к общей записи идемпотентности и удаляемый вместе с ней. В нем условия, псевдоним и нет идентификатора кандидата.
|
||||
|
||||
Решения:
|
||||
@@ -962,7 +964,7 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
|
||||
- Блокировки. Создание и изменение сначала берут исключительную блокировку организации (`CompanyQuotaRepository.LockOrganization`), как чтение карточки и поиск, и только потом разделяемую блокировку проверки членства, блокировки когорты при создании или блокировку строки приглашения при изменении. Поэтому команды одной организации встают в очередь, а не блокируют друг друга при повышении блокировки, и следующая команда, которая тоже списывает ресурсы организации, например отправка, сохраняет тот же порядок. Изменение блокирует строку приглашения отдельным запросом (`LockInvitation`) и читает ее после: блокирующее чтение с соединением таблицы условий после ожидания чужой фиксации сопоставило бы новый `terms_version` со строкой условий, взятой до ожидания, и ничего не нашло бы. Создание повторяется ограниченное число раз, если видимая когорта изменилась во время блокировки.
|
||||
- Индикатор. `salary_fit` всегда `not_available`, а `contact_access` - `not_granted` без полей. Индикатору нужен минимум кандидата, а его вычисление до появления лимита из трех установок в день и семидневного отключения позволило бы организации подбирать минимум правками черновика, поэтому пока не считается и не применяется ни то ни другое.
|
||||
|
||||
Как подключаются следующие операции: правила пары читают индекс по организации и кандидату. Контактное разрешение, ключ C4 на `invitations` и ключи журнала согласий на `organizations` и `invitations` появятся вместе с принятием, первым писателем строк C4 с настоящим приглашением.
|
||||
Как подключаются следующие операции: правила пары читают индекс по организации и кандидату. Контактное разрешение появляется с принятием ([Принятие кандидатом](#принятие-кандидатом)). Колонки C4 журнала согласий пока не имеют внешних ключей на `organizations` и `invitations`; это последующая задача.
|
||||
|
||||
Не реализовано: лимит вилки и счетчик отключения, индикатор относительно минимума кандидата, предел ожидающих приглашений на потребность, повышение, отзыв, сторона кандидата сверх списка приглашений, карточка организации для кандидата, чтение прежних версий условий и обработка приглашений при удалении аккаунта. Матрица ролей и назначений сверх владельца запланирована.
|
||||
|
||||
@@ -997,16 +999,34 @@ Middleware `backend/internal/adapter/primary/http/company_context.go` прове
|
||||
- Приватность отказа. Организация читает только `declined` и `responded_at`: ни одна ее операция не читает `invitation_declines`, а событие аудита не называет причину. Комментарий не логируется, не попадает в уведомления и не копируется в сохраненный исход; кандидат читает причину и комментарий обратно в `decline`.
|
||||
- Порядок проверок после границы: кандидат (403), ключ (422 или повтор), приглашение (404, сохраняется), тот же отказ на отклоненном приглашении (200 с новым ключом или старой версией), другая причина или комментарий на отклоненном приглашении, иное терминальное состояние или прошедший срок (409 при любой версии, сохраняется), версия (412, не сохраняется), затем состояние без открытого ответа (409, сохраняется). `invitation_decline_results` хранит только исход и приглашение: отклоненное приглашение и его отказ не меняются, поэтому повтор собирает тот же ответ, а комментарий хранится в одном месте.
|
||||
- Срок. Истечение пока не реализовано, поэтому ни чтение, ни команда не выполняют переход в `expired`. Просмотр в момент срока и позже ничего не меняет, а отказ в момент срока и позже отвечает 409 `state_conflict`, как контракт требует для опоздавшей команды; приглашение остается `delivered` или `viewed` с прошедшим сроком, пока не появится истечение. Условные UPDATE повторяют проверку срока, поэтому команда не пересечет его между проверкой и записью.
|
||||
- Согласие и разрешение. Принятие не реализовано, поэтому принять приглашение сейчас нельзя, и `contact_consent` и `contact_grant` всегда null, как требует контракт, когда принятие невозможно. Оба поля появятся вместе с `AcceptMyInvitation`.
|
||||
- Согласие и разрешение. Отказ не создает ни согласия, ни разрешения, поэтому после отказа `contact_consent` и `contact_grant` равны null. Принятие описано в [Принятии кандидатом](#принятие-кандидатом).
|
||||
- Скрытие. Чтение кандидата показывает организацию-отправителя и после того, как кандидат скрыл от нее профиль: скрытие не дает организации видеть кандидата, а кандидату нужно знать, кто прислал предложение, чтобы ответить. Исходящее содержимое, наоборот, следует скрытию: уведомление о приглашении во входящих теряет содержимое (`ResolveInvitationNotice`).
|
||||
- Блокировки. Команда кандидата блокирует только строку приглашения (`LockCandidateInvitation`) после собственной записи идемпотентности кандидата и никогда не блокирует организацию. Команда организации берет сначала блокировку организации, а потом строку приглашения, поэтому порядки не пересекаются: команда кандидата не ждет блокировку организации, удерживая строку.
|
||||
- Правила базы миграции 00039: виды событий `viewed` и `declined` без измененных полей; `invitations_answer_matches_state` (у доставленного приглашения нет просмотра и ответа, у просмотренного есть просмотр, у отклоненного есть ответ, и ни то ни другое не раньше доставки); триггер `invitations_guard_answer`, который не дает сдвинуть или отменить просмотр или ответ и выйти из `declined`; `invitation_declines` с известными причинами, границей комментария, триггером, который привязывает строку к отклоненному приглашению с тем же моментом ответа, и запретом UPDATE и DELETE; отложенный ограничивающий триггер `invitations_require_decline`, чтобы отклоненное приглашение без записи отказа не зафиксировалось. Откат миграции отказывает, пока есть просмотр, отказ или сохраненный исход.
|
||||
- Уведомление. В контракте нет вида уведомления об ответе, поэтому организация пока не получает записи во входящих о просмотре или отказе; состояние она видит в своем списке приглашений. Уведомление об ответе запланировано как изменение контракта.
|
||||
|
||||
Не реализовано: истечение по сроку и его применение при чтении, принятие с C4 и контактное разрешение, отмена участия, встречное предложение, которое дало бы `counter`, агрегаты причин отказа с минимальным размером группы, метрики отзывчивости, 30-дневная пауза после отказа и уведомление организации об ответе.
|
||||
Не реализовано: истечение по сроку и его применение при чтении, отмена участия, встречное предложение, которое дало бы `counter`, агрегаты причин отказа с минимальным размером группы, метрики отзывчивости, 30-дневная пауза после отказа и уведомление организации об ответе.
|
||||
|
||||
Тесты: `domain/invitation_answer_test.go` (просмотр только из `delivered` до срока, отказ из `delivered`, `viewed` и `counter`, отклонение терминальных и опоздавших приглашений, правила комментария, правила сохраненного ответа, маскирование), `usecase/invitation/answer_test.go` (чтение без побочного эффекта, сохранение срока, повторы, порядок проверок, чужие вызывающие, неверные комментарии), `adapter/primary/http/v1/invitation_candidate_test.go` (статусы и ответ без данных кандидата) и интеграционные `TestCandidateInvitationViewAndDeclineOverHTTP` (чтение и просмотр с тем же сроком, одновременные просмотры с одним событием, отказ с `other` без комментария и без согласия C4, сохраненное событие ответа, повторы и конфликты, комментарий скрыт от организации и аудита, чужие кандидаты и работодатели, CSRF и Origin, скрытие, устаревшая версия, опоздавшая команда) и `TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback`.
|
||||
|
||||
### Принятие кандидатом
|
||||
|
||||
Реализовано: `AcceptMyInvitation` ([контракт](../../api/README.md#приглашения-и-контактные-разрешения)). Код: `domain/invitation_answer.go` (`Accept`), `domain/contact_grant.go`, `usecase/invitation/accept.go` и `view.go` (вид кандидата с предложением согласия и разрешением), `usecase/consent` (`GrantContact`, запись C4), HTTP-обработчик `adapter/primary/http/v1/invitation_candidate.go`, адаптер `adapter/secondary/postgres/invitation_accept.go` с `db/queries/invitation_answers.sql` и `db/queries/contact_grants.sql`, миграция `00040_accept_invitations.sql`.
|
||||
|
||||
- Одна транзакция. Кандидат принимает текущие условия с согласием C4 из `delivered` или `viewed` до срока, при версии приглашения и версии условий, которые он прочитал. Транзакция берет собственную запись идемпотентности, затем только строку приглашения (`LockCandidateInvitation`) и далее по порядку: переводит приглашение в `accepted` одним условным UPDATE (`responded_at` - время ответа, `version` плюс один; срок и условия сохраняются), записывает согласие C4 в журнал согласий через `consent.Service.GrantContact` (опубликованный текст, название организации в том виде, в котором его показали, выбранные поля, приглашение и его версия условий), сохраняет разрешение ровно на эти поля и добавляет событие аудита `accepted`, которое не называет полей. Сбой любого шага откатывает всю транзакцию.
|
||||
- Порядок проверок. Порядок контракта: кандидат (403), ключ (422 или повтор), приглашение (404, сохраняется), повтор принятого приглашения (200), терминальное состояние или прошедший срок (409 `state_conflict`, сохраняется), версии (412 `version_conflict`, не сохраняется), любое состояние, кроме `delivered` и `viewed` (409, сохраняется), правила согласия (400 по указателю `/consent_c4/text_version` для текста, который не опубликован, и `/consent_c4/fields/N` для вида контакта, которого нет в профиле). Вид считается имеющимся, если профиль хранит его как подтвержденный claim; предположение, которое никто не подтвердил, не раскрывается.
|
||||
- Повторы. Принятое приглашение, у которого разрешение имеет ту же версию условий и тот же набор полей, отвечает 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` как не выданный.
|
||||
- Конкурентность. Командой кандидата блокировка организации не берется. Два конкурентных принятия одной версии дают один переход: второе ждет строку и затем отвечает как повтор - 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.
|
||||
|
||||
## Frontend
|
||||
|
||||
Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности.
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
|
||||
Вызывайте `companyquota.Service.ReserveInvitation` или `ReserveCardView`, передавая репозитории текущего `outbound.UnitOfWork`. Репозиторий из `UnitOfWork.CompanyQuotas()` привязан к транзакции и не должен сохраняться после нее. Резервирование квоты и связанное с ним бизнес-изменение выполняются в одной транзакции, чтобы откат отменял обе записи. Сервис создается с часами приложения и один раз читает действующую политику на операцию.
|
||||
|
||||
Проверка доступа к компании остается ответственностью вызывающего кода. В той же транзакции нужно повторно проверить активное членство и права владельца. Писатели соблюдают такой порядок блокировок: компания, активное членство, запись приглашения или видимости, затем использование квоты. Адаптер квот первым блокирует строку компании; вызывающий код может повторно заблокировать ту же строку в этой транзакции. Не меняйте этот порядок на обратный.
|
||||
Проверка доступа к компании остается ответственностью вызывающего кода. В той же транзакции нужно повторно проверить активное членство и права владельца. Писатели соблюдают такой порядок блокировок: компания, для компании на E0 - ее холдинг (см. [Пул холдинга](#пул-холдинга)), активное членство, запись приглашения или видимости, затем использование квоты. Адаптер квот первым блокирует строку компании, а для компании на E0 сразу после нее - строку холдинга; вызывающий код может повторно заблокировать эти строки в этой транзакции. Не меняйте этот порядок на обратный.
|
||||
|
||||
Блокировка компании сериализует параллельные резервирования. Пока она удерживается, адаптер проверяет существующую запись, считает активное окно и добавляет или обновляет использование. Решение либо разрешает операцию, либо запрещает ее; повторное использование означает разрешение. При отказе запись использования не создается, а `RetryAt` содержит ближайший момент освобождения места по истечении активной записи.
|
||||
Блокировка компании сериализует параллельные резервирования одной компании, а блокировка холдинга сериализует общий пул E0. Пока они удерживаются, адаптер проверяет существующую запись, считает активное окно и добавляет или обновляет использование. Решение либо разрешает операцию, либо запрещает ее; повторное использование означает разрешение. При отказе запись использования не создается, а `RetryAt` содержит ближайший момент освобождения места по истечении активной записи.
|
||||
|
||||
## Окна и повторы
|
||||
|
||||
@@ -24,10 +24,24 @@
|
||||
|
||||
Просмотр карточки определяется парой `(organization_id, candidate_id)`. Повторный просмотр того же кандидата в активном окне не расходует еще один слот уникального просмотра. Время `last_seen_at` обновляется монотонно: часы приложения, переведенные назад, не уменьшают сохраненное время.
|
||||
|
||||
Для активного окна используется строгое сравнение с границей. Запись ровно в момент `now - window` уже истекла. Использование приглашений считается за скользящие 7 дней, просмотры карточек - за скользящие 24 часа. Лимиты общие для запросов и пользователей компании.
|
||||
Для активного окна используется строгое сравнение с границей. Запись ровно в момент `now - window` уже истекла. Использование приглашений считается за скользящие 7 дней, просмотры карточек - за скользящие 24 часа. Лимиты общие для запросов и пользователей компании; исключение - компания на E0, которая делит свои лимиты с остальными E0-компаниями своего холдинга (см. [Пул холдинга](#пул-холдинга)).
|
||||
|
||||
Истекшие записи просмотров удаляются партиями максимум по 100 только после успешного разрешенного резервирования. Истечение окна логическое; очистка не обещает удаление в точно заданный момент. При удалении аккаунта кандидата его запись просмотра удаляется каскадно. При удалении компании удаляются обе таблицы квот. Для использования приглашений нет внешнего ключа на приглашение, поэтому будущее удаление приглашения не сможет удалить ключ идемпотентности.
|
||||
|
||||
## Пул холдинга
|
||||
|
||||
Холдинг объединяет компании, созданные одним аккаунтом-основателем; его хранит таблица `holdings`, миграция `00041_create_holdings.sql`. `CreateWithOwner` сохраняет каждую новую компанию в холдинге аккаунта-владельца в той же транзакции. Холдинг аккаунта создается с его первой компанией, а параллельные создания одного аккаунта дают один холдинг: вставка игнорирует уже существующий ключ основателя, а затем транзакция читает сохраненный холдинг. Холдинг не несет ни профиля, ни права; его единственный эффект - общий пул E0.
|
||||
|
||||
Лимиты E0 (в подключенной демо-политике 10 приглашений за 7 дней и 50 уникальных просмотров карточек за 24 часа) общие для E0-компаний одного холдинга. Резервирование E0 считает строки использования всех компаний холдинга, чей уровень проверки в момент подсчета равен E0. Каждая строка использования остается за компанией, которая ее потребила, а использование компании, которая уже не E0, выходит из общего пула. Компания на E1 и выше считает только свое использование и имеет собственный пул, поэтому ее использование не входит в пул E0.
|
||||
|
||||
Идемпотентность остается на уровне компании. Тот же ID приглашения или повторный просмотр одного кандидата той же компанией внутри окна не списываются второй раз. Один кандидат, просмотренный двумя компаниями одного холдинга, - два списания общего пула.
|
||||
|
||||
Блокировки: для компании на E0 `CompanyQuotaRepository.LockOrganization` и каждое резервирование берут строку холдинга с `FOR NO KEY UPDATE` сразу после строки компании. Поэтому резервирования одного пула идут друг за другом, а второе считает использование, которое первое уже зафиксировало: подсчет начинается после блокировки холдинга. Каждый писатель берет блокировку компании раньше блокировки холдинга, а ни один код не берет блокировку компании, удерживая блокировку холдинга, поэтому блокировка холдинга не добавляет цикл в документированный порядок. Цена: поиски E0, чтения карточек и черновики или отправки приглашений одного холдинга ждут друг друга, пока открыты их транзакции; поиск держит блокировку на всю транзакцию ранжирования.
|
||||
|
||||
Миграция дает каждому основателю один холдинг: основатель компании - аккаунт ее самого раннего членства, то есть владельца, созданного вместе с компанией, а холдинг датируется первой компанией. Откат отказывает, пока холдинг объединяет несколько компаний, потому что схема без холдингов не сохранила бы их общий пул E0. Слияние холдингов разных владельцев не входит в объем.
|
||||
|
||||
## Проверки
|
||||
|
||||
`TestHoldings` в `backend/integration_test/holding_test.go` проверяет общий пул E0 двух компаний одного аккаунта при отдельном пуле компании на E1, отдельный холдинг второго аккаунта, выход использования из пула при повышении компании, параллельные резервирования двух компаний, которые никогда не превышают общий лимит, параллельные создания, заканчивающиеся одним холдингом, и отказ создания с неизвестным основателем. `TestHoldingsMigrationBackfillsFoundersAndGuardsRollback` в `backend/integration_test/holding_migration_test.go` проверяет заполнение и защищенный откат миграции.
|
||||
|
||||
`TestCompanyQuota` в `backend/integration_test/company_quota_test.go` проверяет настоящий адаптер PostgreSQL на изолированной базе. Тест покрывает параллельные резервирования E0, границы E0 и E1, точные границы окон и `RetryAt`, повтор того же ID приглашения, повторный просмотр в рамках компании, монотонное обновление, откат, изменение снимка политики или компании, разрешенное резервирование при включенной E2 и сохраненной проверке компании, отказ для поддельного снимка E2 при сохраненном E0, отказ для выключенной E2 и E3, а также очистку после удаления кандидата. Проверки доставки приглашения нет, поскольку этот процесс пока не реализован.
|
||||
Reference in new issue
Block a user