chore: remove backlog references from code and documentation
This commit is contained in:
1 parent
0529601021
commit
8e7ce8d71c
129 files changed
+699
-701
No files matched your search
+57
-57
@@ -102,7 +102,7 @@ The ML service answers its errors with the same `Problem` schema. Its `ProblemCo
|
||||
|
||||
### Identity: sessions, cookie, and CSRF
|
||||
|
||||
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount` and `ResendEmailVerification` are implemented (TASK-053); the other public operations still answer 501 `not_implemented` after request validation, and the backend's `v1.DenyAllSecurity` rejects every session, so operations that require one answer 401 `unauthenticated`. Values marked as planned come from configuration in TASK-054 to TASK-056.
|
||||
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount` and `ResendEmailVerification` are implemented; the other public operations still answer 501 `not_implemented` after request validation, and the backend's `v1.DenyAllSecurity` rejects every session, so operations that require one answer 401 `unauthenticated`. Values marked as planned come from the planned email confirmation, login, and session configuration.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -121,8 +121,8 @@ Registration and verification:
|
||||
|
||||
- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email, and login answers 401 `invalid_credentials` for both an unknown email and a wrong password.
|
||||
- Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists.
|
||||
- Registering an unverified email again never changes the password hash, the scenario, or the onboarding step of the account row. Every registration, the first and each repeat, stores its own pending credentials (password hash and scenario) on its own verification token, replaces the C1 record, advances the registration version, and invalidates every earlier verification token. Confirming a token (`ConfirmEmail`, TASK-054) must apply the pending credentials of that token only, and must require the password of that registration to confirm a token that carries pending credentials; the current `EmailVerificationRequest` has no password field, so TASK-054 changes the contract. This stops a pre-registration with someone else's password from being adopted by the address owner who clicks the attacker's link, and the reverse. The account row of an unverified account cannot be used to sign in: login (TASK-055) refuses every unverified account and never compares a password with the row or the pending credentials of an unverified account. For a verified email nothing changes; the server sends nothing.
|
||||
- Implementation of registration and resend (TASK-053). Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). Limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, and the limiter keys. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-and-verification-resend).
|
||||
- Registering an unverified email again never changes the password hash, the scenario, or the onboarding step of the account row. Every registration, the first and each repeat, stores its own pending credentials (password hash and scenario) on its own verification token, replaces the C1 record, advances the registration version, and invalidates every earlier verification token. Confirming a token (`ConfirmEmail`) must apply the pending credentials of that token only, and must require the password of that registration to confirm a token that carries pending credentials; the current `EmailVerificationRequest` has no password field, so email confirmation requires a contract change. This stops a pre-registration with someone else's password from being adopted by the address owner who clicks the attacker's link, and the reverse. The account row of an unverified account cannot be used to sign in: login refuses every unverified account and never compares a password with the row or the pending credentials of an unverified account. For a verified email nothing changes; the server sends nothing.
|
||||
- Implementation of registration and resend. Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). Limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, and the limiter keys. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-and-verification-resend).
|
||||
- Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version with the pending credentials of that registration, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions).
|
||||
- Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check.
|
||||
- The verification link is `<frontend origin>/verify-email#token=<token>`. The page removes the fragment with `history.replaceState` and posts the token only after an explicit user action, so the token stays out of server logs and Referer headers and a link scanner does not consume it. Verification does not start a session.
|
||||
@@ -139,11 +139,11 @@ Sessions and CSRF:
|
||||
|
||||
- The `sessionCookie` scheme is the cookie `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps sessions in PostgreSQL and takes the caller only from the session. Only a verified account gets a session. Login revokes the session the request carried and issues a new identifier and CSRF token; logout revokes the session server-side. Planned timeouts: 24 hours idle and 7 days absolute; activity extends only the idle deadline. Both come from the versioned product policy, not from configuration.
|
||||
- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the session-bound token from `Session.csrf_token`. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`.
|
||||
- Every unsafe request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned, TASK-056; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). Public identity operations are rate-limited (429 with `Retry-After`).
|
||||
- Every unsafe request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). Public identity operations are rate-limited (429 with `Retry-After`).
|
||||
- Responses with a session or account carry `Cache-Control: no-store`.
|
||||
- The root `security` requires `sessionCookie`, so an operation that does not declare `security: []` is protected by default.
|
||||
|
||||
How the generated server (ogen v1.24.0) evaluates the schemes, and the mapping planned for TASK-056, are documented on `v1.DenyAllSecurity` and pinned by `TestGeneratedServerSecurityOrder`:
|
||||
How the generated server (ogen v1.24.0) evaluates the schemes, and the mapping planned for session authentication, are documented on `v1.DenyAllSecurity` and pinned by `TestGeneratedServerSecurityOrder`:
|
||||
|
||||
- It calls `HandleSessionCookie` before `HandleSessionCsrf` and passes the context returned by a successful call on. An absent value (no cookie, empty `X-CSRF-Token`) does not call the handler, and a handler that returns `ogenerrors.ErrSkipServerSecurity` counts as unsatisfied; both continue with the next scheme, so `HandleSessionCsrf` also runs without a cookie, with the original context.
|
||||
- Any other handler error stops evaluation and reaches `NewError` as a `SecurityError` whose `Security` is `SessionCookie` or `SessionCsrf`. An unsatisfied requirement reaches `NewError` as a `SecurityError` with `ErrSecurityRequirementIsNotSatisfied` and no `Security` field.
|
||||
@@ -179,7 +179,7 @@ Questionnaire:
|
||||
|
||||
### Candidate profile
|
||||
|
||||
The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD, TASK-066). The operations are in the contract and the business logic is not implemented yet, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` once a session is accepted and the schema is valid.
|
||||
The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD). The operations are in the contract and the business logic is not implemented yet, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` once a session is accepted and the schema is valid.
|
||||
|
||||
| Method and path | operationId | Protection | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -215,11 +215,11 @@ No file, ML, or FSP:
|
||||
|
||||
- The profile is filled in entirely by hand. No field requires a resume, ML extraction, or an FSP account, and the migration and queries create no mandatory link to a file, ML, or FSP. Resume upload and linking an FSP ID are planned additive features; they will add their own fields and sources without changing these.
|
||||
|
||||
Relation to the questionnaire (TASK-150):
|
||||
Relation to the questionnaire:
|
||||
|
||||
- The questionnaire (`/me/questionnaire`) names at most two specializations for assessment; the profile is what the candidate presents about themselves. Same-named concepts are not duplicated under different meanings: the self-assessed grade and the stack are the same claim in two places (in the questionnaire for the start of the assessment and per specialization, in the profile for display), saved separately, and the server never copies one into the other; the total months of experience in the questionnaire and the experience entries of the profile are different claims; work formats live only in the questionnaire, while place, relocation, and salary live only in the profile. The schema descriptions of both sides refer to each other.
|
||||
|
||||
Storage (migration 00013, TASK-066): `candidate_profiles` (the profile row: `user_id`, `version`, times) and `candidate_profile_claims` (one row per stored claim: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). A missing row means `unknown`. Each kind of value has a CHECK for the format and bounds of the contract; `trust_level` is always 0; the tables have no file column, no FSP column, and no confirmed grade. Details are in [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-profile).
|
||||
Storage (migration 00013): `candidate_profiles` (the profile row: `user_id`, `version`, times) and `candidate_profile_claims` (one row per stored claim: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). A missing row means `unknown`. Each kind of value has a CHECK for the format and bounds of the contract; `trust_level` is always 0; the tables have no file column, no FSP column, and no confirmed grade. Details are in [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-profile).
|
||||
|
||||
Open questions for the product owner and legal:
|
||||
|
||||
@@ -230,7 +230,7 @@ Open questions for the product owner and legal:
|
||||
- The minimum for the onboarding step `candidate_profile`: the contract requires no field; which fields complete the step is the product owner's decision.
|
||||
- One source between the questionnaire and the profile: keep the self-assessment and the stack independent, or store one claim and show it in both places.
|
||||
- Soft skills: there is no taxonomy, only free text, up to 10 items of 50 characters; whether a dictionary is needed.
|
||||
- Experience: employer names and descriptions are personal data; how the anonymous card generalizes them (PRD: industry and size) is for the card contract (TASK-185), not this one.
|
||||
- Experience: employer names and descriptions are personal data; how the anonymous card generalizes them (PRD: industry and size) is for the card contract, not this one.
|
||||
- Contact verification (confirming the phone or the email of the profile) is not provided: contacts are claims of level 0.
|
||||
|
||||
`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation`, and `TestProfileAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/profile-contract.test.ts` pins the generated Zod rules, the request types without a confirmed grade, and the absence of profile fields from the organization, invitation, and need schemas.
|
||||
@@ -278,7 +278,7 @@ Attempt lifecycle, with the commands each state accepts:
|
||||
- Limits: `expires_at` and `sessions` (`used`, `max`, `idle_timeout_seconds`, null when the policy defines no session limit) come from the policy version; PRD FR04 allows two sessions within 72 hours. Creation starts session 1. A read or command on the active attempt after `idle_timeout_seconds` without one starts the next session; one beyond `max` starts none, and the attempt becomes `expired`. Reading a terminal attempt or a result never starts a session.
|
||||
- At the limits: a practice already `pending` is graded first. Then `ready_to_finalize` is finalized by the server and becomes `completed`, an unsubmitted additional practice is declined (`completed`, `not_confirmed`), and `in_progress` and `practice_pending` become `expired`. A finalize after that answers 200 with the `completed` attempt; any other command answers 409 `state_conflict`.
|
||||
- Insufficient bank is a distinct state in two places. Before the start, `GetMyAssessmentAvailability` shows `insufficient_bank` for a grade without a published bank or without enough families that this candidate has not seen, and `CreateMyAssessmentAttempt` answers 409 `state_conflict` without creating anything. During an attempt, the terminal state `insufficient_bank` ends it without a confirmed grade instead of repeating families.
|
||||
- No new problem code is added, so TASK-157 gets 409 `state_conflict` plus the availability status instead of a `bank_unavailable` code. The `ProblemCode` enum is copied byte-for-byte into the ML contract (`test_contract_copies.py`), so a new code would also change the ML contract and its generated models. The availability read also tells the client why an attempt cannot start and, for `cooldown`, from when, which a fixed problem detail cannot carry.
|
||||
- No new problem code is added, so attempt creation gets 409 `state_conflict` plus the availability status instead of a `bank_unavailable` code. The `ProblemCode` enum is copied byte-for-byte into the ML contract (`test_contract_copies.py`), so a new code would also change the ML contract and its generated models. The availability read also tells the client why an attempt cannot start and, for `cooldown`, from when, which a fixed problem detail cannot carry.
|
||||
- Availability shows the limits of each grade before the start: `time_limit_seconds`, `max_sessions`, `max_items`, and `practice_required`, null when unknown.
|
||||
- Counting against the retry rules (3 attempts per 180 days, the 30-day same-grade interval): an attempt that ends `not_determined` with the reason `expired` or `practice_incomplete` is the candidate's attempt and counts. `insufficient_bank` and `sandbox_unavailable` are platform faults: they never count and start no interval. After a failure, including the first test, a lower grade can be tested at once.
|
||||
|
||||
@@ -296,7 +296,7 @@ Commands, retries, and versions:
|
||||
- Each item accepts one answer. Sending the stored answer again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Equality is defined per format: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. A different answer for an answered item answers 409 `state_conflict` with the current version; with a stale version the version check comes first and answers 412.
|
||||
- Exception: a practice whose latest verdict is `failed` is outside the repeat rule. A submission with the same or a different solution and the current version queues it again and advances the version.
|
||||
- Finalizing a `completed` attempt answers 200 with that attempt, so the result is computed once. A retry of the finalize that offered an additional practice, sent with a new key, carries the old version and answers 412, so it never declines the offer by accident.
|
||||
- A stale `expected_version` answers 412 `version_conflict`, not 409. This deviates from the wording of the TASK-155 test step and of TASK-152, which say 409. It keeps the repository rule above and the questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is the same, to read the resource again. 409 `state_conflict` is kept for a command that the attempt state does not allow at the current version: the item is not current or has another answer, the attempt is terminal or past its limits, a practice verdict is pending, or the attempt is not ready to finalize. The two codes therefore lead to different client actions.
|
||||
- A stale `expected_version` answers 412 `version_conflict`, not 409. It keeps the repository rule above and the questionnaire precedent: `version_conflict` is 412 for If-Match and for a body `expected_version` alike, because the client action is the same, to read the resource again. 409 `state_conflict` is kept for a command that the attempt state does not allow at the current version: the item is not current or has another answer, the attempt is terminal or past its limits, a practice verdict is pending, or the attempt is not ready to finalize. The two codes therefore lead to different client actions.
|
||||
- A premature finalize answers 409 `state_conflict` without listing the unfinished items, because `Problem` allows no extension fields. The client reads them from the attempt: `state`, `progress`, `current_item`, and `practices`.
|
||||
- Order of checks for a command: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), the attempt (404, after any due transition), the repeat of a stored answer or of finalize on a completed attempt (200), the version (412), the state (409 `state_conflict`), then domain rules (400 with pointers such as `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 `state_conflict` are stored under the key and replayed, while 400, including domain rules, 412, 429, and 5xx are not. Create and answers are rate-limited (429 with `Retry-After`), which also limits sandbox load. `TestAssessmentSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server.
|
||||
|
||||
@@ -324,7 +324,7 @@ Every operation also declares the `default` problem response. A malformed `org_i
|
||||
|
||||
Access:
|
||||
|
||||
- `org_id` in the path is the only source of the organization, and the server checks it against the active membership of the session account; no request has an organization, membership, or role field. The organization contract (TASK-077) owns organizations and memberships and reuses the same path parameter, `parameters.yml#/OrganizationId`.
|
||||
- `org_id` in the path is the only source of the organization, and the server checks it against the active membership of the session account; no request has an organization, membership, or role field. The organization contract owns organizations and memberships and reuses the same path parameter, `parameters.yml#/OrganizationId`.
|
||||
- An account without an active membership in `org_id`, an unknown organization, an unknown need, and a need of another organization all answer 404 `not_found`, so identifiers cannot be probed. A candidate account answers 403 `forbidden`, and so does a member whose role does not allow the operation.
|
||||
- In the MVP only the owner of the organization works with needs. The other roles of the PRD FR07 matrix (recruiter, hiring manager and technical expert for assigned needs) are planned and change no field of the contract.
|
||||
|
||||
@@ -335,7 +335,7 @@ Fields and provenance:
|
||||
- `source` has `origin` (`manual`, `extracted_from_text`, or the planned `imported`), `quote` (an exact excerpt of up to 300 characters, or null), `extracted_in_version`, and `extraction_version`. The quote is an excerpt of the `source_text` of `extracted_in_version`, not necessarily of the current text: a confirmed value keeps its quote after the text changes. Confirming a suggestion keeps its provenance; changing the value makes it `manual`.
|
||||
- A skill has `taxonomy_code`. It is null for a skill that the platform taxonomy does not know: the name stays as given, no code is guessed, and recommendations count the skill as not covered.
|
||||
- With `source_text`, the server extracts suggestions with deterministic rules and a dictionary before it answers, so needs work while ML is disabled. ML suggestions with quotes are planned as an asynchronous addition that creates a new version and never overwrites a confirmed value.
|
||||
- The text is stored as written and may contain requirements that discriminate by a protected characteristic; the extractor never turns them into a need field. The field for what a candidate must not have, with the Labor Code article 64 check, is deferred to TASK-182 and will be added without a breaking change.
|
||||
- The text is stored as written and may contain requirements that discriminate by a protected characteristic; the extractor never turns them into a need field. The field for what a candidate must not have, with the Labor Code article 64 check, is deferred to the requirement validation feature and will be added without a breaking change.
|
||||
|
||||
Requests, confirmation, and changes:
|
||||
|
||||
@@ -350,8 +350,8 @@ Requests, confirmation, and changes:
|
||||
Versions and concurrency:
|
||||
|
||||
- `version` starts at 1 and advances by exactly one with each committed change, including server-side ones. Each version is an immutable snapshot. GET always returns the latest version.
|
||||
- `requirements_version` is the version in which the confirmed requirements were last changed. Confirming, changing, or removing a requirement sets it to the new `version`; a change of the title, the vacancy link, the text, or suggestions only keeps it and invalidates neither the recommendations nor search results. Search runs, selection snapshots (FR10, TASK-193), and invitations refer to `(need_id, requirements_version)`, and only a new `requirements_version` calls for a new selection snapshot. Reading and comparing earlier versions are planned as separate operations that return `NeedRequirementSet` for a version; they add nothing to `Need`.
|
||||
- A change carries `expected_version`, the version the client read, in the body for the same reason as the questionnaire: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; TASK-179 says 409, but the repository rule keeps 412 for If-Match and a body version alike. A body that changes nothing answers 200 with the current need even with an older version, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored.
|
||||
- `requirements_version` is the version in which the confirmed requirements were last changed. Confirming, changing, or removing a requirement sets it to the new `version`; a change of the title, the vacancy link, the text, or suggestions only keeps it and invalidates neither the recommendations nor search results. Search runs, selection snapshots (FR10), and invitations refer to `(need_id, requirements_version)`, and only a new `requirements_version` calls for a new selection snapshot. Reading and comparing earlier versions are planned as separate operations that return `NeedRequirementSet` for a version; they add nothing to `Need`.
|
||||
- A change carries `expected_version`, the version the client read, in the body for the same reason as the questionnaire: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; the repository rule keeps 412 for If-Match and a body version alike. A body that changes nothing answers 200 with the current need even with an older version, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored.
|
||||
|
||||
Readiness:
|
||||
|
||||
@@ -363,18 +363,18 @@ Salary:
|
||||
- `SalaryRange` `[A; B]` has `salary_from` and `salary_to` (`RubAmount`, whole rubles), `currency` (`RUB` only), `period` (`month` only), and `tax_basis` (`net` or `gross`); every field is required. Requests send it as `salary: {value, status}`, so its pointers are under `/salary/value`.
|
||||
- The schema requires bounds that are positive multiples of 1000 up to 100000000 and rejects another currency, period, or basis, for example with `/salary/value/tax_basis`. A missing field of the nested range answers `required` with its pointer, such as `/salary/value/tax_basis`.
|
||||
- The server checks the cross-field rules of PRD FR13 in integer arithmetic: `A < B` and a width `(B - A) / ((A + B) / 2)` from 10% to 40% inclusive, that is `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B`. A violation, including equal bounds, answers 400 with the pointer `/salary/value/salary_to`. `[95000; 105000]` (exactly 10%) and `[80000; 120000]` (exactly 40%) are accepted. FR13 applies the same rules to the range of a need and of an invitation, and `docs/*/ARCHITECTURE.md` now states them for invitations instead of `0 < salary_from <= salary_to`.
|
||||
- Limit against probing hidden minimums (FR13, planned in TASK-211): setting a confirmed range, on creation or on a change, counts against a counter shared by the whole organization, every member and every need, so a new need does not reset it. At most three range settings a day; over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private risk signals of TASK-319.
|
||||
- Limit against probing hidden minimums (FR13, enforcement planned): setting a confirmed range, on creation or on a change, counts against a counter shared by the whole organization, every member and every need, so a new need does not reset it. At most three range settings a day; over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private organization risk signals.
|
||||
|
||||
Recommendations:
|
||||
|
||||
- `recommendations` is computed by the server from the confirmed requirements of `requirements_version` with a versioned policy (`policy_version`, `algorithm_version`, `computed_at`). `status` is `computed`, `pending`, or `not_available` without a confirmed skill. The server may recompute them for the same `requirements_version`, for a new policy or a changed pool of candidates, without a new need version; `computed_at` and `policy_version` then change.
|
||||
- Each category (`specialization` and `grade`) has `score`, `skill_overlap` (weighted share with weight 2 for required and 1 for desired skills, covered and uncovered skills), `money`, and `supply` as a band: `fewer_than_5`, `from_5_to_29`, `30_or_more`. The list order is the ranking.
|
||||
- `money.status` is `computed`, `insufficient_data` (fewer than five candidates with a comparable known minimum), `no_salary`, or `withheld`; the last three use the neutral 0.5 and a null share. `money.share` is rounded down to a quarter (0, 0.25, 0.5, 0.75, 1): each probe of a new upper bound then tells at most which quarter of the group accepts it, and in the smallest allowed group of five a single minimum often does not move the value, while the share still separates a range that most candidates accept from one that few accept.
|
||||
- `score` is `0.5 * Overlap + 0.3 * Money + 0.2 * Supply`, rounded half up to two decimals, computed from the published components: the exact overlap, the quarter-rounded share or the neutral 0.5, and `Supply = min(1, active / 30)`. It is null when `supply` is `fewer_than_5`. The ranking uses Supply only at band precision below five: every group of fewer than five candidates enters it with Supply 0, so neither the score nor the order reveals the exact size of a group below five, which FR08 forbids. For five or more candidates the exact Supply is used, so the TASK-183 fixture (Overlap 1, Money 0.5, 15 active candidates) gives `score` 0.75.
|
||||
- Deviation from the PRD formula and from TASK-183 and TASK-457: the money share in the score and ranking is the quarter-rounded share, not the exact one, and a category with fewer than five candidates has no score. Otherwise the score with the exact share would reveal the share that `money.share` rounds, and a score with the exact Supply of a small group would reveal its size. The breakdown that TASK-457 shows consists of the published components.
|
||||
- `score` is `0.5 * Overlap + 0.3 * Money + 0.2 * Supply`, rounded half up to two decimals, computed from the published components: the exact overlap, the quarter-rounded share or the neutral 0.5, and `Supply = min(1, active / 30)`. It is null when `supply` is `fewer_than_5`. The ranking uses Supply only at band precision below five: every group of fewer than five candidates enters it with Supply 0, so neither the score nor the order reveals the exact size of a group below five, which FR08 forbids. For five or more candidates the exact Supply is used, so the recommendation fixture (Overlap 1, Money 0.5, 15 active candidates) gives `score` 0.75.
|
||||
- Deviation from the PRD formula: the money share in the score and ranking is the quarter-rounded share, not the exact one, and a category with fewer than five candidates has no score. Otherwise the score with the exact share would reveal the share that `money.share` rounds, and a score with the exact Supply of a small group would reveal its size. The displayed breakdown consists of the published components.
|
||||
- Requests cannot set a recommendation, its score, membership, or a candidate minimum: bodies have `additionalProperties: false`, and unknown fields such as `rec_score`, `members`, `candidate_minimum`, `version`, `requirements_version`, or `recommendations` answer 400 with the whole-body pointer. `TestNeedSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server, `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` checks the list decoding, and `frontend/src/shared/api/needs-contract.test.ts` pins the generated Zod limits, the explicit status of every decision, and the absence of these fields in the request types.
|
||||
|
||||
Planned, additive: reading and comparing versions, exclusions (TASK-182), the market range hint (P25-P75) of FR08, the check plan "vacancy -> tasks", a need status for archiving, list filters, and need assignments.
|
||||
Planned, additive: reading and comparing versions, exclusions, the market range hint (P25-P75) of FR08, the check plan "vacancy -> tasks", a need status for archiving, list filters, and need assignments.
|
||||
|
||||
### Support cases
|
||||
|
||||
@@ -391,8 +391,8 @@ Every operation also declares the `default` problem response.
|
||||
Access:
|
||||
|
||||
- The author is the account of the session; no request has a user, account, or organization field. PRD FR18 lets both candidates and company employees contact support, so `/me` serves both scenarios: an employer account opens `support` cases, and the other types answer 403 `forbidden` for it. A case belongs to the account that created it, not to an organization: other members of the same organization never see it.
|
||||
- Another account's case answers 404 `not_found`, the same as an unknown identifier. TASK-314 says "forbidden" for a foreign case URL; the contract answers 404 instead, so identifiers cannot be probed, and the client shows the same "not found" state for a foreign and an unknown case. The author reads the case whatever happened to the object since then, so a refused test or a revoked access never hides it.
|
||||
- The moderation queues of TASK-316 are separate staff operations with their own DTOs; they add nothing to these operations.
|
||||
- Another account's case answers 404 `not_found`, the same as an unknown identifier. The contract answers 404, so identifiers cannot be probed, and the client shows the same "not found" state for a foreign and an unknown case. The author reads the case whatever happened to the object since then, so a refused test or a revoked access never hides it.
|
||||
- The moderation queues are separate staff operations with their own DTOs; they add nothing to these operations.
|
||||
|
||||
Types and object references:
|
||||
|
||||
@@ -406,10 +406,10 @@ Types and object references:
|
||||
|
||||
- The request is a `oneOf` of five variants selected by `type` (`SupportCaseCreateSupport`, `SupportCaseCreateComplaint`, `SupportCaseCreateGradeAppeal`, `SupportCaseCreateAnticheatAppeal`, `SupportCaseCreateManualAssessment`). Each variant restricts its reference schema, so the schema already rejects an organization in a grade appeal or a case in a complaint with the pointer `/object/type`, and a missing field of the type with its pointer, such as `/object` or `/assessment_target`. ogen selects the variant by the value of `type`. An unknown or missing type and a field of another variant such as `complaint_reason` in a support case answer 400 with the whole-body pointer `""`, because they concern the top-level variant; an `object.id` that is not a UUID answers 400 with `/object/id` (example `SupportCaseMalformedReference`).
|
||||
- A category assigned without an attempt is appealed too (FR18): a grade appeal may reference the caller's own manual assessment case once it is `resolved` with `assessed`. An unknown case and another account's case answer 404 `not_found`; an own case of another type, not resolved yet, or resolved with another outcome answers 409 `state_conflict`.
|
||||
- An organization is visible to a candidate that it invited or whose profile the organization contract (TASK-077) shows to the candidate, and to an employer account with an active membership. The server checks every reference against the session account: an unknown object and someone else's object both answer 404 `not_found`, so a reference never reveals whether a foreign object exists. The case stores only `{type, id}`.
|
||||
- An organization is visible to a candidate that it invited or whose profile the organization contract shows to the candidate, and to an employer account with an active membership. The server checks every reference against the session account: an unknown object and someone else's object both answer 404 `not_found`, so a reference never reveals whether a foreign object exists. The case stores only `{type, id}`.
|
||||
- Invitations are in the contract (see Invitations and contact grants below) but not implemented, and anti-cheat review decisions are not in the contract yet. Until they are implemented, every `invitation` reference answers 404 and every anti-cheat appeal answers 409 `state_conflict`; the request shapes stay the same.
|
||||
- `offer_content` and `salary_terms_violation` complaints require an invitation; another object answers 400 with the pointer `/object/type` (a domain rule after the schema).
|
||||
- A failed first test or no attempt at all never blocks a manual assessment. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt; how a manual assessment relates to the C3 consent is decided by TASK-064 and TASK-315.
|
||||
- A failed first test or no attempt at all never blocks a manual assessment. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt; how a manual assessment relates to the C3 consent is defined by consent revocation and manual assessment.
|
||||
|
||||
Content and fields the client never sets:
|
||||
|
||||
@@ -436,11 +436,11 @@ Commands and limits:
|
||||
- No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract. An unavailable anti-cheat appeal and a repeated appeal both use 409 `state_conflict`, and the case or the attempt tells the client why.
|
||||
- `TestSupportCaseSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server, and `frontend/src/shared/api/support-contract.test.ts` pins the generated Zod rules, the absence of status, decision, moderator, and contact fields in the request types, and the absence of moderator identity and internal fields in the case and the summary.
|
||||
|
||||
Open product question for TASK-315: whether repeated manual assessments of the same category follow the retest rules of FR04 (the same grade after 30 days, at most three attempts in 180 days) or their own rule. The contract only allows one open manual assessment per specialization and invents no interval.
|
||||
Open product question for manual assessment: whether repeated manual assessments of the same category follow the retest rules of FR04 (the same grade after 30 days, at most three attempts in 180 days) or their own rule. The contract only allows one open manual assessment per specialization and invents no interval.
|
||||
|
||||
Planned, additive (a new operation or an optional field): replies of the author, attachments, withdrawal of a case, list filters by status and type, the resulting category of a manual assessment in the decision, a next step for the author (TASK-322), staff queues and decisions (TASK-316, TASK-317, TASK-323), and the pause rules of the response target.
|
||||
Planned, additive (a new operation or an optional field): replies of the author, attachments, withdrawal of a case, list filters by status and type, the resulting category of a manual assessment in the decision, a next step for the author, staff queues and decisions, and the pause rules of the response target.
|
||||
|
||||
Planned contract changes (new enum values; like the catalog codes, generated clients reject an unknown value, so each one is released with regenerated clients): object types `vacancy` and `application` for the vacancies and protected applications of FR16, and an object type for the profile findings of TASK-272. `waiting_for_user` and `support_case` are already in the enums, so the reply operation and follow-up cases need no such change. No new event kind or actor kind is planned: an author reply is a `reply` with the actor `user`, a decision revision (TASK-317) is another `decision` event, and experts and moderators are `support`.
|
||||
Planned contract changes (new enum values; like the catalog codes, generated clients reject an unknown value, so each one is released with regenerated clients): object types `vacancy` and `application` for the vacancies and protected applications of FR16, and an object type for the profile analysis findings. `waiting_for_user` and `support_case` are already in the enums, so the reply operation and follow-up cases need no such change. No new event kind or actor kind is planned: an author reply is a `reply` with the actor `user`, a decision revision is another `decision` event, and experts and moderators are `support`.
|
||||
|
||||
### Invitations and contact grants
|
||||
|
||||
@@ -467,9 +467,9 @@ Every success has `Cache-Control: no-store`, and every operation also declares t
|
||||
|
||||
Access:
|
||||
|
||||
- Organization side: `org_id` in the path is the only source of the organization, checked against the active membership of the session account, as for needs. An account without the membership, an unknown organization, an unknown invitation, and an invitation of another organization all answer 404 `not_found`; a candidate account and a member whose role does not allow the operation answer 403 `forbidden`. In the MVP only the owner works with invitations; the other roles of FR07 are planned (TASK-463).
|
||||
- Organization side: `org_id` in the path is the only source of the organization, checked against the active membership of the session account, as for needs. An account without the membership, an unknown organization, an unknown invitation, and an invitation of another organization all answer 404 `not_found`; a candidate account and a member whose role does not allow the operation answer 403 `forbidden`. In the MVP only the owner works with invitations; the other roles of FR07 are planned.
|
||||
- Candidate side: `/me/invitations` is bound to the session account. A draft, an invitation addressed to another candidate, and an unknown identifier answer 404 `not_found`; an employer account answers 403 `forbidden`. No request has a user, candidate, organization, or role field.
|
||||
- The candidate is named only by `candidate_handle` (`CandidateHandle` in `common_schemas.yml`, shared with the search results of FR11, TASK-185), never by an email address, a phone number, or an account or profile identifier. An unknown handle, a handle of another organization, and a profile that the organization may no longer see all answer 400 with the pointer `/candidate_handle`.
|
||||
- The candidate is named only by `candidate_handle` (`CandidateHandle` in `common_schemas.yml`, shared with the search results of FR11), never by an email address, a phone number, or an account or profile identifier. An unknown handle, a handle of another organization, and a profile that the organization may no longer see all answer 400 with the pointer `/candidate_handle`.
|
||||
|
||||
Terms (`InvitationTerms`):
|
||||
|
||||
@@ -481,7 +481,7 @@ Terms (`InvitationTerms`):
|
||||
Versions and conflicts:
|
||||
|
||||
- `version` advances with every committed change, including the view and the server expiry. `terms_version` advances only when the terms change: a draft change of `terms`, or the one raise of the upper bound after sending. Each terms version is immutable.
|
||||
- Every command except the view carries `expected_version`; `AcceptMyInvitation` also carries `terms_version`. 412 `version_conflict`: `expected_version` or, on acceptance, `terms_version` is not current (the stale terms case, example `InvitationStaleTerms`); nothing changed, nothing is stored under the key, and the client reads the invitation again. 409 `state_conflict`: the state does not allow the command, for example an acceptance of a withdrawn or expired invitation, a command at the deadline or later, a send blocked by the pending limit of a need or by the 30-day pause, a change of a sent invitation, or a second raise; it is stored under the key. TASK-197, TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, as for needs and the questionnaire.
|
||||
- Every command except the view carries `expected_version`; `AcceptMyInvitation` also carries `terms_version`. 412 `version_conflict`: `expected_version` or, on acceptance, `terms_version` is not current (the stale terms case, example `InvitationStaleTerms`); nothing changed, nothing is stored under the key, and the client reads the invitation again. 409 `state_conflict`: the state does not allow the command, for example an acceptance of a withdrawn or expired invitation, a command at the deadline or later, a send blocked by the pending limit of a need or by the 30-day pause, a change of a sent invitation, or a second raise; it is stored under the key. The repository rule keeps 412 for any stale version, as for needs and the questionnaire.
|
||||
- Order: after the invitation is found and a due expiry is applied, and after the repeat check, a terminal state (`declined`, `expired`, `withdrawn`, `cancelled_by_candidate`) or, for accept and decline, a passed deadline answers 409 before the version is compared, so the client gets 409 for a withdrawn, expired, or late invitation even with stale versions and shows the final state instead of rereading and retrying. Then come the versions (412) and the remaining state rules (409). This applies to accept, decline, cancel, withdraw, and the salary raise.
|
||||
- Repeats return the same result: a retry with the same Idempotency-Key replays the stored outcome, and a repeated command whose transition already happened answers 200 with the current invitation even with a new key or an older version: a send of a sent invitation, a withdrawal of a withdrawn one, a decline with the same reason and comment, a cancellation of a cancelled one, the same raise, and an acceptance whose `terms_version` and fields equal those of `contact_grant`, the version and fields the candidate accepted, even when a later raise advanced the current `terms_version`. No second consent, grant, quota charge, or audit event is created.
|
||||
- `UpdateOrganizationInvitation` follows the convention of `UpdateOrganizationNeed`: no Idempotency-Key, explicit field replacement, and a body that changes nothing answers 200.
|
||||
@@ -490,7 +490,7 @@ States and the view:
|
||||
|
||||
- `InvitationState` lists every state of the FR12 table: `draft`, `delivered`, `viewed`, `counter`, `accepted`, `interview_scheduled`, `interviewed`, `negotiation`, `terms_agreed`, `no_deal`, `declined`, `expired`, `withdrawn`, `cancelled_by_candidate`. MVP operations produce `draft`, `delivered`, `viewed`, `accepted`, `declined`, `expired`, `withdrawn`, and `cancelled_by_candidate`; the others are listed now so that generated clients accept them when the counter offer, the interview, and the sealed final arrive. The internal `SENT` step is never visible: a send answers with `delivered` after the inbox entry exists.
|
||||
- `expiry_reason` is `invitation_timeout` or the planned `negotiation_timeout`, non-null exactly in `expired`.
|
||||
- The view is an explicit command, `ViewMyInvitation`: it moves `delivered` to `viewed`, keeps the deadline, and returns the current invitation unchanged in any other state. It is idempotent by its effect, so it needs neither an Idempotency-Key nor an `expected_version`, and it never fails because the invitation changed after the client read it. `GetMyInvitation` and `ListMyInvitations` have no side effect; a read only shows a due expiry, which the server applies at the deadline anyway. TASK-200 describes the view as a GET; the command keeps prefetches, retries, and cache refreshes from changing the state that the organization sees.
|
||||
- The view is an explicit command, `ViewMyInvitation`: it moves `delivered` to `viewed`, keeps the deadline, and returns the current invitation unchanged in any other state. It is idempotent by its effect, so it needs neither an Idempotency-Key nor an `expected_version`, and it never fails because the invitation changed after the client read it. `GetMyInvitation` and `ListMyInvitations` have no side effect; a read only shows a due expiry, which the server applies at the deadline anyway. The command keeps prefetches, retries, and cache refreshes from changing the state that the organization sees.
|
||||
- `withdrawn` is the organization's command from any unfinished state, including `draft` and `accepted`, and keeps an existing grant. `cancelled_by_candidate` is the candidate's command from any unfinished state after delivery and revokes the grant of this invitation. A decline is the structured answer before an acceptance.
|
||||
- The deadline is `delivered_at + response_period_days` (3, 7, or 14 days, 7 by default). A view, an email, or a raise never moves it; a command received at the deadline or later is late.
|
||||
|
||||
@@ -498,7 +498,7 @@ Salary and the hidden minimum:
|
||||
|
||||
- The terms reuse `SalaryRange` with the rules of the Needs section: RUB, month, `net` or `gross`, positive multiples of 1000, `A < B`, and a width of 10-40%, checked by the server with the pointer `/terms/salary/salary_to`.
|
||||
- The organization receives only `salary_fit`: `within_range`, `up_to_10_percent_above`, `above`, `withheld`, or `not_available` (no minimum for the offered formats, or one in the other tax basis). The exact minimum appears in no response, example, log, or problem. The server never rejects a range because of the minimum, since a rejection would reveal it. The candidate DTOs carry no indicator; the candidate compares with the own minimum in the profile.
|
||||
- Every change that can move the indicator is an indicator-relevant setting: the range on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, because the indicator compares with the minimum for the offered formats. Each counts against the organization-wide limit of three settings a day, shared with the ranges of needs (429 with Retry-After, TASK-211), and against the withheld counter. A change that keeps the range, the basis, and the formats does not count.
|
||||
- Every change that can move the indicator is an indicator-relevant setting: the range on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, because the indicator compares with the minimum for the offered formats. Each counts against the organization-wide limit of three settings a day, shared with the ranges of needs (429 with Retry-After), and against the withheld counter. A change that keeps the range, the basis, and the formats does not count.
|
||||
- `withheld`: after five indicator-relevant settings within seven days the indicator is off for seven days from the fifth. The response to the fifth setting already shows `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.
|
||||
- Switching the tax basis turns `not_available` into a band or back and so tells the organization the basis of the minimum; this is accepted, and the switch counts against the limit like any other setting.
|
||||
- After a send the base is fixed and the lower bound never decreases. `RaiseOrganizationInvitationSalary` raises `salary_to` once in the whole history of the invitation, creates the next terms version, and answers 409 on a second raise. It follows its own once-only rule and does not count against the daily limit, but it counts against the withheld counter because it moves the upper bound that the indicator compares.
|
||||
@@ -506,12 +506,12 @@ Salary and the hidden minimum:
|
||||
Consent C4 and the contact grant:
|
||||
|
||||
- `GetMyInvitation` shows in `contact_consent` the C4 text for this organization and the kinds of contact that the profile holds. It is null when an acceptance is impossible: the state or the deadline does not allow it, or the profile holds no contact. In the last case the client asks the candidate to add a contact first, because a grant must cover at least one field.
|
||||
- `AcceptMyInvitation` sends `terms_version`, `expected_version`, and `consent_c4` (`ContactConsentAcceptance`): the shown C4 text version, `accepted: true`, and `fields`, at least one of `full_name`, `email`, `phone`, `telegram`, with no default and no preselection. A text version that is not published answers 400 `/consent_c4/text_version`, and a field the profile does not hold answers 400 `/consent_c4/fields/<i>`. The consent is analogous to the C1 acceptance by its `text_version`, and the record matches the C4 ledger of TASK-062 (purpose, text version and hash, organization, field set, source invitation). The permission to pass the data on to the organization's ATS (C4 and FR19) is planned as an additive optional flag that defaults to no transfer.
|
||||
- In one transaction the acceptance moves the invitation to `accepted`, records C4, creates the grant for exactly the selected fields, and writes the audit event (TASK-201). It never publishes the profile (C2) and never lifts a hiding.
|
||||
- `AcceptMyInvitation` sends `terms_version`, `expected_version`, and `consent_c4` (`ContactConsentAcceptance`): the shown C4 text version, `accepted: true`, and `fields`, at least one of `full_name`, `email`, `phone`, `telegram`, with no default and no preselection. A text version that is not published answers 400 `/consent_c4/text_version`, and a field the profile does not hold answers 400 `/consent_c4/fields/<i>`. The consent is analogous to the C1 acceptance by its `text_version`, and the record matches the C4 consent ledger (purpose, text version and hash, organization, field set, source invitation). The permission to pass the data on to the organization's ATS (C4 and FR19) is planned as an additive optional flag that defaults to no transfer.
|
||||
- In one transaction the acceptance moves the invitation to `accepted`, records C4, creates the grant for exactly the selected fields, and writes the audit event. It never publishes the profile (C2) and never lifts a hiding.
|
||||
- The candidate's `contact_grant` has `status` (`active` or `revoked`), `readable`, and `blocked_by`. A grant created while the profile was not published or was hidden from the organization stays `active` with `readable: false` and `blocked_by: visibility`, so the candidate sees why the organization cannot read it (PRD FR12); it becomes readable once the candidate publishes the profile or unhides it. Any visibility change after the grant exists revokes it (`visibility_closed`), and a later publication never reopens it.
|
||||
- Contact values travel only in `ContactDisclosure` from `GetOrganizationInvitationContacts`, separate from the terms and the invitation. Each read checks the membership, C4, the grant and its fields, and the current visibility, without a cache. Without a readable grant the operation answers 404 `not_found`, the same as an unknown invitation. The organization's `contact_access` is `not_granted` (no grant), `available` (with the field kinds), or `closed`, which covers a revoked grant and a grant blocked from the start without saying which. This is the least revealing rule: a revocation, a hiding, and a missing publication look the same, and since every visibility change after the grant revokes it, the organization never observes a later toggle; only a grant blocked from the start can turn `available`, by the candidate's own choice. Fields that the grant does not cover are null.
|
||||
- Revocation: `CancelMyInvitation` revokes the grant of this invitation (`participation_cancelled`); revoking C4 for the organization closes all its grants (`consent_revoked`, TASK-064); revoking C2 or hiding the profile closes them (`visibility_closed`). A withdrawal, a no deal, and a negotiation timeout never revoke a grant; only a new explicit C4 creates a new one. A standalone grant revocation operation belongs to the consent contract (TASK-064, TASK-202).
|
||||
- Value formats: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02, TASK-066) must store contacts in the same formats, so a disclosure never converts or drops a stored value.
|
||||
- Revocation: `CancelMyInvitation` revokes the grant of this invitation (`participation_cancelled`); revoking C4 for the organization closes all its grants (`consent_revoked`); revoking C2 or hiding the profile closes them (`visibility_closed`). A withdrawal, a no deal, and a negotiation timeout never revoke a grant; only a new explicit C4 creates a new one. A standalone grant revocation operation belongs to the consent contract.
|
||||
- Value formats: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never converts or drops a stored value.
|
||||
|
||||
Decline and privacy:
|
||||
|
||||
@@ -526,7 +526,7 @@ No new problem code is added: the `ProblemCode` enum is copied byte-for-byte int
|
||||
|
||||
### Consents
|
||||
|
||||
The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. The read operation is in the contract; its handler is not implemented yet, so it answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind it exists (TASK-062, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#consent-ledger)).
|
||||
The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. The read operation is in the contract; its handler is not implemented yet, so it answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind it exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#consent-ledger)).
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -534,9 +534,9 @@ The `consent` tag covers the consent ledger of the current account (PRD FR01, FR
|
||||
|
||||
- Purposes (`ConsentPurposeCode`): `c1` personal data processing, `c2` publication of the candidate card, `c3` automatic categorization, `c4` transfer of selected contacts to one organization, `c5` import of FSP results. `ConsentPurpose` stays the subset whose text is public before registration (`c1`), so `GetConsentText` does not widen.
|
||||
- The subject comes from the session; no parameter names an account, so the response holds only the caller's own records. A page lists records newest grant first with cursor pagination; the optional `state` filter takes `active`, `superseded`, or `revoked`, and an unknown value answers 400 with the pointer `/state`.
|
||||
- A `ConsentRecord` has the purpose, the accepted `text_version`, the `source` (`registration`, `consent_settings`, or `invitation_acceptance`), `granted_at`, the computed `state`, and `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A `c4` record also names the `organization` (`ConsentOrganization`, whose `name` is the snapshot the consent text showed, so a later rename does not change it), the contact `fields` (`ContactFieldKind`), the `invitation_id`, and the `invitation_terms_version`; they are null for every other purpose. A `c2` record proves the consent to the publication text; which fields were published, and when, is evidence of the publication history ([Candidate visibility](#candidate-visibility), TASK-088), and a field scope on `c2` records would be an additive change. The record never carries a contact value, the subject, or the text hash: the server stores the SHA-256 of exactly the text the subject saw, and the client never sends or receives it, as for C1 at registration.
|
||||
- A `ConsentRecord` has the purpose, the accepted `text_version`, the `source` (`registration`, `consent_settings`, or `invitation_acceptance`), `granted_at`, the computed `state`, and `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A `c4` record also names the `organization` (`ConsentOrganization`, whose `name` is the snapshot the consent text showed, so a later rename does not change it), the contact `fields` (`ContactFieldKind`), the `invitation_id`, and the `invitation_terms_version`; they are null for every other purpose. A `c2` record proves the consent to the publication text; which fields were published, and when, is evidence of the publication history ([Candidate visibility](#candidate-visibility)), and a field scope on `c2` records would be an additive change. The record never carries a contact value, the subject, or the text hash: the server stores the SHA-256 of exactly the text the subject saw, and the client never sends or receives it, as for C1 at registration.
|
||||
- The ledger is append-only. A newer text version of a purpose is a new record and the earlier one becomes `superseded` without any change; a revocation stamps the unrevoked records of the purpose, and for `c4` of one organization, once; a later grant is a new record, and a revoked `c4` of an invitation never comes back. Purposes are independent.
|
||||
- Planned, additive: granting C1, C2, C3, and C5 in the consent settings (TASK-063) and revoking any purpose with its consequences (TASK-064), as new operations of this tag; C1 at registration and C4 in `AcceptMyInvitation` already have their own operations. The C4 permission to pass data on to an ATS and the C4 of an application (PRD Q9) are planned as an additive flag and an additional `source` value.
|
||||
- Planned, additive: granting C1, C2, C3, and C5 in the consent settings and revoking any purpose with its consequences, as new operations of this tag; C1 at registration and C4 in `AcceptMyInvitation` already have their own operations. The C4 permission to pass data on to an ATS and the C4 of an application (PRD Q9) are planned as an additive flag and an additional `source` value.
|
||||
|
||||
Open legal item: whether `c2` is a consent to the distribution of personal data under article 10.1 of 152-FZ, which requires its own consent with the categories of data.
|
||||
|
||||
@@ -544,7 +544,7 @@ No new problem code is added: the contract reuses `validation_failed` and `unaut
|
||||
|
||||
### Organizations
|
||||
|
||||
The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind them exists (TASK-077, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned in TASK-078 and TASK-079.
|
||||
The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind them exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned as part of organization management and access control.
|
||||
|
||||
| Method and path | operationId | Security | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -555,10 +555,10 @@ The `organization` tag covers the organizations of employer accounts and the mem
|
||||
|
||||
Every operation also declares the `default` problem response. A malformed `org_id` answers 400 with the path pointer.
|
||||
|
||||
Active organization context (decision of TASK-077):
|
||||
Active organization context:
|
||||
|
||||
- The context is not stored on the server. Every organization-scoped operation, including the needs and invitations of this contract, names its organization in the path `org_id`, and the server checks that identifier against the active membership of the session account on every request. The identifier grants nothing; a switch between organizations is another `org_id` in the client's routes.
|
||||
- Reason: a session attribute would be a cache of the membership that a removal, a suspension, or a leave would have to invalidate (TASK-079 wants the next read closed, not the browser cache expired), it would make two tabs in two organizations fight over one value, and the path form is already the contract of needs and invitations. TASK-085 clears the tenant-scoped client queries on a switch, which fits a client-side context.
|
||||
- Reason: a session attribute would be a cache of the membership that a removal, a suspension, or a leave would have to invalidate (the next read must be closed without waiting for the browser cache to expire), it would make two tabs in two organizations fight over one value, and the path form is already the contract of needs and invitations. Organization switching clears the tenant-scoped client queries on a switch, which fits a client-side context.
|
||||
- `ListMyOrganizations` is the directory of contexts: the organizations where the caller has an `active` membership, newest membership first, with the caller's role and state. A client picks the context from it, may remember the last choice in the browser as a convenience, and reads the list again after a 404 from an organization path. A person with several memberships sees all of them and works in one at a time; the rights and the data of the organizations stay separate.
|
||||
|
||||
Access:
|
||||
@@ -569,10 +569,10 @@ Access:
|
||||
|
||||
Memberships:
|
||||
|
||||
- A membership is `(user, organization, role, state)` and is unique per pair in any state. `OrganizationRole` has `owner`, `recruiter`, `hiring_manager`, and `technical_expert` (PRD 2.2 and Q3). `MembershipState` has `active`, `suspended` (access stopped, restorable), `removed` (ended by the owner or the platform), and `left` (ended by the member). Only `active` gives access, and the listing returns only `active` memberships; `joined_at` is the moment the membership was first created (a member who returns keeps it, and the latest activation time is a planned `activated_at` of TASK-082); a membership `removed` by the platform must not be reactivated by the owner, by an invitation acceptance, or by the member management on their own (TASK-082, TASK-084), and who removed the member and why become additive fields of the member management; the other states are in the enum so that member management can show them without a contract change. Adding a role or a state is a contract change.
|
||||
- A membership is `(user, organization, role, state)` and is unique per pair in any state. `OrganizationRole` has `owner`, `recruiter`, `hiring_manager`, and `technical_expert` (PRD 2.2 and Q3). `MembershipState` has `active`, `suspended` (access stopped, restorable), `removed` (ended by the owner or the platform), and `left` (ended by the member). Only `active` gives access, and the listing returns only `active` memberships; `joined_at` is the moment the membership was first created (a member who returns keeps it, and the latest activation time is a planned `activated_at` field); a membership `removed` by the platform must not be reactivated by the owner, by an invitation acceptance, or by the member management on their own, and who removed the member and why become additive fields of the member management; the other states are in the enum so that member management can show them without a contract change. Adding a role or a state is a contract change.
|
||||
- The role lives in the membership only. `Organization`, `OrganizationCreate`, `OrganizationUpdate`, and `CandidateOrganizationCard` have no role, owner, or member field. The caller reads their own role in `OrganizationMembership` from `ListMyOrganizations`; the DTO names no account.
|
||||
- There is no `invited` state: an employee joins only through an invitation to an email address (PRD 2.2), which the member-invitation tasks store as a separate record and turn into an `active` membership when the owner of the address accepts it (TASK-081 and TASK-082). A person may hold independent memberships in several organizations.
|
||||
- Applying the full role matrix (recruiter, hiring manager, technical expert) to needs, invitations, and contacts is planned in TASK-083 and TASK-463. Until then the other roles grant nothing: the operations of needs and invitations answer 403 `forbidden` for them, as their sections say. Listing and managing members, changing roles, removing members, and the rule that the last owner cannot be removed are planned in TASK-084 and TASK-085 and add operations, not fields, to this contract.
|
||||
- There is no `invited` state: an employee joins only through an invitation to an email address (PRD 2.2), which the member-invitation tasks store as a separate record and turn into an `active` membership when the owner of the address accepts it. A person may hold independent memberships in several organizations.
|
||||
- Applying the full role matrix (recruiter, hiring manager, technical expert) to needs, invitations, and contacts is planned as part of role-based access control. Until then the other roles grant nothing: the operations of needs and invitations answer 403 `forbidden` for them, as their sections say. Listing and managing members, changing roles, removing members, and the rule that the last owner cannot be removed are planned as part of membership management and add operations, not fields, to this contract.
|
||||
|
||||
Profile:
|
||||
|
||||
@@ -584,9 +584,9 @@ Profile:
|
||||
|
||||
Verification level:
|
||||
|
||||
- `OrganizationVerificationLevel` is `e0`, `e1`, `e2`, or `e3` (PRD FR07). A new organization starts at `e0` on the basis `confirmed_email`, whatever its profile looks like. The server reports a higher level only after a verification process recorded it; the processes for `e1`, `e2`, and `e3` do not exist yet (TASK-086 adds E0/E1 with evidence, a scope, and a history), so a client treats every level but `e0` as unavailable and the contract never reports `e1`, `e2`, or `e3` as reached on its own.
|
||||
- `OrganizationVerificationLevel` is `e0`, `e1`, `e2`, or `e3` (PRD FR07). A new organization starts at `e0` on the basis `confirmed_email`, whatever its profile looks like. The server reports a higher level only after a verification process recorded it; the processes for `e1`, `e2`, and `e3` do not exist yet (the planned verification flow adds E0/E1 with evidence, a scope, and a history), so a client treats every level but `e0` as unavailable and the contract never reports `e1`, `e2`, or `e3` as reached on its own.
|
||||
- No request sets or raises a level or its basis: `OrganizationCreate` and `OrganizationUpdate` are closed objects with only the profile fields, no operation of the contract changes the level, and editing the description, the contacts, or the representatives leaves it as it is. The database keeps the level and the basis in their own columns that the profile statement never writes, and a CHECK ties each level to its own bases. `OrganizationVerification` is read-only: `level`, `basis`, and `changed_at`; the scope of the check and the history of changes (PRD FR07) arrive as additive fields with the first process.
|
||||
- The level selects the quota tier (E0 10 invitations and 50 cards, E1 40 and 150, E2 100 and 400 in the demo policy); `domain.OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the tiers of the policy and has none for `e3`, which the PRD gives a separate policy. The quotas themselves are TASK-087.
|
||||
- The level selects the quota tier (E0 10 invitations and 50 cards, E1 40 and 150, E2 100 and 400 in the demo policy); `domain.OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the tiers of the policy and has none for `e3`, which the PRD gives a separate policy. Quota enforcement is a separate planned feature.
|
||||
|
||||
Candidate card and versions:
|
||||
|
||||
@@ -594,22 +594,22 @@ Candidate card and versions:
|
||||
- `version` starts at 1 and advances with every committed change of the profile. A change carries `expected_version` in the body for the reason the needs give: the generated client cannot read `ETag` yet. A stale value answers 412 `version_conflict` and changes nothing; the repository rule keeps 412 for a stale version, as for needs. A body that changes nothing answers 200 with the current organization, so PATCH needs no Idempotency-Key. POST needs one with the 24-hour replay; only the 201 is stored.
|
||||
- Order of the checks of `UpdateOrganization`: session (401), CSRF and Origin (403), request validation (400), account scenario (403), membership (404) and role (403), a body that changes nothing (200), the version (412), domain rules (400).
|
||||
|
||||
Foreign keys to organizations: `memberships` and `organization_representatives` reference `organizations(id)` now. The consent ledger, the needs, and the invitations carry an `organization_id` and reference it with a restricting foreign key in the migration that creates the invitation records (TASK-198), because the C4 scope needs both references at once and the ledger tests of TASK-062 and TASK-063 use synthetic organization identifiers. The application never deletes an organization.
|
||||
Foreign keys to organizations: `memberships` and `organization_representatives` reference `organizations(id)` now. The consent ledger, the needs, and the invitations carry an `organization_id` and reference it with a restricting foreign key in the migration that creates the invitation records, because the C4 scope needs both references at once and the consent ledger tests use synthetic organization identifiers. The application never deletes an organization.
|
||||
|
||||
Open questions for the product owner:
|
||||
|
||||
- Representatives: may the card show their names to every candidate before an invitation is accepted, and who answers for the right to publish an employee's name (152-FZ)? The alternative is to show representatives only in an invitation sent by their organization.
|
||||
- Organizations per account (blocking for TASK-078 and TASK-087): the PRD sets no limit, and FR07 says that quotas belong to the organization as a whole and never grow on their own, but nothing stops one account from creating many organizations, each at `e0` with its own quota, which multiplies the quotas. This contract invents no number. The mechanism is ready: a cap would answer 409 `state_conflict` on `CreateOrganization` without a change of the schema, and the anti-abuse signals are TASK-319. The owner must decide the limit, or accept the risk explicitly, before the quotas of TASK-087 are enforced and before `CreateOrganization` is opened to users.
|
||||
- Organizations per account (blocking for organization creation and quota enforcement): the PRD sets no limit, and FR07 says that quotas belong to the organization as a whole and never grow on their own, but nothing stops one account from creating many organizations, each at `e0` with its own quota, which multiplies the quotas. This contract invents no number. The mechanism is ready: a cap would answer 409 `state_conflict` on `CreateOrganization` without a change of the schema, and the anti-abuse signals belong to organization risk assessment. The owner must decide the limit, or accept the risk explicitly, before the organization quotas are enforced and before `CreateOrganization` is opened to users.
|
||||
- Sphere: free text now; a taxonomy for the sphere, matching the domains of needs, is a decision for the search filters.
|
||||
- Contacts: whether the card needs a fifth kind, such as a careers page, and whether the email must share the domain of the website.
|
||||
|
||||
Planned, additive: member invitations, listing, role changes, and removal (TASK-081 to TASK-085), the full role matrix (TASK-463), the verification processes and their history (TASK-086), the quotas by level (TASK-087), the card in the candidate's invitation, the number-of-organizations cap, and a sphere code.
|
||||
Planned, additive: member invitations, listing, role changes, and removal, the full role matrix, the verification processes and their history, the quotas by level, the card in the candidate's invitation, the number-of-organizations cap, and a sphere code.
|
||||
|
||||
No new problem code is added: the contract reuses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused`, and `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`, and `TestOrganizationContractFollowsThePRD` pin the generated server and the bundle, and `frontend/src/shared/api/organization-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of role, owner, member, and verification fields in the requests.
|
||||
|
||||
### Candidate visibility
|
||||
|
||||
The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD, TASK-088). The operations are in the contract but their business logic is not implemented, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` after an accepted session and a valid request. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)).
|
||||
The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD). The operations are in the contract but their business logic is not implemented, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` after an accepted session and a valid request. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)).
|
||||
|
||||
| Method and path | operationId | Protection | Success | Specific errors |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -628,7 +628,7 @@ Each operation also declares the problem response `default`. No new problem code
|
||||
Closed by default and three independent settings:
|
||||
|
||||
- A profile is closed by default. A candidate who never published reads `publication.state` `closed`, `closed_reason` `never_published`, an empty field set, and version 0; saving the profile, filling in the questionnaire, or taking an assessment never publishes it. Every setting has its own `version` (0 is "never set"), its own operation, and its own `expected_version` in the body, so a change of one never makes another stale.
|
||||
- The publication and C2 are separate. The consent C2 stays in the consent ledger (`ListMyConsents`) and proves that the candidate accepted the publication text. `Publication` records which fields are published and when, and refers to the C2 record behind them (`consent_id`, the `id` of a `ConsentRecord` of the same account). It does not duplicate the consent: `state` is `published` only while that record is unrevoked, so a revocation of C2 closes the card at once, and `closed_reason` says `consent_revoked`. A new C2 grant never reopens it: the candidate publishes again and the new publication binds to the new record. The body of `SetMyPublication` names no consent: the server binds the current unrevoked C2 record of the account, and without one answers 409 `state_conflict` (the candidate gives C2 first; the grant operation is planned in the consent settings, TASK-063).
|
||||
- The publication and C2 are separate. The consent C2 stays in the consent ledger (`ListMyConsents`) and proves that the candidate accepted the publication text. `Publication` records which fields are published and when, and refers to the C2 record behind them (`consent_id`, the `id` of a `ConsentRecord` of the same account). It does not duplicate the consent: `state` is `published` only while that record is unrevoked, so a revocation of C2 closes the card at once, and `closed_reason` says `consent_revoked`. A new C2 grant never reopens it: the candidate publishes again and the new publication binds to the new record. The body of `SetMyPublication` names no consent: the server binds the current unrevoked C2 record of the account, and without one answers 409 `state_conflict` (the candidate gives C2 first; the grant operation is planned in the consent settings).
|
||||
- The search status is not a consent. `SearchStatus` and `SearchStatusUpdate` have no consent, publication, or organization property, no schema of one family reaches another (a test walks the references), and `SetMySearchStatus` changes nothing but the status. A candidate whose profile is closed who sets `looking` becomes visible to no one.
|
||||
- Hidden organizations are records of the candidate (`HiddenOrganization`: the organization with its current name and `hidden_at`). One record per candidate and organization, at most 1000 per candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published. Hiding and lifting a hiding change neither C2, nor the publication, nor the search status.
|
||||
- Hiding is a PUT of a state, so it is idempotent and takes no Idempotency-Key: hiding an organization again answers 200 with the original record and writes no history. Lifting is a DELETE that answers 204 whether the organization was hidden or not.
|
||||
@@ -637,16 +637,16 @@ The search status and its 30 days:
|
||||
|
||||
- `looking` ("Ищу") stores `confirmed_at` and `lapses_at`. The interval is not a constant of the contract or the code: it is `search_status.searching_confirmation_interval_days` of the effective `product` policy version (30 in the demo version 1), read when the status is confirmed. The stored row names the policy version it used and fixes `lapses_at`, so a later policy change moves no stored time. The owner changes the interval by publishing a new policy version.
|
||||
- After `lapses_at` the status holds as `not_looking` with `lapsed` true. The lapse is computed on every read and never written, so it needs no job and can only narrow: it never publishes, never unhides, and never changes C2 or the hidden organizations. The candidate confirms again with `SetMySearchStatus` and `looking`, which replaces `confirmed_at` and advances the version. A reminder before the lapse is a planned notification.
|
||||
- A lapsed status is never "more public": the non-public `not_looking` is the only state a lapse reaches. Whether `looking` gates the appearance of a published card in search results is a search contract decision (TASK-185), not decided here.
|
||||
- A lapsed status is never "more public": the non-public `not_looking` is the only state a lapse reaches. Whether `looking` gates the appearance of a published card in search results is a search contract decision, not decided here.
|
||||
|
||||
The anonymous card and the preview:
|
||||
|
||||
- `CardField` is a closed set of groups of card values that the candidate chooses to publish: `categories` (the categories confirmed by assessment results), `stack`, `experience` (total months), `soft_skills`, `location`, and `relocation`. The full name, any contact, and the lowest salary have no value, so no request can publish them; contacts reach an organization only through the contact grant of an accepted invitation (C4), and the lowest salary never does. A self-assessed grade is not a category and is never published. The server stores and answers the set in ascending order of the codes.
|
||||
- `AnonymousCardContent` is the card as an organization reads it: a closed object of the six properties above, each null when it is not published or has no value, so the card does not tell the two apart. It has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and no schema of the private profile, a contact, a consent, an invitation, or an organization is reachable from it (`TestAnonymousCardReachesNoProfileOrContactSchema` walks the references). `GetMyCardPreview` returns it with the published fields, or `card` null while the profile is closed, as a private read that creates no view and no history record. The card of an organization's search result (TASK-185) must reuse this content and cannot add a property that identifies the candidate.
|
||||
- `AnonymousCardContent` is the card as an organization reads it: a closed object of the six properties above, each null when it is not published or has no value, so the card does not tell the two apart. It has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and no schema of the private profile, a contact, a consent, an invitation, or an organization is reachable from it (`TestAnonymousCardReachesNoProfileOrContactSchema` walks the references). `GetMyCardPreview` returns it with the published fields, or `card` null while the profile is closed, as a private read that creates no view and no history record. The card of an organization's search result must reuse this content and cannot add a property that identifies the candidate.
|
||||
|
||||
Versions and checks:
|
||||
|
||||
- Both `PUT` operations of the settings follow the profile pattern: the complete new state in the body, `expected_version` in the body (the generated client cannot read the ETag yet), 412 `version_conflict` for a stale or non-existent version, and an unchanged body answers 200 with the current state even over a stale version, so no Idempotency-Key is needed. Order of checks: session (401), CSRF and Origin (403), request validation (400), account scenario (403), a version above the current one (412), an unchanged state (200), a stale version (412), then the C2 for a publication (409). A published state without a field and a closed state with a field answer 400 with the pointer `/fields`; the schema rejects an unknown or repeated card field and unknown properties such as a consent identifier or a confirmation time. `looking` always changes the stored confirmation, so it answers 412 for a stale version even as a repeat. The two 409 `state_conflict` answers are told apart by `errors`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. A closing over a stored publication whose C2 was revoked is a real change (it stores the closing, records `publication_closed`, and revokes the grants); the C2 revocation path (TASK-064) closes the stored publication and revokes the grants in its own transaction. Publishing, hiding, and the history need a verified email (a usecase requirement). `Problem.errors` is not only for `validation_failed`: a `state_conflict` carries one entry as a disambiguator (`consent_required`, `limit_reached`), so a future problem writer must not strip `errors` from non-validation responses. Only values that the candidate confirmed reach the card, a free text value that looks like a contact (email, phone, URL, Telegram link, @handle) is dropped, and adding a card field is a contract change and a migration.
|
||||
- Both `PUT` operations of the settings follow the profile pattern: the complete new state in the body, `expected_version` in the body (the generated client cannot read the ETag yet), 412 `version_conflict` for a stale or non-existent version, and an unchanged body answers 200 with the current state even over a stale version, so no Idempotency-Key is needed. Order of checks: session (401), CSRF and Origin (403), request validation (400), account scenario (403), a version above the current one (412), an unchanged state (200), a stale version (412), then the C2 for a publication (409). A published state without a field and a closed state with a field answer 400 with the pointer `/fields`; the schema rejects an unknown or repeated card field and unknown properties such as a consent identifier or a confirmation time. `looking` always changes the stored confirmation, so it answers 412 for a stale version even as a repeat. The two 409 `state_conflict` answers are told apart by `errors`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. A closing over a stored publication whose C2 was revoked is a real change (it stores the closing, records `publication_closed`, and revokes the grants); the C2 revocation path closes the stored publication and revokes the grants in its own transaction. Publishing, hiding, and the history need a verified email (a usecase requirement). `Problem.errors` is not only for `validation_failed`: a `state_conflict` carries one entry as a disambiguator (`consent_required`, `limit_reached`), so a future problem writer must not strip `errors` from non-validation responses. Only values that the candidate confirmed reach the card, a free text value that looks like a contact (email, phone, URL, Telegram link, @handle) is dropped, and adding a card field is a contract change and a migration.
|
||||
- 404 and anti-enumeration. `HideOrganization` answers the same 404 `not_found`, with the same body and without a different timing, for an organization that does not exist and for one that the candidate cannot see, so it is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned). The identifiers are random, and the general rate limit can answer 429 with Retry-After before any check. `UnhideOrganization` reveals nothing: 204 for any well-formed identifier. A malformed `org_id` answers 400 with the pointer `/org_id`.
|
||||
- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke that grant with the reason `visibility_closed`, in the same transaction as the change (planned together with the operations; the reason is fixed in the invitation contract). Lifting a hiding or publishing again never reopens a grant. The search status never revokes a grant.
|
||||
|
||||
@@ -658,17 +658,17 @@ History:
|
||||
Open questions for the product owner and the lawyer:
|
||||
|
||||
- The search status values: the contract has `looking` and `not_looking`. Whether the PRD needs a third status such as "open to offers" is not decided; a value is an additive change.
|
||||
- Whether `looking` gates the appearance of a published card in search (an organization sees only candidates who are searching) or is only a label. This decides the meaning of a lapse for visibility and belongs to the search contract (TASK-185).
|
||||
- Whether `looking` gates the appearance of a published card in search (an organization sees only candidates who are searching) or is only a label. This decides the meaning of a lapse for visibility and belongs to the search contract.
|
||||
- The set of card fields. The six values are a proposal that matches the profile; the PRD card (FR11) may add, split, or drop some, for example a generalized employer industry and size instead of employers, and each is an additive contract change.
|
||||
- Whether publishing needs a minimum: at least one confirmed category, or a saved profile. The contract only requires one card field and an active C2.
|
||||
- Whether narrowing the published fields, not only closing the publication or hiding an organization, must revoke the contact grants. The invitation contract says any visibility change after a grant revokes it; this contract revokes on closing and hiding only.
|
||||
- How a candidate finds an organization to hide before any invitation. The contract hides by identifier and answers 404 for an organization the candidate cannot see, so hiding the current employer in advance needs an organization lookup for candidates (by name or domain), which must itself be safe against enumeration (a minimum query length, a rate limit, public data only). Without it, hiding works only for organizations that have written to the candidate.
|
||||
- Whether the candidate should learn the name of an organization that viewed the card without an invitation (`CardAccess.organization`), and how long accesses are kept.
|
||||
- The limit of hidden organizations (1000 now) and the retention of the settings and their history together with the consent evidence (152-FZ, PRD 7.3). The history references the account with `ON DELETE CASCADE`, guarded by two triggers: UPDATE is always refused, and DELETE (and the deletion of the account) is refused while the account is verified, the same condition as the consent ledger; the unverified account cleanup removes the history of an account it deletes, and the account deletion procedure extends the condition.
|
||||
- Free text in the card (stack tags, soft skills, location) is guarded only by `CardTextLooksLikeContact`, which errs on the side of dropping (Socket.io is dropped, a bare obfuscation can still slip through); the residual risk is closed by TASK-089 with a closed taxonomy instead of free text.
|
||||
- Free text in the card (stack tags, soft skills, location) is guarded only by `CardTextLooksLikeContact`, which errs on the side of dropping (Socket.io is dropped, a bare obfuscation can still slip through); the residual risk still requires a closed taxonomy in the card builder instead of free text.
|
||||
- Whether C2 is a consent to the distribution of personal data under article 10.1 of 152-FZ and needs its own field scope (see Consents); the history keeps the fields and times in the meantime.
|
||||
- Whether a new C2 text version requires the candidate to consent again for an existing publication. Now a publication stays effective while its C2 record is unrevoked, so a newer text version that the candidate has not accepted does not close it.
|
||||
- Quasi-identifiers and k-anonymity of the card: a rare combination of location, stack, and experience can identify a candidate even without a name. The generalization of rare features and a minimum group size are acceptance criteria of TASK-089, which builds the card; the contract here only fixes the closed set of fields, the confirmed-values-only rule, and the dropping of free text that looks like a contact.
|
||||
- Quasi-identifiers and k-anonymity of the card: a rare combination of location, stack, and experience can identify a candidate even without a name. The generalization of rare features and a minimum group size are acceptance criteria for the card builder; the contract here only fixes the closed set of fields, the confirmed-values-only rule, and the dropping of free text that looks like a contact.
|
||||
- Retention and the right to erasure for the settings history. The hide and unhide records are sensitive (they say which employer a candidate avoids). The history is kept like the consent evidence and is not deletable while the account is confirmed; whether a candidate can erase it, when, and how this meets the three-year consent retention (PRD 7.3) is an open legal question. The account deletion procedure extends the delete condition of the table.
|
||||
|
||||
No new problem code is added. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation`, and `TestPrivacyAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/privacy-contract.test.ts` pins the generated Zod rules, the absence of a consent, a time, a contact, or a salary in the request and card types, and the absence of settings in the organization, invitation, need, profile, and consent files.
|
||||
|
||||
+57
-57
@@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
### Identity: сессии, cookie и CSRF
|
||||
|
||||
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount` и `ResendEmailVerification` реализованы (TASK-053); остальные публичные операции после валидации запроса по-прежнему отвечают 501 `not_implemented`, а `v1.DenyAllSecurity` в backend отклоняет любую сессию, поэтому операции, которым она нужна, отвечают 401 `unauthenticated`. Значения, отмеченные как запланированные, задаются конфигурацией в TASK-054 - TASK-056.
|
||||
Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount` и `ResendEmailVerification` реализованы; остальные публичные операции после валидации запроса по-прежнему отвечают 501 `not_implemented`, а `v1.DenyAllSecurity` в backend отклоняет любую сессию, поэтому операции, которым она нужна, отвечают 401 `unauthenticated`. Значения, отмеченные как запланированные, задаются конфигурацией подтверждения почты, входа и сессий.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -121,8 +121,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email, а вход отвечает 401 `invalid_credentials` и для неизвестного email, и для неверного пароля.
|
||||
- До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта.
|
||||
- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля и сценарий) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует все прежние токены подтверждения. Подтверждение токена (`ConfirmEmail`, TASK-054) обязано применять отложенные данные только этого токена и требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными; в текущем `EmailVerificationRequest` поля пароля нет, поэтому TASK-054 меняет контракт. Это не дает владельцу адреса, перешедшему по ссылке злоумышленника, принять предрегистрацию с чужим паролем, и наоборот. Строкой неподтвержденного аккаунта нельзя войти: вход (TASK-055) отклоняет любой неподтвержденный аккаунт и никогда не сравнивает пароль со строкой или с отложенными данными неподтвержденного аккаунта. Для подтвержденного email ничего не меняется; сервер ничего не отправляет.
|
||||
- Реализация регистрации и повторной отправки (TASK-053). Подтвержденный адрес: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на адрес (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа; на клиента: `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час). Отклоненный запрос дает 429 `rate_limited` с `Retry-After` в целых секундах и не выпускает токен. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток и ключи лимитера. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-и-повторная-отправка-подтверждения).
|
||||
- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля и сценарий) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует все прежние токены подтверждения. Подтверждение токена (`ConfirmEmail`) обязано применять отложенные данные только этого токена и требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными; в текущем `EmailVerificationRequest` поля пароля нет, поэтому подтверждение почты требует изменения контракта. Это не дает владельцу адреса, перешедшему по ссылке злоумышленника, принять предрегистрацию с чужим паролем, и наоборот. Строкой неподтвержденного аккаунта нельзя войти: вход отклоняет любой неподтвержденный аккаунт и никогда не сравнивает пароль со строкой или с отложенными данными неподтвержденного аккаунта. Для подтвержденного email ничего не меняется; сервер ничего не отправляет.
|
||||
- Реализация регистрации и повторной отправки. Подтвержденный адрес: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на адрес (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа; на клиента: `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час). Отклоненный запрос дает 429 `rate_limited` с `Retry-After` в целых секундах и не выпускает токен. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток и ключи лимитера. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-и-повторная-отправка-подтверждения).
|
||||
- Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии с отложенными данными этой регистрации, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики).
|
||||
- Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля.
|
||||
- Ссылка подтверждения имеет вид `<frontend origin>/verify-email#token=<token>`. Страница удаляет фрагмент через `history.replaceState` и отправляет токен только после явного действия пользователя, поэтому токен не попадает в логи сервера и заголовок Referer, а сканер ссылок его не расходует. Подтверждение не создает сессию.
|
||||
@@ -139,11 +139,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
- Схема `sessionCookie` - cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict` и без Domain. Сервер хранит сессии в PostgreSQL и берет вызывающего только из сессии. Сессию получает только подтвержденный аккаунт. Вход отзывает сессию, пришедшую с запросом, и выдает новый идентификатор и CSRF-токен; выход отзывает сессию на сервере. Запланированные тайм-ауты: 24 часа простоя и 7 дней абсолютного срока; активность продлевает только срок простоя. Оба значения берутся из версионированной продуктовой политики, а не из конфигурации.
|
||||
- Схема `sessionCsrf` - заголовок `X-CSRF-Token` с привязанным к сессии токеном из `Session.csrf_token`. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`.
|
||||
- Любой небезопасный запрос, включая публичные, должен нести `Origin` из настроенного allowlist, иначе 403 `csrf_check_failed` (запланировано, TASK-056; см. [руководство по разработке](../docs/ru/DEVELOPMENT.md#сессии-на-локальном-http)). Публичные операции identity ограничены по частоте (429 с `Retry-After`).
|
||||
- Любой небезопасный запрос, включая публичные, должен нести `Origin` из настроенного allowlist, иначе 403 `csrf_check_failed` (запланировано; см. [руководство по разработке](../docs/ru/DEVELOPMENT.md#сессии-на-локальном-http)). Публичные операции identity ограничены по частоте (429 с `Retry-After`).
|
||||
- Ответы с сессией или аккаунтом несут `Cache-Control: no-store`.
|
||||
- Корневой `security` требует `sessionCookie`, поэтому операция без явного `security: []` защищена по умолчанию.
|
||||
|
||||
Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и какое отображение запланировано для TASK-056, описано в `v1.DenyAllSecurity` и закреплено тестом `TestGeneratedServerSecurityOrder`:
|
||||
Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и какое отображение запланировано для аутентификации сессий, описано в `v1.DenyAllSecurity` и закреплено тестом `TestGeneratedServerSecurityOrder`:
|
||||
|
||||
- Он вызывает `HandleSessionCookie` раньше `HandleSessionCsrf` и передает дальше контекст, возвращенный успешным вызовом. Отсутствующее значение (нет cookie, пустой `X-CSRF-Token`) не вызывает обработчик, а обработчик, вернувший `ogenerrors.ErrSkipServerSecurity`, считается невыполненным; в обоих случаях проверка продолжается со следующей схемы, поэтому `HandleSessionCsrf` вызывается и без cookie, с исходным контекстом.
|
||||
- Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`.
|
||||
@@ -179,7 +179,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
### Профиль кандидата
|
||||
|
||||
Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD, TASK-066). Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидной схемы - 501 `not_implemented`.
|
||||
Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD). Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидной схемы - 501 `not_implemented`.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -215,11 +215,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
- Профиль полностью заполняется вручную. Ни одно поле не требует резюме, извлечения ML или аккаунта ФСП, а миграция и запросы не создают обязательной связи с файлом, ML или ФСП. Загрузка резюме и привязка ФСП ID - запланированные аддитивные возможности; они добавят свои поля и источники, не меняя этих.
|
||||
|
||||
Связь с анкетой (TASK-150):
|
||||
Связь с анкетой:
|
||||
|
||||
- Анкета (`/me/questionnaire`) задает не более двух специализаций для оценки; профиль - то, что кандидат показывает о себе. Одноименные понятия не дублируются под разным смыслом: самооценка грейда и стек - одно и то же заявление в двух местах (в анкете для старта оценки и по специализации, в профиле для показа), сохраняются раздельно, и сервер не копирует одно в другое; общий опыт в месяцах в анкете и записи опыта в профиле - разные заявления; форматы работы живут только в анкете, а место, переезд и зарплата - только в профиле. Описания схем обеих сторон ссылаются друг на друга.
|
||||
|
||||
Хранение (миграция 00013, TASK-066): `candidate_profiles` (строка профиля: `user_id`, `version`, времена) и `candidate_profile_claims` (по строке на сохраненное заявление: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). Отсутствие строки значит `unknown`. Для каждого вида значения есть CHECK формата и границ контракта; `trust_level` всегда 0; в таблицах нет ни столбца файла, ни столбца ФСП, ни подтвержденного грейда. Подробности - в [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#профиль-кандидата).
|
||||
Хранение (миграция 00013): `candidate_profiles` (строка профиля: `user_id`, `version`, времена) и `candidate_profile_claims` (по строке на сохраненное заявление: `kind`, `ordinal`, `value` jsonb, `status`, `origin`, `trust_level`, `quote`, `extraction_version`, `confirmed_at`). Отсутствие строки значит `unknown`. Для каждого вида значения есть CHECK формата и границ контракта; `trust_level` всегда 0; в таблицах нет ни столбца файла, ни столбца ФСП, ни подтвержденного грейда. Подробности - в [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#профиль-кандидата).
|
||||
|
||||
Открытые вопросы к владельцу продукта и юристу:
|
||||
|
||||
@@ -230,7 +230,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
- Минимум для шага онбординга `candidate_profile`: контракт не требует ни одного поля; какие поля нужны, чтобы шаг считался пройденным, решает владелец продукта.
|
||||
- Единый источник между анкетой и профилем: оставить самооценку и стек независимыми или хранить одно заявление и показывать в обоих местах.
|
||||
- Софт-скиллы: таксономии нет, свободный текст до 10 штук по 50 символов; нужен ли справочник.
|
||||
- Опыт: названия работодателей и описания - ПДн; как анонимная карточка их обобщает (PRD: отрасль и размер), решает контракт карточки (TASK-185), а не этот.
|
||||
- Опыт: названия работодателей и описания - ПДн; как анонимная карточка их обобщает (PRD: отрасль и размер), решает контракт карточки, а не этот.
|
||||
- Проверка контактов (подтверждение телефона или email профиля) не предусмотрена: контакты - заявления уровня 0.
|
||||
|
||||
`TestCandidateProfileOperationsFollowTheConventions`, `TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory`, `TestCandidateProfileClaimsCarrySourceAndTrustLevelZero`, `TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs`, `TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests`, `TestProfileSchemaValidationPrecedesImplementation` и `TestProfileAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/profile-contract.test.ts` - сгенерированные правила Zod, типы запросов без подтвержденного грейда и отсутствие полей профиля в схемах организации, приглашения и потребности.
|
||||
@@ -278,7 +278,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
- Лимиты: `expires_at` и `sessions` (`used`, `max`, `idle_timeout_seconds`; null, если политика не задает лимит сессий) берутся из версии политики; FR04 в PRD допускает две сессии в пределах 72 часов. Создание начинает сессию 1. Чтение или команда по активной попытке после `idle_timeout_seconds` без них начинает следующую сессию; сессия сверх `max` не начинается, и попытка становится `expired`. Чтение терминальной попытки или результата сессию не начинает.
|
||||
- При достижении лимитов практика в статусе `pending` сначала оценивается. Затем сервер сам завершает `ready_to_finalize` и переводит в `completed`, неотправленная дополнительная практика считается отклоненной (`completed`, `not_confirmed`), а `in_progress` и `practice_pending` становятся `expired`. Завершение после этого дает 200 с попыткой в `completed`; любая другая команда дает 409 `state_conflict`.
|
||||
- Недостаточный банк - отдельное состояние в двух местах. До старта `GetMyAssessmentAvailability` показывает `insufficient_bank` для грейда без опубликованного банка или без достаточного числа семейств, которых кандидат еще не видел, а `CreateMyAssessmentAttempt` отвечает 409 `state_conflict` и ничего не создает. Во время попытки терминальное состояние `insufficient_bank` завершает ее без подтвержденного грейда вместо повтора семейств.
|
||||
- Новый код проблемы не добавлен, поэтому TASK-157 получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может.
|
||||
- Новый код проблемы не добавлен, поэтому создание попытки получает 409 `state_conflict` и статус доступности вместо кода `bank_unavailable`. Перечисление `ProblemCode` побайтно скопировано в ML-контракт (`test_contract_copies.py`), поэтому новый код изменил бы и ML-контракт, и его сгенерированные модели. Чтение доступности к тому же объясняет клиенту, почему попытка не может начаться, и для `cooldown` - с какого момента; фиксированный detail проблемы этого передать не может.
|
||||
- Доступность показывает лимиты каждого грейда до старта: `time_limit_seconds`, `max_sessions`, `max_items` и `practice_required`; null, если значение неизвестно.
|
||||
- Учет в правилах повтора (3 попытки за 180 дней, 30 дней до повтора того же грейда): попытка с итогом `not_determined` по причине `expired` или `practice_incomplete` - попытка кандидата и учитывается. `insufficient_bank` и `sandbox_unavailable` - сбои платформы: они не учитываются и не запускают интервал. После неудачи, включая первый тест, меньший грейд можно проверить сразу.
|
||||
|
||||
@@ -296,7 +296,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
- Каждое задание принимает один ответ. Повторная отправка сохраненного ответа, даже с новым ключом или старым `expected_version`, ничего не сохраняет, не меняет версию и дает 200 с текущей попыткой. Равенство определено для каждого формата: множества для `option_ids` и `line_numbers`, точная последовательность для `element_ids`, числовое равенство для `number`, совпадение текста без нормализации для `text` и `config`, тот же язык и совпадающий исходный код для практики. Другой ответ на уже отвеченное задание дает 409 `state_conflict` при текущей версии; при устаревшей версии ее проверка идет раньше и дает 412.
|
||||
- Исключение: практика, последний вердикт которой `failed`, не подпадает под правило повтора. Отправка того же или другого решения с текущей версией снова ставит его в очередь и увеличивает версию.
|
||||
- Завершение попытки в `completed` дает 200 с этой попыткой, поэтому результат вычисляется один раз. Повтор завершения, которое предложило дополнительную практику, с новым ключом несет старую версию и получает 412, поэтому он не может случайно отклонить предложение.
|
||||
- Устаревший `expected_version` дает 412 `version_conflict`, а не 409. Это отступление от формулировки шага проверки TASK-155 и TASK-152, где указан 409. Так сохраняется правило репозитория выше и прецедент анкеты: `version_conflict` - это 412 и для If-Match, и для `expected_version` в теле, потому что действие клиента одно - прочитать ресурс снова. 409 `state_conflict` оставлен для команды, которую состояние попытки не допускает при текущей версии: задание не текущее или уже имеет другой ответ, попытка терминальная или вышла за лимиты, вердикт практики еще не готов или попытка не готова к завершению. Поэтому два кода ведут к разным действиям клиента.
|
||||
- Устаревший `expected_version` дает 412 `version_conflict`, а не 409. Так сохраняется правило репозитория выше и прецедент анкеты: `version_conflict` - это 412 и для If-Match, и для `expected_version` в теле, потому что действие клиента одно - прочитать ресурс снова. 409 `state_conflict` оставлен для команды, которую состояние попытки не допускает при текущей версии: задание не текущее или уже имеет другой ответ, попытка терминальная или вышла за лимиты, вердикт практики еще не готов или попытка не готова к завершению. Поэтому два кода ведут к разным действиям клиента.
|
||||
- Преждевременное завершение дает 409 `state_conflict` без перечня незавершенных заданий, потому что `Problem` не допускает дополнительных полей. Клиент берет их из попытки: `state`, `progress`, `current_item` и `practices`.
|
||||
- Порядок проверок команды: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403 `forbidden`), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), попытка (404, после всех назревших переходов), повтор сохраненного ответа или завершения завершенной попытки (200), версия (412), состояние (409 `state_conflict`), затем доменные правила (400 с pointer вроде `/answer/option_ids/0`). По соглашению об Idempotency-Key 404 и 409 `state_conflict` сохраняются под ключом и повторяются, а 400 (включая доменные правила), 412, 429 и 5xx - нет. Создание и ответы ограничены по частоте (429 с `Retry-After`), что ограничивает и нагрузку на песочницу. `TestAssessmentSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер.
|
||||
|
||||
@@ -324,7 +324,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
Доступ:
|
||||
|
||||
- `org_id` в пути - единственный источник организации, и сервер сверяет его с действующим членством аккаунта сессии; ни один запрос не содержит поля организации, членства или роли. Организации и членства принадлежат контракту организации (TASK-077), который переиспользует тот же параметр пути `parameters.yml#/OrganizationId`.
|
||||
- `org_id` в пути - единственный источник организации, и сервер сверяет его с действующим членством аккаунта сессии; ни один запрос не содержит поля организации, членства или роли. Организации и членства принадлежат контракту организации, который переиспользует тот же параметр пути `parameters.yml#/OrganizationId`.
|
||||
- Аккаунт без действующего членства в `org_id`, неизвестная организация, неизвестная потребность и потребность другой организации одинаково дают 404 `not_found`, поэтому идентификаторы нельзя перебрать. Аккаунт кандидата получает 403 `forbidden`, как и участник, чья роль не разрешает операцию.
|
||||
- В MVP с потребностями работает только владелец организации. Остальные роли матрицы FR07 в PRD (рекрутер, нанимающий менеджер и техэксперт для назначенных потребностей) запланированы и не меняют ни одного поля контракта.
|
||||
|
||||
@@ -335,7 +335,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
- `source` содержит `origin` (`manual`, `extracted_from_text` или запланированный `imported`), `quote` (точный фрагмент до 300 знаков или null), `extracted_in_version` и `extraction_version`. Цитата - фрагмент `source_text` версии `extracted_in_version`, а не обязательно текущего текста: подтвержденное значение сохраняет цитату после изменения текста. Подтверждение предложения сохраняет его происхождение; изменение значения делает его `manual`.
|
||||
- У навыка есть `taxonomy_code`. Он равен null для навыка, которого нет в таксономии платформы: название остается как указано, код не угадывается, а рекомендации считают навык непокрытым.
|
||||
- При наличии `source_text` сервер до ответа извлекает предложения детерминированными правилами и словарем, поэтому потребности работают при выключенном ML. ML-предложения с цитатами запланированы как асинхронное дополнение, которое создает новую версию и никогда не перезаписывает подтвержденное значение.
|
||||
- Текст хранится как написан и может содержать дискриминирующие требования по защищенным признакам; извлечение никогда не превращает их в поле потребности. Поле того, чего не должно быть у кандидата, с проверкой по ст. 64 ТК РФ отложено до TASK-182 и добавится без ломающих изменений.
|
||||
- Текст хранится как написан и может содержать дискриминирующие требования по защищенным признакам; извлечение никогда не превращает их в поле потребности. Поле того, чего не должно быть у кандидата, с проверкой по ст. 64 ТК РФ отложено до реализации проверки требований и добавится без ломающих изменений.
|
||||
|
||||
Запросы, подтверждение и изменения:
|
||||
|
||||
@@ -350,8 +350,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
Версии и конкурентность:
|
||||
|
||||
- `version` начинается с 1 и растет ровно на единицу с каждым зафиксированным изменением, включая серверные. Каждая версия - неизменяемый снимок. GET всегда возвращает последнюю версию.
|
||||
- `requirements_version` - версия, в которой подтвержденные требования менялись последний раз. Подтверждение, изменение или удаление требования делает ее равной новой `version`; изменение названия, привязки вакансии, текста или только предложений ее сохраняет и не обесценивает ни рекомендации, ни результаты поиска. Запуски поиска, снимки подборки (FR10, TASK-193) и приглашения ссылаются на `(need_id, requirements_version)`, и новый снимок подборки нужен только при новой `requirements_version`. Чтение и сравнение прежних версий запланированы отдельными операциями, которые возвращают `NeedRequirementSet` для версии; в `Need` они ничего не добавляют.
|
||||
- Изменение передает `expected_version` - прочитанную клиентом версию - в теле по той же причине, что и анкета: сгенерированный клиент пока не читает `ETag`. Устаревшее значение дает 412 `version_conflict` и ничего не меняет; в TASK-179 указан 409, но правило репозитория сохраняет 412 и для If-Match, и для версии в теле. Тело, которое ничего не меняет, дает 200 с текущей потребностью даже со старой версией, поэтому PATCH не нужен Idempotency-Key. POST требует его с повтором в течение 24 часов; сохраняется только 201.
|
||||
- `requirements_version` - версия, в которой подтвержденные требования менялись последний раз. Подтверждение, изменение или удаление требования делает ее равной новой `version`; изменение названия, привязки вакансии, текста или только предложений ее сохраняет и не обесценивает ни рекомендации, ни результаты поиска. Запуски поиска, снимки подборки (FR10) и приглашения ссылаются на `(need_id, requirements_version)`, и новый снимок подборки нужен только при новой `requirements_version`. Чтение и сравнение прежних версий запланированы отдельными операциями, которые возвращают `NeedRequirementSet` для версии; в `Need` они ничего не добавляют.
|
||||
- Изменение передает `expected_version` - прочитанную клиентом версию - в теле по той же причине, что и анкета: сгенерированный клиент пока не читает `ETag`. Устаревшее значение дает 412 `version_conflict` и ничего не меняет; правило репозитория сохраняет 412 и для If-Match, и для версии в теле. Тело, которое ничего не меняет, дает 200 с текущей потребностью даже со старой версией, поэтому PATCH не нужен Idempotency-Key. POST требует его с повтором в течение 24 часов; сохраняется только 201.
|
||||
|
||||
Готовность:
|
||||
|
||||
@@ -363,18 +363,18 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
- `SalaryRange` `[A; B]` содержит `salary_from` и `salary_to` (`RubAmount`, целые рубли), `currency` (только `RUB`), `period` (только `month`) и `tax_basis` (`net` или `gross`); все поля обязательны. Запрос передает ее как `salary: {value, status}`, поэтому ее pointer начинаются с `/salary/value`.
|
||||
- Схема требует положительных границ, кратных 1000, до 100000000 и отклоняет другую валюту, период или базу, например с `/salary/value/tax_basis`. Отсутствующее поле вложенной вилки дает `required` со своим pointer, например `/salary/value/tax_basis`.
|
||||
- Межполевые правила FR13 в PRD сервер проверяет в целочисленной арифметике: `A < B` и ширина `(B - A) / ((A + B) / 2)` от 10% до 40% включительно, то есть `20 * (B - A) >= A + B` и `5 * (B - A) <= A + B`. Нарушение, включая равные границы, дает 400 с pointer `/salary/value/salary_to`. `[95000; 105000]` (ровно 10%) и `[80000; 120000]` (ровно 40%) принимаются. FR13 применяет одни правила к вилке потребности и приглашения, и `docs/*/ARCHITECTURE.md` теперь указывает их для приглашений вместо `0 < salary_from <= salary_to`.
|
||||
- Ограничение против подбора скрытых минимумов (FR13, запланировано в TASK-211): задание подтвержденной вилки при создании или изменении учитывается в счетчике, общем для всей организации, всех участников и всех потребностей, поэтому новая потребность его не обнуляет. Не больше трех заданий вилки в сутки; сверх лимита сервер отвечает 429 с Retry-After и ничего не меняет. После пяти заданий за семь дней денежная компонента получает статус `withheld` на семь дней. Повторные изменения вилки также питают приватные сигналы риска TASK-319.
|
||||
- Ограничение против подбора скрытых минимумов (FR13, применение запланировано): задание подтвержденной вилки при создании или изменении учитывается в счетчике, общем для всей организации, всех участников и всех потребностей, поэтому новая потребность его не обнуляет. Не больше трех заданий вилки в сутки; сверх лимита сервер отвечает 429 с Retry-After и ничего не меняет. После пяти заданий за семь дней денежная компонента получает статус `withheld` на семь дней. Повторные изменения вилки также питают приватные сигналы риска организации.
|
||||
|
||||
Рекомендации:
|
||||
|
||||
- `recommendations` вычисляет сервер по подтвержденным требованиям версии `requirements_version` с версионируемой политикой (`policy_version`, `algorithm_version`, `computed_at`). `status` - `computed`, `pending` или `not_available` без подтвержденного навыка. Сервер может пересчитать их для той же `requirements_version` при новой политике или изменившемся пуле кандидатов без новой версии потребности; тогда меняются `computed_at` и `policy_version`.
|
||||
- У каждой категории (`specialization` и `grade`) есть `score`, `skill_overlap` (взвешенная доля с весом 2 для обязательных и 1 для желательных навыков, покрытые и непокрытые навыки), `money` и `supply` диапазоном: `fewer_than_5`, `from_5_to_29`, `30_or_more`. Порядок списка задает ранжирование.
|
||||
- `money.status` - `computed`, `insufficient_data` (меньше пяти кандидатов с известным сопоставимым минимумом), `no_salary` или `withheld`; последние три используют нейтральное 0,5 и null в доле. `money.share` округляется вниз до четверти (0, 0.25, 0.5, 0.75, 1): каждая проба новой верхней границы говорит не больше того, какая четверть группы ее принимает, а в наименьшей допустимой группе из пяти один минимум часто не сдвигает значение; при этом доля по-прежнему отличает вилку, которую принимает большинство, от той, которую принимают немногие.
|
||||
- `score` равен `0.5 * Overlap + 0.3 * Money + 0.2 * Supply` с округлением половины вверх до двух знаков и вычисляется по опубликованным компонентам: точному покрытию, доле с округлением до четверти или нейтральному 0,5 и `Supply = min(1, active / 30)`. Он равен null, когда `supply` - `fewer_than_5`. Ниже пяти ранжирование использует Supply только с точностью диапазона: каждая группа меньше пяти кандидатов входит в него с Supply 0, поэтому ни балл, ни порядок не раскрывают точный размер группы меньше пяти, что запрещает FR08. Для пяти и более кандидатов используется точный Supply, поэтому фикстура TASK-183 (Overlap 1, Money 0,5, 15 активных кандидатов) дает `score` 0.75.
|
||||
- Отступление от формулы PRD, TASK-183 и TASK-457: в балле и ранжировании используется доля денег, округленная до четверти, а не точная, и у категории меньше чем с пятью кандидатами балла нет. Иначе балл с точной долей раскрыл бы долю, которую округляет `money.share`, а балл с точным Supply малой группы - ее размер. Разложение, которое показывает TASK-457, состоит из опубликованных компонент.
|
||||
- `score` равен `0.5 * Overlap + 0.3 * Money + 0.2 * Supply` с округлением половины вверх до двух знаков и вычисляется по опубликованным компонентам: точному покрытию, доле с округлением до четверти или нейтральному 0,5 и `Supply = min(1, active / 30)`. Он равен null, когда `supply` - `fewer_than_5`. Ниже пяти ранжирование использует Supply только с точностью диапазона: каждая группа меньше пяти кандидатов входит в него с Supply 0, поэтому ни балл, ни порядок не раскрывают точный размер группы меньше пяти, что запрещает FR08. Для пяти и более кандидатов используется точный Supply, поэтому фикстура рекомендаций (Overlap 1, Money 0,5, 15 активных кандидатов) дает `score` 0.75.
|
||||
- Отступление от формулы PRD: в балле и ранжировании используется доля денег, округленная до четверти, а не точная, и у категории меньше чем с пятью кандидатами балла нет. Иначе балл с точной долей раскрыл бы долю, которую округляет `money.share`, а балл с точным Supply малой группы - ее размер. Отображаемое разложение, состоит из опубликованных компонент.
|
||||
- Запрос не может задать рекомендацию, ее балл, членство или минимум кандидата: у тел `additionalProperties: false`, и неизвестные поля, например `rec_score`, `members`, `candidate_minimum`, `version`, `requirements_version` или `recommendations`, дают 400 с pointer на все тело. `TestNeedSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер, `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` - декодирование списков, а `frontend/src/shared/api/needs-contract.test.ts` закрепляет ограничения сгенерированного Zod, явный статус каждого решения и отсутствие этих полей в типах запросов.
|
||||
|
||||
Запланировано, добавляется без ломающих изменений: чтение и сравнение версий, исключения (TASK-182), подсказка рыночной вилки (P25-P75) из FR08, план проверки "вакансия -> задания", статус потребности для архивации, фильтры списка и назначения на потребность.
|
||||
Запланировано, добавляется без ломающих изменений: чтение и сравнение версий, исключения, подсказка рыночной вилки (P25-P75) из FR08, план проверки "вакансия -> задания", статус потребности для архивации, фильтры списка и назначения на потребность.
|
||||
|
||||
### Обращения
|
||||
|
||||
@@ -391,8 +391,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
Доступ:
|
||||
|
||||
- Автор - аккаунт сессии; ни один запрос не содержит поля пользователя, аккаунта или организации. FR18 в PRD позволяет обращаться в поддержку и кандидату, и сотруднику компании, поэтому `/me` обслуживает оба сценария: аккаунт работодателя открывает обращения типа `support`, а остальные типы дают ему 403 `forbidden`. Обращение принадлежит создавшему его аккаунту, а не организации: другие участники той же организации его не видят.
|
||||
- Обращение другого аккаунта дает 404 `not_found`, как и неизвестный идентификатор. TASK-314 говорит о "forbidden" для URL чужого обращения; контракт вместо этого отвечает 404, чтобы идентификаторы нельзя было перебрать, и клиент показывает одно и то же состояние "не найдено" для чужого и неизвестного обращения. Автор читает обращение независимо от того, что потом стало с объектом, поэтому отказ в тесте или отозванный доступ его не скрывают.
|
||||
- Очереди модерации из TASK-316 - отдельные служебные операции со своими DTO; к этим операциям они ничего не добавляют.
|
||||
- Обращение другого аккаунта дает 404 `not_found`, как и неизвестный идентификатор. Контракт отвечает 404, чтобы идентификаторы нельзя было перебрать, и клиент показывает одно и то же состояние "не найдено" для чужого и неизвестного обращения. Автор читает обращение независимо от того, что потом стало с объектом, поэтому отказ в тесте или отозванный доступ его не скрывают.
|
||||
- Очереди модерации - отдельные служебные операции со своими DTO; к этим операциям они ничего не добавляют.
|
||||
|
||||
Типы и ссылки на объекты:
|
||||
|
||||
@@ -406,10 +406,10 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
- Запрос - `oneOf` из пяти вариантов, выбираемых по `type` (`SupportCaseCreateSupport`, `SupportCaseCreateComplaint`, `SupportCaseCreateGradeAppeal`, `SupportCaseCreateAnticheatAppeal`, `SupportCaseCreateManualAssessment`). Каждый вариант сужает схему своей ссылки, поэтому уже схема отклоняет организацию в апелляции грейда или обращение в жалобе с pointer `/object/type`, а отсутствующее поле типа - с его pointer, например `/object` или `/assessment_target`. ogen выбирает вариант по значению `type`. Неизвестный или отсутствующий тип и поле другого варианта, например `complaint_reason` в обращении в поддержку, дают 400 с pointer на все тело `""`, потому что относятся к варианту верхнего уровня; `object.id`, который не является UUID, дает 400 с `/object/id` (пример `SupportCaseMalformedReference`).
|
||||
- Категорию, присвоенную без попытки, тоже можно оспорить (FR18): апелляция грейда может ссылаться на собственное обращение ручной оценки, когда оно `resolved` с `assessed`. Неизвестное обращение и обращение другого аккаунта дают 404 `not_found`; собственное обращение другого типа, еще не решенное или решенное с другим исходом дает 409 `state_conflict`.
|
||||
- Организацию видит кандидат, которого она пригласила или которому контракт организации (TASK-077) показывает ее профиль, и аккаунт работодателя с действующим членством в ней. Сервер сверяет каждую ссылку с аккаунтом сессии: неизвестный и чужой объект одинаково дают 404 `not_found`, поэтому ссылка не раскрывает, существует ли чужой объект. Обращение хранит только `{type, id}`.
|
||||
- Организацию видит кандидат, которого она пригласила или которому контракт организации показывает ее профиль, и аккаунт работодателя с действующим членством в ней. Сервер сверяет каждую ссылку с аккаунтом сессии: неизвестный и чужой объект одинаково дают 404 `not_found`, поэтому ссылка не раскрывает, существует ли чужой объект. Обращение хранит только `{type, id}`.
|
||||
- Приглашения есть в контракте (см. раздел Приглашения и контактные разрешения ниже), но не реализованы, а решений античит-проверки в контракте пока нет. До их реализации любая ссылка `invitation` дает 404, а любая античит-апелляция - 409 `state_conflict`; форма запроса не меняется.
|
||||
- Жалобы `offer_content` и `salary_terms_violation` требуют приглашения; другой объект дает 400 с pointer `/object/type` (доменное правило после схемы).
|
||||
- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; связь ручной оценки с согласием C3 решают TASK-064 и TASK-315.
|
||||
- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; связь ручной оценки с согласием C3 определяют отзыв согласия и ручная оценка.
|
||||
|
||||
Содержание и поля, которые клиент не задает:
|
||||
|
||||
@@ -436,11 +436,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
- Новый problem-код не добавляется: перечисление `ProblemCode` побайтно копируется в ML-контракт. Недоступная античит-апелляция и повторная апелляция используют 409 `state_conflict`, а причину клиент узнает из обращения или попытки.
|
||||
- `TestSupportCaseSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер, а `frontend/src/shared/api/support-contract.test.ts` закрепляет правила сгенерированного Zod, отсутствие полей статуса, решения, модератора и контактов в типах запроса и отсутствие личности модератора и внутренних полей в обращении и в сводке.
|
||||
|
||||
Открытый продуктовый вопрос к TASK-315: подчиняются ли повторные ручные оценки той же категории правилам пересдачи из FR04 (тот же грейд через 30 дней, не больше трех попыток за 180 дней) или собственному правилу. Контракт разрешает только одну открытую ручную оценку на специализацию и интервал не придумывает.
|
||||
Открытый продуктовый вопрос для ручной оценки: подчиняются ли повторные ручные оценки той же категории правилам пересдачи из FR04 (тот же грейд через 30 дней, не больше трех попыток за 180 дней) или собственному правилу. Контракт разрешает только одну открытую ручную оценку на специализацию и интервал не придумывает.
|
||||
|
||||
Запланировано, добавляется без ломающих изменений (новая операция или необязательное поле): ответы автора, вложения, отзыв обращения, фильтры списка по статусу и типу, итоговая категория ручной оценки в решении, следующий шаг для автора (TASK-322), служебные очереди и решения (TASK-316, TASK-317, TASK-323) и правила паузы срока ответа.
|
||||
Запланировано, добавляется без ломающих изменений (новая операция или необязательное поле): ответы автора, вложения, отзыв обращения, фильтры списка по статусу и типу, итоговая категория ручной оценки в решении, следующий шаг для автора, служебные очереди и решения и правила паузы срока ответа.
|
||||
|
||||
Запланированные изменения контракта (новые значения перечислений; как и коды каталога, сгенерированные клиенты отклоняют неизвестное значение, поэтому каждое выходит вместе с перегенерированными клиентами): типы объектов `vacancy` и `application` для вакансий и защищенных откликов из FR16 и тип объекта для замечаний к профилю из TASK-272. `waiting_for_user` и `support_case` уже есть в перечислениях, поэтому операции ответа и последующим обращениям такое изменение не нужно. Новых видов событий и участников не планируется: ответ автора - это `reply` с участником `user`, пересмотр решения (TASK-317) - еще одно событие `decision`, а эксперты и модераторы - это `support`.
|
||||
Запланированные изменения контракта (новые значения перечислений; как и коды каталога, сгенерированные клиенты отклоняют неизвестное значение, поэтому каждое выходит вместе с перегенерированными клиентами): типы объектов `vacancy` и `application` для вакансий и защищенных откликов из FR16 и тип объекта для замечаний из анализа профиля. `waiting_for_user` и `support_case` уже есть в перечислениях, поэтому операции ответа и последующим обращениям такое изменение не нужно. Новых видов событий и участников не планируется: ответ автора - это `reply` с участником `user`, пересмотр решения - еще одно событие `decision`, а эксперты и модераторы - это `support`.
|
||||
|
||||
### Приглашения и контактные разрешения
|
||||
|
||||
@@ -467,9 +467,9 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
Доступ:
|
||||
|
||||
- Сторона организации: `org_id` в пути - единственный источник организации, сервер сверяет его с действующим членством аккаунта сессии, как для потребностей. Аккаунт без членства, неизвестная организация, неизвестное приглашение и приглашение другой организации одинаково дают 404 `not_found`; аккаунт кандидата и участник, чья роль не разрешает операцию, получают 403 `forbidden`. В MVP с приглашениями работает только владелец; остальные роли FR07 запланированы (TASK-463).
|
||||
- Сторона организации: `org_id` в пути - единственный источник организации, сервер сверяет его с действующим членством аккаунта сессии, как для потребностей. Аккаунт без членства, неизвестная организация, неизвестное приглашение и приглашение другой организации одинаково дают 404 `not_found`; аккаунт кандидата и участник, чья роль не разрешает операцию, получают 403 `forbidden`. В MVP с приглашениями работает только владелец; остальные роли FR07 запланированы.
|
||||
- Сторона кандидата: `/me/invitations` привязаны к аккаунту сессии. Черновик, приглашение другому кандидату и неизвестный идентификатор дают 404 `not_found`; аккаунт работодателя получает 403 `forbidden`. Ни в одном запросе нет поля пользователя, кандидата, организации или роли.
|
||||
- Кандидат указывается только через `candidate_handle` (`CandidateHandle` в `common_schemas.yml`, общий с результатами поиска FR11, TASK-185), никогда через email, телефон или идентификатор аккаунта либо профиля. Неизвестный handle, handle другой организации и профиль, который организация больше не может видеть, одинаково дают 400 с pointer `/candidate_handle`.
|
||||
- Кандидат указывается только через `candidate_handle` (`CandidateHandle` в `common_schemas.yml`, общий с результатами поиска FR11), никогда через email, телефон или идентификатор аккаунта либо профиля. Неизвестный handle, handle другой организации и профиль, который организация больше не может видеть, одинаково дают 400 с pointer `/candidate_handle`.
|
||||
|
||||
Условия (`InvitationTerms`):
|
||||
|
||||
@@ -481,7 +481,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
Версии и конфликты:
|
||||
|
||||
- `version` растет с каждым зафиксированным изменением, включая просмотр и серверное истечение срока. `terms_version` растет только при изменении условий: изменении `terms` в черновике или единственном повышении верхней границы после отправки. Каждая версия условий неизменяема.
|
||||
- Каждая команда, кроме просмотра, передает `expected_version`; `AcceptMyInvitation` передает еще `terms_version`. 412 `version_conflict`: `expected_version` или, при принятии, `terms_version` не текущие (случай устаревших условий, пример `InvitationStaleTerms`); ничего не изменено, под ключом ничего не сохраняется, клиент перечитывает приглашение. 409 `state_conflict`: состояние не допускает команду, например принятие отозванного или истекшего приглашения, команда в момент дедлайна или позже, отправка, заблокированная лимитом ожидающих по потребности или 30-дневной паузой, изменение отправленного приглашения или второе повышение; такой ответ сохраняется под ключом. TASK-197, TASK-201 и TASK-204 называют 409 для устаревших условий; правило репозитория оставляет 412 для любой устаревшей версии, как для потребностей и анкеты.
|
||||
- Каждая команда, кроме просмотра, передает `expected_version`; `AcceptMyInvitation` передает еще `terms_version`. 412 `version_conflict`: `expected_version` или, при принятии, `terms_version` не текущие (случай устаревших условий, пример `InvitationStaleTerms`); ничего не изменено, под ключом ничего не сохраняется, клиент перечитывает приглашение. 409 `state_conflict`: состояние не допускает команду, например принятие отозванного или истекшего приглашения, команда в момент дедлайна или позже, отправка, заблокированная лимитом ожидающих по потребности или 30-дневной паузой, изменение отправленного приглашения или второе повышение; такой ответ сохраняется под ключом. Правило репозитория оставляет 412 для любой устаревшей версии, как для потребностей и анкеты.
|
||||
- Порядок: после того как приглашение найдено и наступивший срок применен, и после проверки повтора терминальное состояние (`declined`, `expired`, `withdrawn`, `cancelled_by_candidate`) или, для принятия и отказа, прошедший дедлайн дает 409 до сравнения версий. Поэтому клиент получает 409 для отозванного, истекшего или опоздавшего приглашения даже с устаревшими версиями и показывает итоговое состояние, а не перечитывает и повторяет. Затем идут версии (412) и остальные правила состояния (409). Это относится к принятию, отказу, отмене, отзыву и повышению вилки.
|
||||
- Повторы возвращают прежний результат: повтор с тем же Idempotency-Key воспроизводит сохраненный исход, а повтор команды, чей переход уже произошел, отвечает 200 с текущим приглашением даже с новым ключом или старой версией: отправка отправленного, отзыв отозванного, отказ с той же причиной и комментарием, отмена отмененного, то же повышение и принятие, чьи `terms_version` и поля совпадают с `contact_grant` - версией и полями, которые кандидат принял, даже если позднее повышение увеличило текущую `terms_version`. Второе согласие, grant, списание квоты или событие аудита не создаются.
|
||||
- `UpdateOrganizationInvitation` следует соглашению `UpdateOrganizationNeed`: без Idempotency-Key, с явной заменой полей, а тело, которое ничего не меняет, дает 200.
|
||||
@@ -490,7 +490,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
- `InvitationState` перечисляет все состояния таблицы FR12: `draft`, `delivered`, `viewed`, `counter`, `accepted`, `interview_scheduled`, `interviewed`, `negotiation`, `terms_agreed`, `no_deal`, `declined`, `expired`, `withdrawn`, `cancelled_by_candidate`. Операции MVP производят `draft`, `delivered`, `viewed`, `accepted`, `declined`, `expired`, `withdrawn` и `cancelled_by_candidate`; остальные перечислены заранее, чтобы сгенерированные клиенты принимали их, когда появятся встречное предложение, интервью и закрытый финал. Внутренний этап `SENT` не виден: отправка отвечает `delivered` после создания входящей записи.
|
||||
- `expiry_reason` - `invitation_timeout` или запланированный `negotiation_timeout`, не null ровно в `expired`.
|
||||
- Просмотр - явная команда `ViewMyInvitation`: она переводит `delivered` в `viewed`, сохраняет дедлайн и в любом другом состоянии возвращает текущее приглашение без изменений. Команда идемпотентна по эффекту, поэтому ей не нужны ни Idempotency-Key, ни `expected_version`, и она никогда не падает из-за того, что приглашение изменилось после чтения клиентом. `GetMyInvitation` и `ListMyInvitations` побочных эффектов не имеют; чтение лишь показывает наступивший срок, который сервер применяет в момент дедлайна в любом случае. TASK-200 описывает просмотр как GET; команда не дает предзагрузке, повтору или обновлению кеша менять состояние, которое видит организация.
|
||||
- Просмотр - явная команда `ViewMyInvitation`: она переводит `delivered` в `viewed`, сохраняет дедлайн и в любом другом состоянии возвращает текущее приглашение без изменений. Команда идемпотентна по эффекту, поэтому ей не нужны ни Idempotency-Key, ни `expected_version`, и она никогда не падает из-за того, что приглашение изменилось после чтения клиентом. `GetMyInvitation` и `ListMyInvitations` побочных эффектов не имеют; чтение лишь показывает наступивший срок, который сервер применяет в момент дедлайна в любом случае. Команда не дает предзагрузке, повтору или обновлению кеша менять состояние, которое видит организация.
|
||||
- `withdrawn` - команда организации из любого незавершенного состояния, включая `draft` и `accepted`; существующий grant она сохраняет. `cancelled_by_candidate` - команда кандидата из любого незавершенного состояния после доставки; она отзывает grant этого приглашения. Отказ - структурированный ответ до принятия.
|
||||
- Дедлайн равен `delivered_at + response_period_days` (3, 7 или 14 дней, по умолчанию 7). Просмотр, письмо или повышение вилки его не сдвигают; команда, принятая в момент дедлайна или позже, опоздала.
|
||||
|
||||
@@ -498,7 +498,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
- Условия переиспользуют `SalaryRange` с правилами раздела Потребности: RUB, месяц, `net` или `gross`, положительные границы, кратные 1000, `A < B` и ширина 10-40%, которую сервер проверяет с pointer `/terms/salary/salary_to`.
|
||||
- Организация получает только `salary_fit`: `within_range`, `up_to_10_percent_above`, `above`, `withheld` или `not_available` (нет минимума для предложенных форматов или он в другой базе). Точный минимум не появляется ни в ответе, ни в примере, ни в логе, ни в problem. Сервер никогда не отклоняет вилку из-за минимума, потому что отказ сам раскрыл бы его. В DTO кандидата индикатора нет; кандидат сравнивает с собственным минимумом из профиля.
|
||||
- Каждое изменение, которое может сдвинуть индикатор, считается установкой: вилка при создании, а в черновике изменение любой границы, базы или `work_formats`, потому что индикатор сравнивает с минимумом для предложенных форматов. Каждая установка учитывается в общем лимите организации - три в день вместе с вилками потребностей (429 с Retry-After, TASK-211) - и в счетчике `withheld`. Изменение, которое сохраняет вилку, базу и форматы, не учитывается.
|
||||
- Каждое изменение, которое может сдвинуть индикатор, считается установкой: вилка при создании, а в черновике изменение любой границы, базы или `work_formats`, потому что индикатор сравнивает с минимумом для предложенных форматов. Каждая установка учитывается в общем лимите организации - три в день вместе с вилками потребностей (429 с Retry-After) - и в счетчике `withheld`. Изменение, которое сохраняет вилку, базу и форматы, не учитывается.
|
||||
- `withheld`: после пяти установок за семь дней индикатор выключается на семь дней с пятой. Ответ на пятую установку уже показывает `withheld`, как и каждый черновик и каждое приглашение организации, включая существующие, до конца периода.
|
||||
- Переключение базы превращает `not_available` в диапазон или обратно и тем сообщает организации базу минимума; это принято, а переключение учитывается в лимите как любая установка.
|
||||
- После отправки база фиксирована, а нижняя граница не снижается. `RaiseOrganizationInvitationSalary` поднимает `salary_to` один раз за всю историю приглашения, создает следующую версию условий и отвечает 409 на второе повышение. Оно подчиняется своему однократному правилу и не входит в дневной лимит, но учитывается в счетчике `withheld`, потому что сдвигает верхнюю границу, с которой сравнивает индикатор.
|
||||
@@ -506,12 +506,12 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
Согласие C4 и контактное разрешение:
|
||||
|
||||
- `GetMyInvitation` показывает в `contact_consent` текст C4 для этой организации и виды контактов, которые есть в профиле. Поле равно null, когда принять приглашение нельзя: этого не допускает состояние или дедлайн либо в профиле нет контактов. В последнем случае клиент просит кандидата сначала добавить контакт, потому что grant должен покрывать хотя бы одно поле.
|
||||
- `AcceptMyInvitation` передает `terms_version`, `expected_version` и `consent_c4` (`ContactConsentAcceptance`): показанную версию текста C4, `accepted: true` и `fields` - хотя бы одно из `full_name`, `email`, `phone`, `telegram`, без значения по умолчанию и без предвыбора. Неопубликованная версия текста дает 400 `/consent_c4/text_version`, а поле, которого нет в профиле, - 400 `/consent_c4/fields/<i>`. Согласие аналогично принятию C1 по `text_version`, а запись совпадает с реестром C4 из TASK-062 (цель, версия и хэш текста, организация, набор полей, приглашение-источник). Разрешение передавать данные в ATS организации (C4 и FR19) запланировано как дополнительный необязательный флаг, по умолчанию без передачи.
|
||||
- В одной транзакции принятие переводит приглашение в `accepted`, записывает C4, создает grant ровно на выбранные поля и пишет событие аудита (TASK-201). Оно не публикует профиль (C2) и не снимает скрытие.
|
||||
- `AcceptMyInvitation` передает `terms_version`, `expected_version` и `consent_c4` (`ContactConsentAcceptance`): показанную версию текста C4, `accepted: true` и `fields` - хотя бы одно из `full_name`, `email`, `phone`, `telegram`, без значения по умолчанию и без предвыбора. Неопубликованная версия текста дает 400 `/consent_c4/text_version`, а поле, которого нет в профиле, - 400 `/consent_c4/fields/<i>`. Согласие аналогично принятию C1 по `text_version`, а запись совпадает с реестром согласий C4 (цель, версия и хэш текста, организация, набор полей, приглашение-источник). Разрешение передавать данные в ATS организации (C4 и FR19) запланировано как дополнительный необязательный флаг, по умолчанию без передачи.
|
||||
- В одной транзакции принятие переводит приглашение в `accepted`, записывает C4, создает grant ровно на выбранные поля и пишет событие аудита. Оно не публикует профиль (C2) и не снимает скрытие.
|
||||
- У `contact_grant` кандидата есть `status` (`active` или `revoked`), `readable` и `blocked_by`. Grant, созданный, когда профиль не был опубликован или был скрыт от организации, остается `active` с `readable: false` и `blocked_by: visibility`, чтобы кандидат видел, почему организация не может его прочитать (FR12 в PRD); он станет читаемым, когда кандидат опубликует профиль или снимет скрытие. Любое изменение видимости после появления grant отзывает его (`visibility_closed`), и повторная публикация его не открывает.
|
||||
- Значения контактов передаются только в `ContactDisclosure` из `GetOrganizationInvitationContacts`, отдельно от условий и приглашения. Каждое чтение проверяет членство, C4, grant и его поля и текущую видимость без кеша. Без читаемого grant операция отвечает 404 `not_found`, как для неизвестного приглашения. `contact_access` организации - `not_granted` (grant нет), `available` (с видами полей) или `closed`, что покрывает и отозванный grant, и grant, заблокированный с самого начала, не говоря, какой из них. Это наименее раскрывающее правило: отзыв, скрытие и отсутствие публикации выглядят одинаково, а поскольку любое изменение видимости после появления grant его отзывает, организация не наблюдает последующих переключений; стать `available` может только grant, заблокированный с начала, и лишь по собственному выбору кандидата. Поля вне grant равны null.
|
||||
- Отзыв: `CancelMyInvitation` отзывает grant этого приглашения (`participation_cancelled`); отзыв C4 для организации закрывает все ее grants (`consent_revoked`, TASK-064); отзыв C2 или скрытие профиля закрывает их (`visibility_closed`). Отзыв приглашения, `no_deal` и таймаут финала grant не отзывают; новый grant создает только новое явное C4. Отдельная операция отзыва grant относится к контракту согласий (TASK-064, TASK-202).
|
||||
- Форматы значений: ФИО одной строкой до 200 символов, телефон в формате E.164 и имя пользователя Telegram с ведущим @. Контракт профиля (FR02, TASK-066) должен хранить контакты в тех же форматах, чтобы раскрытие не преобразовывало и не отбрасывало сохраненное значение.
|
||||
- Отзыв: `CancelMyInvitation` отзывает grant этого приглашения (`participation_cancelled`); отзыв C4 для организации закрывает все ее grants (`consent_revoked`); отзыв C2 или скрытие профиля закрывает их (`visibility_closed`). Отзыв приглашения, `no_deal` и таймаут финала grant не отзывают; новый grant создает только новое явное C4. Отдельная операция отзыва grant относится к контракту согласий.
|
||||
- Форматы значений: ФИО одной строкой до 200 символов, телефон в формате E.164 и имя пользователя Telegram с ведущим @. Контракт профиля (FR02) должен хранить контакты в тех же форматах, чтобы раскрытие не преобразовывало и не отбрасывало сохраненное значение.
|
||||
|
||||
Отказ и приватность:
|
||||
|
||||
@@ -526,7 +526,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
### Согласия
|
||||
|
||||
Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован, поэтому до появления сессий она отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ней уже есть (TASK-062, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)).
|
||||
Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован, поэтому до появления сессий она отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ней уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)).
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -534,9 +534,9 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
- Цели (`ConsentPurposeCode`): `c1` - обработка персональных данных, `c2` - публикация карточки кандидата, `c3` - автоматическая категоризация, `c4` - передача выбранных контактов одной организации, `c5` - импорт результатов ФСП. `ConsentPurpose` остается подмножеством, текст которого доступен до регистрации (`c1`), поэтому `GetConsentText` не расширяется.
|
||||
- Субъект берется из сессии; ни один параметр не называет аккаунт, поэтому ответ содержит только собственные записи вызывающего. Страница перечисляет записи от новой выдачи к старой с курсорной пагинацией; необязательный фильтр `state` принимает `active`, `superseded` или `revoked`, а неизвестное значение отвечает 400 с указателем `/state`.
|
||||
- `ConsentRecord` содержит цель, принятую `text_version`, `source` (`registration`, `consent_settings` или `invitation_acceptance`), `granted_at`, вычисленное `state`, а также `revoked_at` и `revocation_source` (`consent_settings` или `support_request`). Запись `c4` дополнительно называет `organization` (`ConsentOrganization`, где `name` - снимок названия из текста согласия, поэтому последующее переименование его не меняет), поля контакта `fields` (`ContactFieldKind`), `invitation_id` и `invitation_terms_version`; для остальных целей они равны null. Запись `c2` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации ([Видимость кандидата](#видимость-кандидата), TASK-088), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации.
|
||||
- `ConsentRecord` содержит цель, принятую `text_version`, `source` (`registration`, `consent_settings` или `invitation_acceptance`), `granted_at`, вычисленное `state`, а также `revoked_at` и `revocation_source` (`consent_settings` или `support_request`). Запись `c4` дополнительно называет `organization` (`ConsentOrganization`, где `name` - снимок названия из текста согласия, поэтому последующее переименование его не меняет), поля контакта `fields` (`ContactFieldKind`), `invitation_id` и `invitation_terms_version`; для остальных целей они равны null. Запись `c2` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации ([Видимость кандидата](#видимость-кандидата)), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации.
|
||||
- Журнал только дополняется. Новая версия текста цели - новая запись, а прежняя становится `superseded` без изменений; отзыв один раз ставит отметку на неотозванные записи цели, а для `c4` - одной организации; последующая выдача - новая запись, и отозванное `c4` приглашения не возвращается. Цели независимы.
|
||||
- Запланировано, аддитивно: выдача C1, C2, C3 и C5 в настройках согласий (TASK-063) и отзыв любой цели с последствиями (TASK-064) новыми операциями этого тега; у C1 при регистрации и C4 в `AcceptMyInvitation` уже есть свои операции. Разрешение C4 на передачу данных в ATS и C4 при отклике (Q9 в PRD) запланированы как аддитивный флаг и дополнительное значение `source`.
|
||||
- Запланировано, аддитивно: выдача C1, C2, C3 и C5 в настройках согласий и отзыв любой цели с последствиями новыми операциями этого тега; у C1 при регистрации и C4 в `AcceptMyInvitation` уже есть свои операции. Разрешение C4 на передачу данных в ATS и C4 при отклике (Q9 в PRD) запланированы как аддитивный флаг и дополнительное значение `source`.
|
||||
|
||||
Открытый юридический вопрос: является ли `c2` согласием на распространение персональных данных по статье 10.1 152-ФЗ, которое требует отдельного согласия с категориями данных.
|
||||
|
||||
@@ -544,7 +544,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
### Организации
|
||||
|
||||
Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому до появления сессий каждая отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ними уже есть (TASK-077, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в TASK-078 и TASK-079.
|
||||
Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому до появления сессий каждая отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ними уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в управлении организациями и контроле доступа.
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -555,10 +555,10 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
Каждая операция также объявляет problem-ответ `default`. Некорректный `org_id` отвечает 400 с указателем пути.
|
||||
|
||||
Активный контекст организации (решение TASK-077):
|
||||
Активный контекст организации:
|
||||
|
||||
- Контекст не хранится на сервере. Каждая операция в области организации, включая потребности и приглашения этого контракта, называет организацию в пути `org_id`, а сервер на каждом запросе проверяет этот идентификатор по активному членству аккаунта сессии. Сам идентификатор ничего не дает; переключение между организациями - это другой `org_id` в маршрутах клиента.
|
||||
- Причина: атрибут сессии был бы кешем членства, который пришлось бы сбрасывать при удалении, приостановке или выходе (TASK-079 требует закрыть следующее чтение, а не ждать истечения кеша браузера), две вкладки в двух организациях спорили бы за одно значение, а форма с путем уже является контрактом потребностей и приглашений. TASK-085 очищает клиентские запросы с областью организации при переключении, что согласуется с клиентским контекстом.
|
||||
- Причина: атрибут сессии был бы кешем членства, который пришлось бы сбрасывать при удалении, приостановке или выходе (нужно закрыть следующее чтение, а не ждать истечения кеша браузера), две вкладки в двух организациях спорили бы за одно значение, а форма с путем уже является контрактом потребностей и приглашений. Переключение организации очищает клиентские запросы с ее областью, что согласуется с клиентским контекстом.
|
||||
- `ListMyOrganizations` - справочник контекстов: организации, где у вызывающего `active` членство, от нового членства к старому, с ролью и состоянием вызывающего. Клиент выбирает контекст из него, может помнить последний выбор в браузере для удобства и перечитывает список после 404 по пути организации. Человек с несколькими членствами видит все и работает в одной за раз; права и данные организаций остаются раздельными.
|
||||
|
||||
Доступ:
|
||||
@@ -569,10 +569,10 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
Членства:
|
||||
|
||||
- Членство - это `(пользователь, организация, роль, состояние)`, уникальное для пары в любом состоянии. `OrganizationRole` содержит `owner`, `recruiter`, `hiring_manager` и `technical_expert` (2.2 и Q3 в PRD). `MembershipState` содержит `active`, `suspended` (доступ остановлен, можно вернуть), `removed` (завершено владельцем или платформой) и `left` (завершено участником). Доступ дает только `active`, и список возвращает только `active` членства; `joined_at` - момент первого создания членства (вернувшийся участник сохраняет его, а время последней активации - запланированное поле `activated_at` в TASK-082); членство `removed` по решению платформы не должно само возвращаться в работу по решению владельца, принятию приглашения или управлению участниками (TASK-082, TASK-084), а кто и почему удалил участника - аддитивные поля управления участниками; остальные состояния есть в enum, чтобы управление участниками могло их показывать без изменения контракта. Добавление роли или состояния - изменение контракта.
|
||||
- Членство - это `(пользователь, организация, роль, состояние)`, уникальное для пары в любом состоянии. `OrganizationRole` содержит `owner`, `recruiter`, `hiring_manager` и `technical_expert` (2.2 и Q3 в PRD). `MembershipState` содержит `active`, `suspended` (доступ остановлен, можно вернуть), `removed` (завершено владельцем или платформой) и `left` (завершено участником). Доступ дает только `active`, и список возвращает только `active` членства; `joined_at` - момент первого создания членства (вернувшийся участник сохраняет его, а время последней активации - запланированное поле `activated_at`); членство `removed` по решению платформы не должно само возвращаться в работу по решению владельца, принятию приглашения или управлению участниками, а кто и почему удалил участника - аддитивные поля управления участниками; остальные состояния есть в enum, чтобы управление участниками могло их показывать без изменения контракта. Добавление роли или состояния - изменение контракта.
|
||||
- Роль живет только в членстве. В `Organization`, `OrganizationCreate`, `OrganizationUpdate` и `CandidateOrganizationCard` нет поля роли, владельца или участника. Свою роль вызывающий читает в `OrganizationMembership` из `ListMyOrganizations`; DTO не называет аккаунт.
|
||||
- Состояния `invited` нет: сотрудник попадает в организацию только по приглашению на email (2.2 в PRD), которое задачи приглашения сотрудников хранят отдельной записью и превращают в `active` членство, когда владелец адреса его принимает (TASK-081 и TASK-082). Человек может иметь независимые членства в нескольких организациях.
|
||||
- Применение полной матрицы ролей (рекрутер, нанимающий менеджер, техэксперт) к потребностям, приглашениям и контактам запланировано в TASK-083 и TASK-463. До этого остальные роли ничего не дают: операции потребностей и приглашений отвечают им 403 `forbidden`, как сказано в их разделах. Список и управление участниками, смена ролей, удаление участников и правило, что последнего владельца удалить нельзя, запланированы в TASK-084 и TASK-085 и добавляют в контракт операции, а не поля.
|
||||
- Состояния `invited` нет: сотрудник попадает в организацию только по приглашению на email (2.2 в PRD), которое задачи приглашения сотрудников хранят отдельной записью и превращают в `active` членство, когда владелец адреса его принимает. Человек может иметь независимые членства в нескольких организациях.
|
||||
- Применение полной матрицы ролей (рекрутер, нанимающий менеджер, техэксперт) к потребностям, приглашениям и контактам запланировано в ролевом контроле доступа. До этого остальные роли ничего не дают: операции потребностей и приглашений отвечают им 403 `forbidden`, как сказано в их разделах. Список и управление участниками, смена ролей, удаление участников и правило, что последнего владельца удалить нельзя, запланированы в управлении участниками и добавляют в контракт операции, а не поля.
|
||||
|
||||
Профиль:
|
||||
|
||||
@@ -584,9 +584,9 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
Уровень проверки:
|
||||
|
||||
- `OrganizationVerificationLevel` - `e0`, `e1`, `e2` или `e3` (FR07 в PRD). Новая организация начинает с `e0` на основании `confirmed_email`, как бы ни выглядел ее профиль. Более высокий уровень сервер сообщает только после того, как его записал процесс проверки; процессов для `e1`, `e2` и `e3` еще нет (TASK-086 добавляет E0/E1 с доказательствами, областью действия и историей), поэтому клиент считает любой уровень, кроме `e0`, недоступным, а контракт никогда не сообщает `e1`, `e2` или `e3` достигнутыми сами по себе.
|
||||
- `OrganizationVerificationLevel` - `e0`, `e1`, `e2` или `e3` (FR07 в PRD). Новая организация начинает с `e0` на основании `confirmed_email`, как бы ни выглядел ее профиль. Более высокий уровень сервер сообщает только после того, как его записал процесс проверки; процессов для `e1`, `e2` и `e3` еще нет (запланированный процесс проверки добавляет E0/E1 с доказательствами, областью действия и историей), поэтому клиент считает любой уровень, кроме `e0`, недоступным, а контракт никогда не сообщает `e1`, `e2` или `e3` достигнутыми сами по себе.
|
||||
- Ни один запрос не задает и не повышает уровень или его основание: `OrganizationCreate` и `OrganizationUpdate` - закрытые объекты только с полями профиля, ни одна операция контракта не меняет уровень, а правка описания, контактов или представителей оставляет его как есть. База держит уровень и основание в отдельных столбцах, которые оператор обновления профиля никогда не пишет, а CHECK связывает каждый уровень с его основаниями. `OrganizationVerification` только для чтения: `level`, `basis` и `changed_at`; область проверки и история изменений (FR07 в PRD) придут аддитивными полями с первым процессом.
|
||||
- Уровень выбирает ступень квот (E0 10 приглашений и 50 карточек, E1 40 и 150, E2 100 и 400 в демо-политике); `domain.OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику. Сами квоты - TASK-087.
|
||||
- Уровень выбирает ступень квот (E0 10 приглашений и 50 карточек, E1 40 и 150, E2 100 и 400 в демо-политике); `domain.OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику. Применение квот - отдельная запланированная функция.
|
||||
|
||||
Карточка кандидата и версии:
|
||||
|
||||
@@ -594,22 +594,22 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
- `version` начинается с 1 и растет с каждым зафиксированным изменением профиля. Изменение несет `expected_version` в теле по той же причине, что и потребности: сгенерированный клиент пока не читает `ETag`. Устаревшее значение отвечает 412 `version_conflict` и ничего не меняет; правило репозитория сохраняет 412 для устаревшей версии, как и для потребностей. Тело без изменений отвечает 200 с текущей организацией, поэтому PATCH не нужен Idempotency-Key. POST нужен ключ с повтором на 24 часа; сохраняется только 201.
|
||||
- Порядок проверок `UpdateOrganization`: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), членство (404) и роль (403), тело без изменений (200), версия (412), доменные правила (400).
|
||||
|
||||
Внешние ключи на организации: `memberships` и `organization_representatives` ссылаются на `organizations(id)` уже сейчас. Журнал согласий, потребности и приглашения несут `organization_id` и ссылаются на него ограничивающим внешним ключом в миграции, создающей записи приглашений (TASK-198), потому что для области C4 нужны сразу обе ссылки, а тесты журнала TASK-062 и TASK-063 используют синтетические идентификаторы организаций. Приложение никогда не удаляет организацию.
|
||||
Внешние ключи на организации: `memberships` и `organization_representatives` ссылаются на `organizations(id)` уже сейчас. Журнал согласий, потребности и приглашения несут `organization_id` и ссылаются на него ограничивающим внешним ключом в миграции, создающей записи приглашений, потому что для области C4 нужны сразу обе ссылки, а тесты журнала согласий используют синтетические идентификаторы организаций. Приложение никогда не удаляет организацию.
|
||||
|
||||
Открытые вопросы к владельцу продукта:
|
||||
|
||||
- Представители: может ли карточка показывать их имена любому кандидату до принятия приглашения и кто отвечает за право публиковать имя сотрудника (152-ФЗ)? Альтернатива - показывать представителей только в приглашении, отправленном их организацией.
|
||||
- Организаций на аккаунт (блокирует TASK-078 и TASK-087): в PRD лимита нет, а FR07 говорит, что квоты принадлежат организации целиком и сами не растут, но ничто не мешает одному аккаунту создать много организаций, каждая из которых начинает с `e0` со своей квотой, что умножает квоты. Этот контракт не придумывает число. Механизм готов: ограничение отвечало бы 409 `state_conflict` на `CreateOrganization` без изменения схемы, а сигналы против злоупотреблений - TASK-319. Владелец продукта должен решить лимит или явно принять риск до того, как квоты TASK-087 начнут применяться и до того, как `CreateOrganization` откроют пользователям.
|
||||
- Организаций на аккаунт (блокирует создание организаций и применение квот): в PRD лимита нет, а FR07 говорит, что квоты принадлежат организации целиком и сами не растут, но ничто не мешает одному аккаунту создать много организаций, каждая из которых начинает с `e0` со своей квотой, что умножает квоты. Этот контракт не придумывает число. Механизм готов: ограничение отвечало бы 409 `state_conflict` на `CreateOrganization` без изменения схемы, а сигналы против злоупотреблений относятся к оценке риска организации. Владелец продукта должен решить лимит или явно принять риск до того, как квоты организации начнут применяться и до того, как `CreateOrganization` откроют пользователям.
|
||||
- Сфера: пока свободный текст; таксономия сферы, согласованная с доменами потребностей, - решение для поисковых фильтров.
|
||||
- Контакты: нужен ли в карточке пятый вид, например страница вакансий, и должна ли почта совпадать с доменом сайта.
|
||||
|
||||
Запланировано, аддитивно: приглашения участников, список, смена ролей и удаление (TASK-081 - TASK-085), полная матрица ролей (TASK-463), процессы проверки и их история (TASK-086), квоты по уровню (TASK-087), карточка в приглашении кандидата, ограничение числа организаций и код сферы.
|
||||
Запланировано, аддитивно: приглашения участников, список, смена ролей и удаление, полная матрица ролей, процессы проверки и их история, квоты по уровню, карточка в приглашении кандидата, ограничение числа организаций и код сферы.
|
||||
|
||||
Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused` и `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart` и `TestOrganizationContractFollowsThePRD` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/organization-contract.test.ts` - сгенерированные правила Zod и, на уровне типов, отсутствие полей роли, владельца, участников и уровня проверки в запросах.
|
||||
|
||||
### Видимость кандидата
|
||||
|
||||
Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD, TASK-088). Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидного запроса - 501 `not_implemented`. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)).
|
||||
Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидного запроса - 501 `not_implemented`. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)).
|
||||
|
||||
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -628,7 +628,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
Закрыто по умолчанию и три независимые настройки:
|
||||
|
||||
- Профиль закрыт по умолчанию. Кандидат, который никогда не публиковал, читает `publication.state` `closed`, `closed_reason` `never_published`, пустой набор полей и версию 0; сохранение профиля, заполнение анкеты и оценка его не публикуют. У каждой настройки своя `version` (0 - "никогда не задавалась"), своя операция и свой `expected_version` в теле, поэтому изменение одной никогда не делает устаревшей другую.
|
||||
- Публикация и C2 разделены. Согласие C2 остается в журнале согласий (`ListMyConsents`) и доказывает, что кандидат принял текст публикации. `Publication` хранит, какие поля опубликованы и когда, и ссылается на запись C2 за ними (`consent_id` - `id` записи `ConsentRecord` того же аккаунта). Она не дублирует согласие: `state` равен `published`, только пока эта запись не отозвана, поэтому отзыв C2 закрывает карточку сразу, а `closed_reason` показывает `consent_revoked`. Новая выдача C2 карточку не открывает: кандидат публикует заново, и новая публикация привязывается к новой записи. Тело `SetMyPublication` не называет согласие: сервер привязывает текущую неотозванную запись C2 аккаунта, а без нее отвечает 409 `state_conflict` (кандидат сначала дает C2; операция выдачи запланирована в настройках согласий, TASK-063).
|
||||
- Публикация и C2 разделены. Согласие C2 остается в журнале согласий (`ListMyConsents`) и доказывает, что кандидат принял текст публикации. `Publication` хранит, какие поля опубликованы и когда, и ссылается на запись C2 за ними (`consent_id` - `id` записи `ConsentRecord` того же аккаунта). Она не дублирует согласие: `state` равен `published`, только пока эта запись не отозвана, поэтому отзыв C2 закрывает карточку сразу, а `closed_reason` показывает `consent_revoked`. Новая выдача C2 карточку не открывает: кандидат публикует заново, и новая публикация привязывается к новой записи. Тело `SetMyPublication` не называет согласие: сервер привязывает текущую неотозванную запись C2 аккаунта, а без нее отвечает 409 `state_conflict` (кандидат сначала дает C2; операция выдачи запланирована в настройках согласий).
|
||||
- Статус поиска - не согласие. В `SearchStatus` и `SearchStatusUpdate` нет свойств согласия, публикации или организации, схемы одного семейства не достигают другого (тест обходит ссылки), а `SetMySearchStatus` не меняет ничего, кроме статуса. Кандидат с закрытым профилем, который задал `looking`, не становится видимым никому.
|
||||
- Скрытые организации - записи кандидата (`HiddenOrganization`: организация с ее текущим названием и `hidden_at`). Одна запись на кандидата и организацию, не более 1000 на кандидата. Организация их не читает, не узнает, что скрыта, и видит скрывшего кандидата так же, как неопубликованного. Скрытие и его снятие не меняют ни C2, ни публикацию, ни статус поиска.
|
||||
- Скрытие - это PUT состояния, поэтому оно идемпотентно и не требует Idempotency-Key: повторное скрытие отвечает 200 с исходной записью и не пишет историю. Снятие - DELETE, который отвечает 204, была организация скрыта или нет.
|
||||
@@ -637,16 +637,16 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
|
||||
- `looking` ("Ищу") хранит `confirmed_at` и `lapses_at`. Срок - не константа контракта или кода: это `search_status.searching_confirmation_interval_days` действующей версии политики `product` (в демо-версии 1 - 30), прочитанное при подтверждении статуса. Строка называет версию политики, которой воспользовалась, и фиксирует `lapses_at`, поэтому последующее изменение политики не сдвигает сохраненные времена. Владелец меняет срок публикацией новой версии политики.
|
||||
- После `lapses_at` статус действует как `not_looking` с `lapsed` true. Истечение вычисляется при каждом чтении и нигде не записывается, поэтому не требует задачи и может только сужать: оно никогда не публикует, не снимает скрытие и не меняет C2 или скрытые организации. Кандидат подтверждает снова через `SetMySearchStatus` со значением `looking`, которое заменяет `confirmed_at` и увеличивает версию. Напоминание до истечения - запланированное уведомление.
|
||||
- Истекший статус никогда не становится "более публичным": единственное состояние, до которого доходит истечение, - непубличное `not_looking`. Влияет ли `looking` на появление опубликованной карточки в выдаче поиска - решение контракта поиска (TASK-185), здесь не принято.
|
||||
- Истекший статус никогда не становится "более публичным": единственное состояние, до которого доходит истечение, - непубличное `not_looking`. Влияет ли `looking` на появление опубликованной карточки в выдаче поиска - решение контракта поиска, здесь не принято.
|
||||
|
||||
Анонимная карточка и предпросмотр:
|
||||
|
||||
- `CardField` - закрытый набор групп значений карточки, которые кандидат выбирает публиковать: `categories` (категории, подтвержденные результатами оценки), `stack`, `experience` (суммарно в месяцах), `soft_skills`, `location` и `relocation`. У полного имени, любого контакта и минимальной зарплаты значения нет, поэтому ни один запрос не может их опубликовать; контакты доходят до организации только через контактное разрешение принятого приглашения (C4), а минимальная зарплата не доходит никогда. Самооценка грейда не категория и никогда не публикуется. Сервер хранит и отдает набор в порядке возрастания кодов.
|
||||
- `AnonymousCardContent` - карточка так, как ее читает организация: закрытый объект из шести свойств выше, каждое равно null, если не опубликовано или значения нет, поэтому карточка не различает эти случаи. В ней нет имени, email, телефона, имени в Telegram, работодателя, суммы зарплаты, идентификатора аккаунта или профиля, и из нее недостижима ни одна схема приватного профиля, контакта, согласия, приглашения или организации (`TestAnonymousCardReachesNoProfileOrContactSchema` обходит ссылки). `GetMyCardPreview` возвращает ее с опубликованными полями или `card` null, пока профиль закрыт, как приватное чтение, которое не создает просмотра и записи в истории. Карточка результата поиска организации (TASK-185) должна использовать это содержимое и не вправе добавлять свойство, идентифицирующее кандидата.
|
||||
- `AnonymousCardContent` - карточка так, как ее читает организация: закрытый объект из шести свойств выше, каждое равно null, если не опубликовано или значения нет, поэтому карточка не различает эти случаи. В ней нет имени, email, телефона, имени в Telegram, работодателя, суммы зарплаты, идентификатора аккаунта или профиля, и из нее недостижима ни одна схема приватного профиля, контакта, согласия, приглашения или организации (`TestAnonymousCardReachesNoProfileOrContactSchema` обходит ссылки). `GetMyCardPreview` возвращает ее с опубликованными полями или `card` null, пока профиль закрыт, как приватное чтение, которое не создает просмотра и записи в истории. Карточка результата поиска организации должна использовать это содержимое и не вправе добавлять свойство, идентифицирующее кандидата.
|
||||
|
||||
Версии и проверки:
|
||||
|
||||
- Обе операции `PUT` настроек следуют образцу профиля: полное новое состояние в теле, `expected_version` в теле (сгенерированный клиент пока не читает ETag), 412 `version_conflict` для устаревшей или несуществующей версии, а тело без изменений отвечает 200 с текущим состоянием даже при устаревшей версии, поэтому Idempotency-Key не нужен. Порядок проверок: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), версия выше текущей (412), неизмененное состояние (200), устаревшая версия (412), затем C2 для публикации (409). Состояние `published` без поля и `closed` с полем отвечают 400 с указателем `/fields`; схема отклоняет неизвестное или повторное поле карточки и неизвестные свойства, например идентификатор согласия или время подтверждения. `looking` всегда меняет сохраненное подтверждение, поэтому при устаревшей версии отвечает 412 даже как повтор. Два вида 409 `state_conflict` различаются через `errors`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Закрытие поверх сохраненной публикации с отозванной C2 - настоящее изменение (сохраняет закрытие, пишет `publication_closed` и отзывает разрешения); путь отзыва C2 (TASK-064) сам закрывает сохраненную публикацию и отзывает разрешения в своей транзакции. Публикации, скрытию и истории нужен подтвержденный email (требование юзкейса). `Problem.errors` не только для `validation_failed`: `state_conflict` несет одну запись как уточнение (`consent_required`, `limit_reached`), поэтому будущий писатель problem не должен вырезать `errors` из ответов, не связанных с валидацией. В карточку попадают только подтвержденные значения, свободный текст, похожий на контакт (email, телефон, URL, ссылка Telegram, @handle), отбрасывается, а новое поле карточки - это изменение контракта и миграция.
|
||||
- Обе операции `PUT` настроек следуют образцу профиля: полное новое состояние в теле, `expected_version` в теле (сгенерированный клиент пока не читает ETag), 412 `version_conflict` для устаревшей или несуществующей версии, а тело без изменений отвечает 200 с текущим состоянием даже при устаревшей версии, поэтому Idempotency-Key не нужен. Порядок проверок: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), версия выше текущей (412), неизмененное состояние (200), устаревшая версия (412), затем C2 для публикации (409). Состояние `published` без поля и `closed` с полем отвечают 400 с указателем `/fields`; схема отклоняет неизвестное или повторное поле карточки и неизвестные свойства, например идентификатор согласия или время подтверждения. `looking` всегда меняет сохраненное подтверждение, поэтому при устаревшей версии отвечает 412 даже как повтор. Два вида 409 `state_conflict` различаются через `errors`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Закрытие поверх сохраненной публикации с отозванной C2 - настоящее изменение (сохраняет закрытие, пишет `publication_closed` и отзывает разрешения); путь отзыва C2 сам закрывает сохраненную публикацию и отзывает разрешения в своей транзакции. Публикации, скрытию и истории нужен подтвержденный email (требование юзкейса). `Problem.errors` не только для `validation_failed`: `state_conflict` несет одну запись как уточнение (`consent_required`, `limit_reached`), поэтому будущий писатель problem не должен вырезать `errors` из ответов, не связанных с валидацией. В карточку попадают только подтвержденные значения, свободный текст, похожий на контакт (email, телефон, URL, ссылка Telegram, @handle), отбрасывается, а новое поле карточки - это изменение контракта и миграция.
|
||||
- 404 и защита от перебора. `HideOrganization` отвечает одинаковым 404 `not_found`, с тем же телом и без другого времени ответа, и для несуществующей организации, и для той, которую кандидат не видит, поэтому операция не позволяет спросить, принадлежит ли идентификатор организации. Кандидат видит организацию, приславшую ему приглашение, и организации, которые покажет поиск организаций для кандидата (запланирован). Идентификаторы случайные, а общий лимит запросов может ответить 429 с Retry-After до любой проверки. `UnhideOrganization` ничего не раскрывает: 204 на любой корректный идентификатор. Некорректный `org_id` отвечает 400 с указателем `/org_id`.
|
||||
- Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (запланировано вместе с операциями; причину задает контракт приглашений). Снятие скрытия и повторная публикация разрешение не возвращают. Статус поиска разрешение никогда не отзывает.
|
||||
|
||||
@@ -658,17 +658,17 @@ ML-сервис отвечает на ошибки той же схемой `Pro
|
||||
Открытые вопросы к владельцу продукта и юристу:
|
||||
|
||||
- Значения статуса поиска: в контракте `looking` и `not_looking`. Нужен ли по PRD третий статус, например "открыт к предложениям", не решено; значение - аддитивное изменение.
|
||||
- Влияет ли `looking` на появление опубликованной карточки в поиске (организация видит только ищущих) или это только метка. Это определяет смысл истечения для видимости и относится к контракту поиска (TASK-185).
|
||||
- Влияет ли `looking` на появление опубликованной карточки в поиске (организация видит только ищущих) или это только метка. Это определяет смысл истечения для видимости и относится к контракту поиска.
|
||||
- Набор полей карточки. Шесть значений - предложение, согласованное с профилем; карточка в PRD (FR11) может добавить, разделить или убрать часть, например обобщенную отрасль и размер работодателя вместо работодателей, и каждое изменение аддитивно для контракта.
|
||||
- Нужен ли для публикации минимум: хотя бы одна подтвержденная категория или сохраненный профиль. Контракт требует только одно поле карточки и действующую C2.
|
||||
- Должно ли сужение опубликованных полей, а не только закрытие публикации или скрытие организации, отзывать контактные разрешения. Контракт приглашений говорит, что любое изменение видимости после разрешения его отзывает; этот контракт отзывает только при закрытии и скрытии.
|
||||
- Как кандидат находит организацию, чтобы скрыть ее до любого приглашения. Контракт скрывает по идентификатору и отвечает 404 на организацию, которую кандидат не видит, поэтому заранее скрыть текущего работодателя можно только при поиске организаций для кандидата (по названию или домену), который сам должен быть защищен от перебора (минимальная длина запроса, лимит, только публичные данные). Без него скрытие работает только для организаций, которые уже написали кандидату.
|
||||
- Должен ли кандидат узнавать название организации, которая смотрела карточку без приглашения (`CardAccess.organization`), и сколько хранятся обращения.
|
||||
- Предел скрытых организаций (сейчас 1000) и срок хранения настроек и их истории вместе с доказательствами согласий (152-ФЗ, PRD 7.3). История ссылается на аккаунт с `ON DELETE CASCADE` под защитой двух триггеров: UPDATE запрещен всегда, а DELETE (и удаление аккаунта) запрещен, пока аккаунт подтвержден, как у журнала согласий; очистка неподтвержденных аккаунтов удаляет историю удаляемого аккаунта, а процедура удаления аккаунта расширит условие.
|
||||
- Свободный текст в карточке (теги стека, софт-скиллы, место) защищает только `CardTextLooksLikeContact`, который ошибается в сторону отбрасывания (Socket.io отбрасывается, а простая обфускация все же может пройти); остаточный риск закрывает TASK-089 закрытой таксономией вместо свободного текста.
|
||||
- Свободный текст в карточке (теги стека, софт-скиллы, место) защищает только `CardTextLooksLikeContact`, который ошибается в сторону отбрасывания (Socket.io отбрасывается, а простая обфускация все же может пройти); для устранения остаточного риска построителю карточки еще нужна закрытая таксономия вместо свободного текста.
|
||||
- Является ли C2 согласием на распространение персональных данных по статье 10.1 152-ФЗ и нужна ли ей собственная область полей (см. Согласия); пока поля и времена хранит история.
|
||||
- Требует ли новая версия текста C2 повторного согласия кандидата для уже существующей публикации. Сейчас публикация действует, пока ее запись C2 не отозвана, поэтому более новая версия текста, которую кандидат не принимал, ее не закрывает.
|
||||
- Квазиидентификаторы и k-анонимность карточки: редкое сочетание места, стека и опыта может идентифицировать кандидата и без имени. Обобщение редких признаков и минимальный размер группы - критерии приемки TASK-089, который строит карточку; здесь контракт фиксирует только закрытый набор полей, правило "только подтвержденные значения" и отбрасывание свободного текста, похожего на контакт.
|
||||
- Квазиидентификаторы и k-анонимность карточки: редкое сочетание места, стека и опыта может идентифицировать кандидата и без имени. Обобщение редких признаков и минимальный размер группы - критерии приемки построителя карточки; здесь контракт фиксирует только закрытый набор полей, правило "только подтвержденные значения" и отбрасывание свободного текста, похожего на контакт.
|
||||
- Хранение и право на удаление истории настроек. Записи о скрытии и снятии скрытия чувствительны (они говорят, каких работодателей кандидат избегает). История хранится как доказательства согласий и не удаляется, пока аккаунт подтвержден; может ли кандидат стереть ее, когда и как это согласуется с трехлетним хранением согласий (PRD 7.3) - открытый юридический вопрос. Процедура удаления аккаунта расширит условие удаления таблицы.
|
||||
|
||||
Новый код problem не добавляется. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation` и `TestPrivacyAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/privacy-contract.test.ts` - сгенерированные правила Zod, отсутствие согласия, времени, контакта и зарплаты в типах запросов и карточки и отсутствие настроек в файлах организации, приглашения, потребности, профиля и согласий.
|
||||
|
||||
@@ -28,7 +28,7 @@ CandidateHandle:
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
pattern: ^[A-Za-z0-9_-]+$
|
||||
description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it.
|
||||
description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.
|
||||
examples:
|
||||
- cand_7Qm2xVb9Lr4Kp0Zt
|
||||
AssessmentMode:
|
||||
@@ -2127,7 +2127,7 @@ ConsentPurposeCode:
|
||||
|
||||
- c1: processing of personal data, given at registration.
|
||||
|
||||
- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change.
|
||||
- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change.
|
||||
|
||||
- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.
|
||||
|
||||
@@ -2164,7 +2164,7 @@ ConsentSource:
|
||||
|
||||
- registration: the c1 acceptance of RegisterAccount.
|
||||
|
||||
- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064).
|
||||
- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned).
|
||||
|
||||
- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.
|
||||
|
||||
@@ -2302,7 +2302,7 @@ ContactFieldKind:
|
||||
- telegram: the Telegram username from the profile.
|
||||
|
||||
|
||||
The value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.'
|
||||
The value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.'
|
||||
enum:
|
||||
- full_name
|
||||
- email
|
||||
@@ -2310,7 +2310,7 @@ ContactFieldKind:
|
||||
- telegram
|
||||
ContactConsentText:
|
||||
type: object
|
||||
description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the ledger of TASK-062).
|
||||
description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the consent ledger).
|
||||
additionalProperties: false
|
||||
required:
|
||||
- text_version
|
||||
@@ -2479,7 +2479,7 @@ ContactFullName:
|
||||
description: Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.
|
||||
ContactDisclosure:
|
||||
type: object
|
||||
description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02, TASK-066), which must store the same formats; see ContactFieldKind.
|
||||
description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02), which must store the same formats; see ContactFieldKind.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- invitation_id
|
||||
@@ -3055,7 +3055,7 @@ InvitationSalaryFit:
|
||||
|
||||
- above: the minimum is more than 10% above `B`.
|
||||
|
||||
- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth (the limit of TASK-211). The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.
|
||||
- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.
|
||||
|
||||
- not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis.
|
||||
|
||||
@@ -3584,7 +3584,7 @@ NeedSourceText:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 10000
|
||||
description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).'
|
||||
description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.'
|
||||
NeedValueStatus:
|
||||
type: string
|
||||
description: 'Confirmation state of one need field.
|
||||
@@ -4147,7 +4147,7 @@ NeedMoneyStatus:
|
||||
|
||||
- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.
|
||||
|
||||
- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null.
|
||||
- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null.
|
||||
|
||||
|
||||
An unknown candidate minimum never counts as zero.'
|
||||
@@ -4796,7 +4796,7 @@ MembershipState:
|
||||
|
||||
- suspended: access is stopped, and the owner or the platform may restore it.
|
||||
|
||||
- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.
|
||||
- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management.
|
||||
|
||||
- left: the member ended the membership.
|
||||
|
||||
@@ -4826,7 +4826,7 @@ OrganizationMembership:
|
||||
state:
|
||||
$ref: '#/MembershipState'
|
||||
joined_at:
|
||||
description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`, TASK-082).
|
||||
description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`).
|
||||
allOf:
|
||||
- $ref: '#/Timestamp'
|
||||
OrganizationSummary:
|
||||
@@ -5131,8 +5131,8 @@ CardCategory:
|
||||
$ref: '#/GradeCode'
|
||||
AnonymousCardContent:
|
||||
type: object
|
||||
description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search
|
||||
result are defined by the search contract (TASK-185), which reuses this content.
|
||||
description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are
|
||||
defined by the search contract, which reuses this content.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- categories
|
||||
@@ -5678,14 +5678,14 @@ SupportCaseStatus:
|
||||
- closed
|
||||
SupportCaseObjectType:
|
||||
type: string
|
||||
description: 'Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.
|
||||
description: 'Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.
|
||||
|
||||
|
||||
- assessment_attempt: an assessment attempt of the caller.
|
||||
|
||||
- organization: an organization that the caller can see.
|
||||
|
||||
- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.
|
||||
- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.
|
||||
|
||||
- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'
|
||||
enum:
|
||||
@@ -5977,7 +5977,7 @@ SupportCaseDecision:
|
||||
$ref: '#/Timestamp'
|
||||
SupportCaseActorKind:
|
||||
type: string
|
||||
description: 'Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change.
|
||||
description: 'Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change.
|
||||
|
||||
|
||||
- user: the author of the case.
|
||||
@@ -5991,7 +5991,7 @@ SupportCaseActorKind:
|
||||
- system
|
||||
SupportCaseEventKind:
|
||||
type: string
|
||||
description: 'Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value.
|
||||
description: 'Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value.
|
||||
|
||||
|
||||
- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.
|
||||
|
||||
@@ -44,6 +44,6 @@ schemas:
|
||||
address or a phone number, and it means nothing to another
|
||||
organization. The server resolves it only for the organization in the
|
||||
path. Clients never parse it. It is shared by the invitations of
|
||||
FR12 and the search results of FR11 (TASK-185), which issue it.
|
||||
FR12 and the search results of FR11, which issue it.
|
||||
examples:
|
||||
- cand_7Qm2xVb9Lr4Kp0Zt
|
||||
@@ -5,7 +5,7 @@ schemas:
|
||||
One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another.
|
||||
|
||||
- c1: processing of personal data, given at registration.
|
||||
- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change.
|
||||
- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change.
|
||||
- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.
|
||||
- c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance.
|
||||
- c5: import of FSP results.
|
||||
@@ -35,7 +35,7 @@ schemas:
|
||||
Where the subject gave the consent.
|
||||
|
||||
- registration: the c1 acceptance of RegisterAccount.
|
||||
- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064).
|
||||
- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned).
|
||||
- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.
|
||||
|
||||
A c4 given when sending an application (PRD Q9) is planned as an additional value.
|
||||
|
||||
@@ -9,7 +9,7 @@ schemas:
|
||||
- phone: the contact phone number from the profile.
|
||||
- telegram: the Telegram username from the profile.
|
||||
|
||||
The value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.
|
||||
The value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.
|
||||
enum:
|
||||
- full_name
|
||||
- email
|
||||
@@ -21,7 +21,7 @@ schemas:
|
||||
Currently published text of the consent C4 for this invitation. The
|
||||
server stores an acceptance with `text_version` and the hash of
|
||||
exactly this text, together with the organization, the selected
|
||||
fields, the invitation, and its terms version (the ledger of TASK-062).
|
||||
fields, the invitation, and its terms version (the consent ledger).
|
||||
additionalProperties: false
|
||||
required:
|
||||
- text_version
|
||||
@@ -230,7 +230,7 @@ schemas:
|
||||
is a covered field that the profile no longer holds. The response is
|
||||
never cached or stored by the server for later reads, so a
|
||||
revocation closes the next read at once. The value formats depend on
|
||||
the profile contract (FR02, TASK-066), which must store the same
|
||||
the profile contract (FR02), which must store the same
|
||||
formats; see ContactFieldKind.
|
||||
additionalProperties: false
|
||||
required:
|
||||
|
||||
@@ -354,7 +354,7 @@ schemas:
|
||||
- within_range: the minimum is not above `B`.
|
||||
- up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`.
|
||||
- above: the minimum is more than 10% above `B`.
|
||||
- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth (the limit of TASK-211). The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.
|
||||
- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.
|
||||
- not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis.
|
||||
|
||||
Every change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. Switching the tax basis turns `not_available` into a band or back and so tells the organization the basis of the minimum; this is accepted, and the switch counts against the limit like any other setting.
|
||||
|
||||
@@ -36,7 +36,7 @@ schemas:
|
||||
characteristic, and the extractor never turns such a requirement into
|
||||
a need field. Exclusions, the requirements that a candidate must not
|
||||
meet, are planned as a separate additive field with the Labor Code
|
||||
article 64 check (TASK-182).
|
||||
article 64 check.
|
||||
NeedValueStatus:
|
||||
type: string
|
||||
description: |-
|
||||
@@ -738,7 +738,7 @@ schemas:
|
||||
- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.
|
||||
- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.
|
||||
- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.
|
||||
- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null.
|
||||
- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null.
|
||||
|
||||
An unknown candidate minimum never counts as zero.
|
||||
enum:
|
||||
|
||||
@@ -407,7 +407,7 @@ schemas:
|
||||
|
||||
- active: the member works in the organization with the role.
|
||||
- suspended: access is stopped, and the owner or the platform may restore it.
|
||||
- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.
|
||||
- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management.
|
||||
- left: the member ended the membership.
|
||||
|
||||
One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.
|
||||
@@ -444,7 +444,7 @@ schemas:
|
||||
Moment the membership was first created. A member who left and
|
||||
returns keeps the same value, because the pair has one membership;
|
||||
the moment of the latest activation is a planned additive field
|
||||
(`activated_at`, TASK-082).
|
||||
(`activated_at`).
|
||||
allOf:
|
||||
- $ref: "./common_schemas.yml#/schemas/Timestamp"
|
||||
OrganizationSummary:
|
||||
|
||||
@@ -329,7 +329,7 @@ schemas:
|
||||
unknown value never do. A free text value (a stack tag, a soft skill, the
|
||||
location) that looks like a contact (an email address, a phone number, a
|
||||
URL or domain, a Telegram link, an @handle) is dropped by the builder
|
||||
(TASK-089) and never published. It carries
|
||||
and never published. It carries
|
||||
no name, contact, resume text, employer, salary figure, account or
|
||||
profile identifier, and no schema of the private profile or of a
|
||||
contact disclosure is reachable from it; a contact reaches an
|
||||
@@ -339,7 +339,7 @@ schemas:
|
||||
apart. The set of properties is closed, and an organization-visible
|
||||
card must never gain a property that identifies the candidate. The
|
||||
search ranking and the full card of an organization's search result
|
||||
are defined by the search contract (TASK-185), which reuses this
|
||||
are defined by the search contract, which reuses this
|
||||
content.
|
||||
additionalProperties: false
|
||||
required:
|
||||
|
||||
@@ -51,11 +51,11 @@ schemas:
|
||||
SupportCaseObjectType:
|
||||
type: string
|
||||
description: |-
|
||||
Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.
|
||||
Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.
|
||||
|
||||
- assessment_attempt: an assessment attempt of the caller.
|
||||
- organization: an organization that the caller can see.
|
||||
- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.
|
||||
- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.
|
||||
- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.
|
||||
enum:
|
||||
- assessment_attempt
|
||||
@@ -411,7 +411,7 @@ schemas:
|
||||
SupportCaseActorKind:
|
||||
type: string
|
||||
description: |-
|
||||
Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change.
|
||||
Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change.
|
||||
|
||||
- user: the author of the case.
|
||||
- support: a person of the support, moderation, or expert staff.
|
||||
@@ -423,7 +423,7 @@ schemas:
|
||||
SupportCaseEventKind:
|
||||
type: string
|
||||
description: |-
|
||||
Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value.
|
||||
Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value.
|
||||
|
||||
- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.
|
||||
- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.
|
||||
|
||||
+35
-35
@@ -1172,7 +1172,7 @@ paths:
|
||||
|
||||
The need is saved even when critical fields are missing: the response is 201 with version 1, and `readiness.missing_fields` names each critical field without a confirmed value with a specific question. `recommendations` is computed by the server from the confirmed requirements only; the request cannot set a recommendation, its score, or its components. Creating a need never contacts a candidate or sends an invitation.
|
||||
|
||||
Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, planned in TASK-211). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private risk signals of TASK-319.
|
||||
Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private organization risk signals.
|
||||
|
||||
Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second need. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
|
||||
|
||||
@@ -1292,7 +1292,7 @@ paths:
|
||||
|
||||
The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current need even when `expected_version` is older. An incomplete need is a valid result; `readiness.missing_fields` tells what remains.
|
||||
|
||||
Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, planned in TASK-211). Over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private risk signals of TASK-319.
|
||||
Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private organization risk signals.
|
||||
|
||||
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the need (404 not_found), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose width is outside 10-40%, `/desired_skills/0/name` for a skill that is also in the required list, `/grade/status` or `/required_skills/2/status` for `extracted` with a value that is not the stored suggestion, or `/vacancy_id`), then the salary change limit (429). The schema rejects a missing or non-positive `expected_version`, unknown fields such as `rec_score`, `members`, `candidate_minimum`, or `version`, a field sent as a bare value instead of `{value, status}`, a list sent as null, a salary bound that is not a positive multiple of 1000, and an unknown currency, period, or tax basis.
|
||||
security:
|
||||
@@ -1390,7 +1390,7 @@ paths:
|
||||
|
||||
The terms are complete from the start (PRD FR12): the role, the specialization and the grade, the offer type, the tasks, the team, the technology stack, the work formats and the place of work, the communication method, the salary range in RUB with its tax basis, and the package. Each package condition is either `provided` with a description or explicitly `not_provided`; leaving one out fails validation. A draft without the tax basis or the communication method therefore cannot exist. The draft is created as version 1 with terms version 1, and the candidate does not see it until SendOrganizationInvitation.
|
||||
|
||||
Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing.
|
||||
Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing.
|
||||
|
||||
Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second draft. A different body with the same key answers 422 idempotency_key_reused. 400 and 429 are never stored.
|
||||
|
||||
@@ -1497,7 +1497,7 @@ paths:
|
||||
|
||||
Versions: every committed change creates version `expected_version + 1`; a change of the terms also creates the next terms version, an immutable snapshot, and a change of anything else keeps the terms version. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the invitation again. The version travels in the body because the generated client cannot read the ETag response header yet. The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current invitation even when `expected_version` is older.
|
||||
|
||||
Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200.
|
||||
Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200.
|
||||
|
||||
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the invitation (404 not_found), a body that changes nothing (200), the version (412), the state (409 state_conflict), domain rules (400 with the pointers of CreateOrganizationInvitation), then the salary limit (429).
|
||||
security:
|
||||
@@ -1553,9 +1553,9 @@ paths:
|
||||
description: |-
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization sends invitations.
|
||||
|
||||
Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification (TASK-199), then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending.
|
||||
Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending.
|
||||
|
||||
The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization (TASK-087), with 429 and Retry-After. The pending limit and the quota are planned in TASK-205 and TASK-087.
|
||||
The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. Enforcement of the pending limit and the organization quota is planned.
|
||||
|
||||
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read.
|
||||
|
||||
@@ -1740,13 +1740,13 @@ paths:
|
||||
operationId: GetOrganizationInvitationContacts
|
||||
summary: Read the contacts that the candidate disclosed to the organization.
|
||||
description: |-
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts (TASK-202); the other roles of PRD FR07 are planned.
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts; the other roles of PRD FR07 are planned.
|
||||
|
||||
This is the only operation that returns contact values, and its response is separate from the terms and from the invitation. It answers only while a grant created by the acceptance of this invitation is active and the read is allowed now: on every request the server checks the membership, the consent C4 for this organization, the grant and its fields, and the current visibility of the profile (C2 and the organizations the candidate hid the profile from), with no cache in between, so a revocation closes the next read at once. The response holds exactly the fields that the grant covers; every other field is null. A grant of organization A never answers for organization B.
|
||||
|
||||
Without such a grant the contacts do not exist for the caller, and the operation answers 404 not_found, the same as for an unknown invitation: before an acceptance, after a decline or an expiry, after the candidate revoked C4 or cancelled the participation, after the candidate closed the visibility, and while a grant created when the profile was not published or was hidden from the organization stays blocked. The answer does not tell which applies; `contact_access` of GetOrganizationInvitation tells the organization whether access is `not_granted`, `available`, or `closed`, without the reason, and the candidate sees `readable` and `blocked_by` on the grant. Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens a closed grant; only a new explicit C4 creates a new one.
|
||||
|
||||
Every successful read is recorded in the access audit (planned in TASK-090 and TASK-202), and the response has `Cache-Control: no-store`.
|
||||
Every successful read is recorded in the access audit (planned with the contact access history), and the response has `Cache-Control: no-store`.
|
||||
|
||||
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown invitation, an invitation of another organization, and an invitation without an active readable grant all answer 404 not_found; a member whose role does not allow reading contacts answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer.
|
||||
security:
|
||||
@@ -1871,7 +1871,7 @@ paths:
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The candidate comes from the session. The request has no body.
|
||||
|
||||
The view transition of PRD FR12 (TASK-200) is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`.
|
||||
The view transition of PRD FR12 is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`.
|
||||
|
||||
The command is idempotent by its effect: the first view wins and every repeat returns the current invitation. It therefore needs no Idempotency-Key and no `expected_version`: a view must never fail because the invitation changed after the client read it, for example after a salary raise. A view at the deadline or later first applies the due expiry and answers 200 with `expired`.
|
||||
|
||||
@@ -1919,11 +1919,11 @@ paths:
|
||||
|
||||
Only an acceptance of the current terms version with the consent C4 creates access to contacts (PRD FR12). The body names the `terms_version` the candidate read and accepts, the `expected_version` of the invitation, and `consent_c4`: the C4 text version that the candidate saw, `accepted: true`, and the contact fields the candidate selected. At least one field is required and nothing is preselected or defaulted, so a grant never covers a field the candidate did not choose. The fields come only from the candidate's profile; the request never carries contact values.
|
||||
|
||||
Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash (TASK-062), creates the contact grant for exactly those fields, and writes the audit event (TASK-201). The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it.
|
||||
Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash, creates the contact grant for exactly those fields, and writes the audit event. The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it.
|
||||
|
||||
412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. TASK-197, TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state.
|
||||
412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. The repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state.
|
||||
|
||||
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations (TASK-064). Of two concurrent acceptances only one makes the transition.
|
||||
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations. Of two concurrent acceptances only one makes the transition.
|
||||
|
||||
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on an accepted invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the versions), the versions (412), any other state that does not allow an acceptance (409 state_conflict), then the consent rules (400 with the pointer `/consent_c4/text_version` for a text version that is not the published one, or `/consent_c4/fields/0` for a field that the profile does not hold). The schema rejects a missing `terms_version`, an empty or repeated field list, an unknown field kind, `accepted` other than true, and unknown fields such as `email` or `phone`. The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not.
|
||||
security:
|
||||
@@ -2049,7 +2049,7 @@ paths:
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session.
|
||||
|
||||
Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations (TASK-064).
|
||||
Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations.
|
||||
|
||||
Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an acceptance, and carries no reason; a withdrawal is the organization's command and keeps the grant. Before an answer the client offers the decline.
|
||||
|
||||
@@ -2113,9 +2113,9 @@ paths:
|
||||
|
||||
The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent.
|
||||
|
||||
Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history (TASK-088).
|
||||
Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history.
|
||||
|
||||
Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation.
|
||||
Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag; c1 is given at registration and c4 only in AcceptMyInvitation.
|
||||
|
||||
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed.
|
||||
security:
|
||||
@@ -2192,7 +2192,7 @@ paths:
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were.
|
||||
|
||||
Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself (TASK-064) closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it.
|
||||
Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it.
|
||||
|
||||
The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract).
|
||||
|
||||
@@ -2493,7 +2493,7 @@ paths:
|
||||
|
||||
An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card.
|
||||
|
||||
The storage of accesses is planned with the card and contact operations of the organization side (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 not_implemented after the session and request checks.
|
||||
The storage of accesses is planned with the card and contact operations of the organization side (anonymous card reads and contact reads under the invitation contract); until then the operation answers 501 not_implemented after the session and request checks.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
security:
|
||||
@@ -2576,7 +2576,7 @@ paths:
|
||||
| `anticheat_appeal` | candidate | required; `assessment_attempt` of the caller with an anti-cheat review decision | none |
|
||||
| `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` |
|
||||
|
||||
An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract (TASK-077) shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract (TASK-196) but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until TASK-173 every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal.
|
||||
An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until review decisions are implemented, every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal.
|
||||
|
||||
Ownership of the reference: the server checks the object against the session account on every create. An unknown object and an object of someone else, such as another candidate's attempt, another account's case, or an invitation addressed to another person, both answer 404 not_found, so a reference never reveals whether a foreign object exists. An own case that a grade appeal cannot dispute, because it is not a manual assessment, is not resolved yet, or was resolved with another outcome, answers 409 state_conflict. An identifier that is not a UUID fails validation with the pointer `/object/id`. The case stores only the type and the identifier of the object.
|
||||
|
||||
@@ -2655,7 +2655,7 @@ paths:
|
||||
|
||||
The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one.
|
||||
|
||||
The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer.
|
||||
The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
tags:
|
||||
@@ -5256,7 +5256,7 @@ components:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 10000
|
||||
description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check (TASK-182).'
|
||||
description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.'
|
||||
NeedValueStatus:
|
||||
type: string
|
||||
description: |-
|
||||
@@ -5809,7 +5809,7 @@ components:
|
||||
- computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given.
|
||||
- insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null.
|
||||
- no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null.
|
||||
- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, planned in TASK-211); the policy uses the neutral value 0.5 and `share` is null.
|
||||
- withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null.
|
||||
|
||||
An unknown candidate minimum never counts as zero.
|
||||
enum:
|
||||
@@ -6184,11 +6184,11 @@ components:
|
||||
SupportCaseObjectType:
|
||||
type: string
|
||||
description: |-
|
||||
Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.
|
||||
Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis.
|
||||
|
||||
- assessment_attempt: an assessment attempt of the caller.
|
||||
- organization: an organization that the caller can see.
|
||||
- invitation: an invitation addressed to the caller. Invitations are in the contract (TASK-196) but not implemented yet; until they are, every invitation reference answers 404 not_found.
|
||||
- invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found.
|
||||
- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.
|
||||
enum:
|
||||
- assessment_attempt
|
||||
@@ -6471,7 +6471,7 @@ components:
|
||||
SupportCaseActorKind:
|
||||
type: string
|
||||
description: |-
|
||||
Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change.
|
||||
Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change.
|
||||
|
||||
- user: the author of the case.
|
||||
- support: a person of the support, moderation, or expert staff.
|
||||
@@ -6483,7 +6483,7 @@ components:
|
||||
SupportCaseEventKind:
|
||||
type: string
|
||||
description: |-
|
||||
Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value.
|
||||
Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value.
|
||||
|
||||
- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.
|
||||
- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.
|
||||
@@ -6733,7 +6733,7 @@ components:
|
||||
minLength: 1
|
||||
maxLength: 128
|
||||
pattern: ^[A-Za-z0-9_-]+$
|
||||
description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11 (TASK-185), which issue it.
|
||||
description: Opaque reference to a candidate as one organization sees it, taken from a search result card of that organization. It is not the candidate's account or profile identifier, it never contains an email address or a phone number, and it means nothing to another organization. The server resolves it only for the organization in the path. Clients never parse it. It is shared by the invitations of FR12 and the search results of FR11, which issue it.
|
||||
examples:
|
||||
- cand_7Qm2xVb9Lr4Kp0Zt
|
||||
InvitationRoleTitle:
|
||||
@@ -6941,7 +6941,7 @@ components:
|
||||
- within_range: the minimum is not above `B`.
|
||||
- up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`.
|
||||
- above: the minimum is more than 10% above `B`.
|
||||
- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth (the limit of TASK-211). The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.
|
||||
- withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends.
|
||||
- not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis.
|
||||
|
||||
Every change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. Switching the tax basis turns `not_available` into a band or back and so tells the organization the basis of the minimum; this is accepted, and the switch counts against the limit like any other setting.
|
||||
@@ -7449,7 +7449,7 @@ components:
|
||||
- phone: the contact phone number from the profile.
|
||||
- telegram: the Telegram username from the profile.
|
||||
|
||||
The value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02, TASK-066) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.
|
||||
The value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.
|
||||
enum:
|
||||
- full_name
|
||||
- email
|
||||
@@ -7457,7 +7457,7 @@ components:
|
||||
- telegram
|
||||
ContactConsentText:
|
||||
type: object
|
||||
description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the ledger of TASK-062).
|
||||
description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the consent ledger).
|
||||
additionalProperties: false
|
||||
required:
|
||||
- text_version
|
||||
@@ -7622,7 +7622,7 @@ components:
|
||||
description: Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.
|
||||
ContactDisclosure:
|
||||
type: object
|
||||
description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02, TASK-066), which must store the same formats; see ContactFieldKind.
|
||||
description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02), which must store the same formats; see ContactFieldKind.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- invitation_id
|
||||
@@ -7674,7 +7674,7 @@ components:
|
||||
One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another.
|
||||
|
||||
- c1: processing of personal data, given at registration.
|
||||
- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history (TASK-088), not of this record. Adding a field scope to c2 records later is an additive change.
|
||||
- c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change.
|
||||
- c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric.
|
||||
- c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance.
|
||||
- c5: import of FSP results.
|
||||
@@ -7704,7 +7704,7 @@ components:
|
||||
Where the subject gave the consent.
|
||||
|
||||
- registration: the c1 acceptance of RegisterAccount.
|
||||
- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned, TASK-063 and TASK-064).
|
||||
- consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned).
|
||||
- invitation_acceptance: the c4 acceptance of AcceptMyInvitation.
|
||||
|
||||
A c4 given when sending an application (PRD Q9) is planned as an additional value.
|
||||
@@ -8127,7 +8127,7 @@ components:
|
||||
|
||||
- active: the member works in the organization with the role.
|
||||
- suspended: access is stopped, and the owner or the platform may restore it.
|
||||
- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management (TASK-082, TASK-084) must not reactivate it on their own. Who removed the member and why become additive fields of the member management.
|
||||
- removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management.
|
||||
- left: the member ended the membership.
|
||||
|
||||
One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.
|
||||
@@ -8155,7 +8155,7 @@ components:
|
||||
state:
|
||||
$ref: '#/components/schemas/MembershipState'
|
||||
joined_at:
|
||||
description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`, TASK-082).
|
||||
description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`).
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/Timestamp'
|
||||
OrganizationSummary:
|
||||
@@ -8449,7 +8449,7 @@ components:
|
||||
$ref: '#/components/schemas/GradeCode'
|
||||
AnonymousCardContent:
|
||||
type: object
|
||||
description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract (TASK-185), which reuses this content.
|
||||
description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract, which reuses this content.
|
||||
additionalProperties: false
|
||||
required:
|
||||
- categories
|
||||
|
||||
@@ -6,11 +6,11 @@ post:
|
||||
|
||||
Only an acceptance of the current terms version with the consent C4 creates access to contacts (PRD FR12). The body names the `terms_version` the candidate read and accepts, the `expected_version` of the invitation, and `consent_c4`: the C4 text version that the candidate saw, `accepted: true`, and the contact fields the candidate selected. At least one field is required and nothing is preselected or defaulted, so a grant never covers a field the candidate did not choose. The fields come only from the candidate's profile; the request never carries contact values.
|
||||
|
||||
Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash (TASK-062), creates the contact grant for exactly those fields, and writes the audit event (TASK-201). The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it.
|
||||
Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash, creates the contact grant for exactly those fields, and writes the audit event. The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it.
|
||||
|
||||
412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. TASK-197, TASK-201, and TASK-204 say 409 for stale terms; the repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state.
|
||||
412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. The repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state.
|
||||
|
||||
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations (TASK-064). Of two concurrent acceptances only one makes the transition.
|
||||
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations. Of two concurrent acceptances only one makes the transition.
|
||||
|
||||
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on an accepted invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the versions), the versions (412), any other state that does not allow an acceptance (409 state_conflict), then the consent rules (400 with the pointer `/consent_c4/text_version` for a text version that is not the published one, or `/consent_c4/fields/0` for a field that the profile does not hold). The schema rejects a missing `terms_version`, an empty or repeated field list, an unknown field kind, `accepted` other than true, and unknown fields such as `email` or `phone`. The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not.
|
||||
security:
|
||||
|
||||
@@ -4,7 +4,7 @@ post:
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session.
|
||||
|
||||
Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations (TASK-064).
|
||||
Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations.
|
||||
|
||||
Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an acceptance, and carries no reason; a withdrawal is the organization's command and keeps the grant. Before an answer the client offers the decline.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ post:
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The candidate comes from the session. The request has no body.
|
||||
|
||||
The view transition of PRD FR12 (TASK-200) is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`.
|
||||
The view transition of PRD FR12 is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`.
|
||||
|
||||
The command is idempotent by its effect: the first view wins and every repeat returns the current invitation. It therefore needs no Idempotency-Key and no `expected_version`: a view must never fail because the invitation changed after the client read it, for example after a salary raise. A view at the deadline or later first applies the due expiry and answers 200 with `expired`.
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ get:
|
||||
|
||||
An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card.
|
||||
|
||||
The storage of accesses is planned with the card and contact operations of the organization side (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 not_implemented after the session and request checks.
|
||||
The storage of accesses is planned with the card and contact operations of the organization side (anonymous card reads and contact reads under the invitation contract); until then the operation answers 501 not_implemented after the session and request checks.
|
||||
|
||||
A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
security:
|
||||
|
||||
@@ -4,7 +4,7 @@ put:
|
||||
description: |-
|
||||
Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were.
|
||||
|
||||
Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself (TASK-064) closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it.
|
||||
Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it.
|
||||
|
||||
The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract).
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ get:
|
||||
|
||||
The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent.
|
||||
|
||||
Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history (TASK-088).
|
||||
Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history.
|
||||
|
||||
Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag (TASK-063 and TASK-064); c1 is given at registration and c4 only in AcceptMyInvitation.
|
||||
Granting c1, c2, c3, and c5 in the consent settings and revoking any purpose are planned operations of this tag; c1 is given at registration and c4 only in AcceptMyInvitation.
|
||||
|
||||
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed.
|
||||
security:
|
||||
|
||||
@@ -53,7 +53,7 @@ patch:
|
||||
|
||||
Versions: every committed change creates version `expected_version + 1`; a change of the terms also creates the next terms version, an immutable snapshot, and a change of anything else keeps the terms version. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the invitation again. The version travels in the body because the generated client cannot read the ETag response header yet. The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current invitation even when `expected_version` is older.
|
||||
|
||||
Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200.
|
||||
Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200.
|
||||
|
||||
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the invitation (404 not_found), a body that changes nothing (200), the version (412), the state (409 state_conflict), domain rules (400 with the pointers of CreateOrganizationInvitation), then the salary limit (429).
|
||||
security:
|
||||
|
||||
@@ -2,13 +2,13 @@ get:
|
||||
operationId: GetOrganizationInvitationContacts
|
||||
summary: Read the contacts that the candidate disclosed to the organization.
|
||||
description: |-
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts (TASK-202); the other roles of PRD FR07 are planned.
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts; the other roles of PRD FR07 are planned.
|
||||
|
||||
This is the only operation that returns contact values, and its response is separate from the terms and from the invitation. It answers only while a grant created by the acceptance of this invitation is active and the read is allowed now: on every request the server checks the membership, the consent C4 for this organization, the grant and its fields, and the current visibility of the profile (C2 and the organizations the candidate hid the profile from), with no cache in between, so a revocation closes the next read at once. The response holds exactly the fields that the grant covers; every other field is null. A grant of organization A never answers for organization B.
|
||||
|
||||
Without such a grant the contacts do not exist for the caller, and the operation answers 404 not_found, the same as for an unknown invitation: before an acceptance, after a decline or an expiry, after the candidate revoked C4 or cancelled the participation, after the candidate closed the visibility, and while a grant created when the profile was not published or was hidden from the organization stays blocked. The answer does not tell which applies; `contact_access` of GetOrganizationInvitation tells the organization whether access is `not_granted`, `available`, or `closed`, without the reason, and the candidate sees `readable` and `blocked_by` on the grant. Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens a closed grant; only a new explicit C4 creates a new one.
|
||||
|
||||
Every successful read is recorded in the access audit (planned in TASK-090 and TASK-202), and the response has `Cache-Control: no-store`.
|
||||
Every successful read is recorded in the access audit (planned with the contact access history), and the response has `Cache-Control: no-store`.
|
||||
|
||||
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown invitation, an invitation of another organization, and an invitation without an active readable grant all answer 404 not_found; a member whose role does not allow reading contacts answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer.
|
||||
security:
|
||||
|
||||
@@ -4,9 +4,9 @@ post:
|
||||
description: |-
|
||||
Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization sends invitations.
|
||||
|
||||
Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification (TASK-199), then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending.
|
||||
Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending.
|
||||
|
||||
The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization (TASK-087), with 429 and Retry-After. The pending limit and the quota are planned in TASK-205 and TASK-087.
|
||||
The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. Enforcement of the pending limit and the organization quota is planned.
|
||||
|
||||
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read.
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ post:
|
||||
|
||||
The terms are complete from the start (PRD FR12): the role, the specialization and the grade, the offer type, the tasks, the team, the technology stack, the work formats and the place of work, the communication method, the salary range in RUB with its tax basis, and the package. Each package condition is either `provided` with a description or explicitly `not_provided`; leaving one out fails validation. A draft without the tax basis or the communication method therefore cannot exist. The draft is created as version 1 with terms version 1, and the candidate does not see it until SendOrganizationInvitation.
|
||||
|
||||
Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, planned in TASK-211; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing.
|
||||
Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing.
|
||||
|
||||
Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second draft. A different body with the same key answers 422 idempotency_key_reused. 400 and 429 are never stored.
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ patch:
|
||||
|
||||
The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current need even when `expected_version` is older. An incomplete need is a valid result; `readiness.missing_fields` tells what remains.
|
||||
|
||||
Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, planned in TASK-211). Over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private risk signals of TASK-319.
|
||||
Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private organization risk signals.
|
||||
|
||||
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the need (404 not_found), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose width is outside 10-40%, `/desired_skills/0/name` for a skill that is also in the required list, `/grade/status` or `/required_skills/2/status` for `extracted` with a value that is not the stored suggestion, or `/vacancy_id`), then the salary change limit (429). The schema rejects a missing or non-positive `expected_version`, unknown fields such as `rec_score`, `members`, `candidate_minimum`, or `version`, a field sent as a bare value instead of `{value, status}`, a list sent as null, a salary bound that is not a positive multiple of 1000, and an unknown currency, period, or tax basis.
|
||||
security:
|
||||
|
||||
@@ -50,7 +50,7 @@ post:
|
||||
|
||||
The need is saved even when critical fields are missing: the response is 201 with version 1, and `readiness.missing_fields` names each critical field without a confirmed value with a specific question. `recommendations` is computed by the server from the confirmed requirements only; the request cannot set a recommendation, its score, or its components. Creating a need never contacts a candidate or sends an invitation.
|
||||
|
||||
Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, planned in TASK-211). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private risk signals of TASK-319.
|
||||
Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private organization risk signals.
|
||||
|
||||
Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second need. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ get:
|
||||
|
||||
The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one.
|
||||
|
||||
The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer.
|
||||
The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer.
|
||||
security:
|
||||
- sessionCookie: []
|
||||
tags:
|
||||
|
||||
@@ -49,7 +49,7 @@ post:
|
||||
| `anticheat_appeal` | candidate | required; `assessment_attempt` of the caller with an anti-cheat review decision | none |
|
||||
| `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` |
|
||||
|
||||
An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract (TASK-077) shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract (TASK-196) but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until TASK-173 every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal.
|
||||
An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until review decisions are implemented, every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal.
|
||||
|
||||
Ownership of the reference: the server checks the object against the session account on every create. An unknown object and an object of someone else, such as another candidate's attempt, another account's case, or an invitation addressed to another person, both answer 404 not_found, so a reference never reveals whether a foreign object exists. An own case that a grade appeal cannot dispute, because it is not a manual assessment, is not resolved yet, or was resolved with another outcome, answers 409 state_conflict. An identifier that is not a UUID fails validation with the pointer `/object/id`. The case stores only the type and the identifier of the object.
|
||||
|
||||
|
||||
Reference in new issue
Block a user