feat(api): add invitation, terms version, acceptance, and contact grant contract

This commit is contained in:
shira committed 2026-10-06 13:48:35 +03:00
1 parent b856d4ff54
commit d2c6f1375a
140 files changed
+39767 -303

No files matched your search

+102 -6
View File
@@ -14,7 +14,7 @@ From the repository root, `make -C api check` checks contracts and `make generat
## Contract conventions
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation, the assessment commands, `CreateOrganizationNeed`, and `CreateMySupportCase` require Idempotency-Key, but no operation stores keys yet.
`api/core/` fixes these conventions as reusable components in `openapi.yml` and the files under `components/`: schemas in `components/schemas/*_schemas.yml`, parameters in `parameters.yml`, response headers in `headers.yml`, responses in `responses.yml`, and examples in `examples.yml`. Operations reference them as they are added. Currently implemented: problem responses for errors of the Go public API and the ML service. Idempotency-Key storage, If-Match checks, and pagination are planned behavior for business operations; the declared `RegisterAccount` operation, the assessment commands, `CreateOrganizationNeed`, `CreateMySupportCase`, and the invitation commands require Idempotency-Key, but no operation stores keys yet.
### Errors
@@ -43,7 +43,7 @@ Every error is an RFC 9457 problem with the `application/problem+json` media typ
| `internal` | 500 | Unexpected server error |
| `not_implemented` | 501 | The operation is in the contract but not implemented |
Request validation uses 400 rather than 422. The generated ogen server reports malformed and schema-invalid parameters and bodies through the same decoding errors, and for parameters it does not separate syntax from schema violations; one status keeps client handling uniform. 422 then stays free for Idempotency-Key reuse, as the IETF Idempotency-Key header draft recommends. Domain rules on the body, such as `salary_from <= salary_to`, also answer 400 `validation_failed` with body pointers to the fields involved. Each `errors` item has `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` in the body, an empty string for the whole body, `/limit` for a parameter), `code` (`required` or `invalid`; clients tolerate new values), and a fixed `message`. When the decoder does not record the path of a nested body field, the pointer is the whole body. A body cut by an `http.MaxBytesReader` limit answers 413 `payload_too_large`.
Request validation uses 400 rather than 422. The generated ogen server reports malformed and schema-invalid parameters and bodies through the same decoding errors, and for parameters it does not separate syntax from schema violations; one status keeps client handling uniform. 422 then stays free for Idempotency-Key reuse, as the IETF Idempotency-Key header draft recommends. Domain rules on the body, such as `salary_from <= salary_to`, also answer 400 `validation_failed` with body pointers to the fields involved. Each `errors` item has `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` in the body, an empty string for the whole body, `/limit` for a parameter), `code` (`required` or `invalid`; clients tolerate new values), and a fixed `message`. Body pointers follow the rules in Body pointers below. A body cut by an `http.MaxBytesReader` limit answers 413 `payload_too_large`.
`state_conflict` covers business state conflicts, such as accepting an invitation that was already withdrawn. `idempotency_in_progress` is reserved for concurrent retries; the reusable responses are `StateConflict` and `IdempotencyInProgress`.
@@ -51,6 +51,19 @@ Every operation declares `default: $ref: ../components/responses.yml#/Problem`;
Both verification token codes use 400 because the token is request content, not the target resource: 404 and 410 describe the URI, 409 a resource state, and 422 stays reserved for Idempotency-Key reuse. A malformed token fails schema validation and answers 400 `validation_failed` with the pointer `/token`. `invalid_credentials` and `unauthenticated` share 401 but mean a failed login and a missing session respectively. `email_not_verified` is returned only after the password matched, so it tells the verification state only to someone who already proved the password.
#### Body pointers
The generated decoder records no path of its own. It wraps the error of each object field as `decode field "<name>"` with go-faster/errors, and `problem.Responder` rebuilds the pointer from those wrappers, reading each link through the typed `errors.Formatter` instead of the joined error text. The rules:
- A missing required field answers `required` with its own pointer at any depth, for example `/terms/communication_method` or `/terms/salary/tax_basis`.
- A value that fails during decoding, such as a wrong JSON type, a malformed UUID, or an ambiguous `oneOf` value, answers `invalid` with the pointer of that value, for example `/grade` for a bare grade or `/object/id`.
- A value that decodes but breaks a schema rule, such as a length, a pattern, a multiple of 1000, or an enum, answers `invalid` with its full pointer, including array indices, for example `/required_skills/2/status`; this check runs after decoding.
- An unknown property answers `invalid` with the pointer of the object that contains it, for example `/terms/salary` for a `candidate_minimum` inside the range; the property name is not echoed.
- A failure inside an array element during decoding answers `invalid` with the pointer of the array, for example `/required_skills`, because jx reports no element index.
- The whole-body pointer `""` remains only for a malformed JSON document, a missing body, an unknown top-level property, an unknown or missing discriminator of a top-level `oneOf`, and an error chain that the responder does not recognize, which falls back safely to the whole body.
`responder_test.go` covers a nested object, an array element, a `oneOf` variant field, a top-level field, and an unrecognized chain; the router tests of every contract pin the pointers through the generated server.
### Retries and Idempotency-Key
A mutating command declares the `IdempotencyKey` parameter. The client generates a key (a UUID v4 is recommended) and sends it in the `Idempotency-Key` header without quotes: 1-255 characters `A-Z a-z 0-9 . _ : -`. The server scopes the key by caller and operation and fingerprints the request by method, path, and body.
@@ -81,7 +94,7 @@ Lists use cursor pagination: `limit` from 1 to 100 (20 by default) and an opaque
### Time and money
Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with the `Z` suffix (RFC 3339). Servers always emit UTC. ogen generates `Timestamp` as a named Go type over `time.Time`; call `.UTC()` where a value is converted to it. Money is an integer number of whole rubles (`RubAmount`, int64) with an explicit base: `SalaryRange` requires `salary_from`, `salary_to`, `currency` (`RUB`), `period` (`month`), and `tax_basis` (`net` or `gross`); see Needs below. Invitations are expected to reuse `SalaryRange`.
Timestamps use the `Timestamp` schema: `string`, `format: date-time`, UTC with the `Z` suffix (RFC 3339). Servers always emit UTC. ogen generates `Timestamp` as a named Go type over `time.Time`; call `.UTC()` where a value is converted to it. Money is an integer number of whole rubles (`RubAmount`, int64) with an explicit base: `SalaryRange` requires `salary_from`, `salary_to`, `currency` (`RUB`), `period` (`month`), and `tax_basis` (`net` or `gross`); see Needs below. Invitation terms reuse `SalaryRange` with the same rules.
### ML service errors
@@ -289,7 +302,7 @@ Readiness:
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 has the whole-body pointer.
- 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.
@@ -332,10 +345,10 @@ Types and object references:
| `anticheat_appeal` | candidate | required; an `assessment_attempt` of the caller with an anti-cheat review decision | none | 10 business days |
| `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target`; the server fixes `rubric_version` | 5 business days |
- 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, a field of another variant such as `complaint_reason` in a support case, and an `object.id` that is not a UUID answer 400 with the whole-body pointer `""`, because the decoder does not record the path inside the selected variant (example `SupportCaseMalformedReference`).
- 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}`.
- Invitations and anti-cheat review decisions are not in the contract yet. Until they are, every `invitation` reference answers 404 and every anti-cheat appeal answers 409 `state_conflict`; the request shapes stay the same when they arrive.
- 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.
@@ -370,6 +383,88 @@ Planned, additive (a new operation or an optional field): replies of the author,
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`.
### Invitations and contact grants
The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`).
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
| `GET /api/v1/organizations/{org_id}/invitations` | `ListOrganizationInvitations` | session | 200 `OrganizationInvitationList` | 400, 401, 403 `forbidden`, 404 |
| `POST /api/v1/organizations/{org_id}/invitations` | `CreateOrganizationInvitation` | session and CSRF, Idempotency-Key | 201 `OrganizationInvitation` (`draft`) | 400, 401, 403, 404, 409 `idempotency_in_progress`, 422, 429 |
| `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `GetOrganizationInvitation` | session | 200 `OrganizationInvitation` | 400, 401, 403, 404 |
| `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `UpdateOrganizationInvitation` | session and CSRF | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409 `state_conflict`, 412, 429 |
| `POST .../invitations/{invitation_id}/send` | `SendOrganizationInvitation` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`delivered`) | 400, 401, 403, 404, 409, 412, 422, 429 |
| `POST .../invitations/{invitation_id}/salary-raise` | `RaiseOrganizationInvitationSalary` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409, 412, 422, 429 |
| `POST .../invitations/{invitation_id}/withdraw` | `WithdrawOrganizationInvitation` | session and CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`withdrawn`) | 400, 401, 403, 404, 409, 412, 422, 429 |
| `GET .../invitations/{invitation_id}/contacts` | `GetOrganizationInvitationContacts` | session | 200 `ContactDisclosure` | 400, 401, 403, 404 |
| `GET /api/v1/me/invitations` | `ListMyInvitations` | session | 200 `CandidateInvitationList` | 400, 401, 403 |
| `GET /api/v1/me/invitations/{invitation_id}` | `GetMyInvitation` | session | 200 `CandidateInvitation` | 400, 401, 403, 404 |
| `POST /api/v1/me/invitations/{invitation_id}/view` | `ViewMyInvitation` | session and CSRF | 200 `CandidateInvitation` (`viewed`) | 400, 401, 403, 404, 429 |
| `POST /api/v1/me/invitations/{invitation_id}/accept` | `AcceptMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`accepted`) | 400, 401, 403, 404, 409, 412, 422, 429 |
| `POST /api/v1/me/invitations/{invitation_id}/decline` | `DeclineMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`declined`) | 400, 401, 403, 404, 409, 412, 422, 429 |
| `POST /api/v1/me/invitations/{invitation_id}/cancel` | `CancelMyInvitation` | session and CSRF, Idempotency-Key | 200 `CandidateInvitation` (`cancelled_by_candidate`) | 400, 401, 403, 404, 409, 412, 422, 429 |
Every success has `Cache-Control: no-store`, and every operation also declares the `default` problem response. The paths `...` start with `/api/v1/organizations/{org_id}`. 403 on an unsafe operation is `csrf_check_failed` or `forbidden`; 409 on a command is `state_conflict` or `idempotency_in_progress`; 412 is `version_conflict`; 422 is `idempotency_key_reused`. 429 on a command is the general rate limit with Retry-After, which can answer before any check; on create, update, and send it is also the salary limit or the weekly quota. The contact read and the plain reads declare no 429 of their own, like the other reads of the contract.
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).
- 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`.
Terms (`InvitationTerms`):
- The terms are complete from the first draft and every field is required: `role_title`, `specialization`, `grade`, `offer_type` (`full_time`, `part_time`, `contract`, `internship`), `tasks`, `team`, `tech_stack`, `work_formats`, `location` (null only for a remote-only role; required for `office` or `hybrid` by a domain rule with the pointer `/terms/location`), `communication_method` (`channel` and an optional note), `salary` (`SalaryRange`), and `package`. A draft without the tax basis or the communication method therefore cannot exist: such a body answers 400 `required` with `/terms/salary/tax_basis` or `/terms/communication_method` (examples `InvitationWithoutTaxBasis` and `InvitationWithoutCommunicationMethod`).
- `package` has `bonus`, `equipment`, `training`, and `health_insurance` (ДМС). Each is a `oneOf`: `{status: provided, description}` or `{status: not_provided}` ("Не предусмотрено" in the interface). "Not provided" is an explicit choice: a condition left out answers `required` with its pointer, such as `/terms/package/training`; a `provided` one without a description answers `required` at its `description`; a `not_provided` one with a description answers `invalid` at the item. Generated Zod is not strict and strips that description, so only the server rejects it.
- Deliberate deviation from the wording of the acceptance criteria: the PRD package lists the work format next to the bonus, equipment, training, and ДМС, but here the format is the required `work_formats` term without a "not provided" variant, because a role always has a format and the indicator and the search compare it. This is an open question for the product owner.
- The same schema is the request field and the stored snapshot, so a response can be sent back unchanged. The terms never contain data of the candidate.
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.
- 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.
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.
- `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.
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.
- `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.
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.
- 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.
Decline and privacy:
- `DeclineMyInvitation` takes `reason` (`salary`, `tasks`, `stack`, `work_format`, `package`, `company`, `not_looking`, `other_offer`, `other`) and an optional `comment` of up to 500 characters; `other` needs no comment. The organization sees only `declined` and `responded_at`, never the reason or the comment: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size (planned). The candidate reads both back in `decline`.
- No invitation DTO of either side carries the candidate's name, email address, phone number, Telegram username, account or profile identifier, or salary minimum; examples use synthetic data only. `TestInvitationSchemaValidationPrecedesImplementation` checks the schema rejections and pointers through the generated server, `TestInvitationDTOsCarryNoContactOrMinimum` checks the generated Go DTOs, and `frontend/src/shared/api/invitation-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of contact, minimum, and decline fields.
Open product questions: whether a second unfinished invitation of the same organization to the same candidate is allowed (the PRD is silent, so the contract invents no rule), the package format deviation above, the offer types, the contact kinds, and the decline reasons.
Planned, additive: the counter offer and the company answer, reading earlier terms versions, interview and sealed final operations, list filters, the responsiveness metrics of the organization for the candidate, the approximate amount in the other tax basis, decline aggregates, the ATS flag of C4, and FSP fields as new contact kinds (a new enum value, released with regenerated clients).
No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract, and `version_conflict` and `state_conflict` cover the stale terms and the state conflicts.
### Generator checks
`testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core.
@@ -397,6 +492,7 @@ Known generator limitations:
- Orval Zod schemas ignore `uniqueItems` and do not reject unknown fields of `additionalProperties: false` objects; the server stays authoritative for both.
- ogen generates an optional nullable field as `OptNil<T>`, which tells absent (`IsSet` false), null (`IsNull`), and a value apart. An optional array that is not nullable is a plain slice instead, where nil and `[]` mean different things: an absent field decodes to nil (unchanged) and `[]` to an empty non-nil slice (delete every item), and null fails decoding. An `UpdateOrganizationNeed` handler must therefore test lists with `!= nil`, never with `len`; `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart` pins this.
- Orval clears `src/shared/api/endpoints/` and `src/shared/api/schemas/` before generation (`clean: true`), because a schema used by several tags moves from a tag directory to the schema root.
- The post-Orval step `frontend/codegen/mock-patterns.ts` finds the length bounds of a patterned string by its property name and pattern, so two properties with the same name and pattern must have the same bounds. The invitation terms therefore name the technologies `tech_stack` (`SkillName`, up to 100 characters) next to the questionnaire `stack` (`StackTag`, up to 50), and a package condition carries `description` rather than `value`, which the need decisions use with other bounds.
#### Format unions
+102 -6
View File
@@ -14,7 +14,7 @@
## Соглашения контракта
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount`, команды оценки, `CreateOrganizationNeed` и `CreateMySupportCase` требуют Idempotency-Key, но ни одна операция пока не хранит ключи.
`api/core/` закрепляет эти соглашения как переиспользуемые компоненты в `openapi.yml` и файлах `components/`: схемы в `components/schemas/*_schemas.yml`, параметры в `parameters.yml`, заголовки ответов в `headers.yml`, ответы в `responses.yml`, примеры в `examples.yml`. Операции ссылаются на них по мере появления. Сейчас реализованы problem-ответы для ошибок публичного Go API и ML-сервиса. Хранение Idempotency-Key, проверки If-Match и пагинация - запланированное поведение бизнес-операций; объявленная операция `RegisterAccount`, команды оценки, `CreateOrganizationNeed`, `CreateMySupportCase` и команды приглашений требуют Idempotency-Key, но ни одна операция пока не хранит ключи.
### Ошибки
@@ -43,7 +43,7 @@
| `internal` | 500 | Непредвиденная ошибка сервера |
| `not_implemented` | 501 | Операция есть в контракте, но не реализована |
Для валидации запроса выбран 400, а не 422. Сгенерированный ogen-сервер сообщает о синтаксически неверных и не прошедших проверку схемы параметрах и теле через одни и те же ошибки декодирования, а для параметров не отделяет синтаксис от нарушения схемы; единый статус упрощает обработку на клиенте. Поэтому 422 остается для повторного использования Idempotency-Key, как рекомендует черновик IETF о заголовке Idempotency-Key. Доменные правила тела, например `salary_from <= salary_to`, тоже отвечают 400 `validation_failed` с body pointer на участвующие поля. Каждый элемент `errors` содержит `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` в теле, пустая строка для всего тела, `/limit` для параметра), `code` (`required` или `invalid`; клиенты допускают новые значения) и фиксированный `message`. Если декодер не сохранил путь вложенного поля тела, pointer указывает на все тело. Тело, обрезанное лимитом `http.MaxBytesReader`, дает 413 `payload_too_large`.
Для валидации запроса выбран 400, а не 422. Сгенерированный ogen-сервер сообщает о синтаксически неверных и не прошедших проверку схемы параметрах и теле через одни и те же ошибки декодирования, а для параметров не отделяет синтаксис от нарушения схемы; единый статус упрощает обработку на клиенте. Поэтому 422 остается для повторного использования Idempotency-Key, как рекомендует черновик IETF о заголовке Idempotency-Key. Доменные правила тела, например `salary_from <= salary_to`, тоже отвечают 400 `validation_failed` с body pointer на участвующие поля. Каждый элемент `errors` содержит `in` (`body`, `query`, `path`, `header`, `cookie`), `pointer` (JSON Pointer: `/salary_from` в теле, пустая строка для всего тела, `/limit` для параметра), `code` (`required` или `invalid`; клиенты допускают новые значения) и фиксированный `message`. Pointer тела строится по правилам из раздела Pointer тела ниже. Тело, обрезанное лимитом `http.MaxBytesReader`, дает 413 `payload_too_large`.
`state_conflict` обозначает конфликты бизнес-состояния, например принятие уже отозванного приглашения. `idempotency_in_progress` зарезервирован для параллельных повторов; переиспользуемые ответы - `StateConflict` и `IdempotencyInProgress`.
@@ -51,6 +51,19 @@
Оба кода токена подтверждения используют 400, потому что токен - содержимое запроса, а не целевой ресурс: 404 и 410 описывают URI, 409 - состояние ресурса, а 422 зарезервирован для повторного использования Idempotency-Key. Синтаксически неверный токен не проходит проверку схемы и дает 400 `validation_failed` с pointer `/token`. `invalid_credentials` и `unauthenticated` используют 401, но означают соответственно неудачный вход и отсутствие сессии. `email_not_verified` возвращается только после совпадения пароля, поэтому раскрывает состояние подтверждения только тому, кто уже доказал знание пароля.
#### Pointer тела
Сгенерированный декодер сам путь не записывает. Ошибку каждого поля объекта он оборачивает как `decode field "<name>"` через go-faster/errors, а `problem.Responder` восстанавливает pointer по этим оберткам, читая каждое звено через типизированный `errors.Formatter`, а не через склеенный текст ошибки. Правила:
- Отсутствующее обязательное поле дает `required` со своим pointer на любой глубине, например `/terms/communication_method` или `/terms/salary/tax_basis`.
- Значение, которое не декодируется, например неверный тип JSON, некорректный UUID или неоднозначное значение `oneOf`, дает `invalid` с pointer этого значения, например `/grade` для грейда без решения или `/object/id`.
- Значение, которое декодируется, но нарушает правило схемы (длину, pattern, кратность 1000, enum), дает `invalid` с полным pointer, включая индексы массивов, например `/required_skills/2/status`; эта проверка идет после декодирования.
- Неизвестное свойство дает `invalid` с pointer объекта, который его содержит, например `/terms/salary` для `candidate_minimum` внутри вилки; имя свойства не повторяется.
- Ошибка внутри элемента массива при декодировании дает `invalid` с pointer массива, например `/required_skills`, потому что jx не сообщает индекс элемента.
- Pointer на все тело `""` остается только для некорректного JSON-документа, отсутствующего тела, неизвестного свойства верхнего уровня, неизвестного или отсутствующего дискриминатора `oneOf` верхнего уровня и цепочки ошибок, которую responder не распознал: она безопасно сводится ко всему телу.
`responder_test.go` покрывает вложенный объект, элемент массива, поле варианта `oneOf`, поле верхнего уровня и нераспознанную цепочку; router-тесты каждого контракта закрепляют pointer через сгенерированный сервер.
### Повторы и Idempotency-Key
Изменяющая команда объявляет параметр `IdempotencyKey`. Клиент создает ключ (рекомендуется UUID v4) и передает его в заголовке `Idempotency-Key` без кавычек: 1-255 символов `A-Z a-z 0-9 . _ : -`. Сервер ограничивает ключ вызывающим и операцией и снимает отпечаток запроса по методу, пути и телу.
@@ -81,7 +94,7 @@
### Время и деньги
Метки времени используют схему `Timestamp`: `string`, `format: date-time`, UTC с суффиксом `Z` (RFC 3339). Серверы всегда отдают UTC. ogen генерирует `Timestamp` как именованный Go-тип поверх `time.Time`; при преобразовании к нему вызывайте `.UTC()`. Деньги - целое число полных рублей (`RubAmount`, int64) с явной базой: `SalaryRange` требует `salary_from`, `salary_to`, `currency` (`RUB`), `period` (`month`) и `tax_basis` (`net` или `gross`); см. раздел Потребности ниже. Приглашения, как ожидается, переиспользуют `SalaryRange`.
Метки времени используют схему `Timestamp`: `string`, `format: date-time`, UTC с суффиксом `Z` (RFC 3339). Серверы всегда отдают UTC. ogen генерирует `Timestamp` как именованный Go-тип поверх `time.Time`; при преобразовании к нему вызывайте `.UTC()`. Деньги - целое число полных рублей (`RubAmount`, int64) с явной базой: `SalaryRange` требует `salary_from`, `salary_to`, `currency` (`RUB`), `period` (`month`) и `tax_basis` (`net` или `gross`); см. раздел Потребности ниже. Условия приглашения переиспользуют `SalaryRange` с теми же правилами.
### Ошибки ML-сервиса
@@ -289,7 +302,7 @@ 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`. Для отсутствующего поля вложенной вилки pointer указывает на все тело.
- Схема требует положительных границ, кратных 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.
@@ -332,10 +345,10 @@ ML-сервис отвечает на ошибки той же схемой `Pro
| `anticheat_appeal` | кандидат | обязательна; `assessment_attempt` автора с решением античит-проверки | нет | 10 рабочих дней |
| `manual_assessment` | кандидат | необязательна; прежняя `assessment_attempt` автора в той же специализации | обязательный `assessment_target`; `rubric_version` фиксирует сервер | 5 рабочих дней |
- Запрос - `oneOf` из пяти вариантов, выбираемых по `type` (`SupportCaseCreateSupport`, `SupportCaseCreateComplaint`, `SupportCaseCreateGradeAppeal`, `SupportCaseCreateAnticheatAppeal`, `SupportCaseCreateManualAssessment`). Каждый вариант сужает схему своей ссылки, поэтому уже схема отклоняет организацию в апелляции грейда или обращение в жалобе с pointer `/object/type`, а отсутствующее поле типа - с его pointer, например `/object` или `/assessment_target`. ogen выбирает вариант по значению `type`. Неизвестный или отсутствующий тип, поле другого варианта, например `complaint_reason` в обращении в поддержку, и `object.id`, который не является UUID, дают 400 с pointer на все тело `""`, потому что декодер не записывает путь внутри выбранного варианта (пример `SupportCaseMalformedReference`).
- Запрос - `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}`.
- Приглашений и решений античит-проверки в контракте пока нет. До их появления любая ссылка `invitation` дает 404, а любая античит-апелляция - 409 `state_conflict`; форма запроса при их появлении не меняется.
- Приглашения есть в контракте (см. раздел Приглашения и контактные разрешения ниже), но не реализованы, а решений античит-проверки в контракте пока нет. До их реализации любая ссылка `invitation` дает 404, а любая античит-апелляция - 409 `state_conflict`; форма запроса не меняется.
- Жалобы `offer_content` и `salary_terms_violation` требуют приглашения; другой объект дает 400 с pointer `/object/type` (доменное правило после схемы).
- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; связь ручной оценки с согласием C3 решают TASK-064 и TASK-315.
@@ -370,6 +383,88 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Запланированные изменения контракта (новые значения перечислений; как и коды каталога, сгенерированные клиенты отклоняют неизвестное значение, поэтому каждое выходит вместе с перегенерированными клиентами): типы объектов `vacancy` и `application` для вакансий и защищенных откликов из FR16 и тип объекта для замечаний к профилю из TASK-272. `waiting_for_user` и `support_case` уже есть в перечислениях, поэтому операции ответа и последующим обращениям такое изменение не нужно. Новых видов событий и участников не планируется: ответ автора - это `reply` с участником `user`, пересмотр решения (TASK-317) - еще одно событие `decision`, а эксперты и модераторы - это `support`.
### Приглашения и контактные разрешения
Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Операции есть в контракте; их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока нет сессий (`v1.DenyAllSecurity`).
| Метод и путь | operationId | Защита | Успех | Конкретные ошибки |
| --- | --- | --- | --- | --- |
| `GET /api/v1/organizations/{org_id}/invitations` | `ListOrganizationInvitations` | сессия | 200 `OrganizationInvitationList` | 400, 401, 403 `forbidden`, 404 |
| `POST /api/v1/organizations/{org_id}/invitations` | `CreateOrganizationInvitation` | сессия и CSRF, Idempotency-Key | 201 `OrganizationInvitation` (`draft`) | 400, 401, 403, 404, 409 `idempotency_in_progress`, 422, 429 |
| `GET /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `GetOrganizationInvitation` | сессия | 200 `OrganizationInvitation` | 400, 401, 403, 404 |
| `PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}` | `UpdateOrganizationInvitation` | сессия и CSRF | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409 `state_conflict`, 412, 429 |
| `POST .../invitations/{invitation_id}/send` | `SendOrganizationInvitation` | сессия и CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`delivered`) | 400, 401, 403, 404, 409, 412, 422, 429 |
| `POST .../invitations/{invitation_id}/salary-raise` | `RaiseOrganizationInvitationSalary` | сессия и CSRF, Idempotency-Key | 200 `OrganizationInvitation` | 400, 401, 403, 404, 409, 412, 422, 429 |
| `POST .../invitations/{invitation_id}/withdraw` | `WithdrawOrganizationInvitation` | сессия и CSRF, Idempotency-Key | 200 `OrganizationInvitation` (`withdrawn`) | 400, 401, 403, 404, 409, 412, 422, 429 |
| `GET .../invitations/{invitation_id}/contacts` | `GetOrganizationInvitationContacts` | сессия | 200 `ContactDisclosure` | 400, 401, 403, 404 |
| `GET /api/v1/me/invitations` | `ListMyInvitations` | сессия | 200 `CandidateInvitationList` | 400, 401, 403 |
| `GET /api/v1/me/invitations/{invitation_id}` | `GetMyInvitation` | сессия | 200 `CandidateInvitation` | 400, 401, 403, 404 |
| `POST /api/v1/me/invitations/{invitation_id}/view` | `ViewMyInvitation` | сессия и CSRF | 200 `CandidateInvitation` (`viewed`) | 400, 401, 403, 404, 429 |
| `POST /api/v1/me/invitations/{invitation_id}/accept` | `AcceptMyInvitation` | сессия и CSRF, Idempotency-Key | 200 `CandidateInvitation` (`accepted`) | 400, 401, 403, 404, 409, 412, 422, 429 |
| `POST /api/v1/me/invitations/{invitation_id}/decline` | `DeclineMyInvitation` | сессия и CSRF, Idempotency-Key | 200 `CandidateInvitation` (`declined`) | 400, 401, 403, 404, 409, 412, 422, 429 |
| `POST /api/v1/me/invitations/{invitation_id}/cancel` | `CancelMyInvitation` | сессия и CSRF, Idempotency-Key | 200 `CandidateInvitation` (`cancelled_by_candidate`) | 400, 401, 403, 404, 409, 412, 422, 429 |
Каждый успешный ответ имеет `Cache-Control: no-store`, и каждая операция также объявляет problem-ответ `default`. Пути `...` начинаются с `/api/v1/organizations/{org_id}`. 403 на изменяющей операции - `csrf_check_failed` или `forbidden`; 409 на команде - `state_conflict` или `idempotency_in_progress`; 412 - `version_conflict`; 422 - `idempotency_key_reused`. 429 на команде - общий лимит частоты с Retry-After, который может ответить до любой проверки; на создании, изменении и отправке это также лимит вилки или недельная квота. Чтение контактов и простые чтения собственного 429 не объявляют, как и другие чтения контракта.
Доступ:
- Сторона организации: `org_id` в пути - единственный источник организации, сервер сверяет его с действующим членством аккаунта сессии, как для потребностей. Аккаунт без членства, неизвестная организация, неизвестное приглашение и приглашение другой организации одинаково дают 404 `not_found`; аккаунт кандидата и участник, чья роль не разрешает операцию, получают 403 `forbidden`. В MVP с приглашениями работает только владелец; остальные роли FR07 запланированы (TASK-463).
- Сторона кандидата: `/me/invitations` привязаны к аккаунту сессии. Черновик, приглашение другому кандидату и неизвестный идентификатор дают 404 `not_found`; аккаунт работодателя получает 403 `forbidden`. Ни в одном запросе нет поля пользователя, кандидата, организации или роли.
- Кандидат указывается только через `candidate_handle` (`CandidateHandle` в `common_schemas.yml`, общий с результатами поиска FR11, TASK-185), никогда через email, телефон или идентификатор аккаунта либо профиля. Неизвестный handle, handle другой организации и профиль, который организация больше не может видеть, одинаково дают 400 с pointer `/candidate_handle`.
Условия (`InvitationTerms`):
- Условия полны с первого черновика, и каждое поле обязательно: `role_title`, `specialization`, `grade`, `offer_type` (`full_time`, `part_time`, `contract`, `internship`), `tasks`, `team`, `tech_stack`, `work_formats`, `location` (null только для полностью удаленной роли; для `office` или `hybrid` обязательно по доменному правилу с pointer `/terms/location`), `communication_method` (`channel` и необязательная заметка), `salary` (`SalaryRange`) и `package`. Поэтому черновик без базы net/gross или способа связи существовать не может: такое тело дает 400 `required` с `/terms/salary/tax_basis` или `/terms/communication_method` (примеры `InvitationWithoutTaxBasis` и `InvitationWithoutCommunicationMethod`).
- `package` содержит `bonus`, `equipment`, `training` и `health_insurance` (ДМС). Каждое поле - `oneOf`: `{status: provided, description}` или `{status: not_provided}` ("Не предусмотрено" в интерфейсе). "Не предусмотрено" - явный выбор: пропущенное условие дает `required` со своим pointer, например `/terms/package/training`; `provided` без описания дает `required` на его `description`; `not_provided` с описанием дает `invalid` на самом условии. Сгенерированный Zod не строгий и отбрасывает такое описание, поэтому отклоняет его только сервер.
- Намеренное отступление от формулировки критериев приемки: пакет в PRD называет формат работы рядом с бонусом, оборудованием, обучением и ДМС, но здесь формат - обязательное условие `work_formats` без варианта "не предусмотрено", потому что у роли всегда есть формат, а индикатор и поиск его сравнивают. Это открытый вопрос к владельцу продукта.
- Одна схема служит полем запроса и сохраненным снимком, поэтому ответ можно отправить обратно без изменений. Условия никогда не содержат данных кандидата.
Версии и конфликты:
- `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 для любой устаревшей версии, как для потребностей и анкеты.
- Порядок: после того как приглашение найдено и наступивший срок применен, и после проверки повтора терминальное состояние (`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.
Состояния и просмотр:
- `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; команда не дает предзагрузке, повтору или обновлению кеша менять состояние, которое видит организация.
- `withdrawn` - команда организации из любого незавершенного состояния, включая `draft` и `accepted`; существующий grant она сохраняет. `cancelled_by_candidate` - команда кандидата из любого незавершенного состояния после доставки; она отзывает grant этого приглашения. Отказ - структурированный ответ до принятия.
- Дедлайн равен `delivered_at + response_period_days` (3, 7 или 14 дней, по умолчанию 7). Просмотр, письмо или повышение вилки его не сдвигают; команда, принятая в момент дедлайна или позже, опоздала.
Вилка и скрытый минимум:
- Условия переиспользуют `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`. Изменение, которое сохраняет вилку, базу и форматы, не учитывается.
- `withheld`: после пяти установок за семь дней индикатор выключается на семь дней с пятой. Ответ на пятую установку уже показывает `withheld`, как и каждый черновик и каждое приглашение организации, включая существующие, до конца периода.
- Переключение базы превращает `not_available` в диапазон или обратно и тем сообщает организации базу минимума; это принято, а переключение учитывается в лимите как любая установка.
- После отправки база фиксирована, а нижняя граница не снижается. `RaiseOrganizationInvitationSalary` поднимает `salary_to` один раз за всю историю приглашения, создает следующую версию условий и отвечает 409 на второе повышение. Оно подчиняется своему однократному правилу и не входит в дневной лимит, но учитывается в счетчике `withheld`, потому что сдвигает верхнюю границу, с которой сравнивает индикатор.
Согласие 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) и не снимает скрытие.
- У `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) должен хранить контакты в тех же форматах, чтобы раскрытие не преобразовывало и не отбрасывало сохраненное значение.
Отказ и приватность:
- `DeclineMyInvitation` принимает `reason` (`salary`, `tasks`, `stack`, `work_format`, `package`, `company`, `not_looking`, `other_offer`, `other`) и необязательный `comment` до 500 символов; для `other` комментарий не нужен. Организация видит только `declined` и `responded_at`, но не причину и не комментарий: причина вроде `salary` сообщила бы ей, что скрытый минимум выше вилки. Причины идут только в агрегаты с минимальным размером группы (запланировано). Кандидат читает их обратно в `decline`.
- Ни один DTO приглашения ни одной стороны не содержит ФИО, email, телефон, Telegram, идентификатор аккаунта или профиля или минимум кандидата; примеры используют только синтетические данные. `TestInvitationSchemaValidationPrecedesImplementation` проверяет отказы схемы и pointer через сгенерированный сервер, `TestInvitationDTOsCarryNoContactOrMinimum` - сгенерированные Go DTO, а `frontend/src/shared/api/invitation-contract.test.ts` закрепляет правила сгенерированного Zod и на уровне типов отсутствие полей контактов, минимума и отказа.
Открытые продуктовые вопросы: допустимо ли второе незавершенное приглашение той же организации тому же кандидату (PRD об этом молчит, поэтому контракт правила не придумывает), отступление по формату в пакете выше, типы предложения, виды контактов и причины отказа.
Запланировано, добавляется без ломающих изменений: встречное предложение и ответ компании, чтение прежних версий условий, операции интервью и закрытого финала, фильтры списков, метрики отзывчивости организации для кандидата, ориентировочная сумма в другой базе, агрегаты причин отказа, флаг ATS в C4 и поля ФСП как новые виды контактов (новое значение enum выпускается вместе с перегенерированными клиентами).
Новый код ошибки не добавлен: enum `ProblemCode` побайтно копируется в ML-контракт, а `version_conflict` и `state_conflict` покрывают устаревшие условия и конфликты состояния.
### Проверки генераторов
`testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core.
@@ -397,6 +492,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- Zod-схемы Orval игнорируют `uniqueItems` и не отклоняют неизвестные поля объектов с `additionalProperties: false`; в обоих случаях решает сервер.
- ogen генерирует необязательное nullable-поле как `OptNil<T>`, которое различает отсутствие (`IsSet` false), null (`IsNull`) и значение. Необязательный массив без null, напротив, - обычный slice, где nil и `[]` значат разное: отсутствующее поле декодируется в nil (без изменений), `[]` - в пустой slice, не равный nil (удалить все элементы), а null не декодируется. Поэтому обработчик `UpdateOrganizationNeed` должен проверять списки через `!= nil`, а не через `len`; это закрепляет `TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart`.
- Orval очищает `src/shared/api/endpoints/` и `src/shared/api/schemas/` перед генерацией (`clean: true`), потому что схема, используемая несколькими тегами, переезжает из каталога тега в корень схем.
- Шаг после Orval `frontend/codegen/mock-patterns.ts` ищет границы длины строки с pattern по имени свойства и pattern, поэтому два свойства с одинаковыми именем и pattern должны иметь одинаковые границы. Поэтому технологии в условиях приглашения называются `tech_stack` (`SkillName`, до 100 символов) рядом с `stack` анкеты (`StackTag`, до 50), а условие пакета передает `description`, а не `value`, которое решения потребности используют с другими границами.
#### Объединения форматов
File diff suppressed because it is too large. Load diff
+24
View File
@@ -105,3 +105,27 @@ SupportCaseId:
type: string
format: uuid
example: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d
InvitationId:
name: invitation_id
in: path
required: true
description: >-
Identifier of an invitation of the organization in the path. An
invitation of another organization and an unknown identifier both answer
404 not_found.
schema:
type: string
format: uuid
example: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
MyInvitationId:
name: invitation_id
in: path
required: true
description: >-
Identifier of an invitation addressed to the current candidate. A draft,
an invitation addressed to another candidate, and an unknown identifier
all answer 404 not_found, so identifiers cannot be enumerated.
schema:
type: string
format: uuid
example: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f
+97 -9
View File
@@ -235,9 +235,7 @@ QuestionnaireValidationFailed:
more than two specializations, an unknown specialization, grade, or task
language, an unknown field such as confirmed_grade, a repeated
specialization, or a task language that the specialization's published
bank does not offer; code validation_failed with body pointers. When the
decoder does not record the path of a nested field, the pointer is the
whole body. Nothing was changed.
bank does not offer; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed.
content:
application/problem+json:
schema:
@@ -284,8 +282,7 @@ AssessmentAnswerValidationFailed:
element, more selections than the item allows, a text longer than the
item allows, a language that the practice does not offer, or an unknown
field such as score or duration; code validation_failed with body
pointers. When the decoder does not record the path of a nested field,
the pointer is the whole body. Nothing was stored, and the outcome is
pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was stored, and the outcome is
not stored under the Idempotency-Key.
content:
application/problem+json:
@@ -385,8 +382,7 @@ NeedValidationFailed:
a repeated skill or task, status `extracted` with a value that is not the
stored suggestion, a vacancy that is not a vacancy of the organization,
or a missing or invalid expected_version; code validation_failed with
body pointers. When the decoder does not record the path of a nested
field, the pointer is the whole body. Nothing was changed, and the
body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the
outcome is not stored under an Idempotency-Key.
content:
application/problem+json:
@@ -428,8 +424,7 @@ SupportCaseValidationFailed:
case type does not accept, a missing required field of the type, an
unknown field such as status, decision, moderator, or priority, or a
complaint reason that requires an invitation reference; code
validation_failed with body pointers. When the decoder does not record
the path of a nested field, the pointer is the whole body. Nothing was
validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was
created, and the outcome is not stored under the Idempotency-Key.
content:
application/problem+json:
@@ -466,3 +461,96 @@ SupportCaseCreateConflict:
$ref: ./examples.yml#/SupportCaseAppealExists
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
InvitationValidationFailed:
description: >-
The body does not match the contract or violates an invitation rule: a
missing term or package condition, a package condition left out instead
of `not_provided`, a salary range without its tax basis, a salary bound
that is not a positive multiple of 1000, a lower bound that is not below
the upper one, a range width outside 10-40% of its midpoint, the
`office` or `hybrid` format without a place of work, a repeated
technology, a candidate handle that the organization cannot use, a need
or requirements version that the organization does not have, a response
period other than 3, 7, or 14 days, an unknown field such as a
candidate's email address or salary minimum, or a missing or invalid
expected_version; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the outcome is not stored under an
Idempotency-Key.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
without_tax_basis:
$ref: ./examples.yml#/InvitationWithoutTaxBasis
without_communication_method:
$ref: ./examples.yml#/InvitationWithoutCommunicationMethod
package_condition_left_out:
$ref: ./examples.yml#/InvitationPackageItemMissing
salary_range_too_wide:
$ref: ./examples.yml#/InvitationSalaryRangeTooWide
location_required:
$ref: ./examples.yml#/InvitationLocationRequired
unknown_candidate:
$ref: ./examples.yml#/InvitationUnknownCandidate
candidate_data_in_body:
$ref: ./examples.yml#/InvitationCandidateDataInBody
InvitationAcceptValidationFailed:
description: >-
The body does not match the contract or violates a rule of the consent
C4: a missing `terms_version` or `expected_version`, `accepted` other
than true, an empty or repeated choice of contact fields, an unknown
field kind, a field that the candidate's profile does not hold, a
consent text version that is not the published one, or an unknown field
such as a contact value; code validation_failed with body pointers.
Nothing was changed, no consent or grant was recorded, and the outcome
is not stored under the Idempotency-Key.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
empty_field_choice:
$ref: ./examples.yml#/InvitationConsentWithoutFields
outdated_consent_text:
$ref: ./examples.yml#/InvitationConsentTextOutdated
missing_terms_version:
$ref: ./examples.yml#/InvitationMissingTermsVersion
InvitationVersionConflict:
description: >-
`expected_version` is not the current invitation version, or, for an
acceptance, `terms_version` is not the current terms version; code
version_conflict. Nothing was changed, no consent or grant was
recorded, and the outcome is not stored under an Idempotency-Key; read
the invitation again before retrying.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
stale_terms:
$ref: ./examples.yml#/InvitationStaleTerms
stale_version:
$ref: ./examples.yml#/InvitationStaleVersion
InvitationCommandConflict:
description: >-
The state of the invitation does not allow the command, code
state_conflict: for example an acceptance of a withdrawn or expired
invitation or one past its deadline, a send of an invitation that is no
longer a draft, a send blocked by the pending limit of the need or by
the pause after a decline, or a second raise of the upper salary bound.
The invitation tells the client its state. Or a request with the same
Idempotency-Key is still running, code idempotency_in_progress. Nothing
was changed in either case.
content:
application/problem+json:
schema:
$ref: ./schemas.yml#/Problem
examples:
not_answerable:
$ref: ./examples.yml#/InvitationNotAnswerable
salary_raise_used:
$ref: ./examples.yml#/InvitationSalaryRaiseUsed
send_blocked:
$ref: ./examples.yml#/InvitationSendBlocked
idempotency_in_progress:
$ref: ./examples.yml#/IdempotencyInProgress
File diff suppressed because it is too large. Load diff
@@ -32,3 +32,18 @@ schemas:
description: >-
Opaque cursor of the next page, or null on the last page. Clients
must not parse, build, or store it beyond the current listing.
CandidateHandle:
type: string
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.
examples:
- cand_7Qm2xVb9Lr4Kp0Zt
@@ -0,0 +1,279 @@
schemas:
ContactFieldKind:
type: string
description: |-
Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.
- full_name: the full name from the profile.
- email: the contact email address from the profile.
- 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.
enum:
- full_name
- email
- phone
- 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).
additionalProperties: false
required:
- text_version
- text
properties:
text_version:
$ref: "./identity_schemas.yml#/schemas/ConsentTextVersion"
text:
type: string
minLength: 1
maxLength: 100000
description: >-
Full consent text in plain UTF-8 with the name of the
organization; paragraphs are separated by an empty line. The
client shows it as text, never as HTML, next to the field choice.
ContactConsentOffer:
type: object
description: >-
What the candidate can consent to in an acceptance: the consent text
and the kinds of contact that the candidate's profile holds now. It
holds kinds only, never contact values, and nothing is preselected.
additionalProperties: false
required:
- text
- available_fields
properties:
text:
$ref: "#/schemas/ContactConsentText"
available_fields:
type: array
minItems: 1
maxItems: 4
uniqueItems: true
description: >-
Kinds of contact that the profile holds and that an acceptance may
select. A kind outside this list answers 400 in an acceptance.
items:
$ref: "#/schemas/ContactFieldKind"
ContactConsentAcceptance:
type: object
description: >-
Consent C4 given in an acceptance: the text version the candidate saw,
an explicit `accepted`, and the contact fields the candidate selected.
At least one field is required, so a hidden default or an empty choice
never creates a grant. A text version that is not the currently
published one answers 400 validation_failed with the pointer
`/consent_c4/text_version`, and a field that the profile does not hold
answers 400 with the pointer of that item, such as
`/consent_c4/fields/1`. C4 is given only here, never at registration.
The permission to pass the selected data on to the organization's ATS
(PRD C4 and FR19) is planned as an additive optional flag that
defaults to no transfer.
additionalProperties: false
required:
- text_version
- accepted
- fields
properties:
text_version:
$ref: "./identity_schemas.yml#/schemas/ConsentTextVersion"
accepted:
type: boolean
enum:
- true
description: Explicit consent. Only true is valid.
fields:
type: array
minItems: 1
maxItems: 4
uniqueItems: true
description: >-
Contact fields the organization may read after the acceptance.
The grant covers exactly these fields and no other.
items:
$ref: "#/schemas/ContactFieldKind"
ContactGrantState:
type: string
description: |-
State of a contact grant.
- active: the grant exists. Each read by the organization still checks the consent C4, the grant, and the current visibility of the profile.
- revoked: the grant is closed for good; the organization reads no contact through it. A later publication of the profile or a new acceptance never reopens it; only a new explicit C4 creates a new grant.
enum:
- active
- revoked
ContactRevocationReason:
type: string
description: |-
Why a contact grant was revoked, shown only to the candidate.
- consent_revoked: the candidate revoked the consent C4 for the organization; every grant under it is closed.
- participation_cancelled: the candidate cancelled the participation in this invitation; only the grant of this invitation is closed.
- visibility_closed: the candidate revoked the publication C2 or hid the profile from the organization after the grant existed. A grant created while the visibility already did not allow a read stays active with `blocked_by` `visibility` instead.
The withdrawal of an invitation by the organization, a no deal, and a negotiation timeout never revoke a grant.
enum:
- consent_revoked
- participation_cancelled
- visibility_closed
ContactAccessBlock:
type: string
description: |-
Why an active grant does not allow a read now, shown only to the candidate.
- visibility: the profile was not published (C2) or was hidden from the organization when the candidate accepted, and it still is. The acceptance never publishes the profile or lifts the hiding by itself (PRD FR12); the grant becomes readable once the candidate publishes the profile or unhides it for the organization.
enum:
- visibility
ContactGrant:
type: object
description: >-
Contact grant as the candidate reads it: which fields one organization
may read, from which invitation and terms version, and whether it is
still active. It holds kinds only, never contact values. A grant is
stored apart from the invitation state, so a later change of the
state does not change it unless the state is a cancellation by the
candidate.
additionalProperties: false
required:
- id
- fields
- status
- readable
- blocked_by
- terms_version
- consent_text_version
- granted_at
- revoked_at
- revocation_reason
properties:
id:
type: string
format: uuid
description: Identifier of the grant.
fields:
type: array
minItems: 1
maxItems: 4
uniqueItems: true
description: Contact fields that the grant covers.
items:
$ref: "#/schemas/ContactFieldKind"
status:
$ref: "#/schemas/ContactGrantState"
readable:
type: boolean
description: >-
Whether the organization can read the covered fields now: true
only for an active grant whose current consent and visibility
allow the read. The organization sees the same fact as
`contact_access.status` `available`, without the reason.
blocked_by:
description: >-
Why an active grant is not readable now, or null when it is
readable or revoked; a revoked grant has `revocation_reason`
instead.
oneOf:
- $ref: "#/schemas/ContactAccessBlock"
- type: "null"
terms_version:
description: Terms version of the invitation that the acceptance accepted.
allOf:
- $ref: "./invitation_schemas.yml#/schemas/InvitationTermsVersion"
consent_text_version:
description: Version of the consent C4 text that the candidate accepted.
allOf:
- $ref: "./identity_schemas.yml#/schemas/ConsentTextVersion"
granted_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
revoked_at:
description: Moment of the revocation, or null while the grant is active.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
revocation_reason:
description: Reason of the revocation, or null while the grant is active.
oneOf:
- $ref: "#/schemas/ContactRevocationReason"
- type: "null"
ContactPhoneNumber:
type: string
minLength: 8
maxLength: 16
pattern: '^\+[1-9][0-9]{6,14}$'
description: Phone number in the E.164 format, for example +70000000000.
ContactTelegramUsername:
type: string
minLength: 6
maxLength: 33
pattern: "^@[A-Za-z0-9_]{5,32}$"
description: Telegram username with the leading @.
ContactFullName:
type: string
minLength: 1
maxLength: 200
pattern: '^\S(?:.*\S)?$'
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.
additionalProperties: false
required:
- invitation_id
- grant_id
- fields
- granted_at
- full_name
- email
- phone
- telegram
properties:
invitation_id:
type: string
format: uuid
description: Invitation whose acceptance created the grant.
grant_id:
type: string
format: uuid
description: Grant that allows the read.
fields:
type: array
minItems: 1
maxItems: 4
uniqueItems: true
description: Contact fields that the grant covers.
items:
$ref: "#/schemas/ContactFieldKind"
granted_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
full_name:
oneOf:
- $ref: "#/schemas/ContactFullName"
- type: "null"
email:
oneOf:
- $ref: "./identity_schemas.yml#/schemas/EmailAddress"
- type: "null"
phone:
oneOf:
- $ref: "#/schemas/ContactPhoneNumber"
- type: "null"
telegram:
oneOf:
- $ref: "#/schemas/ContactTelegramUsername"
- type: "null"
@@ -0,0 +1,944 @@
schemas:
InvitationVersion:
type: integer
format: int64
minimum: 1
description: >-
Version of an invitation. Creation makes version 1, and every committed
change advances it by exactly one: a change of the draft, a send, the
first view, an answer, a salary raise, a withdrawal, a cancellation,
and an expiry made by the server. Every command carries the version
the client read as `expected_version`; a stale value answers 412
version_conflict and changes nothing.
examples:
- 3
InvitationTermsVersion:
type: integer
format: int64
minimum: 1
description: >-
Version of the terms of an invitation. The terms of a version are an
immutable snapshot: every committed change of the terms, in the draft
or by the one raise of the upper salary bound after sending, creates
the next terms version, and a change of anything else keeps it. An
acceptance names the terms version it accepts, and the consent C4 and
the contact grant record it.
examples:
- 2
InvitationState:
type: string
description: |-
State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`.
- draft: the organization prepares the terms. The candidate does not see the invitation.
- delivered: the invitation is in the candidate's inbox and the response deadline runs.
- viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged.
- counter: planned; the candidate sent the one counter offer. No MVP operation produces it.
- accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists.
- interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them.
- declined: terminal; the candidate declined with a structured reason. No access arises.
- expired: terminal; a server deadline passed, see `expiry_reason`. No access arises.
- withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it.
- cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked.
Planned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change.
enum:
- draft
- delivered
- viewed
- counter
- accepted
- interview_scheduled
- interviewed
- negotiation
- terms_agreed
- no_deal
- declined
- expired
- withdrawn
- cancelled_by_candidate
InvitationExpiryReason:
type: string
description: |-
Why an invitation expired. Set exactly when the state is `expired`, null otherwise.
- invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created.
- negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it.
enum:
- invitation_timeout
- negotiation_timeout
InvitationResponsePeriod:
type: integer
format: int32
enum:
- 3
- 7
- 14
description: >-
Days the candidate has to answer, chosen by the organization in the
draft from the product policy: 3, 7, or 14. The deadline starts at the
first delivery and is never reset by an email, a view, or a counter
offer.
examples:
- 7
InvitationRoleTitle:
type: string
minLength: 1
maxLength: 200
pattern: '^\S(?:.*\S)?$'
description: >-
Name of the offered role, for example "Middle Go developer in the
payments team". It has no leading or trailing whitespace and no line
breaks. Plain text; clients show it as text, never as HTML.
InvitationTeamDescription:
type: string
minLength: 1
maxLength: 1000
pattern: '\S'
description: >-
Description of the team the candidate would join, such as its size,
roles, and way of working. It may contain line breaks and has at least
one character that is not white space. Plain text; clients show it as
text, never as HTML. It describes the job and must not contain
personal data of employees or candidates.
InvitationOfferType:
type: string
description: |-
Type of the offer.
- full_time: employment with a full working week.
- part_time: employment with a part-time working week.
- contract: a fixed-term or project contract outside employment.
- internship: an internship.
Adding a value is a contract change.
enum:
- full_time
- part_time
- contract
- internship
InvitationCommunicationChannel:
type: string
description: |-
Channel through which the organization will contact the candidate after an acceptance.
- email: a letter to the email address the candidate disclosed.
- phone: a call or a text to the phone number the candidate disclosed.
- telegram: a message to the Telegram username the candidate disclosed.
- video_call: an invitation to a video call, sent through one of the disclosed contacts.
The channel describes the organization's plan; the candidate decides which contacts to disclose, and the server never requires that the disclosed fields include the channel.
enum:
- email
- phone
- telegram
- video_call
InvitationCommunicationMethod:
type: object
description: >-
How the organization will contact the candidate after an acceptance.
It is part of the terms, so the candidate sees it before choosing
which contacts to disclose. An invitation without it cannot exist,
because the terms require it.
additionalProperties: false
required:
- channel
- details
properties:
channel:
$ref: "#/schemas/InvitationCommunicationChannel"
details:
description: >-
Optional short note, for example the first step or the expected
time of the first contact, or null. Plain text without line
breaks; it never contains a link or a contact of an employee.
oneOf:
- $ref: "#/schemas/InvitationCommunicationNote"
- type: "null"
InvitationCommunicationNote:
type: string
minLength: 1
maxLength: 300
pattern: '^\S(?:.*\S)?$'
description: >-
Short note on the communication method, for example "A 30-minute call
with the team lead within three working days". It has no leading or
trailing whitespace and no line breaks. Plain text; clients show it as
text, never as HTML.
InvitationPackageItemText:
type: string
minLength: 1
maxLength: 300
pattern: '^\S(?:.*\S)?$'
description: >-
Short description of a condition, for example "Quarterly bonus up to
20% of the salary". It has no leading or trailing whitespace and no
line breaks. Plain text; clients show it as text, never as HTML.
InvitationPackageItemProvided:
type: object
description: The condition is part of the offer, with its description.
additionalProperties: false
required:
- status
- description
properties:
status:
type: string
enum:
- provided
description:
$ref: "#/schemas/InvitationPackageItemText"
InvitationPackageItemNotProvided:
type: object
description: >-
The organization states explicitly that the offer does not include the
condition ("Не предусмотрено" in the interface). It has no
description.
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- not_provided
InvitationPackageItem:
description: >-
One required condition of the package, selected by `status`:
`provided` with a description, or `not_provided` without one. Not
providing a condition is an explicit choice: the field is required in
the package, so an absent field fails validation instead of meaning
"not provided": it answers 400 `required` with its pointer, such as
`/terms/package/training`. A `provided` item without a description
answers `required` with the pointer of the description, and a
`not_provided` item with a description answers `invalid` with the
pointer of the item. ogen selects the variant by the value of
`status`.
oneOf:
- $ref: "#/schemas/InvitationPackageItemProvided"
- $ref: "#/schemas/InvitationPackageItemNotProvided"
InvitationPackage:
type: object
description: >-
Required section of the package (PRD FR12): the bonus, the equipment,
the training, and the voluntary health insurance (ДМС). Every field is
required and is either provided with a description or explicitly not
provided. The work format of the package is the required
`work_formats` term, which has no "not provided" variant. Adding a
required condition is a breaking change; an optional one is additive.
additionalProperties: false
required:
- bonus
- equipment
- training
- health_insurance
properties:
bonus:
$ref: "#/schemas/InvitationPackageItem"
equipment:
$ref: "#/schemas/InvitationPackageItem"
training:
$ref: "#/schemas/InvitationPackageItem"
health_insurance:
$ref: "#/schemas/InvitationPackageItem"
InvitationTerms:
type: object
description: >-
Terms of an invitation: everything the candidate sees before deciding
and before any contact is disclosed. The same schema is the request
field of a draft and the stored snapshot of a terms version, so a
response can be sent back unchanged. Every field is required; a field
that may have no value says so with an explicit variant (`location`
null for a remote role, a package item `not_provided`). The terms never
contain data of the candidate: no contact, no salary minimum, and no
indicator derived from it. The server checks the cross-field rules
after the schema and answers 400 validation_failed with the pointer of
the field: the salary rules of SalaryRange with `/terms/salary/salary_to`,
a missing place of work for the `office` or `hybrid` format with
`/terms/location`, and a repeated technology in `tech_stack` with the
pointer of the later item.
additionalProperties: false
required:
- role_title
- specialization
- grade
- offer_type
- tasks
- team
- tech_stack
- work_formats
- location
- communication_method
- salary
- package
properties:
role_title:
$ref: "#/schemas/InvitationRoleTitle"
specialization:
$ref: "./catalog_schemas.yml#/schemas/SpecializationCode"
grade:
$ref: "./catalog_schemas.yml#/schemas/GradeCode"
offer_type:
$ref: "#/schemas/InvitationOfferType"
tasks:
type: array
minItems: 1
maxItems: 20
description: Work tasks of the role in the order given.
items:
$ref: "./need_schemas.yml#/schemas/NeedTaskText"
team:
$ref: "#/schemas/InvitationTeamDescription"
tech_stack:
type: array
minItems: 1
maxItems: 30
uniqueItems: true
description: >-
Technologies of the role. The server compares names without regard
to letter case.
items:
$ref: "./need_schemas.yml#/schemas/SkillName"
work_formats:
type: array
minItems: 1
maxItems: 3
uniqueItems: true
description: >-
Work formats the organization offers; the candidate may choose any
of them.
items:
$ref: "./questionnaire_schemas.yml#/schemas/WorkFormat"
location:
description: >-
Place of work for the `office` or `hybrid` format, or null when
the only format is `remote`. It is required with either of those
formats.
oneOf:
- $ref: "./need_schemas.yml#/schemas/NeedLocationName"
- type: "null"
communication_method:
$ref: "#/schemas/InvitationCommunicationMethod"
salary:
$ref: "./need_schemas.yml#/schemas/SalaryRange"
package:
$ref: "#/schemas/InvitationPackage"
InvitationNeedReference:
type: object
description: >-
Need of the same organization that the invitation was built from, with
the requirements version used. A direct invitation has no need. The
link is informational: the invitation keeps its own terms, which may
differ from the need, and a later change of the need never changes
them.
additionalProperties: false
required:
- need_id
- requirements_version
properties:
need_id:
type: string
format: uuid
description: Identifier of a need of the organization in the path.
requirements_version:
description: >-
`requirements_version` of the need that the invitation refers to;
it must be a version that the need has had.
allOf:
- $ref: "./need_schemas.yml#/schemas/NeedVersion"
InvitationSalaryFit:
type: string
description: |-
Coarse indicator for the organization of how the salary range relates to the candidate's hidden minimum (PRD FR13). It is the only information about the minimum that the organization receives; the exact minimum never appears in any response, log, or problem. The server compares the upper bound `B` with the lowest minimum the candidate set for the offered work formats, in integer arithmetic and only in the same tax basis.
- 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.
- 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.
The server never rejects or changes a range because of the minimum: a rejection would itself reveal it.
enum:
- within_range
- up_to_10_percent_above
- above
- withheld
- not_available
InvitationContactAccessState:
type: string
description: |-
Whether the organization may read the candidate's contacts through GetOrganizationInvitationContacts now.
- not_granted: the candidate has not accepted this invitation, so no grant exists.
- available: a grant from this invitation is active and the current consent and visibility allow the read.
- closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate's visibility allows the read, which only follows the candidate's own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization.
enum:
- not_granted
- available
- closed
InvitationContactAccess:
type: object
description: >-
Contact access of the organization through this invitation, without
any contact value. The values come only from
GetOrganizationInvitationContacts.
additionalProperties: false
required:
- status
- fields
properties:
status:
$ref: "#/schemas/InvitationContactAccessState"
fields:
type: array
maxItems: 4
uniqueItems: true
description: >-
Kinds of contact that the read returns while `status` is
`available`; empty otherwise.
items:
$ref: "./contact_grant_schemas.yml#/schemas/ContactFieldKind"
InvitationOrganization:
type: object
description: >-
Organization that sent the invitation, as the candidate sees it before
deciding. The organization contract (TASK-077) adds the public card;
this object only names it.
additionalProperties: false
required:
- id
- name
properties:
id:
type: string
format: uuid
description: Identifier of the organization.
name:
type: string
minLength: 1
maxLength: 200
description: >-
Public name of the organization. Plain text; clients show it as
text, never as HTML.
InvitationDeclineReason:
type: string
description: |-
Structured reason of a decline. Every reason is neutral and none requires a comment.
- salary: the salary range does not fit.
- tasks: the role or the tasks do not fit.
- stack: the technologies do not fit.
- work_format: the work format or the place of work does not fit.
- package: the package does not fit.
- company: the company or its domain does not fit.
- not_looking: the candidate is not looking for a job now.
- other_offer: the candidate accepted another offer.
- other: another reason ("Другое"); a comment stays optional.
The organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change.
enum:
- salary
- tasks
- stack
- work_format
- package
- company
- not_looking
- other_offer
- other
InvitationDeclineComment:
type: string
minLength: 1
maxLength: 500
pattern: '\S'
description: >-
Optional comment of the candidate on the offer. It may contain line
breaks and has at least one character that is not white space. It is
never shown to the organization, never published, and never written to
logs or notifications; only the candidate reads it back. Plain text;
clients show it as text, never as HTML.
InvitationDeclineRecord:
type: object
description: The candidate's own decline, as the candidate reads it back.
additionalProperties: false
required:
- reason
- comment
- declined_at
properties:
reason:
$ref: "#/schemas/InvitationDeclineReason"
comment:
oneOf:
- $ref: "#/schemas/InvitationDeclineComment"
- type: "null"
declined_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
OrganizationInvitation:
type: object
description: >-
Invitation as the organization reads it: the candidate handle, the
current terms version, the state, the coarse salary indicator, and the
contact access without contact values. It never contains the
candidate's name, email address, phone number, or other contact, the
exact salary minimum, or the reason and comment of a decline.
additionalProperties: false
required:
- id
- organization_id
- candidate_handle
- need
- state
- expiry_reason
- version
- terms_version
- terms
- response_period_days
- response_deadline_at
- salary_raise_used
- salary_fit
- contact_access
- created_at
- updated_at
- delivered_at
- viewed_at
- responded_at
properties:
id:
type: string
format: uuid
description: Identifier of the invitation.
organization_id:
type: string
format: uuid
description: >-
Organization that owns the invitation, equal to `org_id` of the
path. It never changes.
candidate_handle:
$ref: "./common_schemas.yml#/schemas/CandidateHandle"
need:
description: Need the invitation was built from, or null for a direct invitation.
oneOf:
- $ref: "#/schemas/InvitationNeedReference"
- type: "null"
state:
$ref: "#/schemas/InvitationState"
expiry_reason:
description: Reason of an expiry, or null unless `state` is `expired`.
oneOf:
- $ref: "#/schemas/InvitationExpiryReason"
- type: "null"
version:
$ref: "#/schemas/InvitationVersion"
terms_version:
$ref: "#/schemas/InvitationTermsVersion"
terms:
$ref: "#/schemas/InvitationTerms"
response_period_days:
$ref: "#/schemas/InvitationResponsePeriod"
response_deadline_at:
description: >-
Moment when the candidate's time to answer ends, set at the first
delivery to `delivered_at` plus `response_period_days`, or null for
a draft. A command received at this moment or later is late. After
an acceptance the deadline no longer applies.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
salary_raise_used:
type: boolean
description: >-
Whether the one raise of the upper salary bound after sending
(PRD FR13) has been used. It counts the whole history of the
invitation.
salary_fit:
$ref: "#/schemas/InvitationSalaryFit"
contact_access:
$ref: "#/schemas/InvitationContactAccess"
created_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
updated_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
delivered_at:
description: Moment of delivery to the candidate's inbox, or null for a draft.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
viewed_at:
description: Moment when the candidate first opened the terms, or null.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
responded_at:
description: Moment of the candidate's acceptance or decline, or null.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
OrganizationInvitationSummary:
type: object
description: >-
Invitation in the organization's list: its identity, state, versions,
role, salary range, deadline, and contact access. Read the invitation
for the full terms and the salary indicator.
additionalProperties: false
required:
- id
- candidate_handle
- need
- state
- expiry_reason
- version
- terms_version
- role_title
- salary
- response_deadline_at
- contact_access
- created_at
- updated_at
properties:
id:
type: string
format: uuid
description: Identifier of the invitation.
candidate_handle:
$ref: "./common_schemas.yml#/schemas/CandidateHandle"
need:
oneOf:
- $ref: "#/schemas/InvitationNeedReference"
- type: "null"
state:
$ref: "#/schemas/InvitationState"
expiry_reason:
oneOf:
- $ref: "#/schemas/InvitationExpiryReason"
- type: "null"
version:
$ref: "#/schemas/InvitationVersion"
terms_version:
$ref: "#/schemas/InvitationTermsVersion"
role_title:
$ref: "#/schemas/InvitationRoleTitle"
salary:
$ref: "./need_schemas.yml#/schemas/SalaryRange"
response_deadline_at:
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
contact_access:
$ref: "#/schemas/InvitationContactAccess"
created_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
updated_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
OrganizationInvitationList:
type: object
description: >-
One page of the invitations of an organization, newest first by
creation time.
additionalProperties: false
required:
- items
- page
properties:
items:
type: array
maxItems: 100
description: Invitations of the page.
items:
$ref: "#/schemas/OrganizationInvitationSummary"
page:
$ref: "./common_schemas.yml#/schemas/PageInfo"
OrganizationInvitationCreate:
type: object
description: >-
New draft for one candidate. The candidate is named only by the
handle from a search result of this organization, never by an email
address, a phone number, or an account identifier. The terms are
complete from the start, so a draft without the tax basis or the
communication method cannot exist. Unknown fields are rejected, so a
request cannot set the state, a version, a deadline, the salary
indicator, contact access, or a candidate's minimum or contact.
additionalProperties: false
required:
- candidate_handle
- terms
properties:
candidate_handle:
$ref: "./common_schemas.yml#/schemas/CandidateHandle"
need:
description: >-
Need of the organization the invitation is built from, or null or
absent for a direct invitation.
oneOf:
- $ref: "#/schemas/InvitationNeedReference"
- type: "null"
response_period_days:
description: Days to answer; absent means 7, the default of the product policy.
allOf:
- $ref: "#/schemas/InvitationResponsePeriod"
terms:
$ref: "#/schemas/InvitationTerms"
OrganizationInvitationUpdate:
type: object
description: >-
Change of a draft over the version the client read. Each field present
replaces that field as a whole and an absent field stays unchanged;
`terms` is always replaced completely, never merged, and a change of
the terms creates the next terms version. `need` sent as null unlinks
the need. The candidate cannot change: a draft for another candidate
is a new draft. Unknown fields are rejected.
additionalProperties: false
required:
- expected_version
properties:
expected_version:
$ref: "#/schemas/InvitationVersion"
need:
oneOf:
- $ref: "#/schemas/InvitationNeedReference"
- type: "null"
response_period_days:
$ref: "#/schemas/InvitationResponsePeriod"
terms:
$ref: "#/schemas/InvitationTerms"
InvitationCommand:
type: object
description: >-
Command without parameters over the invitation version the client
read: send, withdraw, or cancel. Unknown fields are rejected.
additionalProperties: false
required:
- expected_version
properties:
expected_version:
$ref: "#/schemas/InvitationVersion"
InvitationSalaryRaise:
type: object
description: >-
The one raise of the upper salary bound of a sent invitation (PRD
FR13). Only `salary_to` changes; the lower bound, the currency, the
period, and the tax basis stay fixed. Unknown fields are rejected, so
the request cannot lower the lower bound or change the basis.
additionalProperties: false
required:
- expected_version
- salary_to
properties:
expected_version:
$ref: "#/schemas/InvitationVersion"
salary_to:
description: >-
New upper bound, above the current one, with a width of the range
from 10% to 40% of its midpoint.
allOf:
- $ref: "./need_schemas.yml#/schemas/RubAmount"
CandidateInvitation:
type: object
description: >-
Invitation as the addressed candidate reads it: the organization, the
current terms with their version, the state and the deadline, the
text and the choice of the consent C4 while an acceptance is
possible, the candidate's own decline, and the contact grant that the
acceptance created. It has no candidate handle, no need, no salary
indicator, and no contact value: the candidate's own contacts and
salary minimum stay in the profile.
additionalProperties: false
required:
- id
- organization
- state
- expiry_reason
- version
- terms_version
- terms
- response_deadline_at
- delivered_at
- viewed_at
- responded_at
- updated_at
- contact_consent
- decline
- contact_grant
properties:
id:
type: string
format: uuid
description: Identifier of the invitation.
organization:
$ref: "#/schemas/InvitationOrganization"
state:
$ref: "#/schemas/InvitationState"
expiry_reason:
oneOf:
- $ref: "#/schemas/InvitationExpiryReason"
- type: "null"
version:
$ref: "#/schemas/InvitationVersion"
terms_version:
$ref: "#/schemas/InvitationTermsVersion"
terms:
$ref: "#/schemas/InvitationTerms"
response_deadline_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
delivered_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
viewed_at:
description: >-
Moment of the first view recorded by ViewMyInvitation, or null
when the candidate has not opened the terms.
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
responded_at:
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
updated_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
contact_consent:
description: >-
Text and choice of the consent C4 for an acceptance, or null when
an acceptance is impossible now: the state does not allow it, the
deadline has passed, or the profile holds no contact to disclose.
In the last case the client tells the candidate to add a contact
to the profile first, because a grant must cover at least one
field.
oneOf:
- $ref: "./contact_grant_schemas.yml#/schemas/ContactConsentOffer"
- type: "null"
decline:
description: The candidate's decline, or null unless `state` is `declined`.
oneOf:
- $ref: "#/schemas/InvitationDeclineRecord"
- type: "null"
contact_grant:
description: >-
Contact grant that the acceptance of this invitation created, or
null when the invitation was never accepted. It stays after a
revocation, with its status and reason.
oneOf:
- $ref: "./contact_grant_schemas.yml#/schemas/ContactGrant"
- type: "null"
CandidateInvitationSummary:
type: object
description: >-
Invitation in the candidate's inbox: the organization, the state, the
versions, the role, the salary range, and the deadline. Listing never
records a view; GetMyInvitation returns the full terms, and
ViewMyInvitation records the view.
additionalProperties: false
required:
- id
- organization
- state
- expiry_reason
- version
- terms_version
- role_title
- salary
- work_formats
- response_deadline_at
- delivered_at
- viewed_at
- updated_at
properties:
id:
type: string
format: uuid
description: Identifier of the invitation.
organization:
$ref: "#/schemas/InvitationOrganization"
state:
$ref: "#/schemas/InvitationState"
expiry_reason:
oneOf:
- $ref: "#/schemas/InvitationExpiryReason"
- type: "null"
version:
$ref: "#/schemas/InvitationVersion"
terms_version:
$ref: "#/schemas/InvitationTermsVersion"
role_title:
$ref: "#/schemas/InvitationRoleTitle"
salary:
$ref: "./need_schemas.yml#/schemas/SalaryRange"
work_formats:
type: array
minItems: 1
maxItems: 3
uniqueItems: true
items:
$ref: "./questionnaire_schemas.yml#/schemas/WorkFormat"
response_deadline_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
delivered_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
viewed_at:
oneOf:
- $ref: "./common_schemas.yml#/schemas/Timestamp"
- type: "null"
updated_at:
$ref: "./common_schemas.yml#/schemas/Timestamp"
CandidateInvitationList:
type: object
description: >-
One page of the candidate's invitations, newest first by delivery
time.
additionalProperties: false
required:
- items
- page
properties:
items:
type: array
maxItems: 100
description: Invitations of the page.
items:
$ref: "#/schemas/CandidateInvitationSummary"
page:
$ref: "./common_schemas.yml#/schemas/PageInfo"
InvitationAcceptance:
type: object
description: >-
Acceptance of the current terms with the consent C4. The client sends
the `version` and the `terms_version` it read and the contact fields
the candidate selected; nothing is preselected or defaulted. Unknown
fields are rejected, so a request cannot carry contact values, a
grant, or another consent.
additionalProperties: false
required:
- expected_version
- terms_version
- consent_c4
properties:
expected_version:
$ref: "#/schemas/InvitationVersion"
terms_version:
description: >-
Terms version that the candidate read and accepts. A version that
is not the current one answers 412 version_conflict.
allOf:
- $ref: "#/schemas/InvitationTermsVersion"
consent_c4:
$ref: "./contact_grant_schemas.yml#/schemas/ContactConsentAcceptance"
InvitationDeclineRequest:
type: object
description: >-
Structured decline: a reason and an optional comment. Unknown fields
are rejected.
additionalProperties: false
required:
- expected_version
- reason
properties:
expected_version:
$ref: "#/schemas/InvitationVersion"
reason:
$ref: "#/schemas/InvitationDeclineReason"
comment:
description: Optional comment for any reason, including `other`; absent or null means none.
oneOf:
- $ref: "#/schemas/InvitationDeclineComment"
- type: "null"
@@ -55,7 +55,7 @@ schemas:
- 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 not in the contract yet; until they are, every invitation reference answers 404 not_found.
- 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.
- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.
enum:
- assessment_attempt
File diff suppressed because it is too large. Load diff
+144
View File
@@ -32,6 +32,14 @@ tags:
state and provenance, immutable versions, readiness, and category
recommendations. Access comes only from an active membership in the
organization; a need never requires a vacancy.
- name: invitation
description: >-
Invitations from an organization to one candidate: drafts with
complete terms, immutable terms versions, sending, the candidate's
inbox, acceptance with the consent C4, structured declines,
withdrawal and cancellation, and the contact grant. Contacts are
readable only through an active grant, in a response separate from
the terms.
- name: support
description: >-
Support cases of the current account: questions, complaints, appeals
@@ -80,6 +88,30 @@ paths:
$ref: ./routes/organization_needs.yml
/api/v1/organizations/{org_id}/needs/{need_id}:
$ref: ./routes/organization_need.yml
/api/v1/organizations/{org_id}/invitations:
$ref: ./routes/organization_invitations.yml
/api/v1/organizations/{org_id}/invitations/{invitation_id}:
$ref: ./routes/organization_invitation.yml
/api/v1/organizations/{org_id}/invitations/{invitation_id}/send:
$ref: ./routes/organization_invitation_send.yml
/api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise:
$ref: ./routes/organization_invitation_salary_raise.yml
/api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw:
$ref: ./routes/organization_invitation_withdraw.yml
/api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts:
$ref: ./routes/organization_invitation_contacts.yml
/api/v1/me/invitations:
$ref: ./routes/candidate_invitations.yml
/api/v1/me/invitations/{invitation_id}:
$ref: ./routes/candidate_invitation.yml
/api/v1/me/invitations/{invitation_id}/view:
$ref: ./routes/candidate_invitation_view.yml
/api/v1/me/invitations/{invitation_id}/accept:
$ref: ./routes/candidate_invitation_accept.yml
/api/v1/me/invitations/{invitation_id}/decline:
$ref: ./routes/candidate_invitation_decline.yml
/api/v1/me/invitations/{invitation_id}/cancel:
$ref: ./routes/candidate_invitation_cancel.yml
/api/v1/me/support-cases:
$ref: ./routes/support_cases.yml
/api/v1/me/support-cases/{case_id}:
@@ -446,6 +478,106 @@ components:
$ref: ./components/schemas.yml#/SupportCaseSummary
SupportCaseList:
$ref: ./components/schemas.yml#/SupportCaseList
InvitationVersion:
$ref: ./components/schemas.yml#/InvitationVersion
InvitationTermsVersion:
$ref: ./components/schemas.yml#/InvitationTermsVersion
InvitationState:
$ref: ./components/schemas.yml#/InvitationState
InvitationExpiryReason:
$ref: ./components/schemas.yml#/InvitationExpiryReason
InvitationResponsePeriod:
$ref: ./components/schemas.yml#/InvitationResponsePeriod
CandidateHandle:
$ref: ./components/schemas.yml#/CandidateHandle
InvitationRoleTitle:
$ref: ./components/schemas.yml#/InvitationRoleTitle
InvitationTeamDescription:
$ref: ./components/schemas.yml#/InvitationTeamDescription
InvitationOfferType:
$ref: ./components/schemas.yml#/InvitationOfferType
InvitationCommunicationChannel:
$ref: ./components/schemas.yml#/InvitationCommunicationChannel
InvitationCommunicationMethod:
$ref: ./components/schemas.yml#/InvitationCommunicationMethod
InvitationCommunicationNote:
$ref: ./components/schemas.yml#/InvitationCommunicationNote
InvitationPackageItemText:
$ref: ./components/schemas.yml#/InvitationPackageItemText
InvitationPackageItemProvided:
$ref: ./components/schemas.yml#/InvitationPackageItemProvided
InvitationPackageItemNotProvided:
$ref: ./components/schemas.yml#/InvitationPackageItemNotProvided
InvitationPackageItem:
$ref: ./components/schemas.yml#/InvitationPackageItem
InvitationPackage:
$ref: ./components/schemas.yml#/InvitationPackage
InvitationTerms:
$ref: ./components/schemas.yml#/InvitationTerms
InvitationNeedReference:
$ref: ./components/schemas.yml#/InvitationNeedReference
InvitationSalaryFit:
$ref: ./components/schemas.yml#/InvitationSalaryFit
InvitationContactAccessState:
$ref: ./components/schemas.yml#/InvitationContactAccessState
InvitationContactAccess:
$ref: ./components/schemas.yml#/InvitationContactAccess
InvitationOrganization:
$ref: ./components/schemas.yml#/InvitationOrganization
InvitationDeclineReason:
$ref: ./components/schemas.yml#/InvitationDeclineReason
InvitationDeclineComment:
$ref: ./components/schemas.yml#/InvitationDeclineComment
InvitationDeclineRecord:
$ref: ./components/schemas.yml#/InvitationDeclineRecord
OrganizationInvitation:
$ref: ./components/schemas.yml#/OrganizationInvitation
OrganizationInvitationSummary:
$ref: ./components/schemas.yml#/OrganizationInvitationSummary
OrganizationInvitationList:
$ref: ./components/schemas.yml#/OrganizationInvitationList
OrganizationInvitationCreate:
$ref: ./components/schemas.yml#/OrganizationInvitationCreate
OrganizationInvitationUpdate:
$ref: ./components/schemas.yml#/OrganizationInvitationUpdate
InvitationCommand:
$ref: ./components/schemas.yml#/InvitationCommand
InvitationSalaryRaise:
$ref: ./components/schemas.yml#/InvitationSalaryRaise
CandidateInvitation:
$ref: ./components/schemas.yml#/CandidateInvitation
CandidateInvitationSummary:
$ref: ./components/schemas.yml#/CandidateInvitationSummary
CandidateInvitationList:
$ref: ./components/schemas.yml#/CandidateInvitationList
InvitationAcceptance:
$ref: ./components/schemas.yml#/InvitationAcceptance
InvitationDeclineRequest:
$ref: ./components/schemas.yml#/InvitationDeclineRequest
ContactFieldKind:
$ref: ./components/schemas.yml#/ContactFieldKind
ContactConsentText:
$ref: ./components/schemas.yml#/ContactConsentText
ContactConsentOffer:
$ref: ./components/schemas.yml#/ContactConsentOffer
ContactConsentAcceptance:
$ref: ./components/schemas.yml#/ContactConsentAcceptance
ContactGrantState:
$ref: ./components/schemas.yml#/ContactGrantState
ContactAccessBlock:
$ref: ./components/schemas.yml#/ContactAccessBlock
ContactRevocationReason:
$ref: ./components/schemas.yml#/ContactRevocationReason
ContactGrant:
$ref: ./components/schemas.yml#/ContactGrant
ContactPhoneNumber:
$ref: ./components/schemas.yml#/ContactPhoneNumber
ContactTelegramUsername:
$ref: ./components/schemas.yml#/ContactTelegramUsername
ContactFullName:
$ref: ./components/schemas.yml#/ContactFullName
ContactDisclosure:
$ref: ./components/schemas.yml#/ContactDisclosure
parameters:
IdempotencyKey:
$ref: ./components/parameters.yml#/IdempotencyKey
@@ -463,6 +595,10 @@ components:
$ref: ./components/parameters.yml#/NeedId
SupportCaseId:
$ref: ./components/parameters.yml#/SupportCaseId
InvitationId:
$ref: ./components/parameters.yml#/InvitationId
MyInvitationId:
$ref: ./components/parameters.yml#/MyInvitationId
headers:
ETag:
$ref: ./components/headers.yml#/ETag
@@ -539,6 +675,14 @@ components:
$ref: ./components/responses.yml#/SupportCaseValidationFailed
SupportCaseCreateConflict:
$ref: ./components/responses.yml#/SupportCaseCreateConflict
InvitationValidationFailed:
$ref: ./components/responses.yml#/InvitationValidationFailed
InvitationAcceptValidationFailed:
$ref: ./components/responses.yml#/InvitationAcceptValidationFailed
InvitationVersionConflict:
$ref: ./components/responses.yml#/InvitationVersionConflict
InvitationCommandConflict:
$ref: ./components/responses.yml#/InvitationCommandConflict
securitySchemes:
sessionCookie:
type: apiKey
+46
View File
@@ -0,0 +1,46 @@
get:
operationId: GetMyInvitation
summary: Open the terms of an invitation addressed to the current candidate.
description: |-
Requires the session cookie of a candidate account. The candidate comes from the session; the invitation must be addressed to this candidate.
Returns the organization, the current terms version with the full terms, the state, and the deadline. While an acceptance is possible (`delivered` or `viewed` before the deadline), `contact_consent` holds the published text of the consent C4 for this organization and the kinds of contact that the profile holds, with nothing preselected; otherwise it is null. It is null as well when the profile holds no contact: a grant must cover at least one field, so the client asks the candidate to add a contact to the profile before accepting. After an answer the response holds the candidate's own decline or the contact grant that the acceptance created, with the selected kinds, its status, and whether the organization can read it now (`readable`, with `blocked_by` `visibility` when the profile is not published or is hidden from the organization), never contact values. The response never carries the candidate's handle, the need of the organization, the salary indicator of the organization, or any contact or salary minimum of the candidate.
Reading has no side effect on the invitation: it never records a view. The client records that the candidate opened the terms with ViewMyInvitation, an explicit command, so a prefetch, a retry, or a cache refresh never changes the state that the organization sees. The only change a read can cause is the due expiry: a read at the deadline or later first applies the server transition to `expired` with `invitation_timeout`, which would happen without the read as well, and the response shows it. Reading earlier terms versions is planned as a separate operation.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown identifier all answer 404 not_found, so identifiers cannot be enumerated. An `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer.
security:
- sessionCookie: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/MyInvitationId
responses:
"200":
description: The invitation in its current state.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/CandidateInvitation
examples:
delivered:
$ref: ../components/examples.yml#/CandidateInvitationDelivered
viewed:
$ref: ../components/examples.yml#/CandidateInvitationViewed
accepted:
$ref: ../components/examples.yml#/CandidateInvitationAccepted
declined:
$ref: ../components/examples.yml#/CandidateInvitationDeclined
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,69 @@
post:
operationId: AcceptMyInvitation
summary: Accept the current terms and disclose the selected contacts.
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.
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.
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.
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.
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:
- sessionCookie: []
sessionCsrf: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/MyInvitationId
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/InvitationAcceptance
examples:
email_only:
$ref: ../components/examples.yml#/InvitationAcceptEmailOnly
stale_terms:
$ref: ../components/examples.yml#/InvitationAcceptStaleTerms
responses:
"200":
description: >-
The accepted invitation with the contact grant, or the same
invitation when this acceptance was already made.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/CandidateInvitation
examples:
accepted:
$ref: ../components/examples.yml#/CandidateInvitationAccepted
visibility_blocked:
$ref: ../components/examples.yml#/CandidateInvitationAcceptedVisibilityBlocked
"400":
$ref: ../components/responses.yml#/InvitationAcceptValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/InvitationCommandConflict
"412":
$ref: ../components/responses.yml#/InvitationVersionConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,63 @@
post:
operationId: CancelMyInvitation
summary: Cancel the participation in an invitation and revoke its contact grant.
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).
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.
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a cancellation of an invitation that is already `cancelled_by_candidate` answers 200 with it even with a new key or an older `expected_version`. A terminal state other than `cancelled_by_candidate` answers 409 state_conflict even with a stale `expected_version`; otherwise a stale `expected_version` answers 412 version_conflict. The deadline does not limit a cancellation.
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 a cancelled invitation (200), a terminal state (409 state_conflict, whatever the version), then the version (412). 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:
- sessionCookie: []
sessionCsrf: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/MyInvitationId
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/InvitationCommand
examples:
cancel:
$ref: ../components/examples.yml#/InvitationCancelCommand
responses:
"200":
description: >-
The invitation in the state `cancelled_by_candidate` with its grant
revoked.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/CandidateInvitation
examples:
cancelled:
$ref: ../components/examples.yml#/CandidateInvitationCancelled
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/InvitationCommandConflict
"412":
$ref: ../components/responses.yml#/InvitationVersionConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,65 @@
post:
operationId: DeclineMyInvitation
summary: Decline an invitation with a structured reason.
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.
Allowed in `delivered`, `viewed`, and the planned `counter`, before `response_deadline_at`. Moves the invitation to the terminal state `declined` with the reason and the optional comment; no consent and no access arise (PRD FR12). A timely decline counts as an answer for the responsiveness metrics, not as a consent or a hire. The reason is one of InvitationDeclineReason, including the neutral `other`; no reason requires a comment.
Visibility: the organization sees only the state `declined` and `responded_at`. It never sees the reason or the comment of an individual decline, because a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size (planned); the comment is never shown to the organization, published, logged, or sent in a notification. The candidate reads both back in `decline`. A new invitation of the same organization to this candidate is possible only after the 30-day pause.
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a decline of an invitation that is already `declined` with the same reason and comment answers 200 with it even with a new key or an older `expected_version`. A terminal state, another reason or comment on a declined invitation, and a command at the deadline or later answer 409 state_conflict even with a stale `expected_version`; otherwise a stale `expected_version` answers 412 version_conflict.
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 a declined invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the version), the version (412), then any other state that does not allow a decline (409 state_conflict). The schema rejects an unknown reason, an empty comment or one of only white space, a comment over 500 characters, and unknown fields. 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:
- sessionCookie: []
sessionCsrf: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/MyInvitationId
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/InvitationDeclineRequest
examples:
other_without_comment:
$ref: ../components/examples.yml#/InvitationDeclineOther
with_comment:
$ref: ../components/examples.yml#/InvitationDeclineWithComment
responses:
"200":
description: >-
The declined invitation with the candidate's own reason, or the same
invitation when this decline was already made.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/CandidateInvitation
examples:
declined:
$ref: ../components/examples.yml#/CandidateInvitationDeclined
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/InvitationCommandConflict
"412":
$ref: ../components/responses.yml#/InvitationVersionConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,47 @@
post:
operationId: ViewMyInvitation
summary: Record that the current candidate opened the terms of an invitation.
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 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`.
The general rate limit can answer 429 with Retry-After before any check.
Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown identifier all answer 404 not_found. An `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/MyInvitationId
responses:
"200":
description: >-
The invitation, now `viewed` when it was `delivered`, otherwise in
its current state.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/CandidateInvitation
examples:
viewed:
$ref: ../components/examples.yml#/CandidateInvitationViewed
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
+37
View File
@@ -0,0 +1,37 @@
get:
operationId: ListMyInvitations
summary: List the invitations addressed to the current candidate.
description: |-
Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. Returns a page of the candidate's inbox, newest first by delivery time with the identifier as the tie-breaker, with cursor pagination: every invitation that was delivered to this candidate, in any later state, including withdrawn and expired ones. Drafts and invitations addressed to other candidates are never listed.
A summary has the organization, the state, the versions, the role, the salary range, the work formats, and the deadline. Listing never records a view: the state `delivered` stays until ViewMyInvitation records that the candidate opened the terms. Responsiveness metrics of the organization and filters by state are planned and add fields or optional parameters.
Access: 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:
- sessionCookie: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/PageLimit
- $ref: ../components/parameters.yml#/PageCursor
responses:
"200":
description: A page of the invitations of the current candidate.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/CandidateInvitationList
examples:
last_page:
$ref: ../components/examples.yml#/CandidateInvitationListPage
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
default:
$ref: ../components/responses.yml#/Problem
+106
View File
@@ -0,0 +1,106 @@
get:
operationId: GetOrganizationInvitation
summary: Read an invitation of an organization.
description: |-
Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the server-side membership, never from the request. In the MVP only the owner of the organization reads invitations.
Returns the invitation with the current terms version, the state, the deadline, the coarse salary indicator `salary_fit`, and `contact_access`. The candidate appears only as the opaque `candidate_handle`: before and after an acceptance this response never carries the candidate's name, email address, phone number, or other contact, the exact salary minimum, or the reason and comment of a decline. Contact values come only from GetOrganizationInvitationContacts while `contact_access.status` is `available`. Reading earlier terms versions is planned as a separate operation.
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, and an invitation of another organization all answer 404 not_found, so identifiers cannot be probed; a member whose role does not allow reading the invitation answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer.
security:
- sessionCookie: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/InvitationId
responses:
"200":
description: The invitation in its current state.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationInvitation
examples:
draft:
$ref: ../components/examples.yml#/OrganizationInvitationDraft
delivered:
$ref: ../components/examples.yml#/OrganizationInvitationDelivered
accepted:
$ref: ../components/examples.yml#/OrganizationInvitationAccepted
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
default:
$ref: ../components/responses.yml#/Problem
patch:
operationId: UpdateOrganizationInvitation
summary: Change the terms, the need link, or the response period of a draft.
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, and an allowed Origin. The body has no organization, membership, or role field. In the MVP only the owner of the organization changes drafts.
Only a `draft` can change; any other state answers 409 state_conflict. After sending, the only change of the terms is the one raise of the upper salary bound through RaiseOrganizationInvitationSalary. The candidate of a draft cannot change: a draft for another candidate is a new draft.
Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged. `terms` is always sent complete and replaces the terms as a whole, with the same validation as on creation, so a package condition is never dropped by omission. `need` sent as null unlinks the need.
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.
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:
- sessionCookie: []
sessionCsrf: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/InvitationId
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationInvitationUpdate
examples:
change_terms:
$ref: ../components/examples.yml#/InvitationUpdateTerms
responses:
"200":
description: >-
The draft after the change, or the current draft when the body
changes nothing.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationInvitation
examples:
updated:
$ref: ../components/examples.yml#/OrganizationInvitationDraftUpdated
"400":
$ref: ../components/responses.yml#/InvitationValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/StateConflict
"412":
$ref: ../components/responses.yml#/InvitationVersionConflict
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,43 @@
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.
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`.
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:
- sessionCookie: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/InvitationId
responses:
"200":
description: The contacts that the active grant of this invitation covers.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/ContactDisclosure
examples:
email_only:
$ref: ../components/examples.yml#/InvitationContactsEmailOnly
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,65 @@
post:
operationId: RaiseOrganizationInvitationSalary
summary: Raise the upper salary bound of a sent invitation once.
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 changes invitations.
After sending, the salary base is fixed and the lower bound never decreases; the upper bound may be raised exactly once in the whole history of the invitation (PRD FR13). The body carries only the new `salary_to`, so the request cannot change the lower bound, the currency, the period, or the tax basis. The new bound must be above the current one and keep the width of the range from 10% to 40% of its midpoint, otherwise 400 validation_failed with the pointer `/salary_to`. The raise creates the next terms version with every other term unchanged and the next invitation version; the candidate sees the new terms, and an acceptance that names the previous terms version answers 412 version_conflict. The deadline does not change. The raise follows its own once-only rule and does not count against the organization-wide daily limit of three range settings, but it counts against the withheld counter of `salary_fit` (five settings within seven days), because it moves the upper bound that the indicator compares.
Allowed in `delivered`, `viewed`, and `accepted`, and in the planned states `counter`, `interview_scheduled`, `interviewed`, and `no_deal`, where FR13 lets a raise open an early repeated final. During `negotiation`, after `terms_agreed`, in a terminal state, in a `draft` (change the draft instead), and after the raise was used, the server answers 409 state_conflict. A raise after an acceptance changes neither the accepted terms version of the grant nor the grant.
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a raise to the same `salary_to` that was already applied answers 200 with the current invitation even with a new key or an older `expected_version`.
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 Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat of an applied raise (200), a terminal state (409 state_conflict, whatever the version), the version (412), any other state that does not allow a raise and the used raise (409 state_conflict), then the bound and the width (400). 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:
- sessionCookie: []
sessionCsrf: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/InvitationId
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/InvitationSalaryRaise
examples:
raise:
$ref: ../components/examples.yml#/InvitationSalaryRaiseCommand
responses:
"200":
description: >-
The invitation with the raised upper bound and the next terms
version, or the current invitation when the same raise was already
applied.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationInvitation
examples:
raised:
$ref: ../components/examples.yml#/OrganizationInvitationSalaryRaised
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/InvitationCommandConflict
"412":
$ref: ../components/responses.yml#/InvitationVersionConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,65 @@
post:
operationId: SendOrganizationInvitation
summary: Send a draft to the candidate's inbox.
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.
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.
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.
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 Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found), the repeat of a completed send (200), the version (412), the state, the visibility of the candidate, the pending limit and the pause (409 state_conflict), then the quota (429). 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/InvitationId
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/InvitationCommand
examples:
send:
$ref: ../components/examples.yml#/InvitationSendCommand
responses:
"200":
description: >-
The invitation in the candidate's inbox with the state `delivered`
and its deadline, or the invitation in its current state when it was
already sent.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationInvitation
examples:
delivered:
$ref: ../components/examples.yml#/OrganizationInvitationDelivered
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/InvitationCommandConflict
"412":
$ref: ../components/responses.yml#/InvitationVersionConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,62 @@
post:
operationId: WithdrawOrganizationInvitation
summary: Withdraw an invitation.
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 withdraws invitations.
Moves an unfinished invitation to the terminal state `withdrawn` (PRD FR12): a `draft`, which the candidate never sees, a `delivered` or `viewed` invitation before the answer, an `accepted` one, and the planned stages up to `negotiation`. The process closes and no further transition happens in it. Withdrawing a delivered invitation frees its place in the pending limit of the need but never returns the weekly quota. Withdrawing never revokes the consent C4 or a grant that already exists: an accepted invitation keeps its `contact_access`, because only the candidate closes the access, by revoking C4, cancelling the participation, or closing the visibility.
`withdrawn` differs from `cancelled_by_candidate`: the organization withdraws, and the grant stays; the candidate cancels through CancelMyInvitation, and the grant of this invitation is revoked. A terminal invitation (`declined`, `expired`, `cancelled_by_candidate`) answers 409 state_conflict, even with a stale `expected_version`, so the organization sees the final state at once.
Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a withdrawal of an invitation that is already `withdrawn` answers 200 with it even with a new key or an older `expected_version`.
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 Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on a withdrawn invitation (200), a terminal state (409 state_conflict, whatever the version), then the version (412). 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:
- sessionCookie: []
sessionCsrf: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/InvitationId
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/InvitationCommand
examples:
withdraw:
$ref: ../components/examples.yml#/InvitationWithdrawCommand
responses:
"200":
description: The invitation in the state `withdrawn`.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationInvitation
examples:
withdrawn:
$ref: ../components/examples.yml#/OrganizationInvitationWithdrawn
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/InvitationCommandConflict
"412":
$ref: ../components/responses.yml#/InvitationVersionConflict
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
@@ -0,0 +1,103 @@
get:
operationId: ListOrganizationInvitations
summary: List the invitations of an organization.
description: |-
Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the membership that the server holds for the session account, never from the request. In the MVP only the owner of the organization works with invitations, as with needs; the other roles of the PRD FR07 matrix are planned and change no field of this contract.
Returns a page of invitation summaries in every state, drafts included, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. A summary names the candidate only by the opaque `candidate_handle` and has the state, the versions, the role, the salary range, the deadline, and the contact access without any contact value. A declined invitation shows the state `declined` without the reason or the comment. Filters by state and need are planned and add optional parameters.
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 and an unknown organization both answer 404 not_found, so organizations cannot be enumerated; a member whose role does not allow reading invitations answers 403 forbidden. A malformed `org_id`, `limit`, or `cursor` answers 400 validation_failed.
security:
- sessionCookie: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/PageLimit
- $ref: ../components/parameters.yml#/PageCursor
responses:
"200":
description: A page of the invitations of the organization.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationInvitationList
examples:
last_page:
$ref: ../components/examples.yml#/OrganizationInvitationListPage
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/Forbidden
"404":
$ref: ../components/responses.yml#/NotFound
default:
$ref: ../components/responses.yml#/Problem
post:
operationId: CreateOrganizationInvitation
summary: Create an invitation draft for one candidate.
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. The organization comes from the path and the server-side membership; the body has no organization, membership, or role field. In the MVP only the owner of the organization may create an invitation.
The draft is addressed to one person from a search result of this organization: `candidate_handle` is the opaque handle of that card, never an email address, a phone number, or an account identifier. The server resolves the handle for this organization only. An unknown handle, a handle of another organization, and a profile that the organization may no longer see, because the candidate revoked the publication C2 or hid the profile from it, all answer 400 with the pointer `/candidate_handle`, so a handle never reveals which case applies. `need` is optional: a direct invitation has none, and a need given must be a need of the organization with a `requirements_version` that it has had, otherwise 400 with the pointer `/need`. `response_period_days` is 3, 7, or 14 and defaults to 7.
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.
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.
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 Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer: `/candidate_handle`, `/need`, `/terms/salary/salary_to` for a reversed range or a width outside 10-40%, `/terms/location` for the `office` or `hybrid` format without a place of work, or `/terms/tech_stack/1` for a repeated technology), then the salary limit (429). The schema already rejects a missing term or package condition, a salary bound that is not a positive multiple of 1000, an unknown currency, period, or tax basis, and unknown fields such as `state`, `version`, `salary_fit`, `candidate_email`, or `salary_minimum`. The general rate limit can answer 429 with Retry-After before any check.
security:
- sessionCookie: []
sessionCsrf: []
tags:
- invitation
parameters:
- $ref: ../components/parameters.yml#/OrganizationId
- $ref: ../components/parameters.yml#/IdempotencyKey
requestBody:
required: true
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationInvitationCreate
examples:
valid_invitation:
$ref: ../components/examples.yml#/InvitationCreateFromNeed
responses:
"201":
description: >-
The draft was created as version 1 with terms version 1, or a retry
with the same Idempotency-Key replayed its creation.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/OrganizationInvitation
examples:
draft:
$ref: ../components/examples.yml#/OrganizationInvitationDraft
"400":
$ref: ../components/responses.yml#/InvitationValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/IdempotencyInProgress
"422":
$ref: ../components/responses.yml#/UnprocessableContent
"429":
$ref: ../components/responses.yml#/TooManyRequests
default:
$ref: ../components/responses.yml#/Problem
+2 -2
View File
@@ -49,9 +49,9 @@ 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 not in the contract 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 (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.
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 whole-body pointer, because the decoder does not record the path inside the selected variant. The case stores only the type and the identifier of the object.
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.
Limits: an attempt and a resolved manual assessment each accept at most one grade appeal, and an attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a support case that references the appeal as `support_case`. A specialization accepts one open manual assessment, and an object accepts one open complaint; open means not `resolved` or `closed`. A second one answers 409 state_conflict. A grade appeal of an attempt that is still active also answers 409. Every create that passed authentication, validation, and the account scenario counts against a per-account limit from the product policy, including replays, 404, and 409, so the limit also bounds probing of references; over the limit the server answers 429 with Retry-After and creates nothing.
@@ -19,6 +19,7 @@ import (
var regexMap = map[string]ogenregex.Regexp{
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
@@ -27,6 +28,7 @@ var regexMap = map[string]ogenregex.Regexp{
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,14 @@
// Code generated by ogen, DO NOT EDIT.
package api
type AcceptMyInvitationRes interface {
acceptMyInvitationRes()
}
type CancelMyInvitationRes interface {
cancelMyInvitationRes()
}
type ConfirmEmailRes interface {
confirmEmailRes()
}
@@ -13,10 +21,18 @@ type CreateMySupportCaseRes interface {
createMySupportCaseRes()
}
type CreateOrganizationInvitationRes interface {
createOrganizationInvitationRes()
}
type CreateOrganizationNeedRes interface {
createOrganizationNeedRes()
}
type DeclineMyInvitationRes interface {
declineMyInvitationRes()
}
type FinalizeMyAssessmentAttemptRes interface {
finalizeMyAssessmentAttemptRes()
}
@@ -45,6 +61,10 @@ type GetMyAssessmentResultRes interface {
getMyAssessmentResultRes()
}
type GetMyInvitationRes interface {
getMyInvitationRes()
}
type GetMyQuestionnaireRes interface {
getMyQuestionnaireRes()
}
@@ -53,14 +73,30 @@ type GetMySupportCaseRes interface {
getMySupportCaseRes()
}
type GetOrganizationInvitationContactsRes interface {
getOrganizationInvitationContactsRes()
}
type GetOrganizationInvitationRes interface {
getOrganizationInvitationRes()
}
type GetOrganizationNeedRes interface {
getOrganizationNeedRes()
}
type ListMyInvitationsRes interface {
listMyInvitationsRes()
}
type ListMySupportCasesRes interface {
listMySupportCasesRes()
}
type ListOrganizationInvitationsRes interface {
listOrganizationInvitationsRes()
}
type ListOrganizationNeedsRes interface {
listOrganizationNeedsRes()
}
@@ -73,6 +109,10 @@ type LogoutRes interface {
logoutRes()
}
type RaiseOrganizationInvitationSalaryRes interface {
raiseOrganizationInvitationSalaryRes()
}
type RegisterAccountRes interface {
registerAccountRes()
}
@@ -85,10 +125,26 @@ type SaveMyQuestionnaireRes interface {
saveMyQuestionnaireRes()
}
type SendOrganizationInvitationRes interface {
sendOrganizationInvitationRes()
}
type SubmitMyAssessmentAnswerRes interface {
submitMyAssessmentAnswerRes()
}
type UpdateOrganizationInvitationRes interface {
updateOrganizationInvitationRes()
}
type UpdateOrganizationNeedRes interface {
updateOrganizationNeedRes()
}
type ViewMyInvitationRes interface {
viewMyInvitationRes()
}
type WithdrawOrganizationInvitationRes interface {
withdrawOrganizationInvitationRes()
}
File diff suppressed because it is too large. Load diff
@@ -6,29 +6,43 @@ package api
type OperationName = string
const (
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt"
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RegisterAccountOperation OperationName = "RegisterAccount"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
AcceptMyInvitationOperation OperationName = "AcceptMyInvitation"
CancelMyInvitationOperation OperationName = "CancelMyInvitation"
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt"
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RegisterAccountOperation OperationName = "RegisterAccount"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
WithdrawOrganizationInvitationOperation OperationName = "WithdrawOrganizationInvitation"
)
File diff suppressed because it is too large. Load diff
@@ -14,6 +14,164 @@ import (
"github.com/ogen-go/ogen/validate"
)
func (s *Server) decodeAcceptMyInvitationRequest(r *http.Request) (
req *InvitationAcceptance,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request InvitationAcceptance
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCancelMyInvitationRequest(r *http.Request) (
req *InvitationCommand,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request InvitationCommand
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeConfirmEmailRequest(r *http.Request) (
req *EmailVerificationRequest,
rawBody []byte,
@@ -251,6 +409,85 @@ func (s *Server) decodeCreateMySupportCaseRequest(r *http.Request) (
}
}
func (s *Server) decodeCreateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationCreate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationInvitationCreate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCreateOrganizationNeedRequest(r *http.Request) (
req *NeedCreate,
rawBody []byte,
@@ -330,6 +567,85 @@ func (s *Server) decodeCreateOrganizationNeedRequest(r *http.Request) (
}
}
func (s *Server) decodeDeclineMyInvitationRequest(r *http.Request) (
req *InvitationDeclineRequest,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request InvitationDeclineRequest
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeFinalizeMyAssessmentAttemptRequest(r *http.Request) (
req *AssessmentFinalization,
rawBody []byte,
@@ -488,6 +804,85 @@ func (s *Server) decodeLoginRequest(r *http.Request) (
}
}
func (s *Server) decodeRaiseOrganizationInvitationSalaryRequest(r *http.Request) (
req *InvitationSalaryRaise,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request InvitationSalaryRaise
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeRegisterAccountRequest(r *http.Request) (
req *RegistrationRequest,
rawBody []byte,
@@ -725,6 +1120,85 @@ func (s *Server) decodeSaveMyQuestionnaireRequest(r *http.Request) (
}
}
func (s *Server) decodeSendOrganizationInvitationRequest(r *http.Request) (
req *InvitationCommand,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request InvitationCommand
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) (
req *AssessmentAnswerSubmission,
rawBody []byte,
@@ -804,6 +1278,85 @@ func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) (
}
}
func (s *Server) decodeUpdateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationUpdate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationInvitationUpdate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeUpdateOrganizationNeedRequest(r *http.Request) (
req *NeedUpdate,
rawBody []byte,
@@ -882,3 +1435,82 @@ func (s *Server) decodeUpdateOrganizationNeedRequest(r *http.Request) (
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeWithdrawOrganizationInvitationRequest(r *http.Request) (
req *InvitationCommand,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request InvitationCommand
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -56,24 +56,38 @@ func findAuthorization(h http.Header, prefix string) (string, bool) {
// operationRolesSessionCookie is a private map storing roles per operation.
var operationRolesSessionCookie = map[string][]string{
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationNeedOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
GetMyAssessmentAttemptOperation: []string{},
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationNeedOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationNeedsOperation: []string{},
LogoutOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
AcceptMyInvitationOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
GetMyAssessmentAttemptOperation: []string{},
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyInvitationOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
}
// GetRolesForSessionCookie returns the required roles for the given operation.
@@ -99,14 +113,23 @@ func GetRolesForSessionCookie(operation string) []string {
// operationRolesSessionCsrf is a private map storing roles per operation.
var operationRolesSessionCsrf = map[string][]string{
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationNeedOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
LogoutOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
AcceptMyInvitationOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
}
// GetRolesForSessionCsrf returns the required roles for the given operation.
@@ -8,6 +8,94 @@ import (
// Handler handles operations described by OpenAPI v3 specification.
type Handler interface {
// AcceptMyInvitation implements AcceptMyInvitation operation.
//
// 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.
//
// 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.
//
// 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.
//
// 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.
//
// 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.
//
// POST /api/v1/me/invitations/{invitation_id}/accept
AcceptMyInvitation(ctx context.Context, req *InvitationAcceptance, params AcceptMyInvitationParams) (AcceptMyInvitationRes, error)
// CancelMyInvitation implements CancelMyInvitation operation.
//
// 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).
//
// 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.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a cancellation of an invitation that is already `cancelled_by_candidate` answers 200 with it
// even with a new key or an older `expected_version`. A terminal state other than
// `cancelled_by_candidate` answers 409 state_conflict even with a stale `expected_version`; otherwise
// a stale `expected_version` answers 412 version_conflict. The deadline does not limit a cancellation.
//
// 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 a cancelled invitation (200), a terminal state (409 state_conflict, whatever the version), then
// the version (412). 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.
//
// POST /api/v1/me/invitations/{invitation_id}/cancel
CancelMyInvitation(ctx context.Context, req *InvitationCommand, params CancelMyInvitationParams) (CancelMyInvitationRes, error)
// ConfirmEmail implements ConfirmEmail operation.
//
// Public operation without a session. The verification link has the form
@@ -99,10 +187,11 @@ type Handler interface {
//
// 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 not in the contract 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.
// 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.
//
// 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,
@@ -110,8 +199,7 @@ type Handler interface {
// 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
// whole-body pointer, because the decoder does not record the path inside the selected variant. The
// case stores only the type and the identifier of the object.
// pointer `/object/id`. The case stores only the type and the identifier of the object.
//
// Limits: an attempt and a resolved manual assessment each accept at most one grade appeal, and an
// attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a
@@ -165,6 +253,58 @@ type Handler interface {
//
// POST /api/v1/me/support-cases
CreateMySupportCase(ctx context.Context, req SupportCaseCreate, params CreateMySupportCaseParams) (CreateMySupportCaseRes, error)
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// 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. The organization
// comes from the path and the server-side membership; the body has no organization, membership, or
// role field. In the MVP only the owner of the organization may create an invitation.
//
// The draft is addressed to one person from a search result of this organization: `candidate_handle`
// is the opaque handle of that card, never an email address, a phone number, or an account identifier.
// The server resolves the handle for this organization only. An unknown handle, a handle of another
// organization, and a profile that the organization may no longer see, because the candidate revoked
// the publication C2 or hid the profile from it, all answer 400 with the pointer `/candidate_handle`,
// so a handle never reveals which case applies. `need` is optional: a direct invitation has none, and
// a need given must be a need of the organization with a `requirements_version` that it has had,
// otherwise 400 with the pointer `/need`. `response_period_days` is 3, 7, or 14 and defaults to 7.
//
// 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.
//
// 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.
//
// 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 Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a
// pointer: `/candidate_handle`, `/need`, `/terms/salary/salary_to` for a reversed range or a width
// outside 10-40%, `/terms/location` for the `office` or `hybrid` format without a place of work, or
// `/terms/tech_stack/1` for a repeated technology), then the salary limit (429). The schema already
// rejects a missing term or package condition, a salary bound that is not a positive multiple of 1000,
// an unknown currency, period, or tax basis, and unknown fields such as `state`, `version`,
// `salary_fit`, `candidate_email`, or `salary_minimum`. The general rate limit can answer 429 with
// Retry-After before any check.
//
// POST /api/v1/organizations/{org_id}/invitations
CreateOrganizationInvitation(ctx context.Context, req *OrganizationInvitationCreate, params CreateOrganizationInvitationParams) (CreateOrganizationInvitationRes, error)
// CreateOrganizationNeed implements CreateOrganizationNeed operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -218,6 +358,43 @@ type Handler interface {
//
// POST /api/v1/organizations/{org_id}/needs
CreateOrganizationNeed(ctx context.Context, req *NeedCreate, params CreateOrganizationNeedParams) (CreateOrganizationNeedRes, error)
// DeclineMyInvitation implements DeclineMyInvitation operation.
//
// 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.
//
// Allowed in `delivered`, `viewed`, and the planned `counter`, before `response_deadline_at`. Moves
// the invitation to the terminal state `declined` with the reason and the optional comment; no consent
// and no access arise (PRD FR12). A timely decline counts as an answer for the responsiveness metrics,
// not as a consent or a hire. The reason is one of InvitationDeclineReason, including the neutral
// `other`; no reason requires a comment.
//
// Visibility: the organization sees only the state `declined` and `responded_at`. It never sees the
// reason or the comment of an individual decline, because a reason such as `salary` would tell it that
// the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size
// (planned); the comment is never shown to the organization, published, logged, or sent in a
// notification. The candidate reads both back in `decline`. A new invitation of the same organization
// to this candidate is possible only after the 30-day pause.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a decline of an invitation that is already `declined` with the same reason and comment answers
// 200 with it even with a new key or an older `expected_version`. A terminal state, another reason or
// comment on a declined invitation, and a command at the deadline or later answer 409 state_conflict
// even with a stale `expected_version`; otherwise a stale `expected_version` answers 412
// version_conflict.
//
// 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 a declined invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever
// the version), the version (412), then any other state that does not allow a decline (409
// state_conflict). The schema rejects an unknown reason, an empty comment or one of only white space,
// a comment over 500 characters, and unknown fields. 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.
//
// POST /api/v1/me/invitations/{invitation_id}/decline
DeclineMyInvitation(ctx context.Context, req *InvitationDeclineRequest, params DeclineMyInvitationParams) (DeclineMyInvitationRes, error)
// FinalizeMyAssessmentAttempt implements FinalizeMyAssessmentAttempt operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -365,6 +542,37 @@ type Handler interface {
//
// GET /api/v1/me/assessment-attempts/{attempt_id}/result
GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error)
// GetMyInvitation implements GetMyInvitation operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session; the
// invitation must be addressed to this candidate.
//
// Returns the organization, the current terms version with the full terms, the state, and the
// deadline. While an acceptance is possible (`delivered` or `viewed` before the deadline),
// `contact_consent` holds the published text of the consent C4 for this organization and the kinds of
// contact that the profile holds, with nothing preselected; otherwise it is null. It is null as well
// when the profile holds no contact: a grant must cover at least one field, so the client asks the
// candidate to add a contact to the profile before accepting. After an answer the response holds the
// candidate's own decline or the contact grant that the acceptance created, with the selected kinds,
// its status, and whether the organization can read it now (`readable`, with `blocked_by` `visibility`
// when the profile is not published or is hidden from the organization), never contact values. The
// response never carries the candidate's handle, the need of the organization, the salary indicator of
// the organization, or any contact or salary minimum of the candidate.
//
// Reading has no side effect on the invitation: it never records a view. The client records that the
// candidate opened the terms with ViewMyInvitation, an explicit command, so a prefetch, a retry, or a
// cache refresh never changes the state that the organization sees. The only change a read can cause
// is the due expiry: a read at the deadline or later first applies the server transition to `expired`
// with `invitation_timeout`, which would happen without the read as well, and the response shows it.
// Reading earlier terms versions is planned as a separate operation.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer
// account answers 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown
// identifier all answer 404 not_found, so identifiers cannot be enumerated. An `invitation_id` that is
// not a UUID answers 400 validation_failed with the path pointer.
//
// GET /api/v1/me/invitations/{invitation_id}
GetMyInvitation(ctx context.Context, params GetMyInvitationParams) (GetMyInvitationRes, error)
// GetMyQuestionnaire implements GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -400,6 +608,65 @@ type Handler interface {
//
// GET /api/v1/me/support-cases/{case_id}
GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error)
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization and the role come from the server-side membership, never from the request. In the MVP
// only the owner of the organization reads invitations.
//
// Returns the invitation with the current terms version, the state, the deadline, the coarse salary
// indicator `salary_fit`, and `contact_access`. The candidate appears only as the opaque
// `candidate_handle`: before and after an acceptance this response never carries the candidate's name,
// email address, phone number, or other contact, the exact salary minimum, or the reason and comment
// of a decline. Contact values come only from GetOrganizationInvitationContacts while
// `contact_access.status` is `available`. Reading earlier terms versions is planned as a separate
// operation.
//
// 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, and an invitation of another organization all answer
// 404 not_found, so identifiers cannot be probed; a member whose role does not allow reading the
// invitation answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400
// validation_failed with the path pointer.
//
// GET /api/v1/organizations/{org_id}/invitations/{invitation_id}
GetOrganizationInvitation(ctx context.Context, params GetOrganizationInvitationParams) (GetOrganizationInvitationRes, error)
// GetOrganizationInvitationContacts implements GetOrganizationInvitationContacts operation.
//
// 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.
//
// 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`.
//
// 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.
//
// GET /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts
GetOrganizationInvitationContacts(ctx context.Context, params GetOrganizationInvitationContactsParams) (GetOrganizationInvitationContactsRes, error)
// GetOrganizationNeed implements GetOrganizationNeed operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -451,6 +718,24 @@ type Handler interface {
//
// GET /api/v1/specializations
GetSpecializationCatalog(ctx context.Context) (*SpecializationCatalog, error)
// ListMyInvitations implements ListMyInvitations operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
// a request parameter. Returns a page of the candidate's inbox, newest first by delivery time with the
// identifier as the tie-breaker, with cursor pagination: every invitation that was delivered to this
// candidate, in any later state, including withdrawn and expired ones. Drafts and invitations
// addressed to other candidates are never listed.
//
// A summary has the organization, the state, the versions, the role, the salary range, the work
// formats, and the deadline. Listing never records a view: the state `delivered` stays until
// ViewMyInvitation records that the candidate opened the terms. Responsiveness metrics of the
// organization and filters by state are planned and add fields or optional parameters.
//
// Access: 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.
//
// GET /api/v1/me/invitations
ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (ListMyInvitationsRes, error)
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -466,6 +751,28 @@ type Handler interface {
//
// GET /api/v1/me/support-cases
ListMySupportCases(ctx context.Context, params ListMySupportCasesParams) (ListMySupportCasesRes, error)
// ListOrganizationInvitations implements ListOrganizationInvitations operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization and the role come from the membership that the server holds for the session account,
// never from the request. In the MVP only the owner of the organization works with invitations, as
// with needs; the other roles of the PRD FR07 matrix are planned and change no field of this contract.
//
// Returns a page of invitation summaries in every state, drafts included, newest first by creation
// time with the identifier as the tie-breaker, with cursor pagination. A summary names the candidate
// only by the opaque `candidate_handle` and has the state, the versions, the role, the salary range,
// the deadline, and the contact access without any contact value. A declined invitation shows the
// state `declined` without the reason or the comment. Filters by state and need are planned and add
// optional parameters.
//
// 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 and an
// unknown organization both answer 404 not_found, so organizations cannot be enumerated; a member
// whose role does not allow reading invitations answers 403 forbidden. A malformed `org_id`, `limit`,
// or `cursor` answers 400 validation_failed.
//
// GET /api/v1/organizations/{org_id}/invitations
ListOrganizationInvitations(ctx context.Context, params ListOrganizationInvitationsParams) (ListOrganizationInvitationsRes, error)
// ListOrganizationNeeds implements ListOrganizationNeeds operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -521,6 +828,45 @@ type Handler interface {
//
// DELETE /api/v1/identity/sessions/current
Logout(ctx context.Context) (LogoutRes, error)
// RaiseOrganizationInvitationSalary implements RaiseOrganizationInvitationSalary operation.
//
// 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 changes invitations.
//
// After sending, the salary base is fixed and the lower bound never decreases; the upper bound may be
// raised exactly once in the whole history of the invitation (PRD FR13). The body carries only the new
// `salary_to`, so the request cannot change the lower bound, the currency, the period, or the tax
// basis. The new bound must be above the current one and keep the width of the range from 10% to 40%
// of its midpoint, otherwise 400 validation_failed with the pointer `/salary_to`. The raise creates
// the next terms version with every other term unchanged and the next invitation version; the
// candidate sees the new terms, and an acceptance that names the previous terms version answers 412
// version_conflict. The deadline does not change. The raise follows its own once-only rule and does
// not count against the organization-wide daily limit of three range settings, but it counts against
// the withheld counter of `salary_fit` (five settings within seven days), because it moves the upper
// bound that the indicator compares.
//
// Allowed in `delivered`, `viewed`, and `accepted`, and in the planned states `counter`,
// `interview_scheduled`, `interviewed`, and `no_deal`, where FR13 lets a raise open an early repeated
// final. During `negotiation`, after `terms_agreed`, in a terminal state, in a `draft` (change the
// draft instead), and after the raise was used, the server answers 409 state_conflict. A raise after
// an acceptance changes neither the accepted terms version of the grant nor the grant.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a raise to the same `salary_to` that was already applied answers 200 with the current invitation
// even with a new key or an older `expected_version`.
//
// 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 Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404
// not_found, after any due expiry), the repeat of an applied raise (200), a terminal state (409
// state_conflict, whatever the version), the version (412), any other state that does not allow a
// raise and the used raise (409 state_conflict), then the bound and the width (400). 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.
//
// POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise
RaiseOrganizationInvitationSalary(ctx context.Context, req *InvitationSalaryRaise, params RaiseOrganizationInvitationSalaryParams) (RaiseOrganizationInvitationSalaryRes, error)
// RegisterAccount implements RegisterAccount operation.
//
// Public operation without a session. The client reads the current C1 text with GetConsentText and
@@ -617,6 +963,43 @@ type Handler interface {
//
// PUT /api/v1/me/questionnaire
SaveMyQuestionnaire(ctx context.Context, req *CandidateQuestionnaireUpdate) (SaveMyQuestionnaireRes, error)
// SendOrganizationInvitation implements SendOrganizationInvitation operation.
//
// 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.
//
// 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.
//
// 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.
//
// 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 Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404
// not_found), the repeat of a completed send (200), the version (412), the state, the visibility of
// the candidate, the pending limit and the pause (409 state_conflict), then the quota (429). 404 and
// 409 state_conflict are stored under the key; 400, 412, and 429 are not.
//
// POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send
SendOrganizationInvitation(ctx context.Context, req *InvitationCommand, params SendOrganizationInvitationParams) (SendOrganizationInvitationRes, error)
// SubmitMyAssessmentAnswer implements SubmitMyAssessmentAnswer operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -674,6 +1057,50 @@ type Handler interface {
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/answers
SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error)
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// 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, and an allowed Origin. The body has no organization,
// membership, or role field. In the MVP only the owner of the organization changes drafts.
//
// Only a `draft` can change; any other state answers 409 state_conflict. After sending, the only
// change of the terms is the one raise of the upper salary bound through
// RaiseOrganizationInvitationSalary. The candidate of a draft cannot change: a draft for another
// candidate is a new draft.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged. `terms` is
// always sent complete and replaces the terms as a whole, with the same validation as on creation, so
// a package condition is never dropped by omission. `need` sent as null unlinks the need.
//
// 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.
//
// 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).
//
// PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}
UpdateOrganizationInvitation(ctx context.Context, req *OrganizationInvitationUpdate, params UpdateOrganizationInvitationParams) (UpdateOrganizationInvitationRes, error)
// UpdateOrganizationNeed implements UpdateOrganizationNeed operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -741,6 +1168,67 @@ type Handler interface {
//
// PATCH /api/v1/organizations/{org_id}/needs/{need_id}
UpdateOrganizationNeed(ctx context.Context, req *NeedUpdate, params UpdateOrganizationNeedParams) (UpdateOrganizationNeedRes, error)
// ViewMyInvitation implements ViewMyInvitation operation.
//
// 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 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`.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers
// 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown identifier all
// answer 404 not_found. An `invitation_id` that is not a UUID answers 400 validation_failed with the
// path pointer.
//
// POST /api/v1/me/invitations/{invitation_id}/view
ViewMyInvitation(ctx context.Context, params ViewMyInvitationParams) (ViewMyInvitationRes, error)
// WithdrawOrganizationInvitation implements WithdrawOrganizationInvitation operation.
//
// 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 withdraws invitations.
//
// Moves an unfinished invitation to the terminal state `withdrawn` (PRD FR12): a `draft`, which the
// candidate never sees, a `delivered` or `viewed` invitation before the answer, an `accepted` one, and
// the planned stages up to `negotiation`. The process closes and no further transition happens in it.
// Withdrawing a delivered invitation frees its place in the pending limit of the need but never
// returns the weekly quota. Withdrawing never revokes the consent C4 or a grant that already exists:
// an accepted invitation keeps its `contact_access`, because only the candidate closes the access, by
// revoking C4, cancelling the participation, or closing the visibility.
//
// `withdrawn` differs from `cancelled_by_candidate`: the organization withdraws, and the grant stays;
// the candidate cancels through CancelMyInvitation, and the grant of this invitation is revoked. A
// terminal invitation (`declined`, `expired`, `cancelled_by_candidate`) answers 409 state_conflict,
// even with a stale `expected_version`, so the organization sees the final state at once.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a withdrawal of an invitation that is already `withdrawn` answers 200 with it even with a new
// key or an older `expected_version`.
//
// 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 Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404
// not_found, after any due expiry), the repeat on a withdrawn invitation (200), a terminal state (409
// state_conflict, whatever the version), then the version (412). 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.
//
// POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw
WithdrawOrganizationInvitation(ctx context.Context, req *InvitationCommand, params WithdrawOrganizationInvitationParams) (WithdrawOrganizationInvitationRes, error)
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
@@ -13,6 +13,100 @@ type UnimplementedHandler struct{}
var _ Handler = UnimplementedHandler{}
// AcceptMyInvitation implements AcceptMyInvitation operation.
//
// 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.
//
// 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.
//
// 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.
//
// 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.
//
// 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.
//
// POST /api/v1/me/invitations/{invitation_id}/accept
func (UnimplementedHandler) AcceptMyInvitation(ctx context.Context, req *InvitationAcceptance, params AcceptMyInvitationParams) (r AcceptMyInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// CancelMyInvitation implements CancelMyInvitation operation.
//
// 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).
//
// 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.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a cancellation of an invitation that is already `cancelled_by_candidate` answers 200 with it
// even with a new key or an older `expected_version`. A terminal state other than
// `cancelled_by_candidate` answers 409 state_conflict even with a stale `expected_version`; otherwise
// a stale `expected_version` answers 412 version_conflict. The deadline does not limit a cancellation.
//
// 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 a cancelled invitation (200), a terminal state (409 state_conflict, whatever the version), then
// the version (412). 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.
//
// POST /api/v1/me/invitations/{invitation_id}/cancel
func (UnimplementedHandler) CancelMyInvitation(ctx context.Context, req *InvitationCommand, params CancelMyInvitationParams) (r CancelMyInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// ConfirmEmail implements ConfirmEmail operation.
//
// Public operation without a session. The verification link has the form
@@ -110,10 +204,11 @@ func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req *
//
// 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 not in the contract 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.
// 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.
//
// 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,
@@ -121,8 +216,7 @@ func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req *
// 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
// whole-body pointer, because the decoder does not record the path inside the selected variant. The
// case stores only the type and the identifier of the object.
// pointer `/object/id`. The case stores only the type and the identifier of the object.
//
// Limits: an attempt and a resolved manual assessment each accept at most one grade appeal, and an
// attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a
@@ -179,6 +273,61 @@ func (UnimplementedHandler) CreateMySupportCase(ctx context.Context, req Support
return r, ht.ErrNotImplemented
}
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// 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. The organization
// comes from the path and the server-side membership; the body has no organization, membership, or
// role field. In the MVP only the owner of the organization may create an invitation.
//
// The draft is addressed to one person from a search result of this organization: `candidate_handle`
// is the opaque handle of that card, never an email address, a phone number, or an account identifier.
// The server resolves the handle for this organization only. An unknown handle, a handle of another
// organization, and a profile that the organization may no longer see, because the candidate revoked
// the publication C2 or hid the profile from it, all answer 400 with the pointer `/candidate_handle`,
// so a handle never reveals which case applies. `need` is optional: a direct invitation has none, and
// a need given must be a need of the organization with a `requirements_version` that it has had,
// otherwise 400 with the pointer `/need`. `response_period_days` is 3, 7, or 14 and defaults to 7.
//
// 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.
//
// 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.
//
// 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 Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a
// pointer: `/candidate_handle`, `/need`, `/terms/salary/salary_to` for a reversed range or a width
// outside 10-40%, `/terms/location` for the `office` or `hybrid` format without a place of work, or
// `/terms/tech_stack/1` for a repeated technology), then the salary limit (429). The schema already
// rejects a missing term or package condition, a salary bound that is not a positive multiple of 1000,
// an unknown currency, period, or tax basis, and unknown fields such as `state`, `version`,
// `salary_fit`, `candidate_email`, or `salary_minimum`. The general rate limit can answer 429 with
// Retry-After before any check.
//
// POST /api/v1/organizations/{org_id}/invitations
func (UnimplementedHandler) CreateOrganizationInvitation(ctx context.Context, req *OrganizationInvitationCreate, params CreateOrganizationInvitationParams) (r CreateOrganizationInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// CreateOrganizationNeed implements CreateOrganizationNeed operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -235,6 +384,46 @@ func (UnimplementedHandler) CreateOrganizationNeed(ctx context.Context, req *Nee
return r, ht.ErrNotImplemented
}
// DeclineMyInvitation implements DeclineMyInvitation operation.
//
// 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.
//
// Allowed in `delivered`, `viewed`, and the planned `counter`, before `response_deadline_at`. Moves
// the invitation to the terminal state `declined` with the reason and the optional comment; no consent
// and no access arise (PRD FR12). A timely decline counts as an answer for the responsiveness metrics,
// not as a consent or a hire. The reason is one of InvitationDeclineReason, including the neutral
// `other`; no reason requires a comment.
//
// Visibility: the organization sees only the state `declined` and `responded_at`. It never sees the
// reason or the comment of an individual decline, because a reason such as `salary` would tell it that
// the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size
// (planned); the comment is never shown to the organization, published, logged, or sent in a
// notification. The candidate reads both back in `decline`. A new invitation of the same organization
// to this candidate is possible only after the 30-day pause.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a decline of an invitation that is already `declined` with the same reason and comment answers
// 200 with it even with a new key or an older `expected_version`. A terminal state, another reason or
// comment on a declined invitation, and a command at the deadline or later answer 409 state_conflict
// even with a stale `expected_version`; otherwise a stale `expected_version` answers 412
// version_conflict.
//
// 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 a declined invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever
// the version), the version (412), then any other state that does not allow a decline (409
// state_conflict). The schema rejects an unknown reason, an empty comment or one of only white space,
// a comment over 500 characters, and unknown fields. 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.
//
// POST /api/v1/me/invitations/{invitation_id}/decline
func (UnimplementedHandler) DeclineMyInvitation(ctx context.Context, req *InvitationDeclineRequest, params DeclineMyInvitationParams) (r DeclineMyInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// FinalizeMyAssessmentAttempt implements FinalizeMyAssessmentAttempt operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -406,6 +595,40 @@ func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params Ge
return r, ht.ErrNotImplemented
}
// GetMyInvitation implements GetMyInvitation operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session; the
// invitation must be addressed to this candidate.
//
// Returns the organization, the current terms version with the full terms, the state, and the
// deadline. While an acceptance is possible (`delivered` or `viewed` before the deadline),
// `contact_consent` holds the published text of the consent C4 for this organization and the kinds of
// contact that the profile holds, with nothing preselected; otherwise it is null. It is null as well
// when the profile holds no contact: a grant must cover at least one field, so the client asks the
// candidate to add a contact to the profile before accepting. After an answer the response holds the
// candidate's own decline or the contact grant that the acceptance created, with the selected kinds,
// its status, and whether the organization can read it now (`readable`, with `blocked_by` `visibility`
// when the profile is not published or is hidden from the organization), never contact values. The
// response never carries the candidate's handle, the need of the organization, the salary indicator of
// the organization, or any contact or salary minimum of the candidate.
//
// Reading has no side effect on the invitation: it never records a view. The client records that the
// candidate opened the terms with ViewMyInvitation, an explicit command, so a prefetch, a retry, or a
// cache refresh never changes the state that the organization sees. The only change a read can cause
// is the due expiry: a read at the deadline or later first applies the server transition to `expired`
// with `invitation_timeout`, which would happen without the read as well, and the response shows it.
// Reading earlier terms versions is planned as a separate operation.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer
// account answers 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown
// identifier all answer 404 not_found, so identifiers cannot be enumerated. An `invitation_id` that is
// not a UUID answers 400 validation_failed with the path pointer.
//
// GET /api/v1/me/invitations/{invitation_id}
func (UnimplementedHandler) GetMyInvitation(ctx context.Context, params GetMyInvitationParams) (r GetMyInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetMyQuestionnaire implements GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -447,6 +670,71 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
return r, ht.ErrNotImplemented
}
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization and the role come from the server-side membership, never from the request. In the MVP
// only the owner of the organization reads invitations.
//
// Returns the invitation with the current terms version, the state, the deadline, the coarse salary
// indicator `salary_fit`, and `contact_access`. The candidate appears only as the opaque
// `candidate_handle`: before and after an acceptance this response never carries the candidate's name,
// email address, phone number, or other contact, the exact salary minimum, or the reason and comment
// of a decline. Contact values come only from GetOrganizationInvitationContacts while
// `contact_access.status` is `available`. Reading earlier terms versions is planned as a separate
// operation.
//
// 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, and an invitation of another organization all answer
// 404 not_found, so identifiers cannot be probed; a member whose role does not allow reading the
// invitation answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400
// validation_failed with the path pointer.
//
// GET /api/v1/organizations/{org_id}/invitations/{invitation_id}
func (UnimplementedHandler) GetOrganizationInvitation(ctx context.Context, params GetOrganizationInvitationParams) (r GetOrganizationInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetOrganizationInvitationContacts implements GetOrganizationInvitationContacts operation.
//
// 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.
//
// 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`.
//
// 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.
//
// GET /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts
func (UnimplementedHandler) GetOrganizationInvitationContacts(ctx context.Context, params GetOrganizationInvitationContactsParams) (r GetOrganizationInvitationContactsRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetOrganizationNeed implements GetOrganizationNeed operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -504,6 +792,27 @@ func (UnimplementedHandler) GetSpecializationCatalog(ctx context.Context) (r *Sp
return r, ht.ErrNotImplemented
}
// ListMyInvitations implements ListMyInvitations operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
// a request parameter. Returns a page of the candidate's inbox, newest first by delivery time with the
// identifier as the tie-breaker, with cursor pagination: every invitation that was delivered to this
// candidate, in any later state, including withdrawn and expired ones. Drafts and invitations
// addressed to other candidates are never listed.
//
// A summary has the organization, the state, the versions, the role, the salary range, the work
// formats, and the deadline. Listing never records a view: the state `delivered` stays until
// ViewMyInvitation records that the candidate opened the terms. Responsiveness metrics of the
// organization and filters by state are planned and add fields or optional parameters.
//
// Access: 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.
//
// GET /api/v1/me/invitations
func (UnimplementedHandler) ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (r ListMyInvitationsRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -522,6 +831,31 @@ func (UnimplementedHandler) ListMySupportCases(ctx context.Context, params ListM
return r, ht.ErrNotImplemented
}
// ListOrganizationInvitations implements ListOrganizationInvitations operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization and the role come from the membership that the server holds for the session account,
// never from the request. In the MVP only the owner of the organization works with invitations, as
// with needs; the other roles of the PRD FR07 matrix are planned and change no field of this contract.
//
// Returns a page of invitation summaries in every state, drafts included, newest first by creation
// time with the identifier as the tie-breaker, with cursor pagination. A summary names the candidate
// only by the opaque `candidate_handle` and has the state, the versions, the role, the salary range,
// the deadline, and the contact access without any contact value. A declined invitation shows the
// state `declined` without the reason or the comment. Filters by state and need are planned and add
// optional parameters.
//
// 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 and an
// unknown organization both answer 404 not_found, so organizations cannot be enumerated; a member
// whose role does not allow reading invitations answers 403 forbidden. A malformed `org_id`, `limit`,
// or `cursor` answers 400 validation_failed.
//
// GET /api/v1/organizations/{org_id}/invitations
func (UnimplementedHandler) ListOrganizationInvitations(ctx context.Context, params ListOrganizationInvitationsParams) (r ListOrganizationInvitationsRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListOrganizationNeeds implements ListOrganizationNeeds operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -586,6 +920,48 @@ func (UnimplementedHandler) Logout(ctx context.Context) (r LogoutRes, _ error) {
return r, ht.ErrNotImplemented
}
// RaiseOrganizationInvitationSalary implements RaiseOrganizationInvitationSalary operation.
//
// 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 changes invitations.
//
// After sending, the salary base is fixed and the lower bound never decreases; the upper bound may be
// raised exactly once in the whole history of the invitation (PRD FR13). The body carries only the new
// `salary_to`, so the request cannot change the lower bound, the currency, the period, or the tax
// basis. The new bound must be above the current one and keep the width of the range from 10% to 40%
// of its midpoint, otherwise 400 validation_failed with the pointer `/salary_to`. The raise creates
// the next terms version with every other term unchanged and the next invitation version; the
// candidate sees the new terms, and an acceptance that names the previous terms version answers 412
// version_conflict. The deadline does not change. The raise follows its own once-only rule and does
// not count against the organization-wide daily limit of three range settings, but it counts against
// the withheld counter of `salary_fit` (five settings within seven days), because it moves the upper
// bound that the indicator compares.
//
// Allowed in `delivered`, `viewed`, and `accepted`, and in the planned states `counter`,
// `interview_scheduled`, `interviewed`, and `no_deal`, where FR13 lets a raise open an early repeated
// final. During `negotiation`, after `terms_agreed`, in a terminal state, in a `draft` (change the
// draft instead), and after the raise was used, the server answers 409 state_conflict. A raise after
// an acceptance changes neither the accepted terms version of the grant nor the grant.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a raise to the same `salary_to` that was already applied answers 200 with the current invitation
// even with a new key or an older `expected_version`.
//
// 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 Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404
// not_found, after any due expiry), the repeat of an applied raise (200), a terminal state (409
// state_conflict, whatever the version), the version (412), any other state that does not allow a
// raise and the used raise (409 state_conflict), then the bound and the width (400). 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.
//
// POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise
func (UnimplementedHandler) RaiseOrganizationInvitationSalary(ctx context.Context, req *InvitationSalaryRaise, params RaiseOrganizationInvitationSalaryParams) (r RaiseOrganizationInvitationSalaryRes, _ error) {
return r, ht.ErrNotImplemented
}
// RegisterAccount implements RegisterAccount operation.
//
// Public operation without a session. The client reads the current C1 text with GetConsentText and
@@ -691,6 +1067,46 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid
return r, ht.ErrNotImplemented
}
// SendOrganizationInvitation implements SendOrganizationInvitation operation.
//
// 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.
//
// 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.
//
// 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.
//
// 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 Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404
// not_found), the repeat of a completed send (200), the version (412), the state, the visibility of
// the candidate, the pending limit and the pause (409 state_conflict), then the quota (429). 404 and
// 409 state_conflict are stored under the key; 400, 412, and 429 are not.
//
// POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send
func (UnimplementedHandler) SendOrganizationInvitation(ctx context.Context, req *InvitationCommand, params SendOrganizationInvitationParams) (r SendOrganizationInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// SubmitMyAssessmentAnswer implements SubmitMyAssessmentAnswer operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -751,6 +1167,53 @@ func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *A
return r, ht.ErrNotImplemented
}
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// 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, and an allowed Origin. The body has no organization,
// membership, or role field. In the MVP only the owner of the organization changes drafts.
//
// Only a `draft` can change; any other state answers 409 state_conflict. After sending, the only
// change of the terms is the one raise of the upper salary bound through
// RaiseOrganizationInvitationSalary. The candidate of a draft cannot change: a draft for another
// candidate is a new draft.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged. `terms` is
// always sent complete and replaces the terms as a whole, with the same validation as on creation, so
// a package condition is never dropped by omission. `need` sent as null unlinks the need.
//
// 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.
//
// 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).
//
// PATCH /api/v1/organizations/{org_id}/invitations/{invitation_id}
func (UnimplementedHandler) UpdateOrganizationInvitation(ctx context.Context, req *OrganizationInvitationUpdate, params UpdateOrganizationInvitationParams) (r UpdateOrganizationInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// UpdateOrganizationNeed implements UpdateOrganizationNeed operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -821,6 +1284,73 @@ func (UnimplementedHandler) UpdateOrganizationNeed(ctx context.Context, req *Nee
return r, ht.ErrNotImplemented
}
// ViewMyInvitation implements ViewMyInvitation operation.
//
// 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 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`.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers
// 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown identifier all
// answer 404 not_found. An `invitation_id` that is not a UUID answers 400 validation_failed with the
// path pointer.
//
// POST /api/v1/me/invitations/{invitation_id}/view
func (UnimplementedHandler) ViewMyInvitation(ctx context.Context, params ViewMyInvitationParams) (r ViewMyInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// WithdrawOrganizationInvitation implements WithdrawOrganizationInvitation operation.
//
// 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 withdraws invitations.
//
// Moves an unfinished invitation to the terminal state `withdrawn` (PRD FR12): a `draft`, which the
// candidate never sees, a `delivered` or `viewed` invitation before the answer, an `accepted` one, and
// the planned stages up to `negotiation`. The process closes and no further transition happens in it.
// Withdrawing a delivered invitation frees its place in the pending limit of the need but never
// returns the weekly quota. Withdrawing never revokes the consent C4 or a grant that already exists:
// an accepted invitation keeps its `contact_access`, because only the candidate closes the access, by
// revoking C4, cancelling the participation, or closing the visibility.
//
// `withdrawn` differs from `cancelled_by_candidate`: the organization withdraws, and the grant stays;
// the candidate cancels through CancelMyInvitation, and the grant of this invitation is revoked. A
// terminal invitation (`declined`, `expired`, `cancelled_by_candidate`) answers 409 state_conflict,
// even with a stale `expected_version`, so the organization sees the final state at once.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a withdrawal of an invitation that is already `withdrawn` answers 200 with it even with a new
// key or an older `expected_version`.
//
// 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 Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404
// not_found, after any due expiry), the repeat on a withdrawn invitation (200), a terminal state (409
// state_conflict, whatever the version), then the version (412). 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.
//
// POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw
func (UnimplementedHandler) WithdrawOrganizationInvitation(ctx context.Context, req *InvitationCommand, params WithdrawOrganizationInvitationParams) (r WithdrawOrganizationInvitationRes, _ error) {
return r, ht.ErrNotImplemented
}
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
File diff suppressed because it is too large. Load diff
@@ -3,11 +3,13 @@ package problem
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"regexp"
"strings"
faster "github.com/go-faster/errors"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/openapi"
@@ -32,6 +34,18 @@ const (
wholeBodyPointer = ""
)
// decodeFieldMessage matches the message of the wrapper that generated
// decoders put around the error of one object field, for example
// `decode field "terms"`. The name is the JSON property name, which in this
// contract never contains a quote or a backslash.
var decodeFieldMessage = regexp.MustCompile(`^decode field "([^"\\]+)"$`)
// arrayElementMessage is the message of the wrapper that jx puts around the
// error of a callback. Directly under a field wrapper it marks an array
// element, because an object value is always wrapped first by its own
// `decode <Type>` message.
const arrayElementMessage = "callback"
// arrayIndexName matches the "[index]" names that generated validators use
// for array items.
var arrayIndexName = regexp.MustCompile(`^\[(\d+)\]$`)
@@ -184,12 +198,7 @@ func bodyFieldErrors(err error) []api.ProblemFieldError {
var fields []api.ProblemFieldError
if decodeErr, ok := errors.AsType[*ogenerrors.DecodeBodyError](err); ok {
// Only a validation error that is the direct decoding cause names
// top-level fields. A wrapped one comes from a nested object whose
// path the decoder does not record, so it maps to the whole body.
if topLevel, ok := decodeErr.Err.(*validate.Error); ok { //nolint:errorlint // the unwrapped cause alone identifies top-level fields
fields = appendSchemaFieldErrors(fields, topLevel, wholeBodyPointer)
}
fields = decodeFieldErrors(decodeErr.Err)
} else if validationErr, ok := errors.AsType[*validate.Error](err); ok {
// Schema validation after decoding nests field errors by path.
fields = appendSchemaFieldErrors(fields, validationErr, wholeBodyPointer)
@@ -200,6 +209,71 @@ func bodyFieldErrors(err error) []api.ProblemFieldError {
return fields
}
// decodeFieldErrors maps an error of the generated JSON decoder to field
// errors. The decoder records no path of its own; it wraps the error of each
// object field with `decode field "<name>"` through go-faster/errors. The
// pointer is rebuilt from those wrappers, read through the typed
// errors.Formatter of each link rather than from the joined error text:
// - a *validate.Error lists the missing required fields of the object at the
// pointer, which become `required` with their own pointer;
// - an array element has no index in the chain, so the pointer stops at the
// array with `invalid`;
// - any other failure, such as a wrong JSON type, an unknown property, an
// unknown oneOf variant, or a malformed value, is `invalid` at the pointer
// of the value whose decoding failed;
// - a link that is neither a go-faster wrapper nor a leaf ends the walk with
// `invalid` at the pointer reached so far, which is the whole body when no
// field wrapper was recognized.
func decodeFieldErrors(err error) []api.ProblemFieldError {
pointer := wholeBodyPointer
afterField := false
for err != nil {
if validationErr, ok := err.(*validate.Error); ok { //nolint:errorlint // the walk inspects each link of the chain itself
return appendSchemaFieldErrors(nil, validationErr, pointer)
}
formatter, ok := err.(faster.Formatter) //nolint:errorlint // the walk inspects each link of the chain itself
if !ok {
break
}
message, next := linkMessage(formatter)
switch match := decodeFieldMessage.FindStringSubmatch(message); {
case match != nil:
pointer += "/" + escapePointerToken(match[1])
afterField = true
case message == arrayElementMessage && afterField:
return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, pointer, fieldCodeInvalid)}
default:
afterField = false
}
err = next
}
return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, pointer, fieldCodeInvalid)}
}
// linkMessage returns the message of one link of a go-faster/errors chain
// without the messages of the links it wraps, and the next link.
func linkMessage(link faster.Formatter) (string, error) {
printer := &messagePrinter{}
next := link.FormatError(printer)
return printer.message.String(), next
}
// messagePrinter collects the message of one error link. It never asks for
// details, so no stack frame is printed.
type messagePrinter struct {
message strings.Builder
}
func (printer *messagePrinter) Print(args ...any) {
_, _ = fmt.Fprint(&printer.message, args...)
}
func (printer *messagePrinter) Printf(format string, args ...any) {
_, _ = fmt.Fprintf(&printer.message, format, args...)
}
func (*messagePrinter) Detail() bool { return false }
func appendSchemaFieldErrors(fields []api.ProblemFieldError, err *validate.Error, prefix string) []api.ProblemFieldError {
for _, field := range err.Fields {
if len(fields) >= maxFieldErrors {
@@ -14,6 +14,7 @@ import (
"strings"
"testing"
faster "github.com/go-faster/errors"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/openapi"
@@ -96,16 +97,95 @@ func TestHandleServerErrorMapsGeneratedErrors(t *testing.T) {
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/name", Code: "required", Message: fieldMessageRequired}},
},
{
name: "nested decoding failure has no reliable path",
// A chain without go-faster field wrappers is not recognized, so
// even an error text that looks like a field path maps to the
// whole body.
name: "unrecognized decoding chain falls back to the whole body",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{"page":{}}`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: &ogenerrors.DecodeBodyError{
ContentType: "application/json", Body: []byte(`{"page":{}}`),
Err: fmt.Errorf("decode field \"page\": %w", &validate.Error{Fields: []validate.FieldError{{Name: "has_more", Error: validate.ErrFieldRequired}}}),
}},
err: decodeBodyError(`{"page":{}}`,
fmt.Errorf("decode field \"page\": %w", &validate.Error{Fields: []validate.FieldError{{Name: "has_more", Error: validate.ErrFieldRequired}}})),
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "missing field of a nested object",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: decodeBodyError(`{}`, generatedField(generatedObject("CreateItem", generatedField(generatedObject("Terms",
generatedField(&validate.Error{Fields: []validate.FieldError{
{Name: "tax_basis", Error: validate.ErrFieldRequired},
{Name: "a/b", Error: validate.ErrFieldRequired},
}}, "salary")), "terms")), "")),
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{
{In: api.ProblemFieldLocationBody, Pointer: "/terms/salary/tax_basis", Code: "required", Message: fieldMessageRequired},
{In: api.ProblemFieldLocationBody, Pointer: "/terms/salary/a~1b", Code: "required", Message: fieldMessageRequired},
},
},
{
name: "invalid value of a nested object",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: decodeBodyError(`{}`, generatedObject("CreateItem", generatedField(generatedObject("Terms",
generatedField(faster.Wrap(errors.New(`unexpected byte 34 '"'`), `"{" expected`), "salary")), "terms"))),
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/terms/salary", Code: "invalid", Message: fieldMessageInvalid}},
},
{
// jx reports no index for an array element, so the pointer stops
// at the array.
name: "nested array element",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: decodeBodyError(`{}`, generatedObject("CreateItem", generatedField(faster.Wrap(
&validate.Error{Fields: []validate.FieldError{{Name: "status", Error: validate.ErrFieldRequired}}}, "callback"), "skills"))),
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/skills", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "field of a oneOf variant",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: decodeBodyError(`{}`, generatedObject("CreateComplaint", generatedField(generatedObject("Reference",
generatedField(errors.New("invalid UUID length: 2"), "id")), "object"))),
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/object/id", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "ambiguous oneOf value of a nested field",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: decodeBodyError(`{}`, generatedObject("CreateItem", generatedField(
faster.Wrap(faster.Wrap(errors.New("multiple oneOf matches"), "callback"), "capture"), "training"))),
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/training", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "unknown top-level oneOf variant",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: decodeBodyError(`{}`, errors.New("unable to detect sum type variant")),
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "unknown top-level field",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: decodeBodyError(`{}`, generatedObject("CreateItem", errors.New(`unexpected field "state"`))),
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "foreign wrapper inside a recognized chain",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: decodeBodyError(`{}`, generatedObject("CreateItem", generatedField(
fmt.Errorf("parse: %w", &validate.Error{Fields: []validate.FieldError{{Name: "inner", Error: validate.ErrFieldRequired}}}), "terms"))),
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/terms", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "schema validation keeps nested paths",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
@@ -259,3 +339,27 @@ func readOverLimit(t *testing.T) error {
}
return err
}
// decodeBodyError wraps a decoder error the way the generated request decoder
// does.
func decodeBodyError(body string, err error) error {
return &ogenerrors.DecodeRequestError{
OperationContext: ogenerrors.OperationContext{Name: "CreateItem", ID: "CreateItem"},
Err: &ogenerrors.DecodeBodyError{ContentType: "application/json", Body: []byte(body), Err: err},
}
}
// generatedObject wraps the error of an object field the way a generated
// Decode method and the jx object callback do.
func generatedObject(typeName string, err error) error {
return faster.Wrap(faster.Wrap(err, "callback"), "decode "+typeName)
}
// generatedField wraps the error of one field value the way a generated
// Decode method does. An empty name returns the error unchanged.
func generatedField(err error, name string) error {
if name == "" {
return err
}
return faster.Wrap(err, `decode field "`+name+`"`)
}
@@ -483,12 +483,12 @@ func TestQuestionnaireSchemaValidationPrecedesImplementation(t *testing.T) {
code: "invalid",
},
{
// The decoder does not record the path of an unknown field in a
// nested object, so the pointer is the whole body.
// An unknown field inside an array element points at the array:
// the decoder does not report the element index.
name: "confirmed grade set by the candidate",
body: questionnaireBody(strings.Replace(backendWithGo, `"stack"`, `"confirmed_grade":"senior","stack"`, 1)),
statusCode: http.StatusBadRequest,
pointer: "",
pointer: "/specializations",
code: "invalid",
},
{
@@ -670,12 +670,12 @@ func TestAssessmentSchemaValidationPrecedesImplementation(t *testing.T) {
{
name: "practice answer with a seed",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"practice","language":"python","source_code":"print(1)","seed":42}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/answer", code: "invalid",
},
{
name: "format with the fields of another format",
request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","number":254}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/answer", code: "invalid",
},
{
name: "unknown answer format",
@@ -881,22 +881,22 @@ func TestNeedSchemaValidationPrecedesImplementation(t *testing.T) {
location: api.ProblemFieldLocationBody, pointer: "/salary/value/period", code: "invalid",
},
{
// The decoder does not record the path of a missing field in a
// nested object, so the pointer is the whole body.
// The responder rebuilds the path of a missing nested field from
// the decoder's field wrappers.
name: "salary without a tax basis",
request: create(withSalary(`{"value":{"salary_from":120000,"salary_to":160000,"currency":"RUB","period":"month"},"status":"confirmed"}`)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/salary/value/tax_basis", code: "required",
},
{
// A bare range would confirm it implicitly; the status is explicit.
name: "salary range without a decision",
request: create(withSalary(netSalaryRange)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/salary", code: "invalid",
},
{
name: "grade as a bare value",
request: create(strings.Replace(validNeedCreate, `{"value":"junior","status":"confirmed"}`, `"junior"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/grade", code: "invalid",
},
{
name: "grade with an unknown status",
@@ -916,13 +916,20 @@ func TestNeedSchemaValidationPrecedesImplementation(t *testing.T) {
{
name: "candidate minimum inside the salary range",
request: create(withSalary(`{"value":{"salary_from":120000,"salary_to":160000,"currency":"RUB","period":"month","tax_basis":"net","candidate_minimum":130000},"status":"confirmed"}`)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/salary/value", code: "invalid",
},
{
name: "skill with an unknown status",
request: create(strings.Replace(validNeedCreate, `{"name":"Go","status":"confirmed"}`, `{"name":"Go","status":"unknown"}`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/required_skills/0/status", code: "invalid",
},
{
// The decoder reports no index for an array element, so the
// pointer stops at the array.
name: "skill without a status",
request: create(strings.Replace(validNeedCreate, `{"name":"Go","status":"confirmed"}`, `{"name":"Go"}`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/required_skills", code: "invalid",
},
{
name: "empty list of work formats",
request: create(strings.Replace(validNeedCreate, `["remote"]`, `[]`, 1)),
@@ -951,12 +958,12 @@ func TestNeedSchemaValidationPrecedesImplementation(t *testing.T) {
{
name: "update with a list sent as null",
request: update(`"tasks":null`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/tasks", code: "invalid",
},
{
name: "update with a bare grade",
request: update(`"grade":"middle"`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/grade", code: "invalid",
},
{
name: "update without an expected version",
@@ -971,7 +978,7 @@ func TestNeedSchemaValidationPrecedesImplementation(t *testing.T) {
{
name: "update with a version as text",
request: identityRequest{method: http.MethodPatch, path: organizationNeedPath, body: `{"expected_version":"1","grade":null}`, headers: session},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid",
},
{
name: "update that sets the version itself",
@@ -1288,7 +1295,7 @@ func TestSupportCaseSchemaValidationPrecedesImplementation(t *testing.T) {
{
name: "object reference that is not a UUID",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":{"type":"assessment_attempt","id":"42"}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
location: api.ProblemFieldLocationBody, pointer: "/object/id", code: "invalid",
},
{
name: "grade appeal without a reference",
@@ -1370,6 +1377,513 @@ func TestSupportCaseAccessBeforeImplementation(t *testing.T) {
}
}
// Invitation request fixtures shared by the invitation tests.
const (
organizationInvitationsPath = "/api/v1/organizations/01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01/invitations"
organizationInvitationPath = organizationInvitationsPath + "/01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f"
myInvitationsPath = "/api/v1/me/invitations"
myInvitationPath = myInvitationsPath + "/01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f"
invitationSalary = `{"salary_from":200000,"salary_to":260000,"currency":"RUB","period":"month","tax_basis":"net"}`
invitationCommunication = `{"channel":"email","details":null}`
invitationPackage = `{"bonus":{"status":"provided","description":"Годовой бонус"},` +
`"equipment":{"status":"provided","description":"Ноутбук"},"training":{"status":"not_provided"},` +
`"health_insurance":{"status":"not_provided"}}`
validInvitationTerms = `{"role_title":"Middle Go-разработчик","specialization":"backend","grade":"middle",` +
`"offer_type":"full_time","tasks":["Развивать сервис выплат"],"team":"Команда платежей из шести человек",` +
`"tech_stack":["Go","PostgreSQL"],"work_formats":["remote"],"location":null,` +
`"communication_method":` + invitationCommunication + `,"salary":` + invitationSalary + `,"package":` + invitationPackage + `}`
validInvitationCreate = `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt",` +
`"need":{"need_id":"01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12","requirements_version":3},` +
`"response_period_days":7,"terms":` + validInvitationTerms + `}`
validInvitationAccept = `{"expected_version":5,"terms_version":3,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true,"fields":["email"]}}`
)
// invitationCreateWithTerms returns a CreateOrganizationInvitation body whose
// terms are the valid terms with one replacement applied.
func invitationCreateWithTerms(old, replacement string) string {
return `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","terms":` + strings.Replace(validInvitationTerms, old, replacement, 1) + `}`
}
// The schema alone must accept a complete invitation and reject what the
// contract never allows: terms without a required field, a package condition
// left out instead of not_provided, a salary range without a valid RUB base,
// a response period outside 3, 7, and 14, client-set state, versions, salary
// indicator, or candidate contacts, an acceptance without terms_version or
// with an empty or implicit C4 choice, and a decline without a known reason.
// Security accepts the session here, so the request reaches validation; a
// valid request then answers 501 until invitations are implemented.
// Cross-field rules (A < B, the 10-40% width, a place of work for office or
// hybrid) and the current terms version pass the schema; the server checks
// them.
func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
create := func(body string) identityRequest {
return identityRequest{method: http.MethodPost, path: organizationInvitationsPath, body: body, headers: command}
}
update := func(body string) identityRequest {
return identityRequest{method: http.MethodPatch, path: organizationInvitationPath, body: body, headers: session}
}
post := func(path, body string) identityRequest {
return identityRequest{method: http.MethodPost, path: path, body: body, headers: command}
}
accept := func(body string) identityRequest {
return post(myInvitationPath+"/accept", body)
}
decline := func(body string) identityRequest {
return post(myInvitationPath+"/decline", body)
}
for _, test := range []struct {
name string
request identityRequest
location api.ProblemFieldLocation
pointer string
code string
}{
{
name: "list of an organization",
request: identityRequest{method: http.MethodGet, path: organizationInvitationsPath + "?limit=20", headers: session},
},
{
name: "list for an organization identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: "/api/v1/organizations/acme/invitations", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
},
{
name: "create a complete draft from a need",
request: create(validInvitationCreate),
},
{
name: "create a direct draft with the default response period",
request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","need":null,"terms":` + validInvitationTerms + `}`),
},
{
// The cross-field salary rules and the place of work for an
// office format are domain rules that the server checks after
// the schema.
name: "create with a reversed salary range",
request: create(invitationCreateWithTerms(`"salary_from":200000,"salary_to":260000`, `"salary_from":260000,"salary_to":200000`)),
},
{
name: "create with a salary range wider than 40%",
request: create(invitationCreateWithTerms(`"salary_to":260000`, `"salary_to":400000`)),
},
{
name: "create an office role without a place of work",
request: create(invitationCreateWithTerms(`"work_formats":["remote"]`, `"work_formats":["office"]`)),
},
{
name: "create without an Idempotency-Key",
request: identityRequest{method: http.MethodPost, path: organizationInvitationsPath, body: validInvitationCreate, headers: session},
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
},
{
name: "create without a candidate handle",
request: create(`{"terms":` + validInvitationTerms + `}`),
location: api.ProblemFieldLocationBody, pointer: "/candidate_handle", code: "required",
},
{
name: "create for a candidate named by an email address",
request: create(strings.Replace(validInvitationCreate, `"cand_7Qm2xVb9Lr4Kp0Zt"`, `"candidate@example.com"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/candidate_handle", code: "invalid",
},
{
name: "create without terms",
request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt"}`),
location: api.ProblemFieldLocationBody, pointer: "/terms", code: "required",
},
{
// The responder rebuilds the path of a missing nested field from
// the decoder's field wrappers.
name: "terms without a tax basis",
request: create(invitationCreateWithTerms(`,"tax_basis":"net"`, ``)),
location: api.ProblemFieldLocationBody, pointer: "/terms/salary/tax_basis", code: "required",
},
{
name: "terms without a communication method",
request: create(invitationCreateWithTerms(`"communication_method":`+invitationCommunication+`,`, ``)),
location: api.ProblemFieldLocationBody, pointer: "/terms/communication_method", code: "required",
},
{
name: "terms with an unknown communication channel",
request: create(invitationCreateWithTerms(`"channel":"email"`, `"channel":"carrier_pigeon"`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/communication_method/channel", code: "invalid",
},
{
name: "terms without a salary",
request: create(invitationCreateWithTerms(`,"salary":`+invitationSalary, ``)),
location: api.ProblemFieldLocationBody, pointer: "/terms/salary", code: "required",
},
{
name: "terms without tasks",
request: create(invitationCreateWithTerms(`["Развивать сервис выплат"]`, `[]`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/tasks", code: "invalid",
},
{
name: "terms with a task that is not a text",
request: create(invitationCreateWithTerms(`["Развивать сервис выплат"]`, `["Развивать сервис выплат",5]`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/tasks", code: "invalid",
},
{
name: "terms with an unknown field",
request: create(invitationCreateWithTerms(`"role_title"`, `"benefits":"много","role_title"`)),
location: api.ProblemFieldLocationBody, pointer: "/terms", code: "invalid",
},
{
name: "terms with an empty stack",
request: create(invitationCreateWithTerms(`["Go","PostgreSQL"]`, `[]`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/tech_stack", code: "invalid",
},
{
name: "terms with a place of work left out instead of null",
request: create(invitationCreateWithTerms(`"location":null,`, ``)),
location: api.ProblemFieldLocationBody, pointer: "/terms/location", code: "required",
},
{
name: "package condition left out instead of not provided",
request: create(invitationCreateWithTerms(`"training":{"status":"not_provided"},`, ``)),
location: api.ProblemFieldLocationBody, pointer: "/terms/package/training", code: "required",
},
{
name: "package condition provided without a description",
request: create(invitationCreateWithTerms(`{"status":"provided","description":"Ноутбук"}`, `{"status":"provided"}`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/package/equipment/description", code: "required",
},
{
name: "package condition not provided with a description",
request: create(invitationCreateWithTerms(`"training":{"status":"not_provided"}`, `"training":{"status":"not_provided","description":"Курсы"}`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/package/training", code: "invalid",
},
{
name: "package condition as a bare text",
request: create(invitationCreateWithTerms(`{"status":"provided","description":"Ноутбук"}`, `"Ноутбук"`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/package/equipment", code: "invalid",
},
{
name: "salary bound that is not a multiple of 1000",
request: create(invitationCreateWithTerms(`"salary_to":260000`, `"salary_to":260500`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/salary/salary_to", code: "invalid",
},
{
name: "salary bound of zero",
request: create(invitationCreateWithTerms(`"salary_from":200000`, `"salary_from":0`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/salary/salary_from", code: "invalid",
},
{
name: "salary with an unknown tax basis",
request: create(invitationCreateWithTerms(`"tax_basis":"net"`, `"tax_basis":"net_or_gross"`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/salary/tax_basis", code: "invalid",
},
{
name: "salary in another currency",
request: create(invitationCreateWithTerms(`"currency":"RUB"`, `"currency":"USD"`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/salary/currency", code: "invalid",
},
{
name: "response period outside the policy options",
request: create(strings.Replace(validInvitationCreate, `"response_period_days":7`, `"response_period_days":10`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/response_period_days", code: "invalid",
},
{
name: "candidate minimum inside the salary range",
request: create(invitationCreateWithTerms(`"tax_basis":"net"`, `"tax_basis":"net","candidate_minimum":230000`)),
location: api.ProblemFieldLocationBody, pointer: "/terms/salary", code: "invalid",
},
{
name: "candidate email in the body",
request: create(strings.Replace(validInvitationCreate, `{"candidate_handle"`, `{"candidate_email":"candidate@example.com","candidate_handle"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "state set by the employer",
request: create(strings.Replace(validInvitationCreate, `{"candidate_handle"`, `{"state":"accepted","candidate_handle"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "salary indicator set by the employer",
request: create(strings.Replace(validInvitationCreate, `{"candidate_handle"`, `{"salary_fit":"within_range","candidate_handle"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "read of an organization",
request: identityRequest{method: http.MethodGet, path: organizationInvitationPath, headers: session},
},
{
name: "read with an invitation identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: organizationInvitationsPath + "/1", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/invitation_id", code: "invalid",
},
{
name: "update the terms of a draft",
request: update(`{"expected_version":1,"terms":` + validInvitationTerms + `}`),
},
{
name: "unlink the need of a draft",
request: update(`{"expected_version":2,"need":null}`),
},
{
name: "update without an expected version",
request: update(`{"terms":` + validInvitationTerms + `}`),
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
},
{
name: "update with version zero",
request: update(`{"expected_version":0}`),
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid",
},
{
name: "update that sets the terms version itself",
request: update(`{"expected_version":1,"terms_version":7}`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "update that changes the candidate",
request: update(`{"expected_version":1,"candidate_handle":"cand_Hx3Tn8Wq1Ys6Fd2Vb"}`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "send",
request: post(organizationInvitationPath+"/send", `{"expected_version":2}`),
},
{
name: "send without an expected version",
request: post(organizationInvitationPath+"/send", `{}`),
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
},
{
name: "send without an Idempotency-Key",
request: identityRequest{method: http.MethodPost, path: organizationInvitationPath + "/send", body: `{"expected_version":2}`, headers: session},
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
},
{
name: "raise the upper salary bound",
request: post(organizationInvitationPath+"/salary-raise", `{"expected_version":4,"salary_to":280000}`),
},
{
name: "raise that lowers the lower bound too",
request: post(organizationInvitationPath+"/salary-raise", `{"expected_version":4,"salary_from":150000,"salary_to":280000}`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "raise to a bound that is not a multiple of 1000",
request: post(organizationInvitationPath+"/salary-raise", `{"expected_version":4,"salary_to":280500}`),
location: api.ProblemFieldLocationBody, pointer: "/salary_to", code: "invalid",
},
{
name: "withdraw",
request: post(organizationInvitationPath+"/withdraw", `{"expected_version":3}`),
},
{
name: "read the contacts",
request: identityRequest{method: http.MethodGet, path: organizationInvitationPath + "/contacts", headers: session},
},
{
name: "list of the candidate",
request: identityRequest{method: http.MethodGet, path: myInvitationsPath + "?limit=20", headers: session},
},
{
name: "open the terms",
request: identityRequest{method: http.MethodGet, path: myInvitationPath, headers: session},
},
{
name: "open an invitation identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: myInvitationsPath + "/1", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/invitation_id", code: "invalid",
},
{
// The view command has no body, no Idempotency-Key, and no
// expected_version: a repeat returns the current invitation.
name: "record a view",
request: identityRequest{method: http.MethodPost, path: myInvitationPath + "/view", headers: session},
},
{
name: "record a view of an identifier that is not a UUID",
request: identityRequest{method: http.MethodPost, path: myInvitationsPath + "/1/view", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/invitation_id", code: "invalid",
},
{
// A stale terms version passes the schema; the server answers 412.
name: "accept with the email address only",
request: accept(validInvitationAccept),
},
{
name: "accept without a terms version",
request: accept(`{"expected_version":5,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true,"fields":["email"]}}`),
location: api.ProblemFieldLocationBody, pointer: "/terms_version", code: "required",
},
{
name: "accept with terms version zero",
request: accept(strings.Replace(validInvitationAccept, `"terms_version":3`, `"terms_version":0`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/terms_version", code: "invalid",
},
{
name: "accept without an expected version",
request: accept(strings.Replace(validInvitationAccept, `"expected_version":5,`, ``, 1)),
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
},
{
name: "accept without the consent C4",
request: accept(`{"expected_version":5,"terms_version":3}`),
location: api.ProblemFieldLocationBody, pointer: "/consent_c4", code: "required",
},
{
name: "accept with an empty choice of contact fields",
request: accept(strings.Replace(validInvitationAccept, `["email"]`, `[]`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/consent_c4/fields", code: "invalid",
},
{
// A missing field choice is not a hidden default of every field.
name: "accept without a choice of contact fields",
request: accept(strings.Replace(validInvitationAccept, `,"fields":["email"]`, ``, 1)),
location: api.ProblemFieldLocationBody, pointer: "/consent_c4/fields", code: "required",
},
{
name: "accept with an unknown contact field",
request: accept(strings.Replace(validInvitationAccept, `["email"]`, `["passport"]`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/consent_c4/fields/0", code: "invalid",
},
{
name: "accept with a repeated contact field",
request: accept(strings.Replace(validInvitationAccept, `["email"]`, `["email","email"]`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/consent_c4/fields", code: "invalid",
},
{
name: "accept with consent not given",
request: accept(strings.Replace(validInvitationAccept, `"accepted":true`, `"accepted":false`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/consent_c4/accepted", code: "invalid",
},
{
name: "accept that carries a contact value",
request: accept(strings.Replace(validInvitationAccept, `"fields":["email"]`, `"fields":["email"],"email":"candidate@example.com"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/consent_c4", code: "invalid",
},
{
name: "decline with the reason other and no comment",
request: decline(`{"expected_version":4,"reason":"other"}`),
},
{
name: "decline with a comment",
request: decline(`{"expected_version":4,"reason":"salary","comment":"Вилка ниже ожиданий."}`),
},
{
name: "decline without a reason",
request: decline(`{"expected_version":4,"comment":"Не подходит."}`),
location: api.ProblemFieldLocationBody, pointer: "/reason", code: "required",
},
{
name: "decline with an unknown reason",
request: decline(`{"expected_version":4,"reason":"too_old"}`),
location: api.ProblemFieldLocationBody, pointer: "/reason", code: "invalid",
},
{
name: "decline with a blank comment",
request: decline(`{"expected_version":4,"reason":"other","comment":" "}`),
location: api.ProblemFieldLocationBody, pointer: "/comment", code: "invalid",
},
{
name: "decline with a comment over 500 characters",
request: decline(`{"expected_version":4,"reason":"other","comment":"` + strings.Repeat("а", 501) + `"}`),
location: api.ProblemFieldLocationBody, pointer: "/comment", code: "invalid",
},
{
name: "decline with a comment of exactly 500 characters",
request: decline(`{"expected_version":4,"reason":"other","comment":"` + strings.Repeat("а", 500) + `"}`),
},
{
name: "cancel the participation",
request: post(myInvitationPath+"/cancel", `{"expected_version":6}`),
},
{
name: "cancel without an expected version",
request: post(myInvitationPath+"/cancel", `{}`),
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
},
} {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := serveIdentityRequest(t, router, test.request)
if test.code == "" {
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
return
}
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code}
for _, field := range body.Errors {
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
return
}
}
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
})
}
}
// Every invitation operation requires a session; DenyAllSecurity grants none,
// with or without a cookie and a CSRF token.
func TestInvitationAccessBeforeImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
for _, test := range []identityRequest{
{method: http.MethodGet, path: organizationInvitationsPath},
{method: http.MethodGet, path: organizationInvitationsPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPost, path: organizationInvitationsPath, body: validInvitationCreate, headers: command},
{method: http.MethodGet, path: organizationInvitationPath, headers: session},
{method: http.MethodPatch, path: organizationInvitationPath, body: `{"expected_version":1,"need":null}`, headers: session},
{method: http.MethodPost, path: organizationInvitationPath + "/send", body: `{"expected_version":2}`, headers: command},
{method: http.MethodPost, path: organizationInvitationPath + "/salary-raise", body: `{"expected_version":4,"salary_to":280000}`, headers: command},
{method: http.MethodPost, path: organizationInvitationPath + "/withdraw", body: `{"expected_version":3}`, headers: command},
{method: http.MethodGet, path: organizationInvitationPath + "/contacts", headers: session},
{method: http.MethodGet, path: myInvitationsPath, headers: session},
{method: http.MethodGet, path: myInvitationPath, headers: session},
{method: http.MethodPost, path: myInvitationPath + "/view", headers: session},
{method: http.MethodPost, path: myInvitationPath + "/accept", body: validInvitationAccept, headers: command},
{method: http.MethodPost, path: myInvitationPath + "/decline", body: `{"expected_version":4,"reason":"other"}`, headers: command},
{method: http.MethodPost, path: myInvitationPath + "/cancel", body: `{"expected_version":6}`, headers: command},
} {
t.Run(test.method+" "+test.path, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
})
}
}
// invitationResponsePrivateFields are fields that would disclose a candidate's
// contact or hidden salary minimum, or the reason of an individual decline,
// before a grant allows it. Only ContactDisclosure carries contact values.
var invitationResponsePrivateFields = []string{
"email", "phone", "telegram", "full_name", "name", "contacts", "contact",
"salary_minimum", "candidate_minimum", "minimum", "minimum_salary",
"candidate_id", "profile_id", "account_id", "user_id",
}
// The invitation DTOs that either side reads before an acceptance must not be
// able to carry a contact or the hidden minimum, and the organization's DTOs
// must not carry the candidate's decline reason or comment.
func TestInvitationDTOsCarryNoContactOrMinimum(t *testing.T) {
for _, dto := range []any{
api.OrganizationInvitation{}, api.OrganizationInvitationSummary{}, api.InvitationTerms{},
api.InvitationContactAccess{}, api.CandidateInvitation{}, api.CandidateInvitationSummary{},
api.ContactGrant{}, api.ContactConsentOffer{},
} {
assertNoJSONFields(t, dto, invitationResponsePrivateFields)
}
for _, dto := range []any{api.OrganizationInvitation{}, api.OrganizationInvitationSummary{}} {
assertNoJSONFields(t, dto, []string{"decline", "decline_reason", "reason", "comment"})
}
for _, dto := range []any{
api.OrganizationInvitationCreate{}, api.OrganizationInvitationUpdate{}, api.InvitationCommand{},
api.InvitationSalaryRaise{}, api.InvitationAcceptance{}, api.ContactConsentAcceptance{}, api.InvitationDeclineRequest{},
} {
assertNoJSONFields(t, dto, append([]string{"state", "version", "salary_fit", "contact_access", "grant_id"}, invitationResponsePrivateFields...))
}
}
func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) {
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
+1 -1
View File
@@ -448,7 +448,7 @@ Candidate flow: verify email -> complete profile and consent -> answer questionn
Employer flow: verify email -> create company profile -> describe need -> confirm extracted skills -> choose filters -> review an explainable result set -> send a salary offer -> candidate accepts -> only that company can access contacts.
An invitation includes the employer, description, contact channel, both salary bounds, and RUB currency. Both salary values are required whole rubles in multiples of 1000 and must satisfy 0 < salary_from < salary_to, with a width (salary_to - salary_from) / ((salary_from + salary_to) / 2) from 10% to 40% inclusive (PRD FR13); the same rule applies to the salary range of a need. Show the pay period and tax basis (net or gross). vacancy_id is optional. Main transitions are sent -> viewed -> accepted or declined; direct acceptance from sent is allowed. withdrawn and expired are additional states. Retries are idempotent, and transactions protect concurrent state changes.
An invitation includes the employer, description, contact channel, both salary bounds, and RUB currency. Both salary values are required whole rubles in multiples of 1000 and must satisfy 0 < salary_from < salary_to, with a width (salary_to - salary_from) / ((salary_from + salary_to) / 2) from 10% to 40% inclusive (PRD FR13); the same rule applies to the salary range of a need. Show the pay period and tax basis (net or gross). vacancy_id is optional. Main transitions are draft -> delivered -> viewed -> accepted or declined; the internal sending step is never visible, a send answers with delivered, and direct acceptance from delivered is allowed. The candidate records viewed with an explicit view command; reading an invitation has no side effect. withdrawn (by the organization), expired (a server deadline), and cancelled_by_candidate are terminal states. Retries are idempotent, and transactions protect concurrent state changes.
A contact grant belongs to one candidate-company pair and is created after an accepted invitation or a candidate's own application. The server checks the user, company membership, grant, and current visibility on each read. Before a grant, employers receive no contacts, original PDF, messaging links, or contact fragments from resumes or ML.
+1 -1
View File
@@ -448,7 +448,7 @@ backend/
Целевой сценарий работодателя: подтверждение email -> профиль компании -> описание потребности -> выбор или подтверждение извлеченных навыков -> фильтры и объяснимая подборка -> предложение с диапазоном зарплаты -> принятие кандидатом -> контактный доступ только этой компании.
Приглашение содержит работодателя, описание, способ связи, обе границы зарплаты и валюту RUB. Обе границы - целые рубли, кратные 1000, 0 < salary_from < salary_to, ширина (salary_to - salary_from) / ((salary_from + salary_to) / 2) от 10% до 40% включительно (FR13 в PRD); то же правило действует для вилки потребности. Период и база налога (net или gross) показываются явно. vacancy_id необязателен. Базовые переходы: sent -> viewed -> accepted или declined; принять можно также из sent. withdraw и expire - дополнительные состояния. Повторные операции идемпотентны, конкурирующие переходы защищены транзакцией и текущей версией.
Приглашение содержит работодателя, описание, способ связи, обе границы зарплаты и валюту RUB. Обе границы - целые рубли, кратные 1000, 0 < salary_from < salary_to, ширина (salary_to - salary_from) / ((salary_from + salary_to) / 2) от 10% до 40% включительно (FR13 в PRD); то же правило действует для вилки потребности. Период и база налога (net или gross) показываются явно. vacancy_id необязателен. Базовые переходы: draft -> delivered -> viewed -> accepted или declined; внутренний этап отправки не виден, отправка отвечает delivered, принять можно и прямо из delivered. Состояние viewed кандидат фиксирует явной командой просмотра; чтение приглашения побочных эффектов не имеет. withdrawn (отзыв организацией), expired (серверный срок) и cancelled_by_candidate - терминальные состояния. Повторные операции идемпотентны, конкурирующие переходы защищены транзакцией и текущей версией.
contact_grant относится к паре кандидат-компания и создается после принятого приглашения или собственного отклика кандидата. Сервер проверяет пользователя, компанию, grant и актуальную видимость при каждом чтении. До grant работодатель не получает контакты, оригинальный PDF, мессенджеры или контактные фрагменты из резюме и ML.
@@ -3,5 +3,6 @@ export { getCandidateMock } from './candidate/candidate.msw'
export { getCatalogMock } from './catalog/catalog.msw'
export { getHealthMock } from './health/health.msw'
export { getIdentityMock } from './identity/identity.msw'
export { getInvitationMock } from './invitation/invitation.msw'
export { getNeedMock } from './need/need.msw'
export { getSupportMock } from './support/support.msw'
@@ -3,5 +3,6 @@ export * from './candidate/candidate';
export * from './catalog/catalog';
export * from './health/health';
export * from './identity/identity';
export * from './invitation/invitation';
export * from './need/need';
export * from './support/support';
@@ -0,0 +1,337 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import {
faker
} from '@faker-js/faker';
import {
fakeFromPattern
} from '../../mock-pattern';
import {
HttpResponse,
http
} from 'msw';
import type {
RequestHandlerOptions
} from 'msw';
import type {
CandidateInvitation,
CandidateInvitationList,
ContactConsentOffer,
ContactDisclosure,
ContactGrant,
InvitationDeclineRecord,
InvitationNeedReference,
InvitationPackageItemNotProvided,
InvitationPackageItemProvided,
OrganizationInvitation,
OrganizationInvitationList
} from '../../schemas';
export const getListOrganizationInvitationsResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
export const getListOrganizationInvitationsResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitationList, object>> = {}): OrganizationInvitationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getListOrganizationInvitationsResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
export const getCreateOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
export const getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getCreateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getGetOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
export const getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getGetOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getUpdateOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
export const getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getUpdateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getSendOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
export const getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getSendOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getRaiseOrganizationInvitationSalaryResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
export const getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getRaiseOrganizationInvitationSalaryResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getWithdrawOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
export const getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getWithdrawOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getGetOrganizationInvitationContactsResponseMock = (overrideResponse: Partial<Extract<ContactDisclosure, object>> = {}): ContactDisclosure => ({invitation_id: faker.string.uuid(), grant_id: faker.string.uuid(), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', full_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), email: faker.helpers.arrayElement([faker.internet.email(),null,]), phone: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), telegram: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), ...overrideResponse})
export const getListMyInvitationsResponseMock = (overrideResponse: Partial<Extract<CandidateInvitationList, object>> = {}): CandidateInvitationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), organization: {id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), response_deadline_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.date.past().toISOString().slice(0, 19) + 'Z', viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
export const getGetMyInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getGetMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getGetMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial<ContactConsentOffer> = {}): ContactConsentOffer => ({...{text: {text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), text: faker.string.alpha({length: {min: 1, max: 100000}})}, available_fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, ...overrideResponse});
export const getGetMyInvitationResponseInvitationDeclineRecordMock = (overrideResponse: Partial<InvitationDeclineRecord> = {}): InvitationDeclineRecord => ({...{reason: faker.helpers.arrayElement(['salary','tasks','stack','work_format','package','company','not_looking','other_offer','other'] as const), comment: faker.helpers.arrayElement([fakeFromPattern("\\S", {minLength: 1, maxLength: 500}),null,]), declined_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse});
export const getGetMyInvitationResponseContactGrantMock = (overrideResponse: Partial<ContactGrant> = {}): ContactGrant => ({...{id: faker.string.uuid(), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), status: faker.helpers.arrayElement(['active','revoked'] as const), readable: faker.datatype.boolean(), blocked_by: faker.helpers.arrayElement([faker.helpers.arrayElement(['visibility'] as const),null,]), terms_version: faker.number.int({min: 1}), consent_text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', revoked_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), revocation_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['consent_revoked','participation_cancelled','visibility_closed'] as const),null,])}, ...overrideResponse});
export const getGetMyInvitationResponseMock = (overrideResponse: Partial<Extract<CandidateInvitation, object>> = {}): CandidateInvitation => ({id: faker.string.uuid(), organization: {id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getGetMyInvitationResponseInvitationPackageItemProvidedMock()},{...getGetMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getGetMyInvitationResponseInvitationPackageItemProvidedMock()},{...getGetMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getGetMyInvitationResponseInvitationPackageItemProvidedMock()},{...getGetMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getGetMyInvitationResponseInvitationPackageItemProvidedMock()},{...getGetMyInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_deadline_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.date.past().toISOString().slice(0, 19) + 'Z', viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', contact_consent: faker.helpers.arrayElement([{...getGetMyInvitationResponseContactConsentOfferMock()},null,]), decline: faker.helpers.arrayElement([{...getGetMyInvitationResponseInvitationDeclineRecordMock()},null,]), contact_grant: faker.helpers.arrayElement([{...getGetMyInvitationResponseContactGrantMock()},null,]), ...overrideResponse})
export const getViewMyInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getViewMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getViewMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial<ContactConsentOffer> = {}): ContactConsentOffer => ({...{text: {text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), text: faker.string.alpha({length: {min: 1, max: 100000}})}, available_fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, ...overrideResponse});
export const getViewMyInvitationResponseInvitationDeclineRecordMock = (overrideResponse: Partial<InvitationDeclineRecord> = {}): InvitationDeclineRecord => ({...{reason: faker.helpers.arrayElement(['salary','tasks','stack','work_format','package','company','not_looking','other_offer','other'] as const), comment: faker.helpers.arrayElement([fakeFromPattern("\\S", {minLength: 1, maxLength: 500}),null,]), declined_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse});
export const getViewMyInvitationResponseContactGrantMock = (overrideResponse: Partial<ContactGrant> = {}): ContactGrant => ({...{id: faker.string.uuid(), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), status: faker.helpers.arrayElement(['active','revoked'] as const), readable: faker.datatype.boolean(), blocked_by: faker.helpers.arrayElement([faker.helpers.arrayElement(['visibility'] as const),null,]), terms_version: faker.number.int({min: 1}), consent_text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', revoked_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), revocation_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['consent_revoked','participation_cancelled','visibility_closed'] as const),null,])}, ...overrideResponse});
export const getViewMyInvitationResponseMock = (overrideResponse: Partial<Extract<CandidateInvitation, object>> = {}): CandidateInvitation => ({id: faker.string.uuid(), organization: {id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getViewMyInvitationResponseInvitationPackageItemProvidedMock()},{...getViewMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getViewMyInvitationResponseInvitationPackageItemProvidedMock()},{...getViewMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getViewMyInvitationResponseInvitationPackageItemProvidedMock()},{...getViewMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getViewMyInvitationResponseInvitationPackageItemProvidedMock()},{...getViewMyInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_deadline_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.date.past().toISOString().slice(0, 19) + 'Z', viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', contact_consent: faker.helpers.arrayElement([{...getViewMyInvitationResponseContactConsentOfferMock()},null,]), decline: faker.helpers.arrayElement([{...getViewMyInvitationResponseInvitationDeclineRecordMock()},null,]), contact_grant: faker.helpers.arrayElement([{...getViewMyInvitationResponseContactGrantMock()},null,]), ...overrideResponse})
export const getAcceptMyInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getAcceptMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getAcceptMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial<ContactConsentOffer> = {}): ContactConsentOffer => ({...{text: {text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), text: faker.string.alpha({length: {min: 1, max: 100000}})}, available_fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, ...overrideResponse});
export const getAcceptMyInvitationResponseInvitationDeclineRecordMock = (overrideResponse: Partial<InvitationDeclineRecord> = {}): InvitationDeclineRecord => ({...{reason: faker.helpers.arrayElement(['salary','tasks','stack','work_format','package','company','not_looking','other_offer','other'] as const), comment: faker.helpers.arrayElement([fakeFromPattern("\\S", {minLength: 1, maxLength: 500}),null,]), declined_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse});
export const getAcceptMyInvitationResponseContactGrantMock = (overrideResponse: Partial<ContactGrant> = {}): ContactGrant => ({...{id: faker.string.uuid(), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), status: faker.helpers.arrayElement(['active','revoked'] as const), readable: faker.datatype.boolean(), blocked_by: faker.helpers.arrayElement([faker.helpers.arrayElement(['visibility'] as const),null,]), terms_version: faker.number.int({min: 1}), consent_text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', revoked_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), revocation_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['consent_revoked','participation_cancelled','visibility_closed'] as const),null,])}, ...overrideResponse});
export const getAcceptMyInvitationResponseMock = (overrideResponse: Partial<Extract<CandidateInvitation, object>> = {}): CandidateInvitation => ({id: faker.string.uuid(), organization: {id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getAcceptMyInvitationResponseInvitationPackageItemProvidedMock()},{...getAcceptMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getAcceptMyInvitationResponseInvitationPackageItemProvidedMock()},{...getAcceptMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getAcceptMyInvitationResponseInvitationPackageItemProvidedMock()},{...getAcceptMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getAcceptMyInvitationResponseInvitationPackageItemProvidedMock()},{...getAcceptMyInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_deadline_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.date.past().toISOString().slice(0, 19) + 'Z', viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', contact_consent: faker.helpers.arrayElement([{...getAcceptMyInvitationResponseContactConsentOfferMock()},null,]), decline: faker.helpers.arrayElement([{...getAcceptMyInvitationResponseInvitationDeclineRecordMock()},null,]), contact_grant: faker.helpers.arrayElement([{...getAcceptMyInvitationResponseContactGrantMock()},null,]), ...overrideResponse})
export const getDeclineMyInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getDeclineMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getDeclineMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial<ContactConsentOffer> = {}): ContactConsentOffer => ({...{text: {text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), text: faker.string.alpha({length: {min: 1, max: 100000}})}, available_fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, ...overrideResponse});
export const getDeclineMyInvitationResponseInvitationDeclineRecordMock = (overrideResponse: Partial<InvitationDeclineRecord> = {}): InvitationDeclineRecord => ({...{reason: faker.helpers.arrayElement(['salary','tasks','stack','work_format','package','company','not_looking','other_offer','other'] as const), comment: faker.helpers.arrayElement([fakeFromPattern("\\S", {minLength: 1, maxLength: 500}),null,]), declined_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse});
export const getDeclineMyInvitationResponseContactGrantMock = (overrideResponse: Partial<ContactGrant> = {}): ContactGrant => ({...{id: faker.string.uuid(), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), status: faker.helpers.arrayElement(['active','revoked'] as const), readable: faker.datatype.boolean(), blocked_by: faker.helpers.arrayElement([faker.helpers.arrayElement(['visibility'] as const),null,]), terms_version: faker.number.int({min: 1}), consent_text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', revoked_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), revocation_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['consent_revoked','participation_cancelled','visibility_closed'] as const),null,])}, ...overrideResponse});
export const getDeclineMyInvitationResponseMock = (overrideResponse: Partial<Extract<CandidateInvitation, object>> = {}): CandidateInvitation => ({id: faker.string.uuid(), organization: {id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getDeclineMyInvitationResponseInvitationPackageItemProvidedMock()},{...getDeclineMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getDeclineMyInvitationResponseInvitationPackageItemProvidedMock()},{...getDeclineMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getDeclineMyInvitationResponseInvitationPackageItemProvidedMock()},{...getDeclineMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getDeclineMyInvitationResponseInvitationPackageItemProvidedMock()},{...getDeclineMyInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_deadline_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.date.past().toISOString().slice(0, 19) + 'Z', viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', contact_consent: faker.helpers.arrayElement([{...getDeclineMyInvitationResponseContactConsentOfferMock()},null,]), decline: faker.helpers.arrayElement([{...getDeclineMyInvitationResponseInvitationDeclineRecordMock()},null,]), contact_grant: faker.helpers.arrayElement([{...getDeclineMyInvitationResponseContactGrantMock()},null,]), ...overrideResponse})
export const getCancelMyInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial<InvitationPackageItemProvided> = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse});
export const getCancelMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getCancelMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial<ContactConsentOffer> = {}): ContactConsentOffer => ({...{text: {text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), text: faker.string.alpha({length: {min: 1, max: 100000}})}, available_fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, ...overrideResponse});
export const getCancelMyInvitationResponseInvitationDeclineRecordMock = (overrideResponse: Partial<InvitationDeclineRecord> = {}): InvitationDeclineRecord => ({...{reason: faker.helpers.arrayElement(['salary','tasks','stack','work_format','package','company','not_looking','other_offer','other'] as const), comment: faker.helpers.arrayElement([fakeFromPattern("\\S", {minLength: 1, maxLength: 500}),null,]), declined_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse});
export const getCancelMyInvitationResponseContactGrantMock = (overrideResponse: Partial<ContactGrant> = {}): ContactGrant => ({...{id: faker.string.uuid(), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), status: faker.helpers.arrayElement(['active','revoked'] as const), readable: faker.datatype.boolean(), blocked_by: faker.helpers.arrayElement([faker.helpers.arrayElement(['visibility'] as const),null,]), terms_version: faker.number.int({min: 1}), consent_text_version: fakeFromPattern("^[A-Za-z0-9._-]+$", {minLength: 1, maxLength: 64}), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', revoked_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), revocation_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['consent_revoked','participation_cancelled','visibility_closed'] as const),null,])}, ...overrideResponse});
export const getCancelMyInvitationResponseMock = (overrideResponse: Partial<Extract<CandidateInvitation, object>> = {}): CandidateInvitation => ({id: faker.string.uuid(), organization: {id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getCancelMyInvitationResponseInvitationPackageItemProvidedMock()},{...getCancelMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getCancelMyInvitationResponseInvitationPackageItemProvidedMock()},{...getCancelMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getCancelMyInvitationResponseInvitationPackageItemProvidedMock()},{...getCancelMyInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getCancelMyInvitationResponseInvitationPackageItemProvidedMock()},{...getCancelMyInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_deadline_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.date.past().toISOString().slice(0, 19) + 'Z', viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', contact_consent: faker.helpers.arrayElement([{...getCancelMyInvitationResponseContactConsentOfferMock()},null,]), decline: faker.helpers.arrayElement([{...getCancelMyInvitationResponseInvitationDeclineRecordMock()},null,]), contact_grant: faker.helpers.arrayElement([{...getCancelMyInvitationResponseContactGrantMock()},null,]), ...overrideResponse})
export const getListOrganizationInvitationsMockHandler = (overrideResponse?: OrganizationInvitationList | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<OrganizationInvitationList> | OrganizationInvitationList), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/organizations/:orgId/invitations', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getListOrganizationInvitationsResponseMock(),
{ status: 200
})
}, options)
}
export const getCreateOrganizationInvitationMockHandler = (overrideResponse?: OrganizationInvitation | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<OrganizationInvitation> | OrganizationInvitation), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/organizations/:orgId/invitations', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getCreateOrganizationInvitationResponseMock(),
{ status: 201
})
}, options)
}
export const getGetOrganizationInvitationMockHandler = (overrideResponse?: OrganizationInvitation | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<OrganizationInvitation> | OrganizationInvitation), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/organizations/:orgId/invitations/:invitationId', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetOrganizationInvitationResponseMock(),
{ status: 200
})
}, options)
}
export const getUpdateOrganizationInvitationMockHandler = (overrideResponse?: OrganizationInvitation | ((info: Parameters<Parameters<typeof http.patch>[1]>[0]) => Promise<OrganizationInvitation> | OrganizationInvitation), options?: RequestHandlerOptions) => {
return http.patch('*/api/v1/organizations/:orgId/invitations/:invitationId', async (info: Parameters<Parameters<typeof http.patch>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getUpdateOrganizationInvitationResponseMock(),
{ status: 200
})
}, options)
}
export const getSendOrganizationInvitationMockHandler = (overrideResponse?: OrganizationInvitation | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<OrganizationInvitation> | OrganizationInvitation), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/organizations/:orgId/invitations/:invitationId/send', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getSendOrganizationInvitationResponseMock(),
{ status: 200
})
}, options)
}
export const getRaiseOrganizationInvitationSalaryMockHandler = (overrideResponse?: OrganizationInvitation | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<OrganizationInvitation> | OrganizationInvitation), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/organizations/:orgId/invitations/:invitationId/salary-raise', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getRaiseOrganizationInvitationSalaryResponseMock(),
{ status: 200
})
}, options)
}
export const getWithdrawOrganizationInvitationMockHandler = (overrideResponse?: OrganizationInvitation | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<OrganizationInvitation> | OrganizationInvitation), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/organizations/:orgId/invitations/:invitationId/withdraw', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getWithdrawOrganizationInvitationResponseMock(),
{ status: 200
})
}, options)
}
export const getGetOrganizationInvitationContactsMockHandler = (overrideResponse?: ContactDisclosure | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<ContactDisclosure> | ContactDisclosure), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/organizations/:orgId/invitations/:invitationId/contacts', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetOrganizationInvitationContactsResponseMock(),
{ status: 200
})
}, options)
}
export const getListMyInvitationsMockHandler = (overrideResponse?: CandidateInvitationList | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<CandidateInvitationList> | CandidateInvitationList), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/invitations', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getListMyInvitationsResponseMock(),
{ status: 200
})
}, options)
}
export const getGetMyInvitationMockHandler = (overrideResponse?: CandidateInvitation | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<CandidateInvitation> | CandidateInvitation), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/invitations/:invitationId', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetMyInvitationResponseMock(),
{ status: 200
})
}, options)
}
export const getViewMyInvitationMockHandler = (overrideResponse?: CandidateInvitation | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<CandidateInvitation> | CandidateInvitation), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/invitations/:invitationId/view', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getViewMyInvitationResponseMock(),
{ status: 200
})
}, options)
}
export const getAcceptMyInvitationMockHandler = (overrideResponse?: CandidateInvitation | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<CandidateInvitation> | CandidateInvitation), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/invitations/:invitationId/accept', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getAcceptMyInvitationResponseMock(),
{ status: 200
})
}, options)
}
export const getDeclineMyInvitationMockHandler = (overrideResponse?: CandidateInvitation | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<CandidateInvitation> | CandidateInvitation), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/invitations/:invitationId/decline', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getDeclineMyInvitationResponseMock(),
{ status: 200
})
}, options)
}
export const getCancelMyInvitationMockHandler = (overrideResponse?: CandidateInvitation | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<CandidateInvitation> | CandidateInvitation), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/invitations/:invitationId/cancel', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getCancelMyInvitationResponseMock(),
{ status: 200
})
}, options)
}
export const getInvitationMock = () => [
getListOrganizationInvitationsMockHandler(),
getCreateOrganizationInvitationMockHandler(),
getGetOrganizationInvitationMockHandler(),
getUpdateOrganizationInvitationMockHandler(),
getSendOrganizationInvitationMockHandler(),
getRaiseOrganizationInvitationSalaryMockHandler(),
getWithdrawOrganizationInvitationMockHandler(),
getGetOrganizationInvitationContactsMockHandler(),
getListMyInvitationsMockHandler(),
getGetMyInvitationMockHandler(),
getViewMyInvitationMockHandler(),
getAcceptMyInvitationMockHandler(),
getDeclineMyInvitationMockHandler(),
getCancelMyInvitationMockHandler()
]
File diff suppressed because it is too large. Load diff
@@ -188,9 +188,9 @@ export const getCreateMySupportCaseUrl = () => {
* | `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 not in the contract 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 (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.
*
* 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 whole-body pointer, because the decoder does not record the path inside the selected variant. The case stores only the type and the identifier of the object.
* 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.
*
* Limits: an attempt and a resolved manual assessment each accept at most one grade appeal, and an attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a support case that references the appeal as `support_case`. A specialization accepts one open manual assessment, and an object accepts one open complaint; open means not `resolved` or `closed`. A second one answers 409 state_conflict. A grade appeal of an attempt that is still active also answers 409. Every create that passed authentication, validation, and the account scenario counts against a per-account limit from the product policy, including replays, 404, and 409, so the limit also bounds probing of references; over the limit the server answers 429 with Retry-After and creates nothing.
*
@@ -0,0 +1,464 @@
import { describe, expect, expectTypeOf, it } from "vitest";
import {
acceptMyInvitation,
createOrganizationInvitation,
getMyInvitation,
getOrganizationInvitation,
getOrganizationInvitationContacts,
viewMyInvitation,
} from "./endpoints/invitation/invitation";
import {
AcceptMyInvitationBody,
CandidateInvitation,
type CandidateInvitationSummary,
ContactGrant,
ContactDisclosure,
CreateOrganizationInvitationBody,
DeclineMyInvitationBody,
InvitationAcceptance,
type InvitationDeclineRequest,
InvitationPackageItem,
InvitationTerms,
OrganizationInvitation,
OrganizationInvitationCreate,
type OrganizationInvitationSummary,
type OrganizationInvitationUpdate,
SalaryRange,
} from "./schemas";
// These tests pin the generated invitation contract that the FSD adapters
// consume. They fail when regeneration drops a required term, lets a package
// condition default to "not provided" by omission, accepts an acceptance
// without the terms version or with an implicit C4 choice, or adds a field
// that would carry a candidate's contact, the hidden salary minimum, or the
// reason of a decline into a DTO that the organization reads before a grant.
const salary = {
salary_from: 200000,
salary_to: 260000,
currency: "RUB",
period: "month",
tax_basis: "net",
} as const;
const terms = {
role_title: "Middle Go-разработчик в команду платежей",
specialization: "backend",
grade: "middle",
offer_type: "full_time",
tasks: ["Развивать сервис выплат на Go"],
team: "Команда платежей: пять бэкенд-разработчиков и QA-инженер.",
tech_stack: ["Go", "PostgreSQL", "Kafka"],
work_formats: ["remote", "hybrid"],
location: "Москва",
communication_method: { channel: "email", details: null },
salary,
package: {
bonus: { status: "provided", description: "Годовой бонус до 15% оклада" },
equipment: { status: "provided", description: "Ноутбук и монитор" },
training: { status: "not_provided" },
health_insurance: { status: "not_provided" },
},
} as const;
const draft = {
candidate_handle: "cand_7Qm2xVb9Lr4Kp0Zt",
need: { need_id: "01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12", requirements_version: 3 },
response_period_days: 7,
terms,
} as const;
function without<T extends object, K extends keyof T>(value: T, key: K): Omit<T, K> {
const copy: Partial<T> = { ...value };
delete copy[key];
return copy as Omit<T, K>;
}
const createSchemas = [
["OrganizationInvitationCreate", OrganizationInvitationCreate],
["CreateOrganizationInvitationBody", CreateOrganizationInvitationBody],
] as const;
describe.each(createSchemas)("generated %s", (_name, schema) => {
it("accepts a complete draft from a need", () => {
expect(schema.parse(draft)).toEqual(draft);
});
it("accepts a direct draft without a need or a response period", () => {
const direct = { candidate_handle: draft.candidate_handle, terms };
expect(schema.parse(direct)).toEqual(direct);
});
it.each([
["the communication method", "communication_method"],
["the salary range", "salary"],
["the package", "package"],
["the tasks", "tasks"],
["the team", "team"],
["the technology stack", "tech_stack"],
["the offer type", "offer_type"],
["the place of work", "location"],
] as const)("rejects terms without %s", (_case, field) => {
const result = schema.safeParse({ ...draft, terms: without(terms, field) });
expect(result.success).toBe(false);
expect(result.error?.issues).toEqual([expect.objectContaining({ path: ["terms", field] })]);
});
it("rejects a salary range without its tax basis", () => {
const result = schema.safeParse({
...draft,
terms: { ...terms, salary: without(salary, "tax_basis") },
});
expect(result.success).toBe(false);
expect(result.error?.issues).toEqual([
expect.objectContaining({ path: ["terms", "salary", "tax_basis"] }),
]);
});
it("rejects a package condition left out instead of not provided", () => {
const result = schema.safeParse({
...draft,
terms: { ...terms, package: without(terms.package, "training") },
});
expect(result.success).toBe(false);
expect(result.error?.issues).toEqual([
expect.objectContaining({ path: ["terms", "package", "training"] }),
]);
});
it.each([
["a zero lower bound", { salary_from: 0 }, "salary_from"],
["a bound that is not a multiple of 1000", { salary_to: 260500 }, "salary_to"],
["another currency", { currency: "USD" }, "currency"],
["an unknown tax basis", { tax_basis: "net_or_gross" }, "tax_basis"],
])("rejects a salary with %s", (_case, change, field) => {
const range = { ...salary, ...change };
expect(schema.safeParse({ ...draft, terms: { ...terms, salary: range } }).success).toBe(false);
expect(SalaryRange.safeParse(range).error?.issues).toEqual([
expect.objectContaining({ path: [field] }),
]);
});
it("leaves the cross-field salary and place rules to the server", () => {
// A < B, the 10-40% width, and a place for office or hybrid compare
// fields; the server answers 400 with /terms/salary/salary_to or
// /terms/location.
for (const [from, to] of [
[260000, 200000],
[100000, 200000],
]) {
const range = { ...salary, salary_from: from, salary_to: to };
expect(schema.safeParse({ ...draft, terms: { ...terms, salary: range } }).success).toBe(true);
}
expect(
schema.safeParse({ ...draft, terms: { ...terms, work_formats: ["office"], location: null } })
.success,
).toBe(true);
});
it("rejects a response period outside 3, 7, and 14 days", () => {
for (const days of [3, 7, 14]) {
expect(schema.safeParse({ ...draft, response_period_days: days }).success).toBe(true);
}
expect(schema.safeParse({ ...draft, response_period_days: 10 }).success).toBe(false);
});
it("never carries a candidate's contact, minimum, or state in the parsed body", () => {
const parsed = schema.parse({
...draft,
candidate_email: "candidate@example.com",
salary_minimum: 230000,
state: "accepted",
salary_fit: "within_range",
terms: { ...terms, salary: { ...salary, candidate_minimum: 230000 } },
});
// Generated Zod strips unknown keys; the server rejects them with 400.
expect(parsed).not.toHaveProperty("candidate_email");
expect(parsed).not.toHaveProperty("salary_minimum");
expect(parsed).not.toHaveProperty("state");
expect(parsed).not.toHaveProperty("salary_fit");
expect(parsed.terms.salary).not.toHaveProperty("candidate_minimum");
});
});
describe("generated InvitationPackageItem", () => {
it("accepts a provided condition and an explicit not provided", () => {
expect(InvitationPackageItem.parse({ status: "provided", description: "ДМС" })).toEqual({
status: "provided",
description: "ДМС",
});
expect(InvitationPackageItem.parse({ status: "not_provided" })).toEqual({
status: "not_provided",
});
});
it("strips a description from not provided, which only the server rejects", () => {
// Generated Zod is not strict: the not_provided variant matches and the
// extra key is dropped. The server answers 400 /terms/package/<field>.
expect(InvitationPackageItem.parse({ status: "not_provided", description: "Курсы" })).toEqual({
status: "not_provided",
});
});
it.each([
["a provided condition without a description", { status: "provided" }],
["a description without a status", { description: "ДМС" }],
["an unknown status", { status: "unknown" }],
["a bare text", "ДМС"],
["null", null],
])("rejects %s", (_case, item) => {
expect(InvitationPackageItem.safeParse(item).success).toBe(false);
});
});
const acceptance = {
expected_version: 5,
terms_version: 3,
consent_c4: { text_version: "c4-2026-10-01", accepted: true, fields: ["email"] },
} as const;
const acceptSchemas = [
["InvitationAcceptance", InvitationAcceptance],
["AcceptMyInvitationBody", AcceptMyInvitationBody],
] as const;
describe.each(acceptSchemas)("generated %s", (_name, schema) => {
it("accepts the current terms version with the email address only", () => {
expect(schema.parse(acceptance)).toEqual(acceptance);
});
it.each([
["terms_version", without(acceptance, "terms_version"), ["terms_version"]],
["expected_version", without(acceptance, "expected_version"), ["expected_version"]],
["consent_c4", without(acceptance, "consent_c4"), ["consent_c4"]],
[
"the field choice",
{ ...acceptance, consent_c4: without(acceptance.consent_c4, "fields") },
["consent_c4", "fields"],
],
] as const)("requires %s", (_case, body, path) => {
const result = schema.safeParse(body);
expect(result.success).toBe(false);
expect(result.error?.issues).toEqual([expect.objectContaining({ path })]);
});
it.each([
["an empty field choice", { fields: [] }],
["an unknown field kind", { fields: ["passport"] }],
["consent not given", { accepted: false }],
])("rejects a consent with %s", (_case, change) => {
const result = schema.safeParse({
...acceptance,
consent_c4: { ...acceptance.consent_c4, ...change },
});
expect(result.success).toBe(false);
});
it.each([0, 1.5, "3"])("rejects the terms version %s", (version) => {
expect(schema.safeParse({ ...acceptance, terms_version: version }).success).toBe(false);
});
});
describe("generated DeclineMyInvitationBody", () => {
it("accepts the neutral reason other without a comment", () => {
const body = { expected_version: 4, reason: "other" };
expect(DeclineMyInvitationBody.parse(body)).toEqual(body);
});
it.each([
["a missing reason", { expected_version: 4 }],
["an unknown reason", { expected_version: 4, reason: "too_old" }],
["a blank comment", { expected_version: 4, reason: "other", comment: " " }],
[
"a comment over 500 characters",
{ expected_version: 4, reason: "other", comment: "а".repeat(501) },
],
])("rejects %s", (_case, body) => {
expect(DeclineMyInvitationBody.safeParse(body).success).toBe(false);
});
});
const parsedTerms = InvitationTerms.parse(terms);
it("parses an accepted invitation of the organization without contact values", () => {
const parsed = OrganizationInvitation.parse({
id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f",
organization_id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
candidate_handle: "cand_7Qm2xVb9Lr4Kp0Zt",
need: null,
state: "accepted",
expiry_reason: null,
version: 6,
terms_version: 3,
terms: parsedTerms,
response_period_days: 7,
response_deadline_at: "2026-10-13T09:30:00Z",
salary_raise_used: true,
salary_fit: "within_range",
contact_access: { status: "available", fields: ["email"] },
created_at: "2026-10-06T09:00:00Z",
updated_at: "2026-10-06T15:00:00Z",
delivered_at: "2026-10-06T09:30:00Z",
viewed_at: "2026-10-06T12:00:00Z",
responded_at: "2026-10-06T15:00:00Z",
});
expect(parsed.contact_access.fields).toEqual(["email"]);
expect(parsed).not.toHaveProperty("email");
expect(
OrganizationInvitation.safeParse({ ...parsed, salary_fit: "exactly_230000" }).success,
).toBe(false);
});
it("parses an expired invitation of the candidate with its reason", () => {
const parsed = CandidateInvitation.parse({
id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f",
organization: { id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01", name: "ООО Пример Платежи" },
state: "expired",
expiry_reason: "invitation_timeout",
version: 3,
terms_version: 1,
terms: parsedTerms,
response_deadline_at: "2026-10-13T09:30:00Z",
delivered_at: "2026-10-06T09:30:00Z",
viewed_at: null,
responded_at: null,
updated_at: "2026-10-13T09:30:00Z",
contact_consent: null,
decline: null,
contact_grant: null,
});
expect(parsed.expiry_reason).toBe("invitation_timeout");
expect(CandidateInvitation.safeParse({ ...parsed, expiry_reason: "deadline" }).success).toBe(
false,
);
});
it("keeps contact values in a separate disclosure with null for fields not granted", () => {
const parsed = ContactDisclosure.parse({
invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f",
grant_id: "01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70",
fields: ["email"],
granted_at: "2026-10-06T15:00:00Z",
full_name: null,
email: "candidate@example.com",
phone: null,
telegram: null,
});
expect(parsed.phone).toBeNull();
expect(ContactDisclosure.safeParse({ ...parsed, phone: "8 900 000-00-00" }).success).toBe(false);
});
it("parses a grant that is active but blocked by the visibility of the profile", () => {
const parsed = ContactGrant.parse({
id: "01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70",
fields: ["email"],
status: "active",
readable: false,
blocked_by: "visibility",
terms_version: 3,
consent_text_version: "c4-2026-10-01",
granted_at: "2026-10-06T15:00:00Z",
revoked_at: null,
revocation_reason: null,
});
expect(parsed.readable).toBe(false);
expect(ContactGrant.safeParse({ ...parsed, blocked_by: "hidden_from_company" }).success).toBe(
false,
);
});
type ContactOrMinimumKey =
| "email"
| "phone"
| "telegram"
| "full_name"
| "contacts"
| "salary_minimum"
| "candidate_minimum"
| "minimum"
| "candidate_id"
| "profile_id";
type ClientSetKey =
| "state"
| "version"
| "terms_version"
| "salary_fit"
| "contact_access"
| "contact_grant"
| "organization_id";
it("exposes invitation DTOs without contacts, the hidden minimum, or a decline reason", () => {
expectTypeOf<Extract<keyof OrganizationInvitation, ContactOrMinimumKey>>().toEqualTypeOf<never>();
expectTypeOf<
Extract<keyof OrganizationInvitationSummary, ContactOrMinimumKey>
>().toEqualTypeOf<never>();
expectTypeOf<Extract<keyof CandidateInvitation, ContactOrMinimumKey>>().toEqualTypeOf<never>();
expectTypeOf<
Extract<keyof CandidateInvitationSummary, ContactOrMinimumKey>
>().toEqualTypeOf<never>();
expectTypeOf<Extract<keyof InvitationTerms, ContactOrMinimumKey>>().toEqualTypeOf<never>();
expectTypeOf<
Extract<keyof InvitationTerms["salary"], ContactOrMinimumKey>
>().toEqualTypeOf<never>();
// The organization never reads the reason or the comment of a decline.
expectTypeOf<
Extract<keyof OrganizationInvitation, "decline" | "reason" | "comment">
>().toEqualTypeOf<never>();
// Contact values travel only in the separate disclosure.
expectTypeOf<Extract<keyof ContactDisclosure, "email" | "phone">>().toEqualTypeOf<
"email" | "phone"
>();
expectTypeOf(getOrganizationInvitation).returns.resolves.toEqualTypeOf<OrganizationInvitation>();
expectTypeOf(getMyInvitation).returns.resolves.toEqualTypeOf<CandidateInvitation>();
// The view is an explicit command without a body, a key, or a version.
expectTypeOf(viewMyInvitation).parameters.toEqualTypeOf<
[invitationId: string, options?: Parameters<typeof getMyInvitation>[1]]
>();
expectTypeOf(viewMyInvitation).returns.resolves.toEqualTypeOf<CandidateInvitation>();
expectTypeOf(
getOrganizationInvitationContacts,
).returns.resolves.toEqualTypeOf<ContactDisclosure>();
});
it("exposes request DTOs without client-set state, contacts, or a hidden C4 default", () => {
expectTypeOf<
Extract<keyof OrganizationInvitationCreate, ClientSetKey | ContactOrMinimumKey>
>().toEqualTypeOf<never>();
expectTypeOf<
Extract<keyof OrganizationInvitationUpdate, ClientSetKey | ContactOrMinimumKey>
>().toEqualTypeOf<never>();
expectTypeOf<
Extract<
keyof InvitationAcceptance,
Exclude<ClientSetKey, "terms_version"> | ContactOrMinimumKey
>
>().toEqualTypeOf<never>();
expectTypeOf<
Extract<keyof InvitationDeclineRequest, ClientSetKey | ContactOrMinimumKey>
>().toEqualTypeOf<never>();
// The acceptance names the terms version and the field choice explicitly.
expectTypeOf<InvitationAcceptance["terms_version"]>().toEqualTypeOf<number>();
expectTypeOf<InvitationAcceptance["consent_c4"]["fields"]>().toEqualTypeOf<
("full_name" | "email" | "phone" | "telegram")[]
>();
expectTypeOf<InvitationAcceptance["consent_c4"]["accepted"]>().toEqualTypeOf<true>();
expectTypeOf(createOrganizationInvitation)
.parameter(1)
.toEqualTypeOf<OrganizationInvitationCreate>();
expectTypeOf(acceptMyInvitation).parameter(1).toEqualTypeOf<InvitationAcceptance>();
});
@@ -10,9 +10,7 @@ export * from './accountScenario.zod';
export * from './confirmEmailBody.zod';
export * from './consentPurpose.zod';
export * from './consentText.zod';
export * from './consentTextVersion.zod';
export * from './csrfToken.zod';
export * from './emailAddress.zod';
export * from './emailVerificationRequest.zod';
export * from './emailVerificationResendRequest.zod';
export * from './emailVerificationResult.zod';
+12
View File
@@ -5,12 +5,23 @@
* OpenAPI spec version: 0.1.0
*/
export * from './consentTextVersion.zod';
export * from './currencyCode.zod';
export * from './emailAddress.zod';
export * from './gradeCode.zod';
export * from './needLocationName.zod';
export * from './needTaskText.zod';
export * from './needVersion.zod';
export * from './pageInfo.zod';
export * from './problem.zod';
export * from './problemCode.zod';
export * from './problemFieldError.zod';
export * from './problemFieldLocation.zod';
export * from './rubAmount.zod';
export * from './salaryPeriod.zod';
export * from './salaryRange.zod';
export * from './salaryTaxBasis.zod';
export * from './skillName.zod';
export * from './specializationCode.zod';
export * from './taskLanguage.zod';
export * from './timestamp.zod';
@@ -20,5 +31,6 @@ export * from './candidate';
export * from './catalog';
export * from './health';
export * from './identity';
export * from './invitation';
export * from './need';
export * from './support';
@@ -0,0 +1,29 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const acceptMyInvitationBodyConsentC4TextVersionMax = 64;
export const acceptMyInvitationBodyConsentC4TextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const acceptMyInvitationBodyConsentC4FieldsMax = 4;
export const AcceptMyInvitationBody = zod.object({
"expected_version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
"terms_version": zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.').describe('Terms version that the candidate read and accepts. A version that is not the current one answers 412 version_conflict.'),
"consent_c4": zod.object({
"text_version": zod.string().min(1).max(acceptMyInvitationBodyConsentC4TextVersionMax).regex(acceptMyInvitationBodyConsentC4TextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'),
"accepted": zod.literal(true).describe('Explicit consent. Only true is valid.'),
"fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')).min(1).max(acceptMyInvitationBodyConsentC4FieldsMax).describe('Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other.')
}).describe('Consent C4 given in an acceptance: the text version the candidate saw, an explicit `accepted`, and the contact fields the candidate selected. At least one field is required, so a hidden default or an empty choice never creates a grant. A text version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c4/text_version`, and a field that the profile does not hold answers 400 with the pointer of that item, such as `/consent_c4/fields/1`. C4 is given only here, never at registration. The permission to pass the selected data on to the organization\'s ATS (PRD C4 and FR19) is planned as an additive optional flag that defaults to no transfer.')
}).describe('Acceptance of the current terms with the consent C4. The client sends the `version` and the `terms_version` it read and the contact fields the candidate selected; nothing is preselected or defaulted. Unknown fields are rejected, so a request cannot carry contact values, a grant, or another consent.')
export type AcceptMyInvitationBody = zod.input<typeof AcceptMyInvitationBody>;
export type AcceptMyInvitationBodyOutput = zod.output<typeof AcceptMyInvitationBody>;
@@ -0,0 +1,19 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const acceptMyInvitationHeadersIdempotencyKeyMax = 255;
export const acceptMyInvitationHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const AcceptMyInvitationHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(acceptMyInvitationHeadersIdempotencyKeyMax).regex(acceptMyInvitationHeadersIdempotencyKeyRegExp)
})
export type AcceptMyInvitationHeaders = zod.input<typeof AcceptMyInvitationHeaders>;
export type AcceptMyInvitationHeadersOutput = zod.output<typeof AcceptMyInvitationHeaders>;
@@ -0,0 +1,16 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const CancelMyInvitationBody = zod.object({
"expected_version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.')
}).describe('Command without parameters over the invitation version the client read: send, withdraw, or cancel. Unknown fields are rejected.')
export type CancelMyInvitationBody = zod.input<typeof CancelMyInvitationBody>;
export type CancelMyInvitationBodyOutput = zod.output<typeof CancelMyInvitationBody>;
@@ -0,0 +1,19 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const cancelMyInvitationHeadersIdempotencyKeyMax = 255;
export const cancelMyInvitationHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const CancelMyInvitationHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(cancelMyInvitationHeadersIdempotencyKeyMax).regex(cancelMyInvitationHeadersIdempotencyKeyRegExp)
})
export type CancelMyInvitationHeaders = zod.input<typeof CancelMyInvitationHeaders>;
export type CancelMyInvitationHeadersOutput = zod.output<typeof CancelMyInvitationHeaders>;
@@ -0,0 +1,17 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const CandidateHandleMax = 128;
export const CandidateHandleRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const CandidateHandle = zod.string().min(1).max(CandidateHandleMax).regex(CandidateHandleRegExp).describe('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.')
export type CandidateHandle = zod.input<typeof CandidateHandle>;
export type CandidateHandleOutput = zod.output<typeof CandidateHandle>;
@@ -0,0 +1,177 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const candidateInvitationOrganizationNameMax = 200;
export const candidateInvitationTermsRoleTitleMax = 200;
export const candidateInvitationTermsRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationTermsTasksItemMax = 300;
export const candidateInvitationTermsTasksItemRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationTermsTasksMax = 20;
export const candidateInvitationTermsTeamMax = 1000;
export const candidateInvitationTermsTeamRegExp = new RegExp('\\S');
export const candidateInvitationTermsTechStackItemMax = 100;
export const candidateInvitationTermsTechStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationTermsTechStackMax = 30;
export const candidateInvitationTermsWorkFormatsMax = 3;
export const candidateInvitationTermsLocationOneMax = 100;
export const candidateInvitationTermsLocationOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationTermsCommunicationMethodDetailsOneMax = 300;
export const candidateInvitationTermsCommunicationMethodDetailsOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationTermsSalarySalaryFromMin = 1000;
export const candidateInvitationTermsSalarySalaryFromMax = 100000000;
export const candidateInvitationTermsSalarySalaryFromMultipleOf = 1000;
export const candidateInvitationTermsSalarySalaryToMin = 1000;
export const candidateInvitationTermsSalarySalaryToMax = 100000000;
export const candidateInvitationTermsSalarySalaryToMultipleOf = 1000;
export const candidateInvitationTermsPackageBonusOneDescriptionMax = 300;
export const candidateInvitationTermsPackageBonusOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationTermsPackageEquipmentOneDescriptionMax = 300;
export const candidateInvitationTermsPackageEquipmentOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationTermsPackageTrainingOneDescriptionMax = 300;
export const candidateInvitationTermsPackageTrainingOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationTermsPackageHealthInsuranceOneDescriptionMax = 300;
export const candidateInvitationTermsPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationContactConsentOneTextTextVersionMax = 64;
export const candidateInvitationContactConsentOneTextTextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const candidateInvitationContactConsentOneTextTextMax = 100000;
export const candidateInvitationContactConsentOneAvailableFieldsMax = 4;
export const candidateInvitationDeclineOneCommentOneMax = 500;
export const candidateInvitationDeclineOneCommentOneRegExp = new RegExp('\\S');
export const candidateInvitationContactGrantOneFieldsMax = 4;
export const candidateInvitationContactGrantOneConsentTextVersionOneMax = 64;
export const candidateInvitationContactGrantOneConsentTextVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const CandidateInvitation = zod.object({
"id": zod.uuid().describe('Identifier of the invitation.'),
"organization": zod.object({
"id": zod.uuid().describe('Identifier of the organization.'),
"name": zod.string().min(1).max(candidateInvitationOrganizationNameMax).describe('Public name of the organization. Plain text; clients show it as text, never as HTML.')
}).describe('Organization that sent the invitation, as the candidate sees it before deciding. The organization contract (TASK-077) adds the public card; this object only names it.'),
"state": zod.enum(['draft', 'delivered', 'viewed', 'counter', 'accepted', 'interview_scheduled', 'interviewed', 'negotiation', 'terms_agreed', 'no_deal', 'declined', 'expired', 'withdrawn', 'cancelled_by_candidate']).describe('State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`.\n\n- draft: the organization prepares the terms. The candidate does not see the invitation.\n- delivered: the invitation is in the candidate\'s inbox and the response deadline runs.\n- viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged.\n- counter: planned; the candidate sent the one counter offer. No MVP operation produces it.\n- accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists.\n- interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them.\n- declined: terminal; the candidate declined with a structured reason. No access arises.\n- expired: terminal; a server deadline passed, see `expiry_reason`. No access arises.\n- withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it.\n- cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked.\n\nPlanned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change.'),
"expiry_reason": zod.union([zod.enum(['invitation_timeout', 'negotiation_timeout']).describe('Why an invitation expired. Set exactly when the state is `expired`, null otherwise.\n\n- invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created.\n- negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it.'),zod.null()]),
"version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
"terms_version": zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.'),
"terms": zod.object({
"role_title": zod.string().min(1).max(candidateInvitationTermsRoleTitleMax).regex(candidateInvitationTermsRoleTitleRegExp).describe('Name of the offered role, for example "Middle Go developer in the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),
"specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),
"grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
"offer_type": zod.enum(['full_time', 'part_time', 'contract', 'internship']).describe('Type of the offer.\n\n- full_time: employment with a full working week.\n- part_time: employment with a part-time working week.\n- contract: a fixed-term or project contract outside employment.\n- internship: an internship.\n\nAdding a value is a contract change.'),
"tasks": zod.array(zod.string().min(1).max(candidateInvitationTermsTasksItemMax).regex(candidateInvitationTermsTasksItemRegExp).describe('One work task of the team, for example "Move the payout service to an event model". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')).min(1).max(candidateInvitationTermsTasksMax).describe('Work tasks of the role in the order given.'),
"team": zod.string().min(1).max(candidateInvitationTermsTeamMax).regex(candidateInvitationTermsTeamRegExp).describe('Description of the team the candidate would join, such as its size, roles, and way of working. It may contain line breaks and has at least one character that is not white space. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of employees or candidates.'),
"tech_stack": zod.array(zod.string().min(1).max(candidateInvitationTermsTechStackItemMax).regex(candidateInvitationTermsTechStackItemRegExp).describe('Name of a skill or technology as the employer gave it, for example Go, PostgreSQL, or Temporal. It has no leading or trailing whitespace and no line breaks. The server compares names without regard to letter case. Plain text; clients show it as text, never as HTML.')).min(1).max(candidateInvitationTermsTechStackMax).describe('Technologies of the role. The server compares names without regard to letter case.'),
"work_formats": zod.array(zod.enum(['remote', 'office', 'hybrid']).describe('Acceptable work format: `remote`, `office`, or `hybrid`.')).min(1).max(candidateInvitationTermsWorkFormatsMax).describe('Work formats the organization offers; the candidate may choose any of them.'),
"location": zod.union([zod.string().min(1).max(candidateInvitationTermsLocationOneMax).regex(candidateInvitationTermsLocationOneRegExp).describe('Place of work for the office or hybrid format, for example a city, as free text. It describes the employer\'s office, never a candidate\'s address. Plain text without line breaks; clients show it as text, never as HTML.'),zod.null()]).describe('Place of work for the `office` or `hybrid` format, or null when the only format is `remote`. It is required with either of those formats.'),
"communication_method": zod.object({
"channel": zod.enum(['email', 'phone', 'telegram', 'video_call']).describe('Channel through which the organization will contact the candidate after an acceptance.\n\n- email: a letter to the email address the candidate disclosed.\n- phone: a call or a text to the phone number the candidate disclosed.\n- telegram: a message to the Telegram username the candidate disclosed.\n- video_call: an invitation to a video call, sent through one of the disclosed contacts.\n\nThe channel describes the organization\'s plan; the candidate decides which contacts to disclose, and the server never requires that the disclosed fields include the channel.'),
"details": zod.union([zod.string().min(1).max(candidateInvitationTermsCommunicationMethodDetailsOneMax).regex(candidateInvitationTermsCommunicationMethodDetailsOneRegExp).describe('Short note on the communication method, for example "A 30-minute call with the team lead within three working days". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Optional short note, for example the first step or the expected time of the first contact, or null. Plain text without line breaks; it never contains a link or a contact of an employee.')
}).describe('How the organization will contact the candidate after an acceptance. It is part of the terms, so the candidate sees it before choosing which contacts to disclose. An invitation without it cannot exist, because the terms require it.'),
"salary": zod.object({
"salary_from": zod.int().min(candidateInvitationTermsSalarySalaryFromMin).max(candidateInvitationTermsSalarySalaryFromMax).multipleOf(candidateInvitationTermsSalarySalaryFromMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"salary_to": zod.int().min(candidateInvitationTermsSalarySalaryToMin).max(candidateInvitationTermsSalarySalaryToMax).multipleOf(candidateInvitationTermsSalarySalaryToMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('Salary range `[A; B]` in whole rubles with its base: the currency, the pay period, and the tax basis (PRD FR13). The schema requires every field, bounds that are positive multiples of 1000, and the known currency, period, and basis. The server checks the cross-field rules in integer arithmetic: `salary_from < salary_to`, 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 answers 400 validation_failed with the pointer of `salary_to` in the request, for example `/salary/value/salary_to`. For example, `[95000; 105000]` has a width of exactly 10% and `[80000; 120000]` exactly 40%; both are accepted. The rules are the same for a need and an invitation.'),
"package": zod.object({
"bonus": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(candidateInvitationTermsPackageBonusOneDescriptionMax).regex(candidateInvitationTermsPackageBonusOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.'),
"equipment": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(candidateInvitationTermsPackageEquipmentOneDescriptionMax).regex(candidateInvitationTermsPackageEquipmentOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.'),
"training": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(candidateInvitationTermsPackageTrainingOneDescriptionMax).regex(candidateInvitationTermsPackageTrainingOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.'),
"health_insurance": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(candidateInvitationTermsPackageHealthInsuranceOneDescriptionMax).regex(candidateInvitationTermsPackageHealthInsuranceOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.')
}).describe('Required section of the package (PRD FR12): the bonus, the equipment, the training, and the voluntary health insurance (ДМС). Every field is required and is either provided with a description or explicitly not provided. The work format of the package is the required `work_formats` term, which has no "not provided" variant. Adding a required condition is a breaking change; an optional one is additive.')
}).describe('Terms of an invitation: everything the candidate sees before deciding and before any contact is disclosed. The same schema is the request field of a draft and the stored snapshot of a terms version, so a response can be sent back unchanged. Every field is required; a field that may have no value says so with an explicit variant (`location` null for a remote role, a package item `not_provided`). The terms never contain data of the candidate: no contact, no salary minimum, and no indicator derived from it. The server checks the cross-field rules after the schema and answers 400 validation_failed with the pointer of the field: the salary rules of SalaryRange with `/terms/salary/salary_to`, a missing place of work for the `office` or `hybrid` format with `/terms/location`, and a repeated technology in `tech_stack` with the pointer of the later item.'),
"response_deadline_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"delivered_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"viewed_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment of the first view recorded by ViewMyInvitation, or null when the candidate has not opened the terms.'),
"responded_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]),
"updated_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"contact_consent": zod.union([zod.object({
"text": zod.object({
"text_version": zod.string().min(1).max(candidateInvitationContactConsentOneTextTextVersionMax).regex(candidateInvitationContactConsentOneTextTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'),
"text": zod.string().min(1).max(candidateInvitationContactConsentOneTextTextMax).describe('Full consent text in plain UTF-8 with the name of the organization; paragraphs are separated by an empty line. The client shows it as text, never as HTML, next to the field choice.')
}).describe('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).'),
"available_fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')).min(1).max(candidateInvitationContactConsentOneAvailableFieldsMax).describe('Kinds of contact that the profile holds and that an acceptance may select. A kind outside this list answers 400 in an acceptance.')
}).describe('What the candidate can consent to in an acceptance: the consent text and the kinds of contact that the candidate\'s profile holds now. It holds kinds only, never contact values, and nothing is preselected.'),zod.null()]).describe('Text and choice of the consent C4 for an acceptance, or null when an acceptance is impossible now: the state does not allow it, the deadline has passed, or the profile holds no contact to disclose. In the last case the client tells the candidate to add a contact to the profile first, because a grant must cover at least one field.'),
"decline": zod.union([zod.object({
"reason": zod.enum(['salary', 'tasks', 'stack', 'work_format', 'package', 'company', 'not_looking', 'other_offer', 'other']).describe('Structured reason of a decline. Every reason is neutral and none requires a comment.\n\n- salary: the salary range does not fit.\n- tasks: the role or the tasks do not fit.\n- stack: the technologies do not fit.\n- work_format: the work format or the place of work does not fit.\n- package: the package does not fit.\n- company: the company or its domain does not fit.\n- not_looking: the candidate is not looking for a job now.\n- other_offer: the candidate accepted another offer.\n- other: another reason ("Другое"); a comment stays optional.\n\nThe organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change.'),
"comment": zod.union([zod.string().min(1).max(candidateInvitationDeclineOneCommentOneMax).regex(candidateInvitationDeclineOneCommentOneRegExp).describe('Optional comment of the candidate on the offer. It may contain line breaks and has at least one character that is not white space. It is never shown to the organization, never published, and never written to logs or notifications; only the candidate reads it back. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"declined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('The candidate\'s own decline, as the candidate reads it back.'),zod.null()]).describe('The candidate\'s decline, or null unless `state` is `declined`.'),
"contact_grant": zod.union([zod.object({
"id": zod.uuid().describe('Identifier of the grant.'),
"fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')).min(1).max(candidateInvitationContactGrantOneFieldsMax).describe('Contact fields that the grant covers.'),
"status": zod.enum(['active', 'revoked']).describe('State of a contact grant.\n\n- active: the grant exists. Each read by the organization still checks the consent C4, the grant, and the current visibility of the profile.\n- revoked: the grant is closed for good; the organization reads no contact through it. A later publication of the profile or a new acceptance never reopens it; only a new explicit C4 creates a new grant.'),
"readable": zod.boolean().describe('Whether the organization can read the covered fields now: true only for an active grant whose current consent and visibility allow the read. The organization sees the same fact as `contact_access.status` `available`, without the reason.'),
"blocked_by": zod.union([zod.enum(['visibility']).describe('Why an active grant does not allow a read now, shown only to the candidate.\n\n- visibility: the profile was not published (C2) or was hidden from the organization when the candidate accepted, and it still is. The acceptance never publishes the profile or lifts the hiding by itself (PRD FR12); the grant becomes readable once the candidate publishes the profile or unhides it for the organization.'),zod.null()]).describe('Why an active grant is not readable now, or null when it is readable or revoked; a revoked grant has `revocation_reason` instead.'),
"terms_version": zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.').describe('Terms version of the invitation that the acceptance accepted.'),
"consent_text_version": zod.string().min(1).max(candidateInvitationContactGrantOneConsentTextVersionOneMax).regex(candidateInvitationContactGrantOneConsentTextVersionOneRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.').describe('Version of the consent C4 text that the candidate accepted.'),
"granted_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"revoked_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment of the revocation, or null while the grant is active.'),
"revocation_reason": zod.union([zod.enum(['consent_revoked', 'participation_cancelled', 'visibility_closed']).describe('Why a contact grant was revoked, shown only to the candidate.\n\n- consent_revoked: the candidate revoked the consent C4 for the organization; every grant under it is closed.\n- participation_cancelled: the candidate cancelled the participation in this invitation; only the grant of this invitation is closed.\n- visibility_closed: the candidate revoked the publication C2 or hid the profile from the organization after the grant existed. A grant created while the visibility already did not allow a read stays active with `blocked_by` `visibility` instead.\n\nThe withdrawal of an invitation by the organization, a no deal, and a negotiation timeout never revoke a grant.'),zod.null()]).describe('Reason of the revocation, or null while the grant is active.')
}).describe('Contact grant as the candidate reads it: which fields one organization may read, from which invitation and terms version, and whether it is still active. It holds kinds only, never contact values. A grant is stored apart from the invitation state, so a later change of the state does not change it unless the state is a cancellation by the candidate.'),zod.null()]).describe('Contact grant that the acceptance of this invitation created, or null when the invitation was never accepted. It stays after a revocation, with its status and reason.')
}).describe('Invitation as the addressed candidate reads it: the organization, the current terms with their version, the state and the deadline, the text and the choice of the consent C4 while an acceptance is possible, the candidate\'s own decline, and the contact grant that the acceptance created. It has no candidate handle, no need, no salary indicator, and no contact value: the candidate\'s own contacts and salary minimum stay in the profile.')
export type CandidateInvitation = zod.input<typeof CandidateInvitation>;
export type CandidateInvitationOutput = zod.output<typeof CandidateInvitation>;
@@ -0,0 +1,66 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const candidateInvitationListItemsItemOrganizationNameMax = 200;
export const candidateInvitationListItemsItemRoleTitleMax = 200;
export const candidateInvitationListItemsItemRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationListItemsItemSalarySalaryFromMin = 1000;
export const candidateInvitationListItemsItemSalarySalaryFromMax = 100000000;
export const candidateInvitationListItemsItemSalarySalaryFromMultipleOf = 1000;
export const candidateInvitationListItemsItemSalarySalaryToMin = 1000;
export const candidateInvitationListItemsItemSalarySalaryToMax = 100000000;
export const candidateInvitationListItemsItemSalarySalaryToMultipleOf = 1000;
export const candidateInvitationListItemsItemWorkFormatsMax = 3;
export const candidateInvitationListItemsMax = 100;
export const candidateInvitationListPageNextCursorMax = 512;
export const candidateInvitationListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const CandidateInvitationList = zod.object({
"items": zod.array(zod.object({
"id": zod.uuid().describe('Identifier of the invitation.'),
"organization": zod.object({
"id": zod.uuid().describe('Identifier of the organization.'),
"name": zod.string().min(1).max(candidateInvitationListItemsItemOrganizationNameMax).describe('Public name of the organization. Plain text; clients show it as text, never as HTML.')
}).describe('Organization that sent the invitation, as the candidate sees it before deciding. The organization contract (TASK-077) adds the public card; this object only names it.'),
"state": zod.enum(['draft', 'delivered', 'viewed', 'counter', 'accepted', 'interview_scheduled', 'interviewed', 'negotiation', 'terms_agreed', 'no_deal', 'declined', 'expired', 'withdrawn', 'cancelled_by_candidate']).describe('State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`.\n\n- draft: the organization prepares the terms. The candidate does not see the invitation.\n- delivered: the invitation is in the candidate\'s inbox and the response deadline runs.\n- viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged.\n- counter: planned; the candidate sent the one counter offer. No MVP operation produces it.\n- accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists.\n- interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them.\n- declined: terminal; the candidate declined with a structured reason. No access arises.\n- expired: terminal; a server deadline passed, see `expiry_reason`. No access arises.\n- withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it.\n- cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked.\n\nPlanned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change.'),
"expiry_reason": zod.union([zod.enum(['invitation_timeout', 'negotiation_timeout']).describe('Why an invitation expired. Set exactly when the state is `expired`, null otherwise.\n\n- invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created.\n- negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it.'),zod.null()]),
"version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
"terms_version": zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.'),
"role_title": zod.string().min(1).max(candidateInvitationListItemsItemRoleTitleMax).regex(candidateInvitationListItemsItemRoleTitleRegExp).describe('Name of the offered role, for example "Middle Go developer in the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),
"salary": zod.object({
"salary_from": zod.int().min(candidateInvitationListItemsItemSalarySalaryFromMin).max(candidateInvitationListItemsItemSalarySalaryFromMax).multipleOf(candidateInvitationListItemsItemSalarySalaryFromMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"salary_to": zod.int().min(candidateInvitationListItemsItemSalarySalaryToMin).max(candidateInvitationListItemsItemSalarySalaryToMax).multipleOf(candidateInvitationListItemsItemSalarySalaryToMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('Salary range `[A; B]` in whole rubles with its base: the currency, the pay period, and the tax basis (PRD FR13). The schema requires every field, bounds that are positive multiples of 1000, and the known currency, period, and basis. The server checks the cross-field rules in integer arithmetic: `salary_from < salary_to`, 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 answers 400 validation_failed with the pointer of `salary_to` in the request, for example `/salary/value/salary_to`. For example, `[95000; 105000]` has a width of exactly 10% and `[80000; 120000]` exactly 40%; both are accepted. The rules are the same for a need and an invitation.'),
"work_formats": zod.array(zod.enum(['remote', 'office', 'hybrid']).describe('Acceptable work format: `remote`, `office`, or `hybrid`.')).min(1).max(candidateInvitationListItemsItemWorkFormatsMax),
"response_deadline_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"delivered_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"viewed_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]),
"updated_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('Invitation in the candidate\'s inbox: the organization, the state, the versions, the role, the salary range, and the deadline. Listing never records a view; GetMyInvitation returns the full terms, and ViewMyInvitation records the view.')).max(candidateInvitationListItemsMax).describe('Invitations of the page.'),
"page": zod.object({
"has_more": zod.boolean().describe('Whether another page follows this one.'),
"next_cursor": zod.string().min(1).max(candidateInvitationListPageNextCursorMax).regex(candidateInvitationListPageNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.')
}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.')
}).describe('One page of the candidate\'s invitations, newest first by delivery time.')
export type CandidateInvitationList = zod.input<typeof CandidateInvitationList>;
export type CandidateInvitationListOutput = zod.output<typeof CandidateInvitationList>;
@@ -0,0 +1,54 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const candidateInvitationSummaryOrganizationNameMax = 200;
export const candidateInvitationSummaryRoleTitleMax = 200;
export const candidateInvitationSummaryRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const candidateInvitationSummarySalarySalaryFromMin = 1000;
export const candidateInvitationSummarySalarySalaryFromMax = 100000000;
export const candidateInvitationSummarySalarySalaryFromMultipleOf = 1000;
export const candidateInvitationSummarySalarySalaryToMin = 1000;
export const candidateInvitationSummarySalarySalaryToMax = 100000000;
export const candidateInvitationSummarySalarySalaryToMultipleOf = 1000;
export const candidateInvitationSummaryWorkFormatsMax = 3;
export const CandidateInvitationSummary = zod.object({
"id": zod.uuid().describe('Identifier of the invitation.'),
"organization": zod.object({
"id": zod.uuid().describe('Identifier of the organization.'),
"name": zod.string().min(1).max(candidateInvitationSummaryOrganizationNameMax).describe('Public name of the organization. Plain text; clients show it as text, never as HTML.')
}).describe('Organization that sent the invitation, as the candidate sees it before deciding. The organization contract (TASK-077) adds the public card; this object only names it.'),
"state": zod.enum(['draft', 'delivered', 'viewed', 'counter', 'accepted', 'interview_scheduled', 'interviewed', 'negotiation', 'terms_agreed', 'no_deal', 'declined', 'expired', 'withdrawn', 'cancelled_by_candidate']).describe('State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`.\n\n- draft: the organization prepares the terms. The candidate does not see the invitation.\n- delivered: the invitation is in the candidate\'s inbox and the response deadline runs.\n- viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged.\n- counter: planned; the candidate sent the one counter offer. No MVP operation produces it.\n- accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists.\n- interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them.\n- declined: terminal; the candidate declined with a structured reason. No access arises.\n- expired: terminal; a server deadline passed, see `expiry_reason`. No access arises.\n- withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it.\n- cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked.\n\nPlanned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change.'),
"expiry_reason": zod.union([zod.enum(['invitation_timeout', 'negotiation_timeout']).describe('Why an invitation expired. Set exactly when the state is `expired`, null otherwise.\n\n- invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created.\n- negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it.'),zod.null()]),
"version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
"terms_version": zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.'),
"role_title": zod.string().min(1).max(candidateInvitationSummaryRoleTitleMax).regex(candidateInvitationSummaryRoleTitleRegExp).describe('Name of the offered role, for example "Middle Go developer in the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),
"salary": zod.object({
"salary_from": zod.int().min(candidateInvitationSummarySalarySalaryFromMin).max(candidateInvitationSummarySalarySalaryFromMax).multipleOf(candidateInvitationSummarySalarySalaryFromMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"salary_to": zod.int().min(candidateInvitationSummarySalarySalaryToMin).max(candidateInvitationSummarySalarySalaryToMax).multipleOf(candidateInvitationSummarySalarySalaryToMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('Salary range `[A; B]` in whole rubles with its base: the currency, the pay period, and the tax basis (PRD FR13). The schema requires every field, bounds that are positive multiples of 1000, and the known currency, period, and basis. The server checks the cross-field rules in integer arithmetic: `salary_from < salary_to`, 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 answers 400 validation_failed with the pointer of `salary_to` in the request, for example `/salary/value/salary_to`. For example, `[95000; 105000]` has a width of exactly 10% and `[80000; 120000]` exactly 40%; both are accepted. The rules are the same for a need and an invitation.'),
"work_formats": zod.array(zod.enum(['remote', 'office', 'hybrid']).describe('Acceptable work format: `remote`, `office`, or `hybrid`.')).min(1).max(candidateInvitationSummaryWorkFormatsMax),
"response_deadline_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"delivered_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"viewed_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]),
"updated_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('Invitation in the candidate\'s inbox: the organization, the state, the versions, the role, the salary range, and the deadline. Listing never records a view; GetMyInvitation returns the full terms, and ViewMyInvitation records the view.')
export type CandidateInvitationSummary = zod.input<typeof CandidateInvitationSummary>;
export type CandidateInvitationSummaryOutput = zod.output<typeof CandidateInvitationSummary>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ContactAccessBlock = zod.enum(['visibility']).describe('Why an active grant does not allow a read now, shown only to the candidate.\n\n- visibility: the profile was not published (C2) or was hidden from the organization when the candidate accepted, and it still is. The acceptance never publishes the profile or lifts the hiding by itself (PRD FR12); the grant becomes readable once the candidate publishes the profile or unhides it for the organization.')
export type ContactAccessBlock = zod.input<typeof ContactAccessBlock>;
export type ContactAccessBlockOutput = zod.output<typeof ContactAccessBlock>;
@@ -0,0 +1,23 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const contactConsentAcceptanceTextVersionMax = 64;
export const contactConsentAcceptanceTextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const contactConsentAcceptanceFieldsMax = 4;
export const ContactConsentAcceptance = zod.object({
"text_version": zod.string().min(1).max(contactConsentAcceptanceTextVersionMax).regex(contactConsentAcceptanceTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'),
"accepted": zod.literal(true).describe('Explicit consent. Only true is valid.'),
"fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')).min(1).max(contactConsentAcceptanceFieldsMax).describe('Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other.')
}).describe('Consent C4 given in an acceptance: the text version the candidate saw, an explicit `accepted`, and the contact fields the candidate selected. At least one field is required, so a hidden default or an empty choice never creates a grant. A text version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c4/text_version`, and a field that the profile does not hold answers 400 with the pointer of that item, such as `/consent_c4/fields/1`. C4 is given only here, never at registration. The permission to pass the selected data on to the organization\'s ATS (PRD C4 and FR19) is planned as an additive optional flag that defaults to no transfer.')
export type ContactConsentAcceptance = zod.input<typeof ContactConsentAcceptance>;
export type ContactConsentAcceptanceOutput = zod.output<typeof ContactConsentAcceptance>;
@@ -0,0 +1,27 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const contactConsentOfferTextTextVersionMax = 64;
export const contactConsentOfferTextTextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const contactConsentOfferTextTextMax = 100000;
export const contactConsentOfferAvailableFieldsMax = 4;
export const ContactConsentOffer = zod.object({
"text": zod.object({
"text_version": zod.string().min(1).max(contactConsentOfferTextTextVersionMax).regex(contactConsentOfferTextTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'),
"text": zod.string().min(1).max(contactConsentOfferTextTextMax).describe('Full consent text in plain UTF-8 with the name of the organization; paragraphs are separated by an empty line. The client shows it as text, never as HTML, next to the field choice.')
}).describe('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).'),
"available_fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')).min(1).max(contactConsentOfferAvailableFieldsMax).describe('Kinds of contact that the profile holds and that an acceptance may select. A kind outside this list answers 400 in an acceptance.')
}).describe('What the candidate can consent to in an acceptance: the consent text and the kinds of contact that the candidate\'s profile holds now. It holds kinds only, never contact values, and nothing is preselected.')
export type ContactConsentOffer = zod.input<typeof ContactConsentOffer>;
export type ContactConsentOfferOutput = zod.output<typeof ContactConsentOffer>;
@@ -0,0 +1,22 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const contactConsentTextTextVersionMax = 64;
export const contactConsentTextTextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const contactConsentTextTextMax = 100000;
export const ContactConsentText = zod.object({
"text_version": zod.string().min(1).max(contactConsentTextTextVersionMax).regex(contactConsentTextTextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'),
"text": zod.string().min(1).max(contactConsentTextTextMax).describe('Full consent text in plain UTF-8 with the name of the organization; paragraphs are separated by an empty line. The client shows it as text, never as HTML, next to the field choice.')
}).describe('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).')
export type ContactConsentText = zod.input<typeof ContactConsentText>;
export type ContactConsentTextOutput = zod.output<typeof ContactConsentText>;
@@ -0,0 +1,41 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const contactDisclosureFieldsMax = 4;
export const contactDisclosureFullNameOneMax = 200;
export const contactDisclosureFullNameOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const contactDisclosureEmailOneMin = 3;
export const contactDisclosureEmailOneMax = 254;
export const contactDisclosurePhoneOneMin = 8;
export const contactDisclosurePhoneOneMax = 16;
export const contactDisclosurePhoneOneRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
export const contactDisclosureTelegramOneMin = 6;
export const contactDisclosureTelegramOneMax = 33;
export const contactDisclosureTelegramOneRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
export const ContactDisclosure = zod.object({
"invitation_id": zod.uuid().describe('Invitation whose acceptance created the grant.'),
"grant_id": zod.uuid().describe('Grant that allows the read.'),
"fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')).min(1).max(contactDisclosureFieldsMax).describe('Contact fields that the grant covers.'),
"granted_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"full_name": zod.union([zod.string().min(1).max(contactDisclosureFullNameOneMax).regex(contactDisclosureFullNameOneRegExp).describe('Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.'),zod.null()]),
"email": zod.union([zod.email().min(contactDisclosureEmailOneMin).max(contactDisclosureEmailOneMax).describe('Account email address. The server compares addresses without regard to letter case and never reveals in a response whether an address belongs to an account.'),zod.null()]),
"phone": zod.union([zod.string().min(contactDisclosurePhoneOneMin).max(contactDisclosurePhoneOneMax).regex(contactDisclosurePhoneOneRegExp).describe('Phone number in the E.164 format, for example +70000000000.'),zod.null()]),
"telegram": zod.union([zod.string().min(contactDisclosureTelegramOneMin).max(contactDisclosureTelegramOneMax).regex(contactDisclosureTelegramOneRegExp).describe('Telegram username with the leading @.'),zod.null()])
}).describe('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.')
export type ContactDisclosure = zod.input<typeof ContactDisclosure>;
export type ContactDisclosureOutput = zod.output<typeof ContactDisclosure>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ContactFieldKind = zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')
export type ContactFieldKind = zod.input<typeof ContactFieldKind>;
export type ContactFieldKindOutput = zod.output<typeof ContactFieldKind>;
@@ -0,0 +1,17 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ContactFullNameMax = 200;
export const ContactFullNameRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const ContactFullName = zod.string().min(1).max(ContactFullNameMax).regex(ContactFullNameRegExp).describe('Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML.')
export type ContactFullName = zod.input<typeof ContactFullName>;
export type ContactFullNameOutput = zod.output<typeof ContactFullName>;
@@ -0,0 +1,31 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const contactGrantFieldsMax = 4;
export const contactGrantConsentTextVersionOneMax = 64;
export const contactGrantConsentTextVersionOneRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const ContactGrant = zod.object({
"id": zod.uuid().describe('Identifier of the grant.'),
"fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')).min(1).max(contactGrantFieldsMax).describe('Contact fields that the grant covers.'),
"status": zod.enum(['active', 'revoked']).describe('State of a contact grant.\n\n- active: the grant exists. Each read by the organization still checks the consent C4, the grant, and the current visibility of the profile.\n- revoked: the grant is closed for good; the organization reads no contact through it. A later publication of the profile or a new acceptance never reopens it; only a new explicit C4 creates a new grant.'),
"readable": zod.boolean().describe('Whether the organization can read the covered fields now: true only for an active grant whose current consent and visibility allow the read. The organization sees the same fact as `contact_access.status` `available`, without the reason.'),
"blocked_by": zod.union([zod.enum(['visibility']).describe('Why an active grant does not allow a read now, shown only to the candidate.\n\n- visibility: the profile was not published (C2) or was hidden from the organization when the candidate accepted, and it still is. The acceptance never publishes the profile or lifts the hiding by itself (PRD FR12); the grant becomes readable once the candidate publishes the profile or unhides it for the organization.'),zod.null()]).describe('Why an active grant is not readable now, or null when it is readable or revoked; a revoked grant has `revocation_reason` instead.'),
"terms_version": zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.').describe('Terms version of the invitation that the acceptance accepted.'),
"consent_text_version": zod.string().min(1).max(contactGrantConsentTextVersionOneMax).regex(contactGrantConsentTextVersionOneRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.').describe('Version of the consent C4 text that the candidate accepted.'),
"granted_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"revoked_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment of the revocation, or null while the grant is active.'),
"revocation_reason": zod.union([zod.enum(['consent_revoked', 'participation_cancelled', 'visibility_closed']).describe('Why a contact grant was revoked, shown only to the candidate.\n\n- consent_revoked: the candidate revoked the consent C4 for the organization; every grant under it is closed.\n- participation_cancelled: the candidate cancelled the participation in this invitation; only the grant of this invitation is closed.\n- visibility_closed: the candidate revoked the publication C2 or hid the profile from the organization after the grant existed. A grant created while the visibility already did not allow a read stays active with `blocked_by` `visibility` instead.\n\nThe withdrawal of an invitation by the organization, a no deal, and a negotiation timeout never revoke a grant.'),zod.null()]).describe('Reason of the revocation, or null while the grant is active.')
}).describe('Contact grant as the candidate reads it: which fields one organization may read, from which invitation and terms version, and whether it is still active. It holds kinds only, never contact values. A grant is stored apart from the invitation state, so a later change of the state does not change it unless the state is a cancellation by the candidate.')
export type ContactGrant = zod.input<typeof ContactGrant>;
export type ContactGrantOutput = zod.output<typeof ContactGrant>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ContactGrantState = zod.enum(['active', 'revoked']).describe('State of a contact grant.\n\n- active: the grant exists. Each read by the organization still checks the consent C4, the grant, and the current visibility of the profile.\n- revoked: the grant is closed for good; the organization reads no contact through it. A later publication of the profile or a new acceptance never reopens it; only a new explicit C4 creates a new grant.')
export type ContactGrantState = zod.input<typeof ContactGrantState>;
export type ContactGrantStateOutput = zod.output<typeof ContactGrantState>;
@@ -0,0 +1,18 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ContactPhoneNumberMin = 8;
export const ContactPhoneNumberMax = 16;
export const ContactPhoneNumberRegExp = new RegExp('^\\+[1-9][0-9]{6,14}$');
export const ContactPhoneNumber = zod.string().min(ContactPhoneNumberMin).max(ContactPhoneNumberMax).regex(ContactPhoneNumberRegExp).describe('Phone number in the E.164 format, for example +70000000000.')
export type ContactPhoneNumber = zod.input<typeof ContactPhoneNumber>;
export type ContactPhoneNumberOutput = zod.output<typeof ContactPhoneNumber>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ContactRevocationReason = zod.enum(['consent_revoked', 'participation_cancelled', 'visibility_closed']).describe('Why a contact grant was revoked, shown only to the candidate.\n\n- consent_revoked: the candidate revoked the consent C4 for the organization; every grant under it is closed.\n- participation_cancelled: the candidate cancelled the participation in this invitation; only the grant of this invitation is closed.\n- visibility_closed: the candidate revoked the publication C2 or hid the profile from the organization after the grant existed. A grant created while the visibility already did not allow a read stays active with `blocked_by` `visibility` instead.\n\nThe withdrawal of an invitation by the organization, a no deal, and a negotiation timeout never revoke a grant.')
export type ContactRevocationReason = zod.input<typeof ContactRevocationReason>;
export type ContactRevocationReasonOutput = zod.output<typeof ContactRevocationReason>;
@@ -0,0 +1,18 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const ContactTelegramUsernameMin = 6;
export const ContactTelegramUsernameMax = 33;
export const ContactTelegramUsernameRegExp = new RegExp('^@[A-Za-z0-9_]{5,32}$');
export const ContactTelegramUsername = zod.string().min(ContactTelegramUsernameMin).max(ContactTelegramUsernameMax).regex(ContactTelegramUsernameRegExp).describe('Telegram username with the leading @.')
export type ContactTelegramUsername = zod.input<typeof ContactTelegramUsername>;
export type ContactTelegramUsernameOutput = zod.output<typeof ContactTelegramUsername>;
@@ -0,0 +1,127 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const createOrganizationInvitationBodyCandidateHandleMax = 128;
export const createOrganizationInvitationBodyCandidateHandleRegExp = new RegExp('^[A-Za-z0-9_-]+$');
export const createOrganizationInvitationBodyTermsRoleTitleMax = 200;
export const createOrganizationInvitationBodyTermsRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const createOrganizationInvitationBodyTermsTasksItemMax = 300;
export const createOrganizationInvitationBodyTermsTasksItemRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const createOrganizationInvitationBodyTermsTasksMax = 20;
export const createOrganizationInvitationBodyTermsTeamMax = 1000;
export const createOrganizationInvitationBodyTermsTeamRegExp = new RegExp('\\S');
export const createOrganizationInvitationBodyTermsTechStackItemMax = 100;
export const createOrganizationInvitationBodyTermsTechStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const createOrganizationInvitationBodyTermsTechStackMax = 30;
export const createOrganizationInvitationBodyTermsWorkFormatsMax = 3;
export const createOrganizationInvitationBodyTermsLocationOneMax = 100;
export const createOrganizationInvitationBodyTermsLocationOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const createOrganizationInvitationBodyTermsCommunicationMethodDetailsOneMax = 300;
export const createOrganizationInvitationBodyTermsCommunicationMethodDetailsOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const createOrganizationInvitationBodyTermsSalarySalaryFromMin = 1000;
export const createOrganizationInvitationBodyTermsSalarySalaryFromMax = 100000000;
export const createOrganizationInvitationBodyTermsSalarySalaryFromMultipleOf = 1000;
export const createOrganizationInvitationBodyTermsSalarySalaryToMin = 1000;
export const createOrganizationInvitationBodyTermsSalarySalaryToMax = 100000000;
export const createOrganizationInvitationBodyTermsSalarySalaryToMultipleOf = 1000;
export const createOrganizationInvitationBodyTermsPackageBonusOneDescriptionMax = 300;
export const createOrganizationInvitationBodyTermsPackageBonusOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const createOrganizationInvitationBodyTermsPackageEquipmentOneDescriptionMax = 300;
export const createOrganizationInvitationBodyTermsPackageEquipmentOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const createOrganizationInvitationBodyTermsPackageTrainingOneDescriptionMax = 300;
export const createOrganizationInvitationBodyTermsPackageTrainingOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const createOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescriptionMax = 300;
export const createOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const CreateOrganizationInvitationBody = zod.object({
"candidate_handle": zod.string().min(1).max(createOrganizationInvitationBodyCandidateHandleMax).regex(createOrganizationInvitationBodyCandidateHandleRegExp).describe('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.'),
"need": zod.union([zod.object({
"need_id": zod.uuid().describe('Identifier of a need of the organization in the path.'),
"requirements_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.').describe('`requirements_version` of the need that the invitation refers to; it must be a version that the need has had.')
}).describe('Need of the same organization that the invitation was built from, with the requirements version used. A direct invitation has no need. The link is informational: the invitation keeps its own terms, which may differ from the need, and a later change of the need never changes them.'),zod.null()]).exactOptional().describe('Need of the organization the invitation is built from, or null or absent for a direct invitation.'),
"response_period_days": zod.union([zod.literal(3),zod.literal(7),zod.literal(14)]).describe('Days the candidate has to answer, chosen by the organization in the draft from the product policy: 3, 7, or 14. The deadline starts at the first delivery and is never reset by an email, a view, or a counter offer.').exactOptional().describe('Days to answer; absent means 7, the default of the product policy.'),
"terms": zod.object({
"role_title": zod.string().min(1).max(createOrganizationInvitationBodyTermsRoleTitleMax).regex(createOrganizationInvitationBodyTermsRoleTitleRegExp).describe('Name of the offered role, for example "Middle Go developer in the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),
"specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'),
"grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.'),
"offer_type": zod.enum(['full_time', 'part_time', 'contract', 'internship']).describe('Type of the offer.\n\n- full_time: employment with a full working week.\n- part_time: employment with a part-time working week.\n- contract: a fixed-term or project contract outside employment.\n- internship: an internship.\n\nAdding a value is a contract change.'),
"tasks": zod.array(zod.string().min(1).max(createOrganizationInvitationBodyTermsTasksItemMax).regex(createOrganizationInvitationBodyTermsTasksItemRegExp).describe('One work task of the team, for example "Move the payout service to an event model". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')).min(1).max(createOrganizationInvitationBodyTermsTasksMax).describe('Work tasks of the role in the order given.'),
"team": zod.string().min(1).max(createOrganizationInvitationBodyTermsTeamMax).regex(createOrganizationInvitationBodyTermsTeamRegExp).describe('Description of the team the candidate would join, such as its size, roles, and way of working. It may contain line breaks and has at least one character that is not white space. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of employees or candidates.'),
"tech_stack": zod.array(zod.string().min(1).max(createOrganizationInvitationBodyTermsTechStackItemMax).regex(createOrganizationInvitationBodyTermsTechStackItemRegExp).describe('Name of a skill or technology as the employer gave it, for example Go, PostgreSQL, or Temporal. It has no leading or trailing whitespace and no line breaks. The server compares names without regard to letter case. Plain text; clients show it as text, never as HTML.')).min(1).max(createOrganizationInvitationBodyTermsTechStackMax).describe('Technologies of the role. The server compares names without regard to letter case.'),
"work_formats": zod.array(zod.enum(['remote', 'office', 'hybrid']).describe('Acceptable work format: `remote`, `office`, or `hybrid`.')).min(1).max(createOrganizationInvitationBodyTermsWorkFormatsMax).describe('Work formats the organization offers; the candidate may choose any of them.'),
"location": zod.union([zod.string().min(1).max(createOrganizationInvitationBodyTermsLocationOneMax).regex(createOrganizationInvitationBodyTermsLocationOneRegExp).describe('Place of work for the office or hybrid format, for example a city, as free text. It describes the employer\'s office, never a candidate\'s address. Plain text without line breaks; clients show it as text, never as HTML.'),zod.null()]).describe('Place of work for the `office` or `hybrid` format, or null when the only format is `remote`. It is required with either of those formats.'),
"communication_method": zod.object({
"channel": zod.enum(['email', 'phone', 'telegram', 'video_call']).describe('Channel through which the organization will contact the candidate after an acceptance.\n\n- email: a letter to the email address the candidate disclosed.\n- phone: a call or a text to the phone number the candidate disclosed.\n- telegram: a message to the Telegram username the candidate disclosed.\n- video_call: an invitation to a video call, sent through one of the disclosed contacts.\n\nThe channel describes the organization\'s plan; the candidate decides which contacts to disclose, and the server never requires that the disclosed fields include the channel.'),
"details": zod.union([zod.string().min(1).max(createOrganizationInvitationBodyTermsCommunicationMethodDetailsOneMax).regex(createOrganizationInvitationBodyTermsCommunicationMethodDetailsOneRegExp).describe('Short note on the communication method, for example "A 30-minute call with the team lead within three working days". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Optional short note, for example the first step or the expected time of the first contact, or null. Plain text without line breaks; it never contains a link or a contact of an employee.')
}).describe('How the organization will contact the candidate after an acceptance. It is part of the terms, so the candidate sees it before choosing which contacts to disclose. An invitation without it cannot exist, because the terms require it.'),
"salary": zod.object({
"salary_from": zod.int().min(createOrganizationInvitationBodyTermsSalarySalaryFromMin).max(createOrganizationInvitationBodyTermsSalarySalaryFromMax).multipleOf(createOrganizationInvitationBodyTermsSalarySalaryFromMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"salary_to": zod.int().min(createOrganizationInvitationBodyTermsSalarySalaryToMin).max(createOrganizationInvitationBodyTermsSalarySalaryToMax).multipleOf(createOrganizationInvitationBodyTermsSalarySalaryToMultipleOf).describe('Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final.'),
"currency": zod.enum(['RUB']).describe('ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change.'),
"period": zod.enum(['month']).describe('Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change.'),
"tax_basis": zod.enum(['net', 'gross']).describe('Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.')
}).describe('Salary range `[A; B]` in whole rubles with its base: the currency, the pay period, and the tax basis (PRD FR13). The schema requires every field, bounds that are positive multiples of 1000, and the known currency, period, and basis. The server checks the cross-field rules in integer arithmetic: `salary_from < salary_to`, 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 answers 400 validation_failed with the pointer of `salary_to` in the request, for example `/salary/value/salary_to`. For example, `[95000; 105000]` has a width of exactly 10% and `[80000; 120000]` exactly 40%; both are accepted. The rules are the same for a need and an invitation.'),
"package": zod.object({
"bonus": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(createOrganizationInvitationBodyTermsPackageBonusOneDescriptionMax).regex(createOrganizationInvitationBodyTermsPackageBonusOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.'),
"equipment": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(createOrganizationInvitationBodyTermsPackageEquipmentOneDescriptionMax).regex(createOrganizationInvitationBodyTermsPackageEquipmentOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.'),
"training": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(createOrganizationInvitationBodyTermsPackageTrainingOneDescriptionMax).regex(createOrganizationInvitationBodyTermsPackageTrainingOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.'),
"health_insurance": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(createOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescriptionMax).regex(createOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.')
}).describe('Required section of the package (PRD FR12): the bonus, the equipment, the training, and the voluntary health insurance (ДМС). Every field is required and is either provided with a description or explicitly not provided. The work format of the package is the required `work_formats` term, which has no "not provided" variant. Adding a required condition is a breaking change; an optional one is additive.')
}).describe('Terms of an invitation: everything the candidate sees before deciding and before any contact is disclosed. The same schema is the request field of a draft and the stored snapshot of a terms version, so a response can be sent back unchanged. Every field is required; a field that may have no value says so with an explicit variant (`location` null for a remote role, a package item `not_provided`). The terms never contain data of the candidate: no contact, no salary minimum, and no indicator derived from it. The server checks the cross-field rules after the schema and answers 400 validation_failed with the pointer of the field: the salary rules of SalaryRange with `/terms/salary/salary_to`, a missing place of work for the `office` or `hybrid` format with `/terms/location`, and a repeated technology in `tech_stack` with the pointer of the later item.')
}).describe('New draft for one candidate. The candidate is named only by the handle from a search result of this organization, never by an email address, a phone number, or an account identifier. The terms are complete from the start, so a draft without the tax basis or the communication method cannot exist. Unknown fields are rejected, so a request cannot set the state, a version, a deadline, the salary indicator, contact access, or a candidate\'s minimum or contact.')
export type CreateOrganizationInvitationBody = zod.input<typeof CreateOrganizationInvitationBody>;
export type CreateOrganizationInvitationBodyOutput = zod.output<typeof CreateOrganizationInvitationBody>;
@@ -0,0 +1,19 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const createOrganizationInvitationHeadersIdempotencyKeyMax = 255;
export const createOrganizationInvitationHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const CreateOrganizationInvitationHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(createOrganizationInvitationHeadersIdempotencyKeyMax).regex(createOrganizationInvitationHeadersIdempotencyKeyRegExp)
})
export type CreateOrganizationInvitationHeaders = zod.input<typeof CreateOrganizationInvitationHeaders>;
export type CreateOrganizationInvitationHeadersOutput = zod.output<typeof CreateOrganizationInvitationHeaders>;
@@ -0,0 +1,22 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const declineMyInvitationBodyCommentOneMax = 500;
export const declineMyInvitationBodyCommentOneRegExp = new RegExp('\\S');
export const DeclineMyInvitationBody = zod.object({
"expected_version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
"reason": zod.enum(['salary', 'tasks', 'stack', 'work_format', 'package', 'company', 'not_looking', 'other_offer', 'other']).describe('Structured reason of a decline. Every reason is neutral and none requires a comment.\n\n- salary: the salary range does not fit.\n- tasks: the role or the tasks do not fit.\n- stack: the technologies do not fit.\n- work_format: the work format or the place of work does not fit.\n- package: the package does not fit.\n- company: the company or its domain does not fit.\n- not_looking: the candidate is not looking for a job now.\n- other_offer: the candidate accepted another offer.\n- other: another reason ("Другое"); a comment stays optional.\n\nThe organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change.'),
"comment": zod.union([zod.string().min(1).max(declineMyInvitationBodyCommentOneMax).regex(declineMyInvitationBodyCommentOneRegExp).describe('Optional comment of the candidate on the offer. It may contain line breaks and has at least one character that is not white space. It is never shown to the organization, never published, and never written to logs or notifications; only the candidate reads it back. Plain text; clients show it as text, never as HTML.'),zod.null()]).exactOptional().describe('Optional comment for any reason, including `other`; absent or null means none.')
}).describe('Structured decline: a reason and an optional comment. Unknown fields are rejected.')
export type DeclineMyInvitationBody = zod.input<typeof DeclineMyInvitationBody>;
export type DeclineMyInvitationBodyOutput = zod.output<typeof DeclineMyInvitationBody>;
@@ -0,0 +1,19 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const declineMyInvitationHeadersIdempotencyKeyMax = 255;
export const declineMyInvitationHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const DeclineMyInvitationHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(declineMyInvitationHeadersIdempotencyKeyMax).regex(declineMyInvitationHeadersIdempotencyKeyRegExp)
})
export type DeclineMyInvitationHeaders = zod.input<typeof DeclineMyInvitationHeaders>;
export type DeclineMyInvitationHeadersOutput = zod.output<typeof DeclineMyInvitationHeaders>;
@@ -0,0 +1,74 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
export * from './acceptMyInvitationBody.zod';
export * from './acceptMyInvitationHeaders.zod';
export * from './cancelMyInvitationBody.zod';
export * from './cancelMyInvitationHeaders.zod';
export * from './candidateHandle.zod';
export * from './candidateInvitation.zod';
export * from './candidateInvitationList.zod';
export * from './candidateInvitationSummary.zod';
export * from './contactAccessBlock.zod';
export * from './contactConsentAcceptance.zod';
export * from './contactConsentOffer.zod';
export * from './contactConsentText.zod';
export * from './contactDisclosure.zod';
export * from './contactFieldKind.zod';
export * from './contactFullName.zod';
export * from './contactGrant.zod';
export * from './contactGrantState.zod';
export * from './contactPhoneNumber.zod';
export * from './contactRevocationReason.zod';
export * from './contactTelegramUsername.zod';
export * from './createOrganizationInvitationBody.zod';
export * from './createOrganizationInvitationHeaders.zod';
export * from './declineMyInvitationBody.zod';
export * from './declineMyInvitationHeaders.zod';
export * from './invitationAcceptance.zod';
export * from './invitationCommand.zod';
export * from './invitationCommunicationChannel.zod';
export * from './invitationCommunicationMethod.zod';
export * from './invitationCommunicationNote.zod';
export * from './invitationContactAccess.zod';
export * from './invitationContactAccessState.zod';
export * from './invitationDeclineComment.zod';
export * from './invitationDeclineReason.zod';
export * from './invitationDeclineRecord.zod';
export * from './invitationDeclineRequest.zod';
export * from './invitationExpiryReason.zod';
export * from './invitationNeedReference.zod';
export * from './invitationOfferType.zod';
export * from './invitationOrganization.zod';
export * from './invitationPackage.zod';
export * from './invitationPackageItem.zod';
export * from './invitationPackageItemNotProvided.zod';
export * from './invitationPackageItemProvided.zod';
export * from './invitationPackageItemText.zod';
export * from './invitationResponsePeriod.zod';
export * from './invitationRoleTitle.zod';
export * from './invitationSalaryFit.zod';
export * from './invitationSalaryRaise.zod';
export * from './invitationState.zod';
export * from './invitationTeamDescription.zod';
export * from './invitationTerms.zod';
export * from './invitationTermsVersion.zod';
export * from './invitationVersion.zod';
export * from './listMyInvitationsParams.zod';
export * from './listOrganizationInvitationsParams.zod';
export * from './organizationInvitation.zod';
export * from './organizationInvitationCreate.zod';
export * from './organizationInvitationList.zod';
export * from './organizationInvitationSummary.zod';
export * from './organizationInvitationUpdate.zod';
export * from './raiseOrganizationInvitationSalaryBody.zod';
export * from './raiseOrganizationInvitationSalaryHeaders.zod';
export * from './sendOrganizationInvitationBody.zod';
export * from './sendOrganizationInvitationHeaders.zod';
export * from './updateOrganizationInvitationBody.zod';
export * from './withdrawOrganizationInvitationBody.zod';
export * from './withdrawOrganizationInvitationHeaders.zod';
@@ -0,0 +1,29 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const invitationAcceptanceConsentC4TextVersionMax = 64;
export const invitationAcceptanceConsentC4TextVersionRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const invitationAcceptanceConsentC4FieldsMax = 4;
export const InvitationAcceptance = zod.object({
"expected_version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
"terms_version": zod.int().min(1).describe('Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.').describe('Terms version that the candidate read and accepts. A version that is not the current one answers 412 version_conflict.'),
"consent_c4": zod.object({
"text_version": zod.string().min(1).max(invitationAcceptanceConsentC4TextVersionMax).regex(invitationAcceptanceConsentC4TextVersionRegExp).describe('Identifier of the published consent text that the user saw and accepted. The server stores the acceptance with this version and the hash of its text; the client never sends or receives the hash.'),
"accepted": zod.literal(true).describe('Explicit consent. Only true is valid.'),
"fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')).min(1).max(invitationAcceptanceConsentC4FieldsMax).describe('Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other.')
}).describe('Consent C4 given in an acceptance: the text version the candidate saw, an explicit `accepted`, and the contact fields the candidate selected. At least one field is required, so a hidden default or an empty choice never creates a grant. A text version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c4/text_version`, and a field that the profile does not hold answers 400 with the pointer of that item, such as `/consent_c4/fields/1`. C4 is given only here, never at registration. The permission to pass the selected data on to the organization\'s ATS (PRD C4 and FR19) is planned as an additive optional flag that defaults to no transfer.')
}).describe('Acceptance of the current terms with the consent C4. The client sends the `version` and the `terms_version` it read and the contact fields the candidate selected; nothing is preselected or defaulted. Unknown fields are rejected, so a request cannot carry contact values, a grant, or another consent.')
export type InvitationAcceptance = zod.input<typeof InvitationAcceptance>;
export type InvitationAcceptanceOutput = zod.output<typeof InvitationAcceptance>;
@@ -0,0 +1,16 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationCommand = zod.object({
"expected_version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.')
}).describe('Command without parameters over the invitation version the client read: send, withdraw, or cancel. Unknown fields are rejected.')
export type InvitationCommand = zod.input<typeof InvitationCommand>;
export type InvitationCommandOutput = zod.output<typeof InvitationCommand>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationCommunicationChannel = zod.enum(['email', 'phone', 'telegram', 'video_call']).describe('Channel through which the organization will contact the candidate after an acceptance.\n\n- email: a letter to the email address the candidate disclosed.\n- phone: a call or a text to the phone number the candidate disclosed.\n- telegram: a message to the Telegram username the candidate disclosed.\n- video_call: an invitation to a video call, sent through one of the disclosed contacts.\n\nThe channel describes the organization\'s plan; the candidate decides which contacts to disclose, and the server never requires that the disclosed fields include the channel.')
export type InvitationCommunicationChannel = zod.input<typeof InvitationCommunicationChannel>;
export type InvitationCommunicationChannelOutput = zod.output<typeof InvitationCommunicationChannel>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const invitationCommunicationMethodDetailsOneMax = 300;
export const invitationCommunicationMethodDetailsOneRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const InvitationCommunicationMethod = zod.object({
"channel": zod.enum(['email', 'phone', 'telegram', 'video_call']).describe('Channel through which the organization will contact the candidate after an acceptance.\n\n- email: a letter to the email address the candidate disclosed.\n- phone: a call or a text to the phone number the candidate disclosed.\n- telegram: a message to the Telegram username the candidate disclosed.\n- video_call: an invitation to a video call, sent through one of the disclosed contacts.\n\nThe channel describes the organization\'s plan; the candidate decides which contacts to disclose, and the server never requires that the disclosed fields include the channel.'),
"details": zod.union([zod.string().min(1).max(invitationCommunicationMethodDetailsOneMax).regex(invitationCommunicationMethodDetailsOneRegExp).describe('Short note on the communication method, for example "A 30-minute call with the team lead within three working days". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.'),zod.null()]).describe('Optional short note, for example the first step or the expected time of the first contact, or null. Plain text without line breaks; it never contains a link or a contact of an employee.')
}).describe('How the organization will contact the candidate after an acceptance. It is part of the terms, so the candidate sees it before choosing which contacts to disclose. An invitation without it cannot exist, because the terms require it.')
export type InvitationCommunicationMethod = zod.input<typeof InvitationCommunicationMethod>;
export type InvitationCommunicationMethodOutput = zod.output<typeof InvitationCommunicationMethod>;
@@ -0,0 +1,17 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationCommunicationNoteMax = 300;
export const InvitationCommunicationNoteRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const InvitationCommunicationNote = zod.string().min(1).max(InvitationCommunicationNoteMax).regex(InvitationCommunicationNoteRegExp).describe('Short note on the communication method, for example "A 30-minute call with the team lead within three working days". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
export type InvitationCommunicationNote = zod.input<typeof InvitationCommunicationNote>;
export type InvitationCommunicationNoteOutput = zod.output<typeof InvitationCommunicationNote>;
@@ -0,0 +1,18 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const invitationContactAccessFieldsMax = 4;
export const InvitationContactAccess = zod.object({
"status": zod.enum(['not_granted', 'available', 'closed']).describe('Whether the organization may read the candidate\'s contacts through GetOrganizationInvitationContacts now.\n\n- not_granted: the candidate has not accepted this invitation, so no grant exists.\n- available: a grant from this invitation is active and the current consent and visibility allow the read.\n- closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate\'s visibility allows the read, which only follows the candidate\'s own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization.'),
"fields": zod.array(zod.enum(['full_name', 'email', 'phone', 'telegram']).describe('Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another.\n\n- full_name: the full name from the profile.\n- email: the contact email address from the profile.\n- phone: the contact phone number from the profile.\n- telegram: the Telegram username from the profile.\n\nThe 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.')).max(invitationContactAccessFieldsMax).describe('Kinds of contact that the read returns while `status` is `available`; empty otherwise.')
}).describe('Contact access of the organization through this invitation, without any contact value. The values come only from GetOrganizationInvitationContacts.')
export type InvitationContactAccess = zod.input<typeof InvitationContactAccess>;
export type InvitationContactAccessOutput = zod.output<typeof InvitationContactAccess>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationContactAccessState = zod.enum(['not_granted', 'available', 'closed']).describe('Whether the organization may read the candidate\'s contacts through GetOrganizationInvitationContacts now.\n\n- not_granted: the candidate has not accepted this invitation, so no grant exists.\n- available: a grant from this invitation is active and the current consent and visibility allow the read.\n- closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate\'s visibility allows the read, which only follows the candidate\'s own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization.')
export type InvitationContactAccessState = zod.input<typeof InvitationContactAccessState>;
export type InvitationContactAccessStateOutput = zod.output<typeof InvitationContactAccessState>;
@@ -0,0 +1,17 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationDeclineCommentMax = 500;
export const InvitationDeclineCommentRegExp = new RegExp('\\S');
export const InvitationDeclineComment = zod.string().min(1).max(InvitationDeclineCommentMax).regex(InvitationDeclineCommentRegExp).describe('Optional comment of the candidate on the offer. It may contain line breaks and has at least one character that is not white space. It is never shown to the organization, never published, and never written to logs or notifications; only the candidate reads it back. Plain text; clients show it as text, never as HTML.')
export type InvitationDeclineComment = zod.input<typeof InvitationDeclineComment>;
export type InvitationDeclineCommentOutput = zod.output<typeof InvitationDeclineComment>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationDeclineReason = zod.enum(['salary', 'tasks', 'stack', 'work_format', 'package', 'company', 'not_looking', 'other_offer', 'other']).describe('Structured reason of a decline. Every reason is neutral and none requires a comment.\n\n- salary: the salary range does not fit.\n- tasks: the role or the tasks do not fit.\n- stack: the technologies do not fit.\n- work_format: the work format or the place of work does not fit.\n- package: the package does not fit.\n- company: the company or its domain does not fit.\n- not_looking: the candidate is not looking for a job now.\n- other_offer: the candidate accepted another offer.\n- other: another reason ("Другое"); a comment stays optional.\n\nThe organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change.')
export type InvitationDeclineReason = zod.input<typeof InvitationDeclineReason>;
export type InvitationDeclineReasonOutput = zod.output<typeof InvitationDeclineReason>;
@@ -0,0 +1,21 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const invitationDeclineRecordCommentOneMax = 500;
export const invitationDeclineRecordCommentOneRegExp = new RegExp('\\S');
export const InvitationDeclineRecord = zod.object({
"reason": zod.enum(['salary', 'tasks', 'stack', 'work_format', 'package', 'company', 'not_looking', 'other_offer', 'other']).describe('Structured reason of a decline. Every reason is neutral and none requires a comment.\n\n- salary: the salary range does not fit.\n- tasks: the role or the tasks do not fit.\n- stack: the technologies do not fit.\n- work_format: the work format or the place of work does not fit.\n- package: the package does not fit.\n- company: the company or its domain does not fit.\n- not_looking: the candidate is not looking for a job now.\n- other_offer: the candidate accepted another offer.\n- other: another reason ("Другое"); a comment stays optional.\n\nThe organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change.'),
"comment": zod.union([zod.string().min(1).max(invitationDeclineRecordCommentOneMax).regex(invitationDeclineRecordCommentOneRegExp).describe('Optional comment of the candidate on the offer. It may contain line breaks and has at least one character that is not white space. It is never shown to the organization, never published, and never written to logs or notifications; only the candidate reads it back. Plain text; clients show it as text, never as HTML.'),zod.null()]),
"declined_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('The candidate\'s own decline, as the candidate reads it back.')
export type InvitationDeclineRecord = zod.input<typeof InvitationDeclineRecord>;
export type InvitationDeclineRecordOutput = zod.output<typeof InvitationDeclineRecord>;
@@ -0,0 +1,22 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const invitationDeclineRequestCommentOneMax = 500;
export const invitationDeclineRequestCommentOneRegExp = new RegExp('\\S');
export const InvitationDeclineRequest = zod.object({
"expected_version": zod.int().min(1).describe('Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.'),
"reason": zod.enum(['salary', 'tasks', 'stack', 'work_format', 'package', 'company', 'not_looking', 'other_offer', 'other']).describe('Structured reason of a decline. Every reason is neutral and none requires a comment.\n\n- salary: the salary range does not fit.\n- tasks: the role or the tasks do not fit.\n- stack: the technologies do not fit.\n- work_format: the work format or the place of work does not fit.\n- package: the package does not fit.\n- company: the company or its domain does not fit.\n- not_looking: the candidate is not looking for a job now.\n- other_offer: the candidate accepted another offer.\n- other: another reason ("Другое"); a comment stays optional.\n\nThe organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change.'),
"comment": zod.union([zod.string().min(1).max(invitationDeclineRequestCommentOneMax).regex(invitationDeclineRequestCommentOneRegExp).describe('Optional comment of the candidate on the offer. It may contain line breaks and has at least one character that is not white space. It is never shown to the organization, never published, and never written to logs or notifications; only the candidate reads it back. Plain text; clients show it as text, never as HTML.'),zod.null()]).exactOptional().describe('Optional comment for any reason, including `other`; absent or null means none.')
}).describe('Structured decline: a reason and an optional comment. Unknown fields are rejected.')
export type InvitationDeclineRequest = zod.input<typeof InvitationDeclineRequest>;
export type InvitationDeclineRequestOutput = zod.output<typeof InvitationDeclineRequest>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationExpiryReason = zod.enum(['invitation_timeout', 'negotiation_timeout']).describe('Why an invitation expired. Set exactly when the state is `expired`, null otherwise.\n\n- invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created.\n- negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it.')
export type InvitationExpiryReason = zod.input<typeof InvitationExpiryReason>;
export type InvitationExpiryReasonOutput = zod.output<typeof InvitationExpiryReason>;
@@ -0,0 +1,17 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationNeedReference = zod.object({
"need_id": zod.uuid().describe('Identifier of a need of the organization in the path.'),
"requirements_version": zod.int().min(1).describe('Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version.').describe('`requirements_version` of the need that the invitation refers to; it must be a version that the need has had.')
}).describe('Need of the same organization that the invitation was built from, with the requirements version used. A direct invitation has no need. The link is informational: the invitation keeps its own terms, which may differ from the need, and a later change of the need never changes them.')
export type InvitationNeedReference = zod.input<typeof InvitationNeedReference>;
export type InvitationNeedReferenceOutput = zod.output<typeof InvitationNeedReference>;
@@ -0,0 +1,12 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationOfferType = zod.enum(['full_time', 'part_time', 'contract', 'internship']).describe('Type of the offer.\n\n- full_time: employment with a full working week.\n- part_time: employment with a part-time working week.\n- contract: a fixed-term or project contract outside employment.\n- internship: an internship.\n\nAdding a value is a contract change.')
export type InvitationOfferType = zod.input<typeof InvitationOfferType>;
export type InvitationOfferTypeOutput = zod.output<typeof InvitationOfferType>;
@@ -0,0 +1,18 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const invitationOrganizationNameMax = 200;
export const InvitationOrganization = zod.object({
"id": zod.uuid().describe('Identifier of the organization.'),
"name": zod.string().min(1).max(invitationOrganizationNameMax).describe('Public name of the organization. Plain text; clients show it as text, never as HTML.')
}).describe('Organization that sent the invitation, as the candidate sees it before deciding. The organization contract (TASK-077) adds the public card; this object only names it.')
export type InvitationOrganization = zod.input<typeof InvitationOrganization>;
export type InvitationOrganizationOutput = zod.output<typeof InvitationOrganization>;
@@ -0,0 +1,54 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const invitationPackageBonusOneDescriptionMax = 300;
export const invitationPackageBonusOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const invitationPackageEquipmentOneDescriptionMax = 300;
export const invitationPackageEquipmentOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const invitationPackageTrainingOneDescriptionMax = 300;
export const invitationPackageTrainingOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const invitationPackageHealthInsuranceOneDescriptionMax = 300;
export const invitationPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const InvitationPackage = zod.object({
"bonus": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(invitationPackageBonusOneDescriptionMax).regex(invitationPackageBonusOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.'),
"equipment": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(invitationPackageEquipmentOneDescriptionMax).regex(invitationPackageEquipmentOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.'),
"training": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(invitationPackageTrainingOneDescriptionMax).regex(invitationPackageTrainingOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.'),
"health_insurance": zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(invitationPackageHealthInsuranceOneDescriptionMax).regex(invitationPackageHealthInsuranceOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.')
}).describe('Required section of the package (PRD FR12): the bonus, the equipment, the training, and the voluntary health insurance (ДМС). Every field is required and is either provided with a description or explicitly not provided. The work format of the package is the required `work_formats` term, which has no "not provided" variant. Adding a required condition is a breaking change; an optional one is additive.')
export type InvitationPackage = zod.input<typeof InvitationPackage>;
export type InvitationPackageOutput = zod.output<typeof InvitationPackage>;
@@ -0,0 +1,22 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const invitationPackageItemOneDescriptionMax = 300;
export const invitationPackageItemOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const InvitationPackageItem = zod.union([zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(invitationPackageItemOneDescriptionMax).regex(invitationPackageItemOneDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.'),zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')]).describe('One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.')
export type InvitationPackageItem = zod.input<typeof InvitationPackageItem>;
export type InvitationPackageItemOutput = zod.output<typeof InvitationPackageItem>;
@@ -0,0 +1,14 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationPackageItemNotProvided = zod.object({
"status": zod.enum(['not_provided'])
}).describe('The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description.')
export type InvitationPackageItemNotProvided = zod.input<typeof InvitationPackageItemNotProvided>;
export type InvitationPackageItemNotProvidedOutput = zod.output<typeof InvitationPackageItemNotProvided>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const invitationPackageItemProvidedDescriptionMax = 300;
export const invitationPackageItemProvidedDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const InvitationPackageItemProvided = zod.object({
"status": zod.enum(['provided']),
"description": zod.string().min(1).max(invitationPackageItemProvidedDescriptionMax).regex(invitationPackageItemProvidedDescriptionRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
}).describe('The condition is part of the offer, with its description.')
export type InvitationPackageItemProvided = zod.input<typeof InvitationPackageItemProvided>;
export type InvitationPackageItemProvidedOutput = zod.output<typeof InvitationPackageItemProvided>;
@@ -0,0 +1,17 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const InvitationPackageItemTextMax = 300;
export const InvitationPackageItemTextRegExp = new RegExp('^\\S(?:.*\\S)?$');
export const InvitationPackageItemText = zod.string().min(1).max(InvitationPackageItemTextMax).regex(InvitationPackageItemTextRegExp).describe('Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML.')
export type InvitationPackageItemText = zod.input<typeof InvitationPackageItemText>;
export type InvitationPackageItemTextOutput = zod.output<typeof InvitationPackageItemText>;
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more