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.
|
||||
Reference in new issue
Block a user