From d2c6f1375ac77a24e4148f5fb8b33ef9c97927ac Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 13:48:35 +0300 Subject: [PATCH] feat(api): add invitation, terms version, acceptance, and contact grant contract --- api/README.en.md | 108 +- api/README.md | 108 +- api/core/components/examples.yml | 1249 ++- api/core/components/parameters.yml | 24 + api/core/components/responses.yml | 106 +- api/core/components/schemas.yml | 1052 +- .../components/schemas/common_schemas.yml | 15 + .../schemas/contact_grant_schemas.yml | 279 + .../components/schemas/invitation_schemas.yml | 944 ++ .../components/schemas/support_schemas.yml | 2 +- api/core/openapi.bundle.yml | 3132 +++++- api/core/openapi.yml | 144 + api/core/routes/candidate_invitation.yml | 46 + .../routes/candidate_invitation_accept.yml | 69 + .../routes/candidate_invitation_cancel.yml | 63 + .../routes/candidate_invitation_decline.yml | 65 + api/core/routes/candidate_invitation_view.yml | 47 + api/core/routes/candidate_invitations.yml | 37 + api/core/routes/organization_invitation.yml | 106 + .../organization_invitation_contacts.yml | 43 + .../organization_invitation_salary_raise.yml | 65 + .../routes/organization_invitation_send.yml | 65 + .../organization_invitation_withdraw.yml | 62 + api/core/routes/organization_invitations.yml | 103 + api/core/routes/support_cases.yml | 4 +- .../adapter/primary/http/api/oas_cfg_gen.go | 2 + .../primary/http/api/oas_handlers_gen.go | 3562 ++++++- .../primary/http/api/oas_interfaces_gen.go | 56 + .../adapter/primary/http/api/oas_json_gen.go | 9126 +++++++++++++++++ .../primary/http/api/oas_operations_gen.go | 64 +- .../primary/http/api/oas_parameters_gen.go | 2136 ++++ .../http/api/oas_request_decoders_gen.go | 632 ++ .../http/api/oas_response_encoders_gen.go | 1702 +++ .../primary/http/api/oas_router_gen.go | 1067 +- .../primary/http/api/oas_schemas_gen.go | 4061 +++++++- .../primary/http/api/oas_security_gen.go | 75 +- .../primary/http/api/oas_server_gen.go | 500 +- .../primary/http/api/oas_unimplemented_gen.go | 542 +- .../primary/http/api/oas_validators_gen.go | 3163 ++++++ .../adapter/primary/http/problem/responder.go | 86 +- .../primary/http/problem/responder_test.go | 114 +- .../adapter/primary/http/router_test.go | 544 +- docs/en/ARCHITECTURE.md | 2 +- docs/ru/ARCHITECTURE.md | 2 +- .../src/shared/api/endpoints/index.msw.ts | 1 + frontend/src/shared/api/endpoints/index.ts | 1 + .../endpoints/invitation/invitation.msw.ts | 337 + .../api/endpoints/invitation/invitation.ts | 1520 +++ .../shared/api/endpoints/support/support.ts | 4 +- .../shared/api/invitation-contract.test.ts | 464 + .../{identity => }/consentTextVersion.zod.ts | 0 .../schemas/{need => }/currencyCode.zod.ts | 0 .../{identity => }/emailAddress.zod.ts | 0 .../src/shared/api/schemas/identity/index.ts | 2 - frontend/src/shared/api/schemas/index.ts | 12 + .../invitation/acceptMyInvitationBody.zod.ts | 29 + .../acceptMyInvitationHeaders.zod.ts | 19 + .../invitation/cancelMyInvitationBody.zod.ts | 16 + .../cancelMyInvitationHeaders.zod.ts | 19 + .../schemas/invitation/candidateHandle.zod.ts | 17 + .../invitation/candidateInvitation.zod.ts | 177 + .../invitation/candidateInvitationList.zod.ts | 66 + .../candidateInvitationSummary.zod.ts | 54 + .../invitation/contactAccessBlock.zod.ts | 12 + .../contactConsentAcceptance.zod.ts | 23 + .../invitation/contactConsentOffer.zod.ts | 27 + .../invitation/contactConsentText.zod.ts | 22 + .../invitation/contactDisclosure.zod.ts | 41 + .../invitation/contactFieldKind.zod.ts | 12 + .../schemas/invitation/contactFullName.zod.ts | 17 + .../schemas/invitation/contactGrant.zod.ts | 31 + .../invitation/contactGrantState.zod.ts | 12 + .../invitation/contactPhoneNumber.zod.ts | 18 + .../invitation/contactRevocationReason.zod.ts | 12 + .../invitation/contactTelegramUsername.zod.ts | 18 + .../createOrganizationInvitationBody.zod.ts | 127 + ...createOrganizationInvitationHeaders.zod.ts | 19 + .../invitation/declineMyInvitationBody.zod.ts | 22 + .../declineMyInvitationHeaders.zod.ts | 19 + .../shared/api/schemas/invitation/index.ts | 74 + .../invitation/invitationAcceptance.zod.ts | 29 + .../invitation/invitationCommand.zod.ts | 16 + .../invitationCommunicationChannel.zod.ts | 12 + .../invitationCommunicationMethod.zod.ts | 20 + .../invitationCommunicationNote.zod.ts | 17 + .../invitation/invitationContactAccess.zod.ts | 18 + .../invitationContactAccessState.zod.ts | 12 + .../invitationDeclineComment.zod.ts | 17 + .../invitation/invitationDeclineReason.zod.ts | 12 + .../invitation/invitationDeclineRecord.zod.ts | 21 + .../invitationDeclineRequest.zod.ts | 22 + .../invitation/invitationExpiryReason.zod.ts | 12 + .../invitation/invitationNeedReference.zod.ts | 17 + .../invitation/invitationOfferType.zod.ts | 12 + .../invitation/invitationOrganization.zod.ts | 18 + .../invitation/invitationPackage.zod.ts | 54 + .../invitation/invitationPackageItem.zod.ts | 22 + .../invitationPackageItemNotProvided.zod.ts | 14 + .../invitationPackageItemProvided.zod.ts | 20 + .../invitationPackageItemText.zod.ts | 17 + .../invitationResponsePeriod.zod.ts | 12 + .../invitation/invitationRoleTitle.zod.ts | 17 + .../invitation/invitationSalaryFit.zod.ts | 12 + .../invitation/invitationSalaryRaise.zod.ts | 21 + .../schemas/invitation/invitationState.zod.ts | 12 + .../invitationTeamDescription.zod.ts | 17 + .../schemas/invitation/invitationTerms.zod.ts | 114 + .../invitation/invitationTermsVersion.zod.ts | 14 + .../invitation/invitationVersion.zod.ts | 14 + .../invitation/listMyInvitationsParams.zod.ts | 23 + .../listOrganizationInvitationsParams.zod.ts | 23 + .../invitation/organizationInvitation.zod.ts | 149 + .../organizationInvitationCreate.zod.ts | 127 + .../organizationInvitationList.zod.ts | 72 + .../organizationInvitationSummary.zod.ts | 60 + .../organizationInvitationUpdate.zod.ts | 124 + ...iseOrganizationInvitationSalaryBody.zod.ts | 21 + ...OrganizationInvitationSalaryHeaders.zod.ts | 19 + .../sendOrganizationInvitationBody.zod.ts | 16 + .../sendOrganizationInvitationHeaders.zod.ts | 19 + .../updateOrganizationInvitationBody.zod.ts | 124 + .../withdrawOrganizationInvitationBody.zod.ts | 16 + ...thdrawOrganizationInvitationHeaders.zod.ts | 19 + frontend/src/shared/api/schemas/need/index.ts | 9 - .../{need => }/needLocationName.zod.ts | 0 .../schemas/{need => }/needTaskText.zod.ts | 0 .../api/schemas/{need => }/needVersion.zod.ts | 0 .../api/schemas/{need => }/rubAmount.zod.ts | 0 .../schemas/{need => }/salaryPeriod.zod.ts | 0 .../api/schemas/{need => }/salaryRange.zod.ts | 0 .../schemas/{need => }/salaryTaxBasis.zod.ts | 0 .../api/schemas/{need => }/skillName.zod.ts | 0 .../support/createMySupportCaseBody.zod.ts | 2 +- .../api/schemas/support/supportCase.zod.ts | 2 +- .../schemas/support/supportCaseCreate.zod.ts | 2 +- .../support/supportCaseCreateSupport.zod.ts | 2 +- .../schemas/support/supportCaseList.zod.ts | 2 +- .../support/supportCaseObjectReference.zod.ts | 2 +- .../support/supportCaseObjectType.zod.ts | 2 +- .../schemas/support/supportCaseSummary.zod.ts | 2 +- 140 files changed, 39767 insertions(+), 303 deletions(-) create mode 100644 api/core/components/schemas/contact_grant_schemas.yml create mode 100644 api/core/components/schemas/invitation_schemas.yml create mode 100644 api/core/routes/candidate_invitation.yml create mode 100644 api/core/routes/candidate_invitation_accept.yml create mode 100644 api/core/routes/candidate_invitation_cancel.yml create mode 100644 api/core/routes/candidate_invitation_decline.yml create mode 100644 api/core/routes/candidate_invitation_view.yml create mode 100644 api/core/routes/candidate_invitations.yml create mode 100644 api/core/routes/organization_invitation.yml create mode 100644 api/core/routes/organization_invitation_contacts.yml create mode 100644 api/core/routes/organization_invitation_salary_raise.yml create mode 100644 api/core/routes/organization_invitation_send.yml create mode 100644 api/core/routes/organization_invitation_withdraw.yml create mode 100644 api/core/routes/organization_invitations.yml create mode 100644 frontend/src/shared/api/endpoints/invitation/invitation.msw.ts create mode 100644 frontend/src/shared/api/endpoints/invitation/invitation.ts create mode 100644 frontend/src/shared/api/invitation-contract.test.ts rename frontend/src/shared/api/schemas/{identity => }/consentTextVersion.zod.ts (100%) rename frontend/src/shared/api/schemas/{need => }/currencyCode.zod.ts (100%) rename frontend/src/shared/api/schemas/{identity => }/emailAddress.zod.ts (100%) create mode 100644 frontend/src/shared/api/schemas/invitation/acceptMyInvitationBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/acceptMyInvitationHeaders.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/cancelMyInvitationBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/cancelMyInvitationHeaders.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/candidateHandle.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/candidateInvitation.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/candidateInvitationList.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/candidateInvitationSummary.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactAccessBlock.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactConsentAcceptance.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactConsentOffer.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactConsentText.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactDisclosure.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactFieldKind.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactFullName.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactGrant.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactGrantState.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactPhoneNumber.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactRevocationReason.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/contactTelegramUsername.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/createOrganizationInvitationBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/createOrganizationInvitationHeaders.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/declineMyInvitationBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/declineMyInvitationHeaders.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/index.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationAcceptance.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationCommand.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationCommunicationChannel.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationCommunicationMethod.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationCommunicationNote.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationContactAccess.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationContactAccessState.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationDeclineComment.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationDeclineReason.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationDeclineRecord.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationDeclineRequest.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationExpiryReason.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationNeedReference.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationOfferType.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationOrganization.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationPackage.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationPackageItem.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationPackageItemNotProvided.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationPackageItemProvided.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationPackageItemText.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationResponsePeriod.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationRoleTitle.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationSalaryFit.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationSalaryRaise.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationState.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationTeamDescription.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationTerms.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationTermsVersion.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/invitationVersion.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/listMyInvitationsParams.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/listOrganizationInvitationsParams.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/organizationInvitation.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/organizationInvitationCreate.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/organizationInvitationList.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/organizationInvitationSummary.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/organizationInvitationUpdate.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/raiseOrganizationInvitationSalaryBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/raiseOrganizationInvitationSalaryHeaders.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/sendOrganizationInvitationBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/sendOrganizationInvitationHeaders.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/updateOrganizationInvitationBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/withdrawOrganizationInvitationBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/invitation/withdrawOrganizationInvitationHeaders.zod.ts rename frontend/src/shared/api/schemas/{need => }/needLocationName.zod.ts (100%) rename frontend/src/shared/api/schemas/{need => }/needTaskText.zod.ts (100%) rename frontend/src/shared/api/schemas/{need => }/needVersion.zod.ts (100%) rename frontend/src/shared/api/schemas/{need => }/rubAmount.zod.ts (100%) rename frontend/src/shared/api/schemas/{need => }/salaryPeriod.zod.ts (100%) rename frontend/src/shared/api/schemas/{need => }/salaryRange.zod.ts (100%) rename frontend/src/shared/api/schemas/{need => }/salaryTaxBasis.zod.ts (100%) rename frontend/src/shared/api/schemas/{need => }/skillName.zod.ts (100%) diff --git a/api/README.en.md b/api/README.en.md index e20643d..7cf35e2 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -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 ""` 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/`. 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`, 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 diff --git a/api/README.md b/api/README.md index 92c24ba..8bbf9be 100644 --- a/api/README.md +++ b/api/README.md @@ -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 ""` через 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/`. Согласие аналогично принятию 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`, которое различает отсутствие (`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`, которое решения потребности используют с другими границами. #### Объединения форматов diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index 4d03267..35802fa 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -1948,7 +1948,7 @@ NeedSalaryRangeTooWide: message: The value does not match the contract. NeedSalaryWithoutTaxBasis: summary: A salary range without its tax basis - description: The decoder does not record the path of a missing field in a nested object, so the pointer is the whole body. + description: The responder rebuilds the path of a missing nested field from the decoder, so the pointer names the missing field. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -1958,9 +1958,9 @@ NeedSalaryWithoutTaxBasis: trace_id: 7c8d9e0f-1a2b-4c3d-9e4f-5a6b7c8d9e0a errors: - in: body - pointer: "" - code: invalid - message: The value does not match the contract. + pointer: /salary/value/tax_basis + code: required + message: The value is required. NeedExtractedValueMismatch: summary: Status extracted with a value that is not the stored suggestion description: A request may keep only the stored suggestion unconfirmed. To set another value, it sends status confirmed. @@ -1978,7 +1978,7 @@ NeedExtractedValueMismatch: message: The value does not match the contract. NeedUnknownField: summary: The client sent its own recommendation score - description: Recommendations, membership, and candidate minimums are never request fields; any unknown field fails validation. + description: Recommendations, membership, and candidate minimums are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -2224,7 +2224,7 @@ SupportCaseBlankDescription: message: The value does not match the contract. SupportCaseUnknownType: summary: The case type is not one of the five types - description: The variant is selected by `type` before a field path is recorded, so the pointer is the whole body. + description: An unknown discriminator of the top-level oneOf concerns the whole body, so the pointer is empty. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -2239,7 +2239,7 @@ SupportCaseUnknownType: message: The value does not match the contract. SupportCaseUnknownField: summary: The client sent its own status or decision - description: Status, decision, moderator, priority, and response target are never request fields; any unknown field fails validation. + description: Status, decision, moderator, priority, and response target are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -2254,7 +2254,7 @@ SupportCaseUnknownField: message: The value does not match the contract. SupportCaseMalformedReference: summary: The object identifier is not a UUID - description: The decoder rejects the identifier inside the selected variant without recording its path, so the pointer is the whole body. + description: The decoder rejects the identifier inside the selected variant, and the pointer names it. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -2264,7 +2264,7 @@ SupportCaseMalformedReference: trace_id: 0f1a2b3c-4d5e-4f6a-9b7c-8d9e0f1a2b3c errors: - in: body - pointer: "" + pointer: /object/id code: invalid message: The value does not match the contract. SupportCaseComplaintNeedsInvitation: @@ -2290,3 +2290,1234 @@ SupportCaseAppealExists: code: state_conflict detail: The resource is in a state that does not allow this operation. trace_id: 9e0f1a2b-3c4d-4e5f-8a6b-7c8d9e0f1a2b +InvitationCreateFromNeed: + summary: A draft for a candidate from the search results of a need + description: "Every term is present: net salary range, communication method, and each package condition, provided or explicitly not provided." + value: + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + response_period_days: 7 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: not_provided + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока +InvitationUpdateTerms: + summary: The draft gets the training condition; the terms are sent complete + value: + expected_version: 1 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока +InvitationSendCommand: + summary: Send the draft that the client read as version 2 + value: + expected_version: 2 +InvitationSalaryRaiseCommand: + summary: The one raise of the upper bound from 260000 to 280000 net + value: + expected_version: 4 + salary_to: 280000 +InvitationWithdrawCommand: + summary: Withdraw the invitation that the client read as version 3 + value: + expected_version: 3 +InvitationAcceptEmailOnly: + summary: Accept terms version 3 and disclose only the email address + value: + expected_version: 5 + terms_version: 3 + consent_c4: + text_version: c4-2026-10-01 + accepted: true + fields: + - email +InvitationAcceptStaleTerms: + summary: Accept terms version 2 after the organization raised the salary + description: The candidate read version 4 with terms version 2; the raise made version 5 with terms version 3, so the server answers 412. + value: + expected_version: 4 + terms_version: 2 + consent_c4: + text_version: c4-2026-10-01 + accepted: true + fields: + - email + - phone +InvitationDeclineOther: + summary: Decline with the neutral reason other and no comment + value: + expected_version: 4 + reason: other +InvitationDeclineWithComment: + summary: Decline with a reason and an optional comment + value: + expected_version: 4 + reason: work_format + comment: Ищу только полностью удаленную работу. +InvitationCancelCommand: + summary: Cancel the participation after the acceptance + value: + expected_version: 6 +OrganizationInvitationDraft: + summary: A new draft, version 1 with terms version 1 + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: draft + expiry_reason: null + version: 1 + terms_version: 1 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: not_provided + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: null + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:00:00Z" + delivered_at: null + viewed_at: null + responded_at: null +OrganizationInvitationDraftUpdated: + summary: The draft after the terms change, version 2 with terms version 2 + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: draft + expiry_reason: null + version: 2 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: null + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:20:00Z" + delivered_at: null + viewed_at: null + responded_at: null +OrganizationInvitationDelivered: + summary: The invitation in the candidate's inbox with a seven-day deadline + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: delivered + expiry_reason: null + version: 3 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: "2026-10-13T09:30:00Z" + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: null + responded_at: null +OrganizationInvitationSalaryRaised: + summary: "The viewed invitation after the one raise of the upper bound: terms version 3" + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: viewed + expiry_reason: null + version: 5 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: "2026-10-13T09:30:00Z" + salary_raise_used: true + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T14:00:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: null +OrganizationInvitationAccepted: + summary: "The accepted invitation: the email address is readable through the contacts operation" + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + 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" +OrganizationInvitationWithdrawn: + summary: The invitation withdrawn by the organization before an answer + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: withdrawn + expiry_reason: null + version: 4 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: "2026-10-13T09:30:00Z" + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T11:00:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: null + responded_at: null +OrganizationInvitationListPage: + summary: The last page of the invitations of an organization + description: The organization sees that the second invitation was declined, but not the reason or the comment. + value: + items: + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + response_deadline_at: "2026-10-13T09:30:00Z" + contact_access: + status: available + fields: + - email + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T15:00:00Z" + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + candidate_handle: cand_Hx3Tn8Wq1Ys6Fd2Vb + need: null + state: declined + expiry_reason: null + version: 4 + terms_version: 1 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + response_deadline_at: "2026-10-08T10:00:00Z" + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-05T09:00:00Z" + updated_at: "2026-10-06T08:00:00Z" + page: + has_more: false + next_cursor: null +CandidateInvitationDelivered: + summary: The delivered invitation as GetMyInvitation reads it, before a view is recorded + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: delivered + expiry_reason: null + version: 3 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + 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-06T09:30:00Z" + contact_consent: + text: + text_version: c4-2026-10-01 + text: Я разрешаю передать ООО Пример Платежи выбранные мной контактные данные для связи по этому приглашению. Согласие можно отозвать в любой момент в разделе согласий. + available_fields: + - full_name + - email + - phone + decline: null + contact_grant: null +CandidateInvitationViewed: + summary: The terms after ViewMyInvitation, with the C4 choice and no contact + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: viewed + expiry_reason: null + version: 4 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: null + updated_at: "2026-10-06T12:00:00Z" + contact_consent: + text: + text_version: c4-2026-10-01 + text: Я разрешаю передать ООО Пример Платежи выбранные мной контактные данные для связи по этому приглашению. Согласие можно отозвать в любой момент в разделе согласий. + available_fields: + - full_name + - email + - phone + decline: null + contact_grant: null +CandidateInvitationAcceptedVisibilityBlocked: + summary: "Accepted while the profile is hidden from the organization: the grant is active but not readable" + description: The acceptance never lifts the hiding or publishes the profile. The organization sees contact_access closed without the reason. + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: "2026-10-06T15:00:00Z" + updated_at: "2026-10-06T15:00:00Z" + contact_consent: null + decline: null + contact_grant: + 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 +CandidateInvitationAccepted: + summary: The accepted invitation with the grant for the email address only + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: "2026-10-06T15:00:00Z" + updated_at: "2026-10-06T15:00:00Z" + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: active + readable: true + blocked_by: null + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: "2026-10-06T15:00:00Z" + revoked_at: null + revocation_reason: null +CandidateInvitationDeclined: + summary: The declined invitation with the candidate's own reason + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: declined + expiry_reason: null + version: 5 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: "2026-10-06T16:00:00Z" + updated_at: "2026-10-06T16:00:00Z" + contact_consent: null + decline: + reason: other + comment: null + declined_at: "2026-10-06T16:00:00Z" + contact_grant: null +CandidateInvitationCancelled: + summary: The participation cancelled after the acceptance; the grant of this invitation is revoked + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: cancelled_by_candidate + expiry_reason: null + version: 7 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: "2026-10-06T15:00:00Z" + updated_at: "2026-10-07T10:00:00Z" + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: revoked + readable: false + blocked_by: null + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: "2026-10-06T15:00:00Z" + revoked_at: "2026-10-07T10:00:00Z" + revocation_reason: participation_cancelled +CandidateInvitationListPage: + summary: The last page of the candidate's inbox + value: + items: + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: viewed + expiry_reason: null + version: 4 + terms_version: 2 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + work_formats: + - remote + - hybrid + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + updated_at: "2026-10-06T12:00:00Z" + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: expired + expiry_reason: invitation_timeout + version: 3 + terms_version: 1 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + work_formats: + - remote + - hybrid + response_deadline_at: "2026-10-04T10:00:00Z" + delivered_at: "2026-10-01T10:00:00Z" + viewed_at: null + updated_at: "2026-10-04T10:00:00Z" + page: + has_more: false + next_cursor: null +InvitationContactsEmailOnly: + summary: Synthetic contacts through a grant that covers only the email address + description: Every field the grant does not cover is null. The values are synthetic. + value: + 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 +InvitationWithoutTaxBasis: + summary: A salary range without its tax basis + description: The tax basis is a required field of SalaryRange; the pointer names the missing nested field. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 1f2a3b4c-5d6e-4f7a-8b9c-0d1e2f3a4b5c + errors: + - in: body + pointer: /terms/salary/tax_basis + code: required + message: The value is required. +InvitationWithoutCommunicationMethod: + summary: Terms without the communication method + description: The communication method is a required term; the pointer names the missing nested field. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d + errors: + - in: body + pointer: /terms/communication_method + code: required + message: The value is required. +InvitationPackageItemMissing: + summary: A package without the training condition + description: "Not providing a condition is the explicit item {status: not_provided}; leaving it out is a missing required field." + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 3b4c5d6e-7f8a-4b9c-8d0e-2f3a4b5c6d7e + errors: + - in: body + pointer: /terms/package/training + code: required + message: The value is required. +InvitationSalaryRangeTooWide: + summary: A salary range wider than 40% of its midpoint + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 4c5d6e7f-8a9b-4c0d-9e1f-3a4b5c6d7e8f + errors: + - in: body + pointer: /terms/salary/salary_to + code: invalid + message: The value does not match the contract. +InvitationLocationRequired: + summary: The hybrid format without a place of work + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 5d6e7f8a-9b0c-4d1e-8f2a-4b5c6d7e8f9a + errors: + - in: body + pointer: /terms/location + code: invalid + message: The value does not match the contract. +InvitationUnknownCandidate: + summary: A candidate handle that this organization cannot use + description: An unknown handle, a handle of another organization, and a profile that is no longer visible to the organization get the same answer. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-5c6d7e8f9a0b + errors: + - in: body + pointer: /candidate_handle + code: invalid + message: The value does not match the contract. +InvitationCandidateDataInBody: + summary: The request carried a candidate's email address or salary minimum + description: Contacts and minimums are never request fields; any unknown field fails validation, and an unknown top-level field such as candidate_email points at the whole body. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 7f8a9b0c-1d2e-4f3a-8b4c-6d7e8f9a0b1c + errors: + - in: body + pointer: "" + code: invalid + message: The value does not match the contract. +InvitationConsentWithoutFields: + summary: An acceptance with an empty choice of contact fields + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 8a9b0c1d-2e3f-4a4b-9c5d-7e8f9a0b1c2d + errors: + - in: body + pointer: /consent_c4/fields + code: invalid + message: The value does not match the contract. +InvitationConsentTextOutdated: + summary: An acceptance of a C4 text version that is no longer published + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 9b0c1d2e-3f4a-4b5c-8d6e-8f9a0b1c2d3e + errors: + - in: body + pointer: /consent_c4/text_version + code: invalid + message: The value does not match the contract. +InvitationMissingTermsVersion: + summary: An acceptance without terms_version + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 0c1d2e3f-4a5b-4c6d-9e7f-9a0b1c2d3e4f + errors: + - in: body + pointer: /terms_version + code: required + message: The value is required. +InvitationStaleTerms: + summary: The acceptance named a terms version that is no longer current + description: The organization raised the salary after the candidate read the terms. Nothing changed and no consent or grant was recorded; the client reads the invitation again and shows the new terms for a new decision. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 1d2e3f4a-5b6c-4d7e-8f8a-0b1c2d3e4f5a +InvitationStaleVersion: + summary: The command carried a stale expected_version + description: The invitation changed after the client read it. Nothing changed; the client reads the invitation again. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 2e3f4a5b-6c7d-4e8f-9a9b-1c2d3e4f5a6b +InvitationNotAnswerable: + summary: The invitation no longer accepts an answer + description: For example, it was withdrawn, it expired, or the deadline has passed. + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 3f4a5b6c-7d8e-4f9a-8b0c-2d3e4f5a6b7c +InvitationSalaryRaiseUsed: + summary: The upper bound of this invitation was already raised once + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 4a5b6c7d-8e9f-4a0b-9c1d-3e4f5a6b7c8d +InvitationSendBlocked: + summary: The send is blocked by the pending limit of the need or the pause after a decline + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 5b6c7d8e-9f0a-4b1c-8d2e-4f5a6b7c8d9e diff --git a/api/core/components/parameters.yml b/api/core/components/parameters.yml index 938e03a..ff4e6ce 100644 --- a/api/core/components/parameters.yml +++ b/api/core/components/parameters.yml @@ -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 diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index d13a447..846e0bd 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -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 diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 3427493..78ebf58 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -23,6 +23,14 @@ PageInfo: maxLength: 512 pattern: ^[A-Za-z0-9_-]+$ 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 AssessmentMode: type: string description: 'Measurement method of an attempt. The server selects it from the published task bank of the category; the client never chooses it. @@ -1387,6 +1395,243 @@ SpecializationCatalog: description: Grade scale in ascending order. items: $ref: '#/CatalogGrade' +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: '#/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: '#/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: '#/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: '#/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: '#/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: '#/ContactFieldKind' + status: + $ref: '#/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: '#/ContactAccessBlock' + - type: 'null' + terms_version: + description: Terms version of the invitation that the acceptance accepted. + allOf: + - $ref: '#/InvitationTermsVersion' + consent_text_version: + description: Version of the consent C4 text that the candidate accepted. + allOf: + - $ref: '#/ConsentTextVersion' + granted_at: + $ref: '#/Timestamp' + revoked_at: + description: Moment of the revocation, or null while the grant is active. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + revocation_reason: + description: Reason of the revocation, or null while the grant is active. + oneOf: + - $ref: '#/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: '#/ContactFieldKind' + granted_at: + $ref: '#/Timestamp' + full_name: + oneOf: + - $ref: '#/ContactFullName' + - type: 'null' + email: + oneOf: + - $ref: '#/EmailAddress' + - type: 'null' + phone: + oneOf: + - $ref: '#/ContactPhoneNumber' + - type: 'null' + telegram: + oneOf: + - $ref: '#/ContactTelegramUsername' + - type: 'null' HealthResponse: type: object additionalProperties: false @@ -1624,6 +1869,811 @@ Session: $ref: '#/Account' csrf_token: $ref: '#/CsrfToken' +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: '#/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: '#/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: '#/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: '#/InvitationPackageItemProvided' + - $ref: '#/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: '#/InvitationPackageItem' + equipment: + $ref: '#/InvitationPackageItem' + training: + $ref: '#/InvitationPackageItem' + health_insurance: + $ref: '#/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: '#/InvitationRoleTitle' + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' + offer_type: + $ref: '#/InvitationOfferType' + tasks: + type: array + minItems: 1 + maxItems: 20 + description: Work tasks of the role in the order given. + items: + $ref: '#/NeedTaskText' + team: + $ref: '#/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: '#/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: '#/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: '#/NeedLocationName' + - type: 'null' + communication_method: + $ref: '#/InvitationCommunicationMethod' + salary: + $ref: '#/SalaryRange' + package: + $ref: '#/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: '#/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: '#/InvitationContactAccessState' + fields: + type: array + maxItems: 4 + uniqueItems: true + description: Kinds of contact that the read returns while `status` is `available`; empty otherwise. + items: + $ref: '#/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: '#/InvitationDeclineReason' + comment: + oneOf: + - $ref: '#/InvitationDeclineComment' + - type: 'null' + declined_at: + $ref: '#/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: '#/CandidateHandle' + need: + description: Need the invitation was built from, or null for a direct invitation. + oneOf: + - $ref: '#/InvitationNeedReference' + - type: 'null' + state: + $ref: '#/InvitationState' + expiry_reason: + description: Reason of an expiry, or null unless `state` is `expired`. + oneOf: + - $ref: '#/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/InvitationVersion' + terms_version: + $ref: '#/InvitationTermsVersion' + terms: + $ref: '#/InvitationTerms' + response_period_days: + $ref: '#/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: '#/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: '#/InvitationSalaryFit' + contact_access: + $ref: '#/InvitationContactAccess' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' + delivered_at: + description: Moment of delivery to the candidate's inbox, or null for a draft. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + viewed_at: + description: Moment when the candidate first opened the terms, or null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + responded_at: + description: Moment of the candidate's acceptance or decline, or null. + oneOf: + - $ref: '#/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: '#/CandidateHandle' + need: + oneOf: + - $ref: '#/InvitationNeedReference' + - type: 'null' + state: + $ref: '#/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/InvitationVersion' + terms_version: + $ref: '#/InvitationTermsVersion' + role_title: + $ref: '#/InvitationRoleTitle' + salary: + $ref: '#/SalaryRange' + response_deadline_at: + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + contact_access: + $ref: '#/InvitationContactAccess' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/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: '#/OrganizationInvitationSummary' + page: + $ref: '#/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: '#/CandidateHandle' + need: + description: Need of the organization the invitation is built from, or null or absent for a direct invitation. + oneOf: + - $ref: '#/InvitationNeedReference' + - type: 'null' + response_period_days: + description: Days to answer; absent means 7, the default of the product policy. + allOf: + - $ref: '#/InvitationResponsePeriod' + terms: + $ref: '#/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: '#/InvitationVersion' + need: + oneOf: + - $ref: '#/InvitationNeedReference' + - type: 'null' + response_period_days: + $ref: '#/InvitationResponsePeriod' + terms: + $ref: '#/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: '#/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: '#/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: '#/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: '#/InvitationOrganization' + state: + $ref: '#/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/InvitationVersion' + terms_version: + $ref: '#/InvitationTermsVersion' + terms: + $ref: '#/InvitationTerms' + response_deadline_at: + $ref: '#/Timestamp' + delivered_at: + $ref: '#/Timestamp' + viewed_at: + description: Moment of the first view recorded by ViewMyInvitation, or null when the candidate has not opened the terms. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + responded_at: + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + updated_at: + $ref: '#/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: '#/ContactConsentOffer' + - type: 'null' + decline: + description: The candidate's decline, or null unless `state` is `declined`. + oneOf: + - $ref: '#/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: '#/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: '#/InvitationOrganization' + state: + $ref: '#/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/InvitationVersion' + terms_version: + $ref: '#/InvitationTermsVersion' + role_title: + $ref: '#/InvitationRoleTitle' + salary: + $ref: '#/SalaryRange' + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/WorkFormat' + response_deadline_at: + $ref: '#/Timestamp' + delivered_at: + $ref: '#/Timestamp' + viewed_at: + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + updated_at: + $ref: '#/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: '#/CandidateInvitationSummary' + page: + $ref: '#/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: '#/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: '#/InvitationTermsVersion' + consent_c4: + $ref: '#/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: '#/InvitationVersion' + reason: + $ref: '#/InvitationDeclineReason' + comment: + description: Optional comment for any reason, including `other`; absent or null means none. + oneOf: + - $ref: '#/InvitationDeclineComment' + - type: 'null' NeedVersion: type: integer format: int64 @@ -2884,7 +3934,7 @@ SupportCaseObjectType: - 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: diff --git a/api/core/components/schemas/common_schemas.yml b/api/core/components/schemas/common_schemas.yml index 9bace9a..b340ecc 100644 --- a/api/core/components/schemas/common_schemas.yml +++ b/api/core/components/schemas/common_schemas.yml @@ -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 diff --git a/api/core/components/schemas/contact_grant_schemas.yml b/api/core/components/schemas/contact_grant_schemas.yml new file mode 100644 index 0000000..c0935ae --- /dev/null +++ b/api/core/components/schemas/contact_grant_schemas.yml @@ -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" diff --git a/api/core/components/schemas/invitation_schemas.yml b/api/core/components/schemas/invitation_schemas.yml new file mode 100644 index 0000000..6596a44 --- /dev/null +++ b/api/core/components/schemas/invitation_schemas.yml @@ -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" diff --git a/api/core/components/schemas/support_schemas.yml b/api/core/components/schemas/support_schemas.yml index 762230a..6c0972a 100644 --- a/api/core/components/schemas/support_schemas.yml +++ b/api/core/components/schemas/support_schemas.yml @@ -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 diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index e63c66f..100d676 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -19,6 +19,8 @@ tags: description: 'Assessment attempts of the current candidate: availability, start and resume, answers and the code practice, finalization, and the result. Answers, keys, and attempt history are visible only to the candidate.' - name: need description: 'Hiring needs of an organization: requirements with their confirmation 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 of a grade or an anti-cheat decision, and manual assessment requests. The author sees the number, the status, the response target, the decision, and the public history; moderators and internal notes stay hidden.' paths: @@ -1042,6 +1044,771 @@ paths: $ref: '#/components/responses/TooManyRequests' default: $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations: + 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/OrganizationId' + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the invitations of the organization. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitationList' + examples: + last_page: + $ref: '#/components/examples/OrganizationInvitationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/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/OrganizationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitationCreate' + examples: + valid_invitation: + $ref: '#/components/examples/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/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + draft: + $ref: '#/components/examples/OrganizationInvitationDraft' + '400': + $ref: '#/components/responses/InvitationValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/IdempotencyInProgress' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}: + 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/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + responses: + '200': + description: The invitation in its current state. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + draft: + $ref: '#/components/examples/OrganizationInvitationDraft' + delivered: + $ref: '#/components/examples/OrganizationInvitationDelivered' + accepted: + $ref: '#/components/examples/OrganizationInvitationAccepted' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/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/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitationUpdate' + examples: + change_terms: + $ref: '#/components/examples/InvitationUpdateTerms' + responses: + '200': + description: The draft after the change, or the current draft when the body changes nothing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + updated: + $ref: '#/components/examples/OrganizationInvitationDraftUpdated' + '400': + $ref: '#/components/responses/InvitationValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/StateConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}/send: + 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/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationCommand' + examples: + send: + $ref: '#/components/examples/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/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + delivered: + $ref: '#/components/examples/OrganizationInvitationDelivered' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise: + 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/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationSalaryRaise' + examples: + raise: + $ref: '#/components/examples/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/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + raised: + $ref: '#/components/examples/OrganizationInvitationSalaryRaised' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw: + 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/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationCommand' + examples: + withdraw: + $ref: '#/components/examples/InvitationWithdrawCommand' + responses: + '200': + description: The invitation in the state `withdrawn`. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + withdrawn: + $ref: '#/components/examples/OrganizationInvitationWithdrawn' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts: + 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/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + responses: + '200': + description: The contacts that the active grant of this invitation covers. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ContactDisclosure' + examples: + email_only: + $ref: '#/components/examples/InvitationContactsEmailOnly' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations: + 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/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the invitations of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitationList' + examples: + last_page: + $ref: '#/components/examples/CandidateInvitationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}: + 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/MyInvitationId' + responses: + '200': + description: The invitation in its current state. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + delivered: + $ref: '#/components/examples/CandidateInvitationDelivered' + viewed: + $ref: '#/components/examples/CandidateInvitationViewed' + accepted: + $ref: '#/components/examples/CandidateInvitationAccepted' + declined: + $ref: '#/components/examples/CandidateInvitationDeclined' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}/view: + 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/MyInvitationId' + responses: + '200': + description: The invitation, now `viewed` when it was `delivered`, otherwise in its current state. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + viewed: + $ref: '#/components/examples/CandidateInvitationViewed' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}/accept: + 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/MyInvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationAcceptance' + examples: + email_only: + $ref: '#/components/examples/InvitationAcceptEmailOnly' + stale_terms: + $ref: '#/components/examples/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/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + accepted: + $ref: '#/components/examples/CandidateInvitationAccepted' + visibility_blocked: + $ref: '#/components/examples/CandidateInvitationAcceptedVisibilityBlocked' + '400': + $ref: '#/components/responses/InvitationAcceptValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}/decline: + 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/MyInvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationDeclineRequest' + examples: + other_without_comment: + $ref: '#/components/examples/InvitationDeclineOther' + with_comment: + $ref: '#/components/examples/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/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + declined: + $ref: '#/components/examples/CandidateInvitationDeclined' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}/cancel: + 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/MyInvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationCommand' + examples: + cancel: + $ref: '#/components/examples/InvitationCancelCommand' + responses: + '200': + description: The invitation in the state `cancelled_by_candidate` with its grant revoked. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + cancelled: + $ref: '#/components/examples/CandidateInvitationCancelled' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' /api/v1/me/support-cases: get: operationId: ListMySupportCases @@ -1094,9 +1861,9 @@ paths: | `anticheat_appeal` | candidate | required; `assessment_attempt` of the caller with an anti-cheat review decision | none | | `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` | - An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract (TASK-077) shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are 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. @@ -3989,7 +4756,7 @@ components: - 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 @@ -4463,6 +5230,1012 @@ components: $ref: '#/components/schemas/SupportCaseSummary' page: $ref: '#/components/schemas/PageInfo' + 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 + 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 + 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: '#/components/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: '#/components/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: '#/components/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: '#/components/schemas/InvitationPackageItemProvided' + - $ref: '#/components/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: '#/components/schemas/InvitationPackageItem' + equipment: + $ref: '#/components/schemas/InvitationPackageItem' + training: + $ref: '#/components/schemas/InvitationPackageItem' + health_insurance: + $ref: '#/components/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: '#/components/schemas/InvitationRoleTitle' + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + offer_type: + $ref: '#/components/schemas/InvitationOfferType' + tasks: + type: array + minItems: 1 + maxItems: 20 + description: Work tasks of the role in the order given. + items: + $ref: '#/components/schemas/NeedTaskText' + team: + $ref: '#/components/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: '#/components/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: '#/components/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: '#/components/schemas/NeedLocationName' + - type: 'null' + communication_method: + $ref: '#/components/schemas/InvitationCommunicationMethod' + salary: + $ref: '#/components/schemas/SalaryRange' + package: + $ref: '#/components/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: '#/components/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: '#/components/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: '#/components/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: '#/components/schemas/InvitationDeclineReason' + comment: + oneOf: + - $ref: '#/components/schemas/InvitationDeclineComment' + - type: 'null' + declined_at: + $ref: '#/components/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: '#/components/schemas/CandidateHandle' + need: + description: Need the invitation was built from, or null for a direct invitation. + oneOf: + - $ref: '#/components/schemas/InvitationNeedReference' + - type: 'null' + state: + $ref: '#/components/schemas/InvitationState' + expiry_reason: + description: Reason of an expiry, or null unless `state` is `expired`. + oneOf: + - $ref: '#/components/schemas/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/components/schemas/InvitationVersion' + terms_version: + $ref: '#/components/schemas/InvitationTermsVersion' + terms: + $ref: '#/components/schemas/InvitationTerms' + response_period_days: + $ref: '#/components/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: '#/components/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: '#/components/schemas/InvitationSalaryFit' + contact_access: + $ref: '#/components/schemas/InvitationContactAccess' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + delivered_at: + description: Moment of delivery to the candidate's inbox, or null for a draft. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + viewed_at: + description: Moment when the candidate first opened the terms, or null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + responded_at: + description: Moment of the candidate's acceptance or decline, or null. + oneOf: + - $ref: '#/components/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: '#/components/schemas/CandidateHandle' + need: + oneOf: + - $ref: '#/components/schemas/InvitationNeedReference' + - type: 'null' + state: + $ref: '#/components/schemas/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/components/schemas/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/components/schemas/InvitationVersion' + terms_version: + $ref: '#/components/schemas/InvitationTermsVersion' + role_title: + $ref: '#/components/schemas/InvitationRoleTitle' + salary: + $ref: '#/components/schemas/SalaryRange' + response_deadline_at: + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + contact_access: + $ref: '#/components/schemas/InvitationContactAccess' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/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: '#/components/schemas/OrganizationInvitationSummary' + page: + $ref: '#/components/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: '#/components/schemas/CandidateHandle' + need: + description: Need of the organization the invitation is built from, or null or absent for a direct invitation. + oneOf: + - $ref: '#/components/schemas/InvitationNeedReference' + - type: 'null' + response_period_days: + description: Days to answer; absent means 7, the default of the product policy. + allOf: + - $ref: '#/components/schemas/InvitationResponsePeriod' + terms: + $ref: '#/components/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: '#/components/schemas/InvitationVersion' + need: + oneOf: + - $ref: '#/components/schemas/InvitationNeedReference' + - type: 'null' + response_period_days: + $ref: '#/components/schemas/InvitationResponsePeriod' + terms: + $ref: '#/components/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: '#/components/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: '#/components/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: '#/components/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: '#/components/schemas/InvitationOrganization' + state: + $ref: '#/components/schemas/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/components/schemas/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/components/schemas/InvitationVersion' + terms_version: + $ref: '#/components/schemas/InvitationTermsVersion' + terms: + $ref: '#/components/schemas/InvitationTerms' + response_deadline_at: + $ref: '#/components/schemas/Timestamp' + delivered_at: + $ref: '#/components/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: '#/components/schemas/Timestamp' + - type: 'null' + responded_at: + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + updated_at: + $ref: '#/components/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: '#/components/schemas/ContactConsentOffer' + - type: 'null' + decline: + description: The candidate's decline, or null unless `state` is `declined`. + oneOf: + - $ref: '#/components/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: '#/components/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: '#/components/schemas/InvitationOrganization' + state: + $ref: '#/components/schemas/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/components/schemas/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/components/schemas/InvitationVersion' + terms_version: + $ref: '#/components/schemas/InvitationTermsVersion' + role_title: + $ref: '#/components/schemas/InvitationRoleTitle' + salary: + $ref: '#/components/schemas/SalaryRange' + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/components/schemas/WorkFormat' + response_deadline_at: + $ref: '#/components/schemas/Timestamp' + delivered_at: + $ref: '#/components/schemas/Timestamp' + viewed_at: + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + updated_at: + $ref: '#/components/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: '#/components/schemas/CandidateInvitationSummary' + page: + $ref: '#/components/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: '#/components/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: '#/components/schemas/InvitationTermsVersion' + consent_c4: + $ref: '#/components/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: '#/components/schemas/InvitationVersion' + reason: + $ref: '#/components/schemas/InvitationDeclineReason' + comment: + description: Optional comment for any reason, including `other`; absent or null means none. + oneOf: + - $ref: '#/components/schemas/InvitationDeclineComment' + - type: 'null' + 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: '#/components/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: '#/components/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: '#/components/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: '#/components/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: '#/components/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 + 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 + 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 + 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: '#/components/schemas/ContactFieldKind' + status: + $ref: '#/components/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: '#/components/schemas/ContactAccessBlock' + - type: 'null' + terms_version: + description: Terms version of the invitation that the acceptance accepted. + allOf: + - $ref: '#/components/schemas/InvitationTermsVersion' + consent_text_version: + description: Version of the consent C4 text that the candidate accepted. + allOf: + - $ref: '#/components/schemas/ConsentTextVersion' + granted_at: + $ref: '#/components/schemas/Timestamp' + revoked_at: + description: Moment of the revocation, or null while the grant is active. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + revocation_reason: + description: Reason of the revocation, or null while the grant is active. + oneOf: + - $ref: '#/components/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: '#/components/schemas/ContactFieldKind' + granted_at: + $ref: '#/components/schemas/Timestamp' + full_name: + oneOf: + - $ref: '#/components/schemas/ContactFullName' + - type: 'null' + email: + oneOf: + - $ref: '#/components/schemas/EmailAddress' + - type: 'null' + phone: + oneOf: + - $ref: '#/components/schemas/ContactPhoneNumber' + - type: 'null' + telegram: + oneOf: + - $ref: '#/components/schemas/ContactTelegramUsername' + - type: 'null' HealthResponse: type: object additionalProperties: false @@ -4563,6 +6336,24 @@ components: 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 headers: ETag: description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version. @@ -4797,7 +6588,7 @@ components: forbidden: $ref: '#/components/examples/Forbidden' QuestionnaireValidationFailed: - description: 'The body does not match the contract or violates a questionnaire rule: 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.' + description: 'The body does not match the contract or violates a questionnaire rule: 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. 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: @@ -4828,7 +6619,7 @@ components: specialization_not_in_questionnaire: $ref: '#/components/examples/AssessmentSpecializationNotInQuestionnaire' AssessmentAnswerValidationFailed: - description: 'The body does not match the contract or the answer does not fit the item: a format other than the item format, an option, element, or line that the item does not have, an order that is not a permutation of every 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 not stored under the Idempotency-Key.' + description: 'The body does not match the contract or the answer does not fit the item: a format other than the item format, an option, element, or line that the item does not have, an order that is not a permutation of every 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. 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: schema: @@ -4890,7 +6681,7 @@ components: version_conflict: $ref: '#/components/examples/AssessmentStaleVersion' NeedValidationFailed: - description: 'The body does not match the contract or violates a need rule: an unknown field such as rec_score, members, or candidate_minimum, a field sent as a bare value instead of `{value, status}`, a list sent as null, an unknown specialization, grade, work format, currency, period, or 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, 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 outcome is not stored under an Idempotency-Key.' + description: 'The body does not match the contract or violates a need rule: an unknown field such as rec_score, members, or candidate_minimum, a field sent as a bare value instead of `{value, status}`, a list sent as null, an unknown specialization, grade, work format, currency, period, or 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, 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. 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: @@ -4920,7 +6711,7 @@ components: version_conflict: $ref: '#/components/examples/NeedStaleVersion' SupportCaseValidationFailed: - description: 'The body does not match the contract or violates a case rule: an empty or blank description, including one made only of Unicode spaces, an unknown case type, an object identifier that is not a UUID, an object type that the 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 created, and the outcome is not stored under the Idempotency-Key.' + description: 'The body does not match the contract or violates a case rule: an empty or blank description, including one made only of Unicode spaces, an unknown case type, an object identifier that is not a UUID, an object type that the 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. 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: schema: @@ -4947,6 +6738,66 @@ components: $ref: '#/components/examples/SupportCaseAppealExists' idempotency_in_progress: $ref: '#/components/examples/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: '#/components/schemas/Problem' + examples: + without_tax_basis: + $ref: '#/components/examples/InvitationWithoutTaxBasis' + without_communication_method: + $ref: '#/components/examples/InvitationWithoutCommunicationMethod' + package_condition_left_out: + $ref: '#/components/examples/InvitationPackageItemMissing' + salary_range_too_wide: + $ref: '#/components/examples/InvitationSalaryRangeTooWide' + location_required: + $ref: '#/components/examples/InvitationLocationRequired' + unknown_candidate: + $ref: '#/components/examples/InvitationUnknownCandidate' + candidate_data_in_body: + $ref: '#/components/examples/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: '#/components/schemas/Problem' + examples: + empty_field_choice: + $ref: '#/components/examples/InvitationConsentWithoutFields' + outdated_consent_text: + $ref: '#/components/examples/InvitationConsentTextOutdated' + missing_terms_version: + $ref: '#/components/examples/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: '#/components/schemas/Problem' + examples: + stale_terms: + $ref: '#/components/examples/InvitationStaleTerms' + stale_version: + $ref: '#/components/examples/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: '#/components/schemas/Problem' + examples: + not_answerable: + $ref: '#/components/examples/InvitationNotAnswerable' + salary_raise_used: + $ref: '#/components/examples/InvitationSalaryRaiseUsed' + send_blocked: + $ref: '#/components/examples/InvitationSendBlocked' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' securitySchemes: sessionCookie: type: apiKey @@ -6660,7 +8511,7 @@ components: message: The value does not match the contract. NeedSalaryWithoutTaxBasis: summary: A salary range without its tax basis - description: The decoder does not record the path of a missing field in a nested object, so the pointer is the whole body. + description: The responder rebuilds the path of a missing nested field from the decoder, so the pointer names the missing field. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -6670,9 +8521,9 @@ components: trace_id: 7c8d9e0f-1a2b-4c3d-9e4f-5a6b7c8d9e0a errors: - in: body - pointer: '' - code: invalid - message: The value does not match the contract. + pointer: /salary/value/tax_basis + code: required + message: The value is required. NeedExtractedValueMismatch: summary: Status extracted with a value that is not the stored suggestion description: A request may keep only the stored suggestion unconfirmed. To set another value, it sends status confirmed. @@ -6690,7 +8541,7 @@ components: message: The value does not match the contract. NeedUnknownField: summary: The client sent its own recommendation score - description: Recommendations, membership, and candidate minimums are never request fields; any unknown field fails validation. + description: Recommendations, membership, and candidate minimums are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -6921,6 +8772,1246 @@ components: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 0f1a2b3c-4d5e-4f6a-8b7c-8d9e0f1a2b3d + OrganizationInvitationListPage: + summary: The last page of the invitations of an organization + description: The organization sees that the second invitation was declined, but not the reason or the comment. + value: + items: + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + response_deadline_at: '2026-10-13T09:30:00Z' + contact_access: + status: available + fields: + - email + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T15:00:00Z' + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + candidate_handle: cand_Hx3Tn8Wq1Ys6Fd2Vb + need: null + state: declined + expiry_reason: null + version: 4 + terms_version: 1 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + response_deadline_at: '2026-10-08T10:00:00Z' + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-05T09:00:00Z' + updated_at: '2026-10-06T08:00:00Z' + page: + has_more: false + next_cursor: null + InvitationCreateFromNeed: + summary: A draft for a candidate from the search results of a need + description: 'Every term is present: net salary range, communication method, and each package condition, provided or explicitly not provided.' + value: + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + response_period_days: 7 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: not_provided + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + OrganizationInvitationDraft: + summary: A new draft, version 1 with terms version 1 + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: draft + expiry_reason: null + version: 1 + terms_version: 1 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: not_provided + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: null + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:00:00Z' + delivered_at: null + viewed_at: null + responded_at: null + InvitationWithoutTaxBasis: + summary: A salary range without its tax basis + description: The tax basis is a required field of SalaryRange; the pointer names the missing nested field. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 1f2a3b4c-5d6e-4f7a-8b9c-0d1e2f3a4b5c + errors: + - in: body + pointer: /terms/salary/tax_basis + code: required + message: The value is required. + InvitationWithoutCommunicationMethod: + summary: Terms without the communication method + description: The communication method is a required term; the pointer names the missing nested field. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d + errors: + - in: body + pointer: /terms/communication_method + code: required + message: The value is required. + InvitationPackageItemMissing: + summary: A package without the training condition + description: 'Not providing a condition is the explicit item {status: not_provided}; leaving it out is a missing required field.' + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 3b4c5d6e-7f8a-4b9c-8d0e-2f3a4b5c6d7e + errors: + - in: body + pointer: /terms/package/training + code: required + message: The value is required. + InvitationSalaryRangeTooWide: + summary: A salary range wider than 40% of its midpoint + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 4c5d6e7f-8a9b-4c0d-9e1f-3a4b5c6d7e8f + errors: + - in: body + pointer: /terms/salary/salary_to + code: invalid + message: The value does not match the contract. + InvitationLocationRequired: + summary: The hybrid format without a place of work + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 5d6e7f8a-9b0c-4d1e-8f2a-4b5c6d7e8f9a + errors: + - in: body + pointer: /terms/location + code: invalid + message: The value does not match the contract. + InvitationUnknownCandidate: + summary: A candidate handle that this organization cannot use + description: An unknown handle, a handle of another organization, and a profile that is no longer visible to the organization get the same answer. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-5c6d7e8f9a0b + errors: + - in: body + pointer: /candidate_handle + code: invalid + message: The value does not match the contract. + InvitationCandidateDataInBody: + summary: The request carried a candidate's email address or salary minimum + description: Contacts and minimums are never request fields; any unknown field fails validation, and an unknown top-level field such as candidate_email points at the whole body. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 7f8a9b0c-1d2e-4f3a-8b4c-6d7e8f9a0b1c + errors: + - in: body + pointer: '' + code: invalid + message: The value does not match the contract. + OrganizationInvitationDelivered: + summary: The invitation in the candidate's inbox with a seven-day deadline + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: delivered + expiry_reason: null + version: 3 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: '2026-10-13T09:30:00Z' + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: null + responded_at: null + OrganizationInvitationAccepted: + summary: 'The accepted invitation: the email address is readable through the contacts operation' + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + 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' + InvitationUpdateTerms: + summary: The draft gets the training condition; the terms are sent complete + value: + expected_version: 1 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + OrganizationInvitationDraftUpdated: + summary: The draft after the terms change, version 2 with terms version 2 + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: draft + expiry_reason: null + version: 2 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: null + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:20:00Z' + delivered_at: null + viewed_at: null + responded_at: null + StateConflict: + summary: The resource state does not allow the operation + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b + InvitationStaleTerms: + summary: The acceptance named a terms version that is no longer current + description: The organization raised the salary after the candidate read the terms. Nothing changed and no consent or grant was recorded; the client reads the invitation again and shows the new terms for a new decision. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 1d2e3f4a-5b6c-4d7e-8f8a-0b1c2d3e4f5a + InvitationStaleVersion: + summary: The command carried a stale expected_version + description: The invitation changed after the client read it. Nothing changed; the client reads the invitation again. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 2e3f4a5b-6c7d-4e8f-9a9b-1c2d3e4f5a6b + InvitationSendCommand: + summary: Send the draft that the client read as version 2 + value: + expected_version: 2 + InvitationNotAnswerable: + summary: The invitation no longer accepts an answer + description: For example, it was withdrawn, it expired, or the deadline has passed. + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 3f4a5b6c-7d8e-4f9a-8b0c-2d3e4f5a6b7c + InvitationSalaryRaiseUsed: + summary: The upper bound of this invitation was already raised once + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 4a5b6c7d-8e9f-4a0b-9c1d-3e4f5a6b7c8d + InvitationSendBlocked: + summary: The send is blocked by the pending limit of the need or the pause after a decline + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 5b6c7d8e-9f0a-4b1c-8d2e-4f5a6b7c8d9e + InvitationSalaryRaiseCommand: + summary: The one raise of the upper bound from 260000 to 280000 net + value: + expected_version: 4 + salary_to: 280000 + OrganizationInvitationSalaryRaised: + summary: 'The viewed invitation after the one raise of the upper bound: terms version 3' + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: viewed + expiry_reason: null + version: 5 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: '2026-10-13T09:30:00Z' + salary_raise_used: true + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T14:00:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: null + InvitationWithdrawCommand: + summary: Withdraw the invitation that the client read as version 3 + value: + expected_version: 3 + OrganizationInvitationWithdrawn: + summary: The invitation withdrawn by the organization before an answer + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cand_7Qm2xVb9Lr4Kp0Zt + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: withdrawn + expiry_reason: null + version: 4 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: '2026-10-13T09:30:00Z' + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T11:00:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: null + responded_at: null + InvitationContactsEmailOnly: + summary: Synthetic contacts through a grant that covers only the email address + description: Every field the grant does not cover is null. The values are synthetic. + value: + 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 + CandidateInvitationListPage: + summary: The last page of the candidate's inbox + value: + items: + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: viewed + expiry_reason: null + version: 4 + terms_version: 2 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + work_formats: + - remote + - hybrid + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + updated_at: '2026-10-06T12:00:00Z' + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: expired + expiry_reason: invitation_timeout + version: 3 + terms_version: 1 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + work_formats: + - remote + - hybrid + response_deadline_at: '2026-10-04T10:00:00Z' + delivered_at: '2026-10-01T10:00:00Z' + viewed_at: null + updated_at: '2026-10-04T10:00:00Z' + page: + has_more: false + next_cursor: null + CandidateInvitationDelivered: + summary: The delivered invitation as GetMyInvitation reads it, before a view is recorded + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: delivered + expiry_reason: null + version: 3 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + 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-06T09:30:00Z' + contact_consent: + text: + text_version: c4-2026-10-01 + text: Я разрешаю передать ООО Пример Платежи выбранные мной контактные данные для связи по этому приглашению. Согласие можно отозвать в любой момент в разделе согласий. + available_fields: + - full_name + - email + - phone + decline: null + contact_grant: null + CandidateInvitationViewed: + summary: The terms after ViewMyInvitation, with the C4 choice and no contact + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: viewed + expiry_reason: null + version: 4 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: null + updated_at: '2026-10-06T12:00:00Z' + contact_consent: + text: + text_version: c4-2026-10-01 + text: Я разрешаю передать ООО Пример Платежи выбранные мной контактные данные для связи по этому приглашению. Согласие можно отозвать в любой момент в разделе согласий. + available_fields: + - full_name + - email + - phone + decline: null + contact_grant: null + CandidateInvitationAccepted: + summary: The accepted invitation with the grant for the email address only + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: '2026-10-06T15:00:00Z' + updated_at: '2026-10-06T15:00:00Z' + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: active + readable: true + blocked_by: null + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: '2026-10-06T15:00:00Z' + revoked_at: null + revocation_reason: null + CandidateInvitationDeclined: + summary: The declined invitation with the candidate's own reason + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: declined + expiry_reason: null + version: 5 + terms_version: 2 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: '2026-10-06T16:00:00Z' + updated_at: '2026-10-06T16:00:00Z' + contact_consent: null + decline: + reason: other + comment: null + declined_at: '2026-10-06T16:00:00Z' + contact_grant: null + InvitationAcceptEmailOnly: + summary: Accept terms version 3 and disclose only the email address + value: + expected_version: 5 + terms_version: 3 + consent_c4: + text_version: c4-2026-10-01 + accepted: true + fields: + - email + InvitationAcceptStaleTerms: + summary: Accept terms version 2 after the organization raised the salary + description: The candidate read version 4 with terms version 2; the raise made version 5 with terms version 3, so the server answers 412. + value: + expected_version: 4 + terms_version: 2 + consent_c4: + text_version: c4-2026-10-01 + accepted: true + fields: + - email + - phone + CandidateInvitationAcceptedVisibilityBlocked: + summary: 'Accepted while the profile is hidden from the organization: the grant is active but not readable' + description: The acceptance never lifts the hiding or publishes the profile. The organization sees contact_access closed without the reason. + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: '2026-10-06T15:00:00Z' + updated_at: '2026-10-06T15:00:00Z' + contact_consent: null + decline: null + contact_grant: + 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 + InvitationConsentWithoutFields: + summary: An acceptance with an empty choice of contact fields + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 8a9b0c1d-2e3f-4a4b-9c5d-7e8f9a0b1c2d + errors: + - in: body + pointer: /consent_c4/fields + code: invalid + message: The value does not match the contract. + InvitationConsentTextOutdated: + summary: An acceptance of a C4 text version that is no longer published + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 9b0c1d2e-3f4a-4b5c-8d6e-8f9a0b1c2d3e + errors: + - in: body + pointer: /consent_c4/text_version + code: invalid + message: The value does not match the contract. + InvitationMissingTermsVersion: + summary: An acceptance without terms_version + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 0c1d2e3f-4a5b-4c6d-9e7f-9a0b1c2d3e4f + errors: + - in: body + pointer: /terms_version + code: required + message: The value is required. + InvitationDeclineOther: + summary: Decline with the neutral reason other and no comment + value: + expected_version: 4 + reason: other + InvitationDeclineWithComment: + summary: Decline with a reason and an optional comment + value: + expected_version: 4 + reason: work_format + comment: Ищу только полностью удаленную работу. + InvitationCancelCommand: + summary: Cancel the participation after the acceptance + value: + expected_version: 6 + CandidateInvitationCancelled: + summary: The participation cancelled after the acceptance; the grant of this invitation is revoked + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: cancelled_by_candidate + expiry_reason: null + version: 7 + terms_version: 3 + 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: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: '2026-10-06T15:00:00Z' + updated_at: '2026-10-07T10:00:00Z' + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: revoked + readable: false + blocked_by: null + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: '2026-10-06T15:00:00Z' + revoked_at: '2026-10-07T10:00:00Z' + revocation_reason: participation_cancelled SupportCaseListPage: summary: The last page of the case summaries of the current account value: @@ -7078,7 +10169,7 @@ components: message: The value does not match the contract. SupportCaseUnknownType: summary: The case type is not one of the five types - description: The variant is selected by `type` before a field path is recorded, so the pointer is the whole body. + description: An unknown discriminator of the top-level oneOf concerns the whole body, so the pointer is empty. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -7093,7 +10184,7 @@ components: message: The value does not match the contract. SupportCaseUnknownField: summary: The client sent its own status or decision - description: Status, decision, moderator, priority, and response target are never request fields; any unknown field fails validation. + description: Status, decision, moderator, priority, and response target are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -7108,7 +10199,7 @@ components: message: The value does not match the contract. SupportCaseMalformedReference: summary: The object identifier is not a UUID - description: The decoder rejects the identifier inside the selected variant without recording its path, so the pointer is the whole body. + description: The decoder rejects the identifier inside the selected variant, and the pointer names it. value: type: urn:lincodex:problem:validation_failed title: Request validation failed @@ -7118,7 +10209,7 @@ components: trace_id: 0f1a2b3c-4d5e-4f6a-9b7c-8d9e0f1a2b3c errors: - in: body - pointer: '' + pointer: /object/id code: invalid message: The value does not match the contract. SupportCaseComplaintNeedsInvitation: @@ -7196,15 +10287,6 @@ components: message: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам. created_at: '2026-10-01T10:00:00Z' updated_at: '2026-10-09T14:30:00Z' - StateConflict: - summary: The resource state does not allow the operation - value: - type: urn:lincodex:problem:state_conflict - title: Resource state conflict - status: 409 - code: state_conflict - detail: The resource is in a state that does not allow this operation. - trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b PayloadTooLarge: summary: The request body exceeds the limit value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index a1d44c9..c7ada19 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -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 diff --git a/api/core/routes/candidate_invitation.yml b/api/core/routes/candidate_invitation.yml new file mode 100644 index 0000000..21f444b --- /dev/null +++ b/api/core/routes/candidate_invitation.yml @@ -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 diff --git a/api/core/routes/candidate_invitation_accept.yml b/api/core/routes/candidate_invitation_accept.yml new file mode 100644 index 0000000..fd2d179 --- /dev/null +++ b/api/core/routes/candidate_invitation_accept.yml @@ -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 diff --git a/api/core/routes/candidate_invitation_cancel.yml b/api/core/routes/candidate_invitation_cancel.yml new file mode 100644 index 0000000..07a2804 --- /dev/null +++ b/api/core/routes/candidate_invitation_cancel.yml @@ -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 diff --git a/api/core/routes/candidate_invitation_decline.yml b/api/core/routes/candidate_invitation_decline.yml new file mode 100644 index 0000000..f0029e3 --- /dev/null +++ b/api/core/routes/candidate_invitation_decline.yml @@ -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 diff --git a/api/core/routes/candidate_invitation_view.yml b/api/core/routes/candidate_invitation_view.yml new file mode 100644 index 0000000..0fa90d4 --- /dev/null +++ b/api/core/routes/candidate_invitation_view.yml @@ -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 diff --git a/api/core/routes/candidate_invitations.yml b/api/core/routes/candidate_invitations.yml new file mode 100644 index 0000000..8df47da --- /dev/null +++ b/api/core/routes/candidate_invitations.yml @@ -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 diff --git a/api/core/routes/organization_invitation.yml b/api/core/routes/organization_invitation.yml new file mode 100644 index 0000000..672d4bd --- /dev/null +++ b/api/core/routes/organization_invitation.yml @@ -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 diff --git a/api/core/routes/organization_invitation_contacts.yml b/api/core/routes/organization_invitation_contacts.yml new file mode 100644 index 0000000..f052fe6 --- /dev/null +++ b/api/core/routes/organization_invitation_contacts.yml @@ -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 diff --git a/api/core/routes/organization_invitation_salary_raise.yml b/api/core/routes/organization_invitation_salary_raise.yml new file mode 100644 index 0000000..655d282 --- /dev/null +++ b/api/core/routes/organization_invitation_salary_raise.yml @@ -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 diff --git a/api/core/routes/organization_invitation_send.yml b/api/core/routes/organization_invitation_send.yml new file mode 100644 index 0000000..e735882 --- /dev/null +++ b/api/core/routes/organization_invitation_send.yml @@ -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 diff --git a/api/core/routes/organization_invitation_withdraw.yml b/api/core/routes/organization_invitation_withdraw.yml new file mode 100644 index 0000000..e918d52 --- /dev/null +++ b/api/core/routes/organization_invitation_withdraw.yml @@ -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 diff --git a/api/core/routes/organization_invitations.yml b/api/core/routes/organization_invitations.yml new file mode 100644 index 0000000..58641eb --- /dev/null +++ b/api/core/routes/organization_invitations.yml @@ -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 diff --git a/api/core/routes/support_cases.yml b/api/core/routes/support_cases.yml index 6b24c61..508d30f 100644 --- a/api/core/routes/support_cases.yml +++ b/api/core/routes/support_cases.yml @@ -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. diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index a71f7db..6c00edd 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -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="), } diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 7109a4e..6aedbb8 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -33,6 +33,556 @@ func (c *codeRecorder) Unwrap() http.ResponseWriter { return c.ResponseWriter } +// handleAcceptMyInvitationRequest handles 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 (s *Server) handleAcceptMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("AcceptMyInvitation"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}/accept"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), AcceptMyInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: AcceptMyInvitationOperation, + ID: "AcceptMyInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, AcceptMyInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, AcceptMyInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeAcceptMyInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeAcceptMyInvitationRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response AcceptMyInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: AcceptMyInvitationOperation, + OperationSummary: "Accept the current terms and disclose the selected contacts.", + OperationID: "AcceptMyInvitation", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *InvitationAcceptance + Params = AcceptMyInvitationParams + Response = AcceptMyInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackAcceptMyInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.AcceptMyInvitation(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.AcceptMyInvitation(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeAcceptMyInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleCancelMyInvitationRequest handles 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 (s *Server) handleCancelMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CancelMyInvitation"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}/cancel"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CancelMyInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: CancelMyInvitationOperation, + ID: "CancelMyInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, CancelMyInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, CancelMyInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeCancelMyInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeCancelMyInvitationRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response CancelMyInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CancelMyInvitationOperation, + OperationSummary: "Cancel the participation in an invitation and revoke its contact grant.", + OperationID: "CancelMyInvitation", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *InvitationCommand + Params = CancelMyInvitationParams + Response = CancelMyInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackCancelMyInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.CancelMyInvitation(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.CancelMyInvitation(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeCancelMyInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleConfirmEmailRequest handles ConfirmEmail operation. // // Public operation without a session. The verification link has the form @@ -499,10 +1049,11 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca // // 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, @@ -510,8 +1061,7 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca // 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 @@ -792,6 +1342,289 @@ func (s *Server) handleCreateMySupportCaseRequest(args [0]string, argsEscaped bo } } +// handleCreateOrganizationInvitationRequest handles 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 (s *Server) handleCreateOrganizationInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CreateOrganizationInvitation"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateOrganizationInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: CreateOrganizationInvitationOperation, + ID: "CreateOrganizationInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, CreateOrganizationInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, CreateOrganizationInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeCreateOrganizationInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeCreateOrganizationInvitationRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response CreateOrganizationInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CreateOrganizationInvitationOperation, + OperationSummary: "Create an invitation draft for one candidate.", + OperationID: "CreateOrganizationInvitation", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *OrganizationInvitationCreate + Params = CreateOrganizationInvitationParams + Response = CreateOrganizationInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackCreateOrganizationInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.CreateOrganizationInvitation(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.CreateOrganizationInvitation(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeCreateOrganizationInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleCreateOrganizationNeedRequest handles CreateOrganizationNeed operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF @@ -1076,6 +1909,274 @@ func (s *Server) handleCreateOrganizationNeedRequest(args [1]string, argsEscaped } } +// handleDeclineMyInvitationRequest handles 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 (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("DeclineMyInvitation"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}/decline"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), DeclineMyInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: DeclineMyInvitationOperation, + ID: "DeclineMyInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, DeclineMyInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, DeclineMyInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeDeclineMyInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeDeclineMyInvitationRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response DeclineMyInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: DeclineMyInvitationOperation, + OperationSummary: "Decline an invitation with a structured reason.", + OperationID: "DeclineMyInvitation", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *InvitationDeclineRequest + Params = DeclineMyInvitationParams + Response = DeclineMyInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackDeclineMyInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.DeclineMyInvitation(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.DeclineMyInvitation(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeDeclineMyInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleFinalizeMyAssessmentAttemptRequest handles FinalizeMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -2656,6 +3757,231 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped } } +// handleGetMyInvitationRequest handles 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 (s *Server) handleGetMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyInvitation"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetMyInvitationOperation, + ID: "GetMyInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeGetMyInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response GetMyInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyInvitationOperation, + OperationSummary: "Open the terms of an invitation addressed to the current candidate.", + OperationID: "GetMyInvitation", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetMyInvitationParams + Response = GetMyInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetMyInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyInvitation(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetMyInvitation(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetMyInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetMyQuestionnaireRequest handles GetMyQuestionnaire operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -3064,6 +4390,461 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool, } } +// handleGetOrganizationInvitationRequest handles 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 (s *Server) handleGetOrganizationInvitationRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetOrganizationInvitation"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetOrganizationInvitationOperation, + ID: "GetOrganizationInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeGetOrganizationInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response GetOrganizationInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetOrganizationInvitationOperation, + OperationSummary: "Read an invitation of an organization.", + OperationID: "GetOrganizationInvitation", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetOrganizationInvitationParams + Response = GetOrganizationInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetOrganizationInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetOrganizationInvitation(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetOrganizationInvitation(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetOrganizationInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleGetOrganizationInvitationContactsRequest handles 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 (s *Server) handleGetOrganizationInvitationContactsRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetOrganizationInvitationContacts"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationInvitationContactsOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetOrganizationInvitationContactsOperation, + ID: "GetOrganizationInvitationContacts", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationInvitationContactsOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeGetOrganizationInvitationContactsParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response GetOrganizationInvitationContactsRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetOrganizationInvitationContactsOperation, + OperationSummary: "Read the contacts that the candidate disclosed to the organization.", + OperationID: "GetOrganizationInvitationContacts", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetOrganizationInvitationContactsParams + Response = GetOrganizationInvitationContactsRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetOrganizationInvitationContactsParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetOrganizationInvitationContacts(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetOrganizationInvitationContacts(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetOrganizationInvitationContactsResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetOrganizationNeedRequest handles GetOrganizationNeed operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. The @@ -3442,6 +5223,222 @@ func (s *Server) handleGetSpecializationCatalogRequest(args [0]string, argsEscap } } +// handleListMyInvitationsRequest handles 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 (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListMyInvitations"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/invitations"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyInvitationsOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: ListMyInvitationsOperation, + ID: "ListMyInvitations", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListMyInvitationsOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeListMyInvitationsParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response ListMyInvitationsRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListMyInvitationsOperation, + OperationSummary: "List the invitations addressed to the current candidate.", + OperationID: "ListMyInvitations", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "limit", + In: "query", + }: params.Limit, + { + Name: "cursor", + In: "query", + }: params.Cursor, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = ListMyInvitationsParams + Response = ListMyInvitationsRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListMyInvitationsParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListMyInvitations(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListMyInvitations(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeListMyInvitationsResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleListMySupportCasesRequest handles ListMySupportCases operation. // // Requires the session cookie of a candidate or an employer account. Returns a page of the cases that @@ -3655,6 +5652,230 @@ func (s *Server) handleListMySupportCasesRequest(args [0]string, argsEscaped boo } } +// handleListOrganizationInvitationsRequest handles 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 (s *Server) handleListOrganizationInvitationsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListOrganizationInvitations"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListOrganizationInvitationsOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: ListOrganizationInvitationsOperation, + ID: "ListOrganizationInvitations", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListOrganizationInvitationsOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeListOrganizationInvitationsParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response ListOrganizationInvitationsRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListOrganizationInvitationsOperation, + OperationSummary: "List the invitations of an organization.", + OperationID: "ListOrganizationInvitations", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "limit", + In: "query", + }: params.Limit, + { + Name: "cursor", + In: "query", + }: params.Cursor, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = ListOrganizationInvitationsParams + Response = ListOrganizationInvitationsRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListOrganizationInvitationsParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListOrganizationInvitations(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListOrganizationInvitations(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeListOrganizationInvitationsResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleListOrganizationNeedsRequest handles ListOrganizationNeeds operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. The @@ -4257,6 +6478,280 @@ func (s *Server) handleLogoutRequest(args [0]string, argsEscaped bool, w http.Re } } +// handleRaiseOrganizationInvitationSalaryRequest handles 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 (s *Server) handleRaiseOrganizationInvitationSalaryRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("RaiseOrganizationInvitationSalary"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), RaiseOrganizationInvitationSalaryOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: RaiseOrganizationInvitationSalaryOperation, + ID: "RaiseOrganizationInvitationSalary", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, RaiseOrganizationInvitationSalaryOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, RaiseOrganizationInvitationSalaryOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeRaiseOrganizationInvitationSalaryParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeRaiseOrganizationInvitationSalaryRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response RaiseOrganizationInvitationSalaryRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: RaiseOrganizationInvitationSalaryOperation, + OperationSummary: "Raise the upper salary bound of a sent invitation once.", + OperationID: "RaiseOrganizationInvitationSalary", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *InvitationSalaryRaise + Params = RaiseOrganizationInvitationSalaryParams + Response = RaiseOrganizationInvitationSalaryRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackRaiseOrganizationInvitationSalaryParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.RaiseOrganizationInvitationSalary(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.RaiseOrganizationInvitationSalary(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeRaiseOrganizationInvitationSalaryResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleRegisterAccountRequest handles RegisterAccount operation. // // Public operation without a session. The client reads the current C1 text with GetConsentText and @@ -4876,6 +7371,278 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo } } +// handleSendOrganizationInvitationRequest handles 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 (s *Server) handleSendOrganizationInvitationRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("SendOrganizationInvitation"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}/send"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), SendOrganizationInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: SendOrganizationInvitationOperation, + ID: "SendOrganizationInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, SendOrganizationInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, SendOrganizationInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeSendOrganizationInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeSendOrganizationInvitationRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response SendOrganizationInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: SendOrganizationInvitationOperation, + OperationSummary: "Send a draft to the candidate's inbox.", + OperationID: "SendOrganizationInvitation", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *InvitationCommand + Params = SendOrganizationInvitationParams + Response = SendOrganizationInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackSendOrganizationInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.SendOrganizationInvitation(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.SendOrganizationInvitation(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeSendOrganizationInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleSubmitMyAssessmentAnswerRequest handles SubmitMyAssessmentAnswer operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -5164,6 +7931,281 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap } } +// handleUpdateOrganizationInvitationRequest handles 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 (s *Server) handleUpdateOrganizationInvitationRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("UpdateOrganizationInvitation"), + semconv.HTTPRequestMethodKey.String("PATCH"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateOrganizationInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: UpdateOrganizationInvitationOperation, + ID: "UpdateOrganizationInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, UpdateOrganizationInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, UpdateOrganizationInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeUpdateOrganizationInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeUpdateOrganizationInvitationRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response UpdateOrganizationInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: UpdateOrganizationInvitationOperation, + OperationSummary: "Change the terms, the need link, or the response period of a draft.", + OperationID: "UpdateOrganizationInvitation", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + }, + Raw: r, + } + + type ( + Request = *OrganizationInvitationUpdate + Params = UpdateOrganizationInvitationParams + Response = UpdateOrganizationInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackUpdateOrganizationInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.UpdateOrganizationInvitation(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.UpdateOrganizationInvitation(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeUpdateOrganizationInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleUpdateOrganizationNeedRequest handles UpdateOrganizationNeed operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF @@ -5461,3 +8503,511 @@ func (s *Server) handleUpdateOrganizationNeedRequest(args [2]string, argsEscaped return } } + +// handleViewMyInvitationRequest handles 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 (s *Server) handleViewMyInvitationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ViewMyInvitation"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/invitations/{invitation_id}/view"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ViewMyInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: ViewMyInvitationOperation, + ID: "ViewMyInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ViewMyInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, ViewMyInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeViewMyInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response ViewMyInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ViewMyInvitationOperation, + OperationSummary: "Record that the current candidate opened the terms of an invitation.", + OperationID: "ViewMyInvitation", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = ViewMyInvitationParams + Response = ViewMyInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackViewMyInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ViewMyInvitation(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ViewMyInvitation(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeViewMyInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleWithdrawOrganizationInvitationRequest handles 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 (s *Server) handleWithdrawOrganizationInvitationRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("WithdrawOrganizationInvitation"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), WithdrawOrganizationInvitationOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: WithdrawOrganizationInvitationOperation, + ID: "WithdrawOrganizationInvitation", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, WithdrawOrganizationInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, WithdrawOrganizationInvitationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeWithdrawOrganizationInvitationParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeWithdrawOrganizationInvitationRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response WithdrawOrganizationInvitationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: WithdrawOrganizationInvitationOperation, + OperationSummary: "Withdraw an invitation.", + OperationID: "WithdrawOrganizationInvitation", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + { + Name: "invitation_id", + In: "path", + }: params.InvitationID, + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = *InvitationCommand + Params = WithdrawOrganizationInvitationParams + Response = WithdrawOrganizationInvitationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackWithdrawOrganizationInvitationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.WithdrawOrganizationInvitation(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.WithdrawOrganizationInvitation(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeWithdrawOrganizationInvitationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index fc7d652..7c73702 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -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() +} diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index 2be1905..b37ae40 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -14,6 +14,272 @@ import ( "github.com/ogen-go/ogen/validate" ) +// Encode encodes AcceptMyInvitationBadRequest as json. +func (s *AcceptMyInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcceptMyInvitationBadRequest from json. +func (s *AcceptMyInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcceptMyInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcceptMyInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcceptMyInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcceptMyInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AcceptMyInvitationConflict as json. +func (s *AcceptMyInvitationConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcceptMyInvitationConflict from json. +func (s *AcceptMyInvitationConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcceptMyInvitationConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcceptMyInvitationConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcceptMyInvitationConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcceptMyInvitationConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AcceptMyInvitationForbidden as json. +func (s *AcceptMyInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcceptMyInvitationForbidden from json. +func (s *AcceptMyInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcceptMyInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcceptMyInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcceptMyInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcceptMyInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AcceptMyInvitationNotFound as json. +func (s *AcceptMyInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcceptMyInvitationNotFound from json. +func (s *AcceptMyInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcceptMyInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcceptMyInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcceptMyInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcceptMyInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AcceptMyInvitationPreconditionFailed as json. +func (s *AcceptMyInvitationPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcceptMyInvitationPreconditionFailed from json. +func (s *AcceptMyInvitationPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcceptMyInvitationPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcceptMyInvitationPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcceptMyInvitationPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcceptMyInvitationPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AcceptMyInvitationUnauthorized as json. +func (s *AcceptMyInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcceptMyInvitationUnauthorized from json. +func (s *AcceptMyInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcceptMyInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcceptMyInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcceptMyInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcceptMyInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AcceptMyInvitationUnprocessableEntity as json. +func (s *AcceptMyInvitationUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcceptMyInvitationUnprocessableEntity from json. +func (s *AcceptMyInvitationUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcceptMyInvitationUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcceptMyInvitationUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcceptMyInvitationUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcceptMyInvitationUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *Account) Encode(e *jx.Encoder) { e.ObjStart() @@ -4245,6 +4511,272 @@ func (s *CalibrationStatus) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes CancelMyInvitationBadRequest as json. +func (s *CancelMyInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CancelMyInvitationBadRequest from json. +func (s *CancelMyInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CancelMyInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CancelMyInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CancelMyInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CancelMyInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CancelMyInvitationConflict as json. +func (s *CancelMyInvitationConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CancelMyInvitationConflict from json. +func (s *CancelMyInvitationConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CancelMyInvitationConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CancelMyInvitationConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CancelMyInvitationConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CancelMyInvitationConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CancelMyInvitationForbidden as json. +func (s *CancelMyInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CancelMyInvitationForbidden from json. +func (s *CancelMyInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CancelMyInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CancelMyInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CancelMyInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CancelMyInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CancelMyInvitationNotFound as json. +func (s *CancelMyInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CancelMyInvitationNotFound from json. +func (s *CancelMyInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CancelMyInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CancelMyInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CancelMyInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CancelMyInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CancelMyInvitationPreconditionFailed as json. +func (s *CancelMyInvitationPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CancelMyInvitationPreconditionFailed from json. +func (s *CancelMyInvitationPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CancelMyInvitationPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CancelMyInvitationPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CancelMyInvitationPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CancelMyInvitationPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CancelMyInvitationUnauthorized as json. +func (s *CancelMyInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CancelMyInvitationUnauthorized from json. +func (s *CancelMyInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CancelMyInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CancelMyInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CancelMyInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CancelMyInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CancelMyInvitationUnprocessableEntity as json. +func (s *CancelMyInvitationUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CancelMyInvitationUnprocessableEntity from json. +func (s *CancelMyInvitationUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CancelMyInvitationUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CancelMyInvitationUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CancelMyInvitationUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CancelMyInvitationUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *CandidateExperience) Encode(e *jx.Encoder) { e.ObjStart() @@ -4358,6 +4890,763 @@ func (s *CandidateExperience) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes CandidateHandle as json. +func (s CandidateHandle) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes CandidateHandle from json. +func (s *CandidateHandle) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateHandle to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CandidateHandle(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CandidateHandle) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateHandle) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CandidateInvitation) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CandidateInvitation) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("organization") + s.Organization.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("expiry_reason") + s.ExpiryReason.Encode(e) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("terms_version") + s.TermsVersion.Encode(e) + } + { + e.FieldStart("terms") + s.Terms.Encode(e) + } + { + e.FieldStart("response_deadline_at") + s.ResponseDeadlineAt.Encode(e) + } + { + e.FieldStart("delivered_at") + s.DeliveredAt.Encode(e) + } + { + e.FieldStart("viewed_at") + s.ViewedAt.Encode(e) + } + { + e.FieldStart("responded_at") + s.RespondedAt.Encode(e) + } + { + e.FieldStart("updated_at") + s.UpdatedAt.Encode(e) + } + { + e.FieldStart("contact_consent") + s.ContactConsent.Encode(e) + } + { + e.FieldStart("decline") + s.Decline.Encode(e) + } + { + e.FieldStart("contact_grant") + s.ContactGrant.Encode(e) + } +} + +var jsonFieldsNameOfCandidateInvitation = [15]string{ + 0: "id", + 1: "organization", + 2: "state", + 3: "expiry_reason", + 4: "version", + 5: "terms_version", + 6: "terms", + 7: "response_deadline_at", + 8: "delivered_at", + 9: "viewed_at", + 10: "responded_at", + 11: "updated_at", + 12: "contact_consent", + 13: "decline", + 14: "contact_grant", +} + +// Decode decodes CandidateInvitation from json. +func (s *CandidateInvitation) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateInvitation to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "organization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Organization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"organization\"") + } + case "state": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "expiry_reason": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.ExpiryReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expiry_reason\"") + } + case "version": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "terms_version": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.TermsVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms_version\"") + } + case "terms": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.Terms.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms\"") + } + case "response_deadline_at": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.ResponseDeadlineAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"response_deadline_at\"") + } + case "delivered_at": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.DeliveredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"delivered_at\"") + } + case "viewed_at": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.ViewedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"viewed_at\"") + } + case "responded_at": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.RespondedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"responded_at\"") + } + case "updated_at": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.UpdatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"updated_at\"") + } + case "contact_consent": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.ContactConsent.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"contact_consent\"") + } + case "decline": + requiredBitSet[1] |= 1 << 5 + if err := func() error { + if err := s.Decline.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"decline\"") + } + case "contact_grant": + requiredBitSet[1] |= 1 << 6 + if err := func() error { + if err := s.ContactGrant.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"contact_grant\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CandidateInvitation") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b01111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCandidateInvitation) { + name = jsonFieldsNameOfCandidateInvitation[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CandidateInvitation) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateInvitation) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CandidateInvitationList) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CandidateInvitationList) encodeFields(e *jx.Encoder) { + { + e.FieldStart("items") + e.ArrStart() + for _, elem := range s.Items { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("page") + s.Page.Encode(e) + } +} + +var jsonFieldsNameOfCandidateInvitationList = [2]string{ + 0: "items", + 1: "page", +} + +// Decode decodes CandidateInvitationList from json. +func (s *CandidateInvitationList) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateInvitationList to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "items": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Items = make([]CandidateInvitationSummary, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CandidateInvitationSummary + if err := elem.Decode(d); err != nil { + return err + } + s.Items = append(s.Items, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"items\"") + } + case "page": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Page.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"page\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CandidateInvitationList") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCandidateInvitationList) { + name = jsonFieldsNameOfCandidateInvitationList[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CandidateInvitationList) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateInvitationList) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CandidateInvitationSummary) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CandidateInvitationSummary) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("organization") + s.Organization.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("expiry_reason") + s.ExpiryReason.Encode(e) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("terms_version") + s.TermsVersion.Encode(e) + } + { + e.FieldStart("role_title") + s.RoleTitle.Encode(e) + } + { + e.FieldStart("salary") + s.Salary.Encode(e) + } + { + e.FieldStart("work_formats") + e.ArrStart() + for _, elem := range s.WorkFormats { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("response_deadline_at") + s.ResponseDeadlineAt.Encode(e) + } + { + e.FieldStart("delivered_at") + s.DeliveredAt.Encode(e) + } + { + e.FieldStart("viewed_at") + s.ViewedAt.Encode(e) + } + { + e.FieldStart("updated_at") + s.UpdatedAt.Encode(e) + } +} + +var jsonFieldsNameOfCandidateInvitationSummary = [13]string{ + 0: "id", + 1: "organization", + 2: "state", + 3: "expiry_reason", + 4: "version", + 5: "terms_version", + 6: "role_title", + 7: "salary", + 8: "work_formats", + 9: "response_deadline_at", + 10: "delivered_at", + 11: "viewed_at", + 12: "updated_at", +} + +// Decode decodes CandidateInvitationSummary from json. +func (s *CandidateInvitationSummary) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CandidateInvitationSummary to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "organization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Organization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"organization\"") + } + case "state": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "expiry_reason": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.ExpiryReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expiry_reason\"") + } + case "version": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "terms_version": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.TermsVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms_version\"") + } + case "role_title": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.RoleTitle.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"role_title\"") + } + case "salary": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.Salary.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"salary\"") + } + case "work_formats": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + s.WorkFormats = make([]WorkFormat, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem WorkFormat + if err := elem.Decode(d); err != nil { + return err + } + s.WorkFormats = append(s.WorkFormats, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"work_formats\"") + } + case "response_deadline_at": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.ResponseDeadlineAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"response_deadline_at\"") + } + case "delivered_at": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.DeliveredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"delivered_at\"") + } + case "viewed_at": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.ViewedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"viewed_at\"") + } + case "updated_at": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.UpdatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"updated_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CandidateInvitationSummary") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b00011111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCandidateInvitationSummary) { + name = jsonFieldsNameOfCandidateInvitationSummary[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CandidateInvitationSummary) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CandidateInvitationSummary) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *CandidateQuestionnaire) Encode(e *jx.Encoder) { e.ObjStart() @@ -6095,6 +7384,1151 @@ func (s *ConsentTextVersion) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ContactAccessBlock as json. +func (s ContactAccessBlock) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ContactAccessBlock from json. +func (s *ContactAccessBlock) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactAccessBlock to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ContactAccessBlock(v) { + case ContactAccessBlockVisibility: + *s = ContactAccessBlockVisibility + default: + *s = ContactAccessBlock(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ContactAccessBlock) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactAccessBlock) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ContactConsentAcceptance) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ContactConsentAcceptance) encodeFields(e *jx.Encoder) { + { + e.FieldStart("text_version") + s.TextVersion.Encode(e) + } + { + e.FieldStart("accepted") + s.Accepted.Encode(e) + } + { + e.FieldStart("fields") + e.ArrStart() + for _, elem := range s.Fields { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfContactConsentAcceptance = [3]string{ + 0: "text_version", + 1: "accepted", + 2: "fields", +} + +// Decode decodes ContactConsentAcceptance from json. +func (s *ContactConsentAcceptance) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactConsentAcceptance to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "text_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.TextVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text_version\"") + } + case "accepted": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Accepted.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"accepted\"") + } + case "fields": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.Fields = make([]ContactFieldKind, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ContactFieldKind + if err := elem.Decode(d); err != nil { + return err + } + s.Fields = append(s.Fields, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"fields\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ContactConsentAcceptance") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfContactConsentAcceptance) { + name = jsonFieldsNameOfContactConsentAcceptance[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ContactConsentAcceptance) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactConsentAcceptance) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactConsentAcceptanceAccepted as json. +func (s ContactConsentAcceptanceAccepted) Encode(e *jx.Encoder) { + e.Bool(bool(s)) +} + +// Decode decodes ContactConsentAcceptanceAccepted from json. +func (s *ContactConsentAcceptanceAccepted) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactConsentAcceptanceAccepted to nil") + } + v, err := d.Bool() + if err != nil { + return err + } + *s = ContactConsentAcceptanceAccepted(v) + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ContactConsentAcceptanceAccepted) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactConsentAcceptanceAccepted) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ContactConsentOffer) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ContactConsentOffer) encodeFields(e *jx.Encoder) { + { + e.FieldStart("text") + s.Text.Encode(e) + } + { + e.FieldStart("available_fields") + e.ArrStart() + for _, elem := range s.AvailableFields { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfContactConsentOffer = [2]string{ + 0: "text", + 1: "available_fields", +} + +// Decode decodes ContactConsentOffer from json. +func (s *ContactConsentOffer) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactConsentOffer to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "text": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Text.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text\"") + } + case "available_fields": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.AvailableFields = make([]ContactFieldKind, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ContactFieldKind + if err := elem.Decode(d); err != nil { + return err + } + s.AvailableFields = append(s.AvailableFields, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"available_fields\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ContactConsentOffer") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfContactConsentOffer) { + name = jsonFieldsNameOfContactConsentOffer[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ContactConsentOffer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactConsentOffer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ContactConsentText) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ContactConsentText) encodeFields(e *jx.Encoder) { + { + e.FieldStart("text_version") + s.TextVersion.Encode(e) + } + { + e.FieldStart("text") + e.Str(s.Text) + } +} + +var jsonFieldsNameOfContactConsentText = [2]string{ + 0: "text_version", + 1: "text", +} + +// Decode decodes ContactConsentText from json. +func (s *ContactConsentText) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactConsentText to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "text_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.TextVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text_version\"") + } + case "text": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Text = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"text\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ContactConsentText") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfContactConsentText) { + name = jsonFieldsNameOfContactConsentText[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ContactConsentText) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactConsentText) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ContactDisclosure) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ContactDisclosure) encodeFields(e *jx.Encoder) { + { + e.FieldStart("invitation_id") + json.EncodeUUID(e, s.InvitationID) + } + { + e.FieldStart("grant_id") + json.EncodeUUID(e, s.GrantID) + } + { + e.FieldStart("fields") + e.ArrStart() + for _, elem := range s.Fields { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("granted_at") + s.GrantedAt.Encode(e) + } + { + e.FieldStart("full_name") + s.FullName.Encode(e) + } + { + e.FieldStart("email") + s.Email.Encode(e) + } + { + e.FieldStart("phone") + s.Phone.Encode(e) + } + { + e.FieldStart("telegram") + s.Telegram.Encode(e) + } +} + +var jsonFieldsNameOfContactDisclosure = [8]string{ + 0: "invitation_id", + 1: "grant_id", + 2: "fields", + 3: "granted_at", + 4: "full_name", + 5: "email", + 6: "phone", + 7: "telegram", +} + +// Decode decodes ContactDisclosure from json. +func (s *ContactDisclosure) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactDisclosure to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "invitation_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.InvitationID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"invitation_id\"") + } + case "grant_id": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := json.DecodeUUID(d) + s.GrantID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"grant_id\"") + } + case "fields": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + s.Fields = make([]ContactFieldKind, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ContactFieldKind + if err := elem.Decode(d); err != nil { + return err + } + s.Fields = append(s.Fields, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"fields\"") + } + case "granted_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.GrantedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"granted_at\"") + } + case "full_name": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.FullName.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"full_name\"") + } + case "email": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Email.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email\"") + } + case "phone": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.Phone.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"phone\"") + } + case "telegram": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.Telegram.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"telegram\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ContactDisclosure") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b11111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfContactDisclosure) { + name = jsonFieldsNameOfContactDisclosure[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ContactDisclosure) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactDisclosure) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactFieldKind as json. +func (s ContactFieldKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ContactFieldKind from json. +func (s *ContactFieldKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactFieldKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ContactFieldKind(v) { + case ContactFieldKindFullName: + *s = ContactFieldKindFullName + case ContactFieldKindEmail: + *s = ContactFieldKindEmail + case ContactFieldKindPhone: + *s = ContactFieldKindPhone + case ContactFieldKindTelegram: + *s = ContactFieldKindTelegram + default: + *s = ContactFieldKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ContactFieldKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactFieldKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactFullName as json. +func (s ContactFullName) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ContactFullName from json. +func (s *ContactFullName) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactFullName to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ContactFullName(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ContactFullName) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactFullName) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *ContactGrant) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *ContactGrant) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("fields") + e.ArrStart() + for _, elem := range s.Fields { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("readable") + e.Bool(s.Readable) + } + { + e.FieldStart("blocked_by") + s.BlockedBy.Encode(e) + } + { + e.FieldStart("terms_version") + s.TermsVersion.Encode(e) + } + { + e.FieldStart("consent_text_version") + s.ConsentTextVersion.Encode(e) + } + { + e.FieldStart("granted_at") + s.GrantedAt.Encode(e) + } + { + e.FieldStart("revoked_at") + s.RevokedAt.Encode(e) + } + { + e.FieldStart("revocation_reason") + s.RevocationReason.Encode(e) + } +} + +var jsonFieldsNameOfContactGrant = [10]string{ + 0: "id", + 1: "fields", + 2: "status", + 3: "readable", + 4: "blocked_by", + 5: "terms_version", + 6: "consent_text_version", + 7: "granted_at", + 8: "revoked_at", + 9: "revocation_reason", +} + +// Decode decodes ContactGrant from json. +func (s *ContactGrant) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactGrant to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "fields": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Fields = make([]ContactFieldKind, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ContactFieldKind + if err := elem.Decode(d); err != nil { + return err + } + s.Fields = append(s.Fields, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"fields\"") + } + case "status": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "readable": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + v, err := d.Bool() + s.Readable = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"readable\"") + } + case "blocked_by": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.BlockedBy.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"blocked_by\"") + } + case "terms_version": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.TermsVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms_version\"") + } + case "consent_text_version": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.ConsentTextVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"consent_text_version\"") + } + case "granted_at": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.GrantedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"granted_at\"") + } + case "revoked_at": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.RevokedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"revoked_at\"") + } + case "revocation_reason": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.RevocationReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"revocation_reason\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode ContactGrant") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfContactGrant) { + name = jsonFieldsNameOfContactGrant[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ContactGrant) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactGrant) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactGrantState as json. +func (s ContactGrantState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ContactGrantState from json. +func (s *ContactGrantState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactGrantState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ContactGrantState(v) { + case ContactGrantStateActive: + *s = ContactGrantStateActive + case ContactGrantStateRevoked: + *s = ContactGrantStateRevoked + default: + *s = ContactGrantState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ContactGrantState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactGrantState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactPhoneNumber as json. +func (s ContactPhoneNumber) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ContactPhoneNumber from json. +func (s *ContactPhoneNumber) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactPhoneNumber to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ContactPhoneNumber(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ContactPhoneNumber) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactPhoneNumber) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactRevocationReason as json. +func (s ContactRevocationReason) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes ContactRevocationReason from json. +func (s *ContactRevocationReason) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactRevocationReason to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch ContactRevocationReason(v) { + case ContactRevocationReasonConsentRevoked: + *s = ContactRevocationReasonConsentRevoked + case ContactRevocationReasonParticipationCancelled: + *s = ContactRevocationReasonParticipationCancelled + case ContactRevocationReasonVisibilityClosed: + *s = ContactRevocationReasonVisibilityClosed + default: + *s = ContactRevocationReason(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ContactRevocationReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactRevocationReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactTelegramUsername as json. +func (s ContactTelegramUsername) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes ContactTelegramUsername from json. +func (s *ContactTelegramUsername) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ContactTelegramUsername to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ContactTelegramUsername(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s ContactTelegramUsername) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ContactTelegramUsername) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CreateMyAssessmentAttemptBadRequest as json. func (s *CreateMyAssessmentAttemptBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -6513,6 +8947,234 @@ func (s *CreateMySupportCaseUnprocessableEntity) UnmarshalJSON(data []byte) erro return s.Decode(d) } +// Encode encodes CreateOrganizationInvitationBadRequest as json. +func (s *CreateOrganizationInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateOrganizationInvitationBadRequest from json. +func (s *CreateOrganizationInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateOrganizationInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateOrganizationInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateOrganizationInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateOrganizationInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateOrganizationInvitationConflict as json. +func (s *CreateOrganizationInvitationConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateOrganizationInvitationConflict from json. +func (s *CreateOrganizationInvitationConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateOrganizationInvitationConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateOrganizationInvitationConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateOrganizationInvitationConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateOrganizationInvitationConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateOrganizationInvitationForbidden as json. +func (s *CreateOrganizationInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateOrganizationInvitationForbidden from json. +func (s *CreateOrganizationInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateOrganizationInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateOrganizationInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateOrganizationInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateOrganizationInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateOrganizationInvitationNotFound as json. +func (s *CreateOrganizationInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateOrganizationInvitationNotFound from json. +func (s *CreateOrganizationInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateOrganizationInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateOrganizationInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateOrganizationInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateOrganizationInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateOrganizationInvitationUnauthorized as json. +func (s *CreateOrganizationInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateOrganizationInvitationUnauthorized from json. +func (s *CreateOrganizationInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateOrganizationInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateOrganizationInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateOrganizationInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateOrganizationInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateOrganizationInvitationUnprocessableEntity as json. +func (s *CreateOrganizationInvitationUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateOrganizationInvitationUnprocessableEntity from json. +func (s *CreateOrganizationInvitationUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateOrganizationInvitationUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CreateOrganizationInvitationUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateOrganizationInvitationUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateOrganizationInvitationUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CreateOrganizationNeedBadRequest as json. func (s *CreateOrganizationNeedBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -6819,6 +9481,272 @@ func (s *CurrencyCode) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes DeclineMyInvitationBadRequest as json. +func (s *DeclineMyInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes DeclineMyInvitationBadRequest from json. +func (s *DeclineMyInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DeclineMyInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = DeclineMyInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *DeclineMyInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DeclineMyInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes DeclineMyInvitationConflict as json. +func (s *DeclineMyInvitationConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes DeclineMyInvitationConflict from json. +func (s *DeclineMyInvitationConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DeclineMyInvitationConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = DeclineMyInvitationConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *DeclineMyInvitationConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DeclineMyInvitationConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes DeclineMyInvitationForbidden as json. +func (s *DeclineMyInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes DeclineMyInvitationForbidden from json. +func (s *DeclineMyInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DeclineMyInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = DeclineMyInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *DeclineMyInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DeclineMyInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes DeclineMyInvitationNotFound as json. +func (s *DeclineMyInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes DeclineMyInvitationNotFound from json. +func (s *DeclineMyInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DeclineMyInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = DeclineMyInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *DeclineMyInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DeclineMyInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes DeclineMyInvitationPreconditionFailed as json. +func (s *DeclineMyInvitationPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes DeclineMyInvitationPreconditionFailed from json. +func (s *DeclineMyInvitationPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DeclineMyInvitationPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = DeclineMyInvitationPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *DeclineMyInvitationPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DeclineMyInvitationPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes DeclineMyInvitationUnauthorized as json. +func (s *DeclineMyInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes DeclineMyInvitationUnauthorized from json. +func (s *DeclineMyInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DeclineMyInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = DeclineMyInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *DeclineMyInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DeclineMyInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes DeclineMyInvitationUnprocessableEntity as json. +func (s *DeclineMyInvitationUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes DeclineMyInvitationUnprocessableEntity from json. +func (s *DeclineMyInvitationUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode DeclineMyInvitationUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = DeclineMyInvitationUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *DeclineMyInvitationUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *DeclineMyInvitationUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes DirectionCode as json. func (s DirectionCode) Encode(e *jx.Encoder) { e.Str(string(s)) @@ -8209,6 +11137,158 @@ func (s *GetMyAssessmentResultUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GetMyInvitationBadRequest as json. +func (s *GetMyInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyInvitationBadRequest from json. +func (s *GetMyInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyInvitationForbidden as json. +func (s *GetMyInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyInvitationForbidden from json. +func (s *GetMyInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyInvitationNotFound as json. +func (s *GetMyInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyInvitationNotFound from json. +func (s *GetMyInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyInvitationUnauthorized as json. +func (s *GetMyInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyInvitationUnauthorized from json. +func (s *GetMyInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetMyQuestionnaireForbidden as json. func (s *GetMyQuestionnaireForbidden) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -8399,6 +11479,310 @@ func (s *GetMySupportCaseUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GetOrganizationInvitationBadRequest as json. +func (s *GetOrganizationInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationInvitationBadRequest from json. +func (s *GetOrganizationInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationInvitationContactsBadRequest as json. +func (s *GetOrganizationInvitationContactsBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationInvitationContactsBadRequest from json. +func (s *GetOrganizationInvitationContactsBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationInvitationContactsBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationInvitationContactsBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationInvitationContactsBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationInvitationContactsBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationInvitationContactsForbidden as json. +func (s *GetOrganizationInvitationContactsForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationInvitationContactsForbidden from json. +func (s *GetOrganizationInvitationContactsForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationInvitationContactsForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationInvitationContactsForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationInvitationContactsForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationInvitationContactsForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationInvitationContactsNotFound as json. +func (s *GetOrganizationInvitationContactsNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationInvitationContactsNotFound from json. +func (s *GetOrganizationInvitationContactsNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationInvitationContactsNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationInvitationContactsNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationInvitationContactsNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationInvitationContactsNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationInvitationContactsUnauthorized as json. +func (s *GetOrganizationInvitationContactsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationInvitationContactsUnauthorized from json. +func (s *GetOrganizationInvitationContactsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationInvitationContactsUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationInvitationContactsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationInvitationContactsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationInvitationContactsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationInvitationForbidden as json. +func (s *GetOrganizationInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationInvitationForbidden from json. +func (s *GetOrganizationInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationInvitationNotFound as json. +func (s *GetOrganizationInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationInvitationNotFound from json. +func (s *GetOrganizationInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetOrganizationInvitationUnauthorized as json. +func (s *GetOrganizationInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetOrganizationInvitationUnauthorized from json. +func (s *GetOrganizationInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetOrganizationInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetOrganizationInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetOrganizationInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetOrganizationInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetOrganizationNeedBadRequest as json. func (s *GetOrganizationNeedBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -8859,6 +12243,2510 @@ func (s *IdentityRequestAcceptedStatus) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *InvitationAcceptance) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationAcceptance) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + e.FieldStart("terms_version") + s.TermsVersion.Encode(e) + } + { + e.FieldStart("consent_c4") + s.ConsentC4.Encode(e) + } +} + +var jsonFieldsNameOfInvitationAcceptance = [3]string{ + 0: "expected_version", + 1: "terms_version", + 2: "consent_c4", +} + +// Decode decodes InvitationAcceptance from json. +func (s *InvitationAcceptance) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationAcceptance to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "terms_version": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.TermsVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms_version\"") + } + case "consent_c4": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.ConsentC4.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"consent_c4\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationAcceptance") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationAcceptance) { + name = jsonFieldsNameOfInvitationAcceptance[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationAcceptance) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationAcceptance) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationCommand) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationCommand) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } +} + +var jsonFieldsNameOfInvitationCommand = [1]string{ + 0: "expected_version", +} + +// Decode decodes InvitationCommand from json. +func (s *InvitationCommand) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationCommand to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationCommand") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationCommand) { + name = jsonFieldsNameOfInvitationCommand[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationCommand) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationCommand) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationCommunicationChannel as json. +func (s InvitationCommunicationChannel) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes InvitationCommunicationChannel from json. +func (s *InvitationCommunicationChannel) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationCommunicationChannel to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch InvitationCommunicationChannel(v) { + case InvitationCommunicationChannelEmail: + *s = InvitationCommunicationChannelEmail + case InvitationCommunicationChannelPhone: + *s = InvitationCommunicationChannelPhone + case InvitationCommunicationChannelTelegram: + *s = InvitationCommunicationChannelTelegram + case InvitationCommunicationChannelVideoCall: + *s = InvitationCommunicationChannelVideoCall + default: + *s = InvitationCommunicationChannel(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationCommunicationChannel) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationCommunicationChannel) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationCommunicationMethod) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationCommunicationMethod) encodeFields(e *jx.Encoder) { + { + e.FieldStart("channel") + s.Channel.Encode(e) + } + { + e.FieldStart("details") + s.Details.Encode(e) + } +} + +var jsonFieldsNameOfInvitationCommunicationMethod = [2]string{ + 0: "channel", + 1: "details", +} + +// Decode decodes InvitationCommunicationMethod from json. +func (s *InvitationCommunicationMethod) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationCommunicationMethod to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "channel": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Channel.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"channel\"") + } + case "details": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Details.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"details\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationCommunicationMethod") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationCommunicationMethod) { + name = jsonFieldsNameOfInvitationCommunicationMethod[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationCommunicationMethod) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationCommunicationMethod) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationCommunicationNote as json. +func (s InvitationCommunicationNote) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes InvitationCommunicationNote from json. +func (s *InvitationCommunicationNote) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationCommunicationNote to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = InvitationCommunicationNote(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationCommunicationNote) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationCommunicationNote) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationContactAccess) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationContactAccess) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("fields") + e.ArrStart() + for _, elem := range s.Fields { + elem.Encode(e) + } + e.ArrEnd() + } +} + +var jsonFieldsNameOfInvitationContactAccess = [2]string{ + 0: "status", + 1: "fields", +} + +// Decode decodes InvitationContactAccess from json. +func (s *InvitationContactAccess) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationContactAccess to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "fields": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + s.Fields = make([]ContactFieldKind, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem ContactFieldKind + if err := elem.Decode(d); err != nil { + return err + } + s.Fields = append(s.Fields, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"fields\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationContactAccess") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationContactAccess) { + name = jsonFieldsNameOfInvitationContactAccess[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationContactAccess) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationContactAccess) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationContactAccessState as json. +func (s InvitationContactAccessState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes InvitationContactAccessState from json. +func (s *InvitationContactAccessState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationContactAccessState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch InvitationContactAccessState(v) { + case InvitationContactAccessStateNotGranted: + *s = InvitationContactAccessStateNotGranted + case InvitationContactAccessStateAvailable: + *s = InvitationContactAccessStateAvailable + case InvitationContactAccessStateClosed: + *s = InvitationContactAccessStateClosed + default: + *s = InvitationContactAccessState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationContactAccessState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationContactAccessState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationDeclineComment as json. +func (s InvitationDeclineComment) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes InvitationDeclineComment from json. +func (s *InvitationDeclineComment) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationDeclineComment to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = InvitationDeclineComment(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationDeclineComment) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationDeclineComment) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationDeclineReason as json. +func (s InvitationDeclineReason) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes InvitationDeclineReason from json. +func (s *InvitationDeclineReason) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationDeclineReason to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch InvitationDeclineReason(v) { + case InvitationDeclineReasonSalary: + *s = InvitationDeclineReasonSalary + case InvitationDeclineReasonTasks: + *s = InvitationDeclineReasonTasks + case InvitationDeclineReasonStack: + *s = InvitationDeclineReasonStack + case InvitationDeclineReasonWorkFormat: + *s = InvitationDeclineReasonWorkFormat + case InvitationDeclineReasonPackage: + *s = InvitationDeclineReasonPackage + case InvitationDeclineReasonCompany: + *s = InvitationDeclineReasonCompany + case InvitationDeclineReasonNotLooking: + *s = InvitationDeclineReasonNotLooking + case InvitationDeclineReasonOtherOffer: + *s = InvitationDeclineReasonOtherOffer + case InvitationDeclineReasonOther: + *s = InvitationDeclineReasonOther + default: + *s = InvitationDeclineReason(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationDeclineReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationDeclineReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationDeclineRecord) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationDeclineRecord) encodeFields(e *jx.Encoder) { + { + e.FieldStart("reason") + s.Reason.Encode(e) + } + { + e.FieldStart("comment") + s.Comment.Encode(e) + } + { + e.FieldStart("declined_at") + s.DeclinedAt.Encode(e) + } +} + +var jsonFieldsNameOfInvitationDeclineRecord = [3]string{ + 0: "reason", + 1: "comment", + 2: "declined_at", +} + +// Decode decodes InvitationDeclineRecord from json. +func (s *InvitationDeclineRecord) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationDeclineRecord to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "reason": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Reason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"reason\"") + } + case "comment": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Comment.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"comment\"") + } + case "declined_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.DeclinedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"declined_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationDeclineRecord") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationDeclineRecord) { + name = jsonFieldsNameOfInvitationDeclineRecord[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationDeclineRecord) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationDeclineRecord) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationDeclineRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationDeclineRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + e.FieldStart("reason") + s.Reason.Encode(e) + } + { + if s.Comment.Set { + e.FieldStart("comment") + s.Comment.Encode(e) + } + } +} + +var jsonFieldsNameOfInvitationDeclineRequest = [3]string{ + 0: "expected_version", + 1: "reason", + 2: "comment", +} + +// Decode decodes InvitationDeclineRequest from json. +func (s *InvitationDeclineRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationDeclineRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "reason": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Reason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"reason\"") + } + case "comment": + if err := func() error { + s.Comment.Reset() + if err := s.Comment.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"comment\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationDeclineRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationDeclineRequest) { + name = jsonFieldsNameOfInvitationDeclineRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationDeclineRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationDeclineRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationExpiryReason as json. +func (s InvitationExpiryReason) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes InvitationExpiryReason from json. +func (s *InvitationExpiryReason) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationExpiryReason to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch InvitationExpiryReason(v) { + case InvitationExpiryReasonInvitationTimeout: + *s = InvitationExpiryReasonInvitationTimeout + case InvitationExpiryReasonNegotiationTimeout: + *s = InvitationExpiryReasonNegotiationTimeout + default: + *s = InvitationExpiryReason(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationExpiryReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationExpiryReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationNeedReference) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationNeedReference) encodeFields(e *jx.Encoder) { + { + e.FieldStart("need_id") + json.EncodeUUID(e, s.NeedID) + } + { + e.FieldStart("requirements_version") + s.RequirementsVersion.Encode(e) + } +} + +var jsonFieldsNameOfInvitationNeedReference = [2]string{ + 0: "need_id", + 1: "requirements_version", +} + +// Decode decodes InvitationNeedReference from json. +func (s *InvitationNeedReference) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationNeedReference to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "need_id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.NeedID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"need_id\"") + } + case "requirements_version": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.RequirementsVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"requirements_version\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationNeedReference") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationNeedReference) { + name = jsonFieldsNameOfInvitationNeedReference[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationNeedReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationNeedReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationOfferType as json. +func (s InvitationOfferType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes InvitationOfferType from json. +func (s *InvitationOfferType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationOfferType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch InvitationOfferType(v) { + case InvitationOfferTypeFullTime: + *s = InvitationOfferTypeFullTime + case InvitationOfferTypePartTime: + *s = InvitationOfferTypePartTime + case InvitationOfferTypeContract: + *s = InvitationOfferTypeContract + case InvitationOfferTypeInternship: + *s = InvitationOfferTypeInternship + default: + *s = InvitationOfferType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationOfferType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationOfferType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationOrganization) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationOrganization) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("name") + e.Str(s.Name) + } +} + +var jsonFieldsNameOfInvitationOrganization = [2]string{ + 0: "id", + 1: "name", +} + +// Decode decodes InvitationOrganization from json. +func (s *InvitationOrganization) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationOrganization to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "name": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Name = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"name\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationOrganization") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationOrganization) { + name = jsonFieldsNameOfInvitationOrganization[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationOrganization) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationOrganization) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationPackage) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationPackage) encodeFields(e *jx.Encoder) { + { + e.FieldStart("bonus") + s.Bonus.Encode(e) + } + { + e.FieldStart("equipment") + s.Equipment.Encode(e) + } + { + e.FieldStart("training") + s.Training.Encode(e) + } + { + e.FieldStart("health_insurance") + s.HealthInsurance.Encode(e) + } +} + +var jsonFieldsNameOfInvitationPackage = [4]string{ + 0: "bonus", + 1: "equipment", + 2: "training", + 3: "health_insurance", +} + +// Decode decodes InvitationPackage from json. +func (s *InvitationPackage) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationPackage to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "bonus": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Bonus.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"bonus\"") + } + case "equipment": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Equipment.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"equipment\"") + } + case "training": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Training.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"training\"") + } + case "health_insurance": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.HealthInsurance.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"health_insurance\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationPackage") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationPackage) { + name = jsonFieldsNameOfInvitationPackage[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationPackage) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationPackage) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationPackageItem as json. +func (s InvitationPackageItem) Encode(e *jx.Encoder) { + switch s.Type { + case InvitationPackageItemProvidedInvitationPackageItem: + s.InvitationPackageItemProvided.Encode(e) + case InvitationPackageItemNotProvidedInvitationPackageItem: + s.InvitationPackageItemNotProvided.Encode(e) + } +} + +func (s InvitationPackageItem) encodeFields(e *jx.Encoder) { + switch s.Type { + case InvitationPackageItemProvidedInvitationPackageItem: + s.InvitationPackageItemProvided.encodeFields(e) + case InvitationPackageItemNotProvidedInvitationPackageItem: + s.InvitationPackageItemNotProvided.encodeFields(e) + } +} + +// Decode decodes InvitationPackageItem from json. +func (s *InvitationPackageItem) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationPackageItem to nil") + } + // Sum type fields. + if typ := d.Next(); typ != jx.Object { + return errors.Errorf("unexpected json type %q", typ) + } + + var found bool + if err := d.Capture(func(d *jx.Decoder) error { + return d.ObjBytes(func(d *jx.Decoder, key []byte) error { + switch string(key) { + case "description": + // Type-based discrimination: check if field has expected JSON type + if typ := d.Next(); typ != jx.String { + // Field exists but has wrong type, not a match for this variant + return d.Skip() + } + match := InvitationPackageItemProvidedInvitationPackageItem + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "status": + // Value-based discrimination: check enum value + if typ := d.Next(); typ != jx.String { + return d.Skip() + } + value, err := d.StrBytes() + if err != nil { + return err + } + switch string(value) { + case "not_provided": + match := InvitationPackageItemNotProvidedInvitationPackageItem + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "provided": + match := InvitationPackageItemProvidedInvitationPackageItem + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + default: + // Unknown enum value, ignore and continue + } + return nil + } + return d.Skip() + }) + }); err != nil { + return errors.Wrap(err, "capture") + } + if !found { + return errors.New("unable to detect sum type variant") + } + switch s.Type { + case InvitationPackageItemProvidedInvitationPackageItem: + if err := s.InvitationPackageItemProvided.Decode(d); err != nil { + return err + } + case InvitationPackageItemNotProvidedInvitationPackageItem: + if err := s.InvitationPackageItemNotProvided.Decode(d); err != nil { + return err + } + default: + return errors.Errorf("inferred invalid type: %s", s.Type) + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationPackageItem) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationPackageItem) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationPackageItemNotProvided) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationPackageItemNotProvided) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } +} + +var jsonFieldsNameOfInvitationPackageItemNotProvided = [1]string{ + 0: "status", +} + +// Decode decodes InvitationPackageItemNotProvided from json. +func (s *InvitationPackageItemNotProvided) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationPackageItemNotProvided to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationPackageItemNotProvided") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationPackageItemNotProvided) { + name = jsonFieldsNameOfInvitationPackageItemNotProvided[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationPackageItemNotProvided) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationPackageItemNotProvided) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationPackageItemNotProvidedStatus as json. +func (s InvitationPackageItemNotProvidedStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes InvitationPackageItemNotProvidedStatus from json. +func (s *InvitationPackageItemNotProvidedStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationPackageItemNotProvidedStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch InvitationPackageItemNotProvidedStatus(v) { + case InvitationPackageItemNotProvidedStatusNotProvided: + *s = InvitationPackageItemNotProvidedStatusNotProvided + default: + *s = InvitationPackageItemNotProvidedStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationPackageItemNotProvidedStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationPackageItemNotProvidedStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationPackageItemProvided) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationPackageItemProvided) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("description") + s.Description.Encode(e) + } +} + +var jsonFieldsNameOfInvitationPackageItemProvided = [2]string{ + 0: "status", + 1: "description", +} + +// Decode decodes InvitationPackageItemProvided from json. +func (s *InvitationPackageItemProvided) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationPackageItemProvided to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "description": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Description.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"description\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationPackageItemProvided") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationPackageItemProvided) { + name = jsonFieldsNameOfInvitationPackageItemProvided[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationPackageItemProvided) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationPackageItemProvided) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationPackageItemProvidedStatus as json. +func (s InvitationPackageItemProvidedStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes InvitationPackageItemProvidedStatus from json. +func (s *InvitationPackageItemProvidedStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationPackageItemProvidedStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch InvitationPackageItemProvidedStatus(v) { + case InvitationPackageItemProvidedStatusProvided: + *s = InvitationPackageItemProvidedStatusProvided + default: + *s = InvitationPackageItemProvidedStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationPackageItemProvidedStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationPackageItemProvidedStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationPackageItemText as json. +func (s InvitationPackageItemText) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes InvitationPackageItemText from json. +func (s *InvitationPackageItemText) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationPackageItemText to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = InvitationPackageItemText(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationPackageItemText) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationPackageItemText) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationResponsePeriod as json. +func (s InvitationResponsePeriod) Encode(e *jx.Encoder) { + e.Int32(int32(s)) +} + +// Decode decodes InvitationResponsePeriod from json. +func (s *InvitationResponsePeriod) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationResponsePeriod to nil") + } + v, err := d.Int32() + if err != nil { + return err + } + *s = InvitationResponsePeriod(v) + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationResponsePeriod) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationResponsePeriod) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationRoleTitle as json. +func (s InvitationRoleTitle) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes InvitationRoleTitle from json. +func (s *InvitationRoleTitle) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationRoleTitle to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = InvitationRoleTitle(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationRoleTitle) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationRoleTitle) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationSalaryFit as json. +func (s InvitationSalaryFit) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes InvitationSalaryFit from json. +func (s *InvitationSalaryFit) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationSalaryFit to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch InvitationSalaryFit(v) { + case InvitationSalaryFitWithinRange: + *s = InvitationSalaryFitWithinRange + case InvitationSalaryFitUpTo10PercentAbove: + *s = InvitationSalaryFitUpTo10PercentAbove + case InvitationSalaryFitAbove: + *s = InvitationSalaryFitAbove + case InvitationSalaryFitWithheld: + *s = InvitationSalaryFitWithheld + case InvitationSalaryFitNotAvailable: + *s = InvitationSalaryFitNotAvailable + default: + *s = InvitationSalaryFit(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationSalaryFit) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationSalaryFit) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationSalaryRaise) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationSalaryRaise) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + e.FieldStart("salary_to") + s.SalaryTo.Encode(e) + } +} + +var jsonFieldsNameOfInvitationSalaryRaise = [2]string{ + 0: "expected_version", + 1: "salary_to", +} + +// Decode decodes InvitationSalaryRaise from json. +func (s *InvitationSalaryRaise) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationSalaryRaise to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "salary_to": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.SalaryTo.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"salary_to\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationSalaryRaise") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationSalaryRaise) { + name = jsonFieldsNameOfInvitationSalaryRaise[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationSalaryRaise) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationSalaryRaise) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationState as json. +func (s InvitationState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes InvitationState from json. +func (s *InvitationState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch InvitationState(v) { + case InvitationStateDraft: + *s = InvitationStateDraft + case InvitationStateDelivered: + *s = InvitationStateDelivered + case InvitationStateViewed: + *s = InvitationStateViewed + case InvitationStateCounter: + *s = InvitationStateCounter + case InvitationStateAccepted: + *s = InvitationStateAccepted + case InvitationStateInterviewScheduled: + *s = InvitationStateInterviewScheduled + case InvitationStateInterviewed: + *s = InvitationStateInterviewed + case InvitationStateNegotiation: + *s = InvitationStateNegotiation + case InvitationStateTermsAgreed: + *s = InvitationStateTermsAgreed + case InvitationStateNoDeal: + *s = InvitationStateNoDeal + case InvitationStateDeclined: + *s = InvitationStateDeclined + case InvitationStateExpired: + *s = InvitationStateExpired + case InvitationStateWithdrawn: + *s = InvitationStateWithdrawn + case InvitationStateCancelledByCandidate: + *s = InvitationStateCancelledByCandidate + default: + *s = InvitationState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationTeamDescription as json. +func (s InvitationTeamDescription) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes InvitationTeamDescription from json. +func (s *InvitationTeamDescription) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationTeamDescription to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = InvitationTeamDescription(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationTeamDescription) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationTeamDescription) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *InvitationTerms) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *InvitationTerms) encodeFields(e *jx.Encoder) { + { + e.FieldStart("role_title") + s.RoleTitle.Encode(e) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("grade") + s.Grade.Encode(e) + } + { + e.FieldStart("offer_type") + s.OfferType.Encode(e) + } + { + e.FieldStart("tasks") + e.ArrStart() + for _, elem := range s.Tasks { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("team") + s.Team.Encode(e) + } + { + e.FieldStart("tech_stack") + e.ArrStart() + for _, elem := range s.TechStack { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("work_formats") + e.ArrStart() + for _, elem := range s.WorkFormats { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("location") + s.Location.Encode(e) + } + { + e.FieldStart("communication_method") + s.CommunicationMethod.Encode(e) + } + { + e.FieldStart("salary") + s.Salary.Encode(e) + } + { + e.FieldStart("package") + s.Package.Encode(e) + } +} + +var jsonFieldsNameOfInvitationTerms = [12]string{ + 0: "role_title", + 1: "specialization", + 2: "grade", + 3: "offer_type", + 4: "tasks", + 5: "team", + 6: "tech_stack", + 7: "work_formats", + 8: "location", + 9: "communication_method", + 10: "salary", + 11: "package", +} + +// Decode decodes InvitationTerms from json. +func (s *InvitationTerms) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationTerms to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "role_title": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.RoleTitle.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"role_title\"") + } + case "specialization": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "grade": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Grade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"grade\"") + } + case "offer_type": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.OfferType.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"offer_type\"") + } + case "tasks": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + s.Tasks = make([]NeedTaskText, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem NeedTaskText + if err := elem.Decode(d); err != nil { + return err + } + s.Tasks = append(s.Tasks, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tasks\"") + } + case "team": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Team.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"team\"") + } + case "tech_stack": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + s.TechStack = make([]SkillName, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem SkillName + if err := elem.Decode(d); err != nil { + return err + } + s.TechStack = append(s.TechStack, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"tech_stack\"") + } + case "work_formats": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + s.WorkFormats = make([]WorkFormat, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem WorkFormat + if err := elem.Decode(d); err != nil { + return err + } + s.WorkFormats = append(s.WorkFormats, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"work_formats\"") + } + case "location": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.Location.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"location\"") + } + case "communication_method": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.CommunicationMethod.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"communication_method\"") + } + case "salary": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.Salary.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"salary\"") + } + case "package": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.Package.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"package\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode InvitationTerms") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfInvitationTerms) { + name = jsonFieldsNameOfInvitationTerms[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *InvitationTerms) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationTerms) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationTermsVersion as json. +func (s InvitationTermsVersion) Encode(e *jx.Encoder) { + unwrapped := int64(s) + + e.Int64(unwrapped) +} + +// Decode decodes InvitationTermsVersion from json. +func (s *InvitationTermsVersion) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationTermsVersion to nil") + } + var unwrapped int64 + if err := func() error { + v, err := d.Int64() + unwrapped = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = InvitationTermsVersion(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationTermsVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationTermsVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationVersion as json. +func (s InvitationVersion) Encode(e *jx.Encoder) { + unwrapped := int64(s) + + e.Int64(unwrapped) +} + +// Decode decodes InvitationVersion from json. +func (s *InvitationVersion) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode InvitationVersion to nil") + } + var unwrapped int64 + if err := func() error { + v, err := d.Int64() + unwrapped = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = InvitationVersion(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s InvitationVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *InvitationVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ItemContent as json. func (s ItemContent) Encode(e *jx.Encoder) { switch s.Type { @@ -9170,6 +15058,120 @@ func (s *ItemContent) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListMyInvitationsBadRequest as json. +func (s *ListMyInvitationsBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyInvitationsBadRequest from json. +func (s *ListMyInvitationsBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyInvitationsBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyInvitationsBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyInvitationsBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyInvitationsBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyInvitationsForbidden as json. +func (s *ListMyInvitationsForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyInvitationsForbidden from json. +func (s *ListMyInvitationsForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyInvitationsForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyInvitationsForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyInvitationsForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyInvitationsForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyInvitationsUnauthorized as json. +func (s *ListMyInvitationsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyInvitationsUnauthorized from json. +func (s *ListMyInvitationsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyInvitationsUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyInvitationsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyInvitationsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyInvitationsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ListMySupportCasesBadRequest as json. func (s *ListMySupportCasesBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -9246,6 +15248,158 @@ func (s *ListMySupportCasesUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListOrganizationInvitationsBadRequest as json. +func (s *ListOrganizationInvitationsBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListOrganizationInvitationsBadRequest from json. +func (s *ListOrganizationInvitationsBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListOrganizationInvitationsBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListOrganizationInvitationsBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListOrganizationInvitationsBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListOrganizationInvitationsBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListOrganizationInvitationsForbidden as json. +func (s *ListOrganizationInvitationsForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListOrganizationInvitationsForbidden from json. +func (s *ListOrganizationInvitationsForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListOrganizationInvitationsForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListOrganizationInvitationsForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListOrganizationInvitationsForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListOrganizationInvitationsForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListOrganizationInvitationsNotFound as json. +func (s *ListOrganizationInvitationsNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListOrganizationInvitationsNotFound from json. +func (s *ListOrganizationInvitationsNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListOrganizationInvitationsNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListOrganizationInvitationsNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListOrganizationInvitationsNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListOrganizationInvitationsNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListOrganizationInvitationsUnauthorized as json. +func (s *ListOrganizationInvitationsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListOrganizationInvitationsUnauthorized from json. +func (s *ListOrganizationInvitationsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListOrganizationInvitationsUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListOrganizationInvitationsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListOrganizationInvitationsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListOrganizationInvitationsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ListOrganizationNeedsBadRequest as json. func (s *ListOrganizationNeedsBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -15214,6 +21368,358 @@ func (s *NilCandidateExperience) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ContactAccessBlock as json. +func (o NilContactAccessBlock) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes ContactAccessBlock from json. +func (o *NilContactAccessBlock) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilContactAccessBlock to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ContactAccessBlock + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilContactAccessBlock) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilContactAccessBlock) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactConsentOffer as json. +func (o NilContactConsentOffer) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ContactConsentOffer from json. +func (o *NilContactConsentOffer) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilContactConsentOffer to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ContactConsentOffer + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilContactConsentOffer) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilContactConsentOffer) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactFullName as json. +func (o NilContactFullName) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ContactFullName from json. +func (o *NilContactFullName) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilContactFullName to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ContactFullName + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilContactFullName) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilContactFullName) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactGrant as json. +func (o NilContactGrant) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ContactGrant from json. +func (o *NilContactGrant) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilContactGrant to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ContactGrant + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilContactGrant) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilContactGrant) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactPhoneNumber as json. +func (o NilContactPhoneNumber) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ContactPhoneNumber from json. +func (o *NilContactPhoneNumber) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilContactPhoneNumber to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ContactPhoneNumber + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilContactPhoneNumber) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilContactPhoneNumber) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactRevocationReason as json. +func (o NilContactRevocationReason) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes ContactRevocationReason from json. +func (o *NilContactRevocationReason) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilContactRevocationReason to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ContactRevocationReason + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilContactRevocationReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilContactRevocationReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ContactTelegramUsername as json. +func (o NilContactTelegramUsername) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes ContactTelegramUsername from json. +func (o *NilContactTelegramUsername) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilContactTelegramUsername to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v ContactTelegramUsername + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilContactTelegramUsername) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilContactTelegramUsername) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes EmailAddress as json. +func (o NilEmailAddress) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes EmailAddress from json. +func (o *NilEmailAddress) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilEmailAddress to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v EmailAddress + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilEmailAddress) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilEmailAddress) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes float64 as json. func (o NilFloat64) Encode(e *jx.Encoder) { if o.Null { @@ -15350,6 +21856,226 @@ func (s *NilInt32) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes InvitationCommunicationNote as json. +func (o NilInvitationCommunicationNote) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes InvitationCommunicationNote from json. +func (o *NilInvitationCommunicationNote) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilInvitationCommunicationNote to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v InvitationCommunicationNote + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilInvitationCommunicationNote) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilInvitationCommunicationNote) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationDeclineComment as json. +func (o NilInvitationDeclineComment) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes InvitationDeclineComment from json. +func (o *NilInvitationDeclineComment) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilInvitationDeclineComment to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v InvitationDeclineComment + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilInvitationDeclineComment) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilInvitationDeclineComment) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationDeclineRecord as json. +func (o NilInvitationDeclineRecord) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes InvitationDeclineRecord from json. +func (o *NilInvitationDeclineRecord) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilInvitationDeclineRecord to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v InvitationDeclineRecord + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilInvitationDeclineRecord) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilInvitationDeclineRecord) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationExpiryReason as json. +func (o NilInvitationExpiryReason) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes InvitationExpiryReason from json. +func (o *NilInvitationExpiryReason) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilInvitationExpiryReason to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v InvitationExpiryReason + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilInvitationExpiryReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilInvitationExpiryReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationNeedReference as json. +func (o NilInvitationNeedReference) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes InvitationNeedReference from json. +func (o *NilInvitationNeedReference) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilInvitationNeedReference to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v InvitationNeedReference + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilInvitationNeedReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilInvitationNeedReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes NeedDomainName as json. func (o NilNeedDomainName) Encode(e *jx.Encoder) { if o.Null { @@ -16754,6 +23480,72 @@ func (s *OnboardingStep) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes InvitationResponsePeriod as json. +func (o OptInvitationResponsePeriod) Encode(e *jx.Encoder) { + if !o.Set { + return + } + e.Int32(int32(o.Value)) +} + +// Decode decodes InvitationResponsePeriod from json. +func (o *OptInvitationResponsePeriod) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptInvitationResponsePeriod to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptInvitationResponsePeriod) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptInvitationResponsePeriod) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationTerms as json. +func (o OptInvitationTerms) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes InvitationTerms from json. +func (o *OptInvitationTerms) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptInvitationTerms to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptInvitationTerms) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptInvitationTerms) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes NeedTitle as json. func (o OptNeedTitle) Encode(e *jx.Encoder) { if !o.Set { @@ -16787,6 +23579,104 @@ func (s *OptNeedTitle) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes InvitationDeclineComment as json. +func (o OptNilInvitationDeclineComment) Encode(e *jx.Encoder) { + if !o.Set { + return + } + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes InvitationDeclineComment from json. +func (o *OptNilInvitationDeclineComment) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptNilInvitationDeclineComment to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v InvitationDeclineComment + o.Value = v + o.Set = true + o.Null = true + return nil + } + o.Set = true + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptNilInvitationDeclineComment) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptNilInvitationDeclineComment) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes InvitationNeedReference as json. +func (o OptNilInvitationNeedReference) Encode(e *jx.Encoder) { + if !o.Set { + return + } + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes InvitationNeedReference from json. +func (o *OptNilInvitationNeedReference) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptNilInvitationNeedReference to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v InvitationNeedReference + o.Value = v + o.Set = true + o.Null = true + return nil + } + o.Set = true + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptNilInvitationNeedReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptNilInvitationNeedReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes NeedDomainInput as json. func (o OptNilNeedDomainInput) Encode(e *jx.Encoder) { if !o.Set { @@ -17633,6 +24523,1064 @@ func (s *OrderItemContentFormat) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *OrganizationInvitation) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *OrganizationInvitation) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("organization_id") + json.EncodeUUID(e, s.OrganizationID) + } + { + e.FieldStart("candidate_handle") + s.CandidateHandle.Encode(e) + } + { + e.FieldStart("need") + s.Need.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("expiry_reason") + s.ExpiryReason.Encode(e) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("terms_version") + s.TermsVersion.Encode(e) + } + { + e.FieldStart("terms") + s.Terms.Encode(e) + } + { + e.FieldStart("response_period_days") + s.ResponsePeriodDays.Encode(e) + } + { + e.FieldStart("response_deadline_at") + s.ResponseDeadlineAt.Encode(e) + } + { + e.FieldStart("salary_raise_used") + e.Bool(s.SalaryRaiseUsed) + } + { + e.FieldStart("salary_fit") + s.SalaryFit.Encode(e) + } + { + e.FieldStart("contact_access") + s.ContactAccess.Encode(e) + } + { + e.FieldStart("created_at") + s.CreatedAt.Encode(e) + } + { + e.FieldStart("updated_at") + s.UpdatedAt.Encode(e) + } + { + e.FieldStart("delivered_at") + s.DeliveredAt.Encode(e) + } + { + e.FieldStart("viewed_at") + s.ViewedAt.Encode(e) + } + { + e.FieldStart("responded_at") + s.RespondedAt.Encode(e) + } +} + +var jsonFieldsNameOfOrganizationInvitation = [19]string{ + 0: "id", + 1: "organization_id", + 2: "candidate_handle", + 3: "need", + 4: "state", + 5: "expiry_reason", + 6: "version", + 7: "terms_version", + 8: "terms", + 9: "response_period_days", + 10: "response_deadline_at", + 11: "salary_raise_used", + 12: "salary_fit", + 13: "contact_access", + 14: "created_at", + 15: "updated_at", + 16: "delivered_at", + 17: "viewed_at", + 18: "responded_at", +} + +// Decode decodes OrganizationInvitation from json. +func (s *OrganizationInvitation) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OrganizationInvitation to nil") + } + var requiredBitSet [3]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "organization_id": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := json.DecodeUUID(d) + s.OrganizationID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"organization_id\"") + } + case "candidate_handle": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.CandidateHandle.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"candidate_handle\"") + } + case "need": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Need.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"need\"") + } + case "state": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "expiry_reason": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.ExpiryReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expiry_reason\"") + } + case "version": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "terms_version": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.TermsVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms_version\"") + } + case "terms": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.Terms.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms\"") + } + case "response_period_days": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.ResponsePeriodDays.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"response_period_days\"") + } + case "response_deadline_at": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.ResponseDeadlineAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"response_deadline_at\"") + } + case "salary_raise_used": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + v, err := d.Bool() + s.SalaryRaiseUsed = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"salary_raise_used\"") + } + case "salary_fit": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.SalaryFit.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"salary_fit\"") + } + case "contact_access": + requiredBitSet[1] |= 1 << 5 + if err := func() error { + if err := s.ContactAccess.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"contact_access\"") + } + case "created_at": + requiredBitSet[1] |= 1 << 6 + if err := func() error { + if err := s.CreatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"created_at\"") + } + case "updated_at": + requiredBitSet[1] |= 1 << 7 + if err := func() error { + if err := s.UpdatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"updated_at\"") + } + case "delivered_at": + requiredBitSet[2] |= 1 << 0 + if err := func() error { + if err := s.DeliveredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"delivered_at\"") + } + case "viewed_at": + requiredBitSet[2] |= 1 << 1 + if err := func() error { + if err := s.ViewedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"viewed_at\"") + } + case "responded_at": + requiredBitSet[2] |= 1 << 2 + if err := func() error { + if err := s.RespondedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"responded_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode OrganizationInvitation") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [3]uint8{ + 0b11111111, + 0b11111111, + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfOrganizationInvitation) { + name = jsonFieldsNameOfOrganizationInvitation[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *OrganizationInvitation) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OrganizationInvitation) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *OrganizationInvitationCreate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *OrganizationInvitationCreate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("candidate_handle") + s.CandidateHandle.Encode(e) + } + { + if s.Need.Set { + e.FieldStart("need") + s.Need.Encode(e) + } + } + { + if s.ResponsePeriodDays.Set { + e.FieldStart("response_period_days") + s.ResponsePeriodDays.Encode(e) + } + } + { + e.FieldStart("terms") + s.Terms.Encode(e) + } +} + +var jsonFieldsNameOfOrganizationInvitationCreate = [4]string{ + 0: "candidate_handle", + 1: "need", + 2: "response_period_days", + 3: "terms", +} + +// Decode decodes OrganizationInvitationCreate from json. +func (s *OrganizationInvitationCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OrganizationInvitationCreate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "candidate_handle": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.CandidateHandle.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"candidate_handle\"") + } + case "need": + if err := func() error { + s.Need.Reset() + if err := s.Need.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"need\"") + } + case "response_period_days": + if err := func() error { + s.ResponsePeriodDays.Reset() + if err := s.ResponsePeriodDays.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"response_period_days\"") + } + case "terms": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Terms.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode OrganizationInvitationCreate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfOrganizationInvitationCreate) { + name = jsonFieldsNameOfOrganizationInvitationCreate[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *OrganizationInvitationCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OrganizationInvitationCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *OrganizationInvitationList) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *OrganizationInvitationList) encodeFields(e *jx.Encoder) { + { + e.FieldStart("items") + e.ArrStart() + for _, elem := range s.Items { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("page") + s.Page.Encode(e) + } +} + +var jsonFieldsNameOfOrganizationInvitationList = [2]string{ + 0: "items", + 1: "page", +} + +// Decode decodes OrganizationInvitationList from json. +func (s *OrganizationInvitationList) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OrganizationInvitationList to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "items": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Items = make([]OrganizationInvitationSummary, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem OrganizationInvitationSummary + if err := elem.Decode(d); err != nil { + return err + } + s.Items = append(s.Items, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"items\"") + } + case "page": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Page.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"page\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode OrganizationInvitationList") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfOrganizationInvitationList) { + name = jsonFieldsNameOfOrganizationInvitationList[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *OrganizationInvitationList) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OrganizationInvitationList) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *OrganizationInvitationSummary) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *OrganizationInvitationSummary) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("candidate_handle") + s.CandidateHandle.Encode(e) + } + { + e.FieldStart("need") + s.Need.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("expiry_reason") + s.ExpiryReason.Encode(e) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } + { + e.FieldStart("terms_version") + s.TermsVersion.Encode(e) + } + { + e.FieldStart("role_title") + s.RoleTitle.Encode(e) + } + { + e.FieldStart("salary") + s.Salary.Encode(e) + } + { + e.FieldStart("response_deadline_at") + s.ResponseDeadlineAt.Encode(e) + } + { + e.FieldStart("contact_access") + s.ContactAccess.Encode(e) + } + { + e.FieldStart("created_at") + s.CreatedAt.Encode(e) + } + { + e.FieldStart("updated_at") + s.UpdatedAt.Encode(e) + } +} + +var jsonFieldsNameOfOrganizationInvitationSummary = [13]string{ + 0: "id", + 1: "candidate_handle", + 2: "need", + 3: "state", + 4: "expiry_reason", + 5: "version", + 6: "terms_version", + 7: "role_title", + 8: "salary", + 9: "response_deadline_at", + 10: "contact_access", + 11: "created_at", + 12: "updated_at", +} + +// Decode decodes OrganizationInvitationSummary from json. +func (s *OrganizationInvitationSummary) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OrganizationInvitationSummary to nil") + } + var requiredBitSet [2]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "candidate_handle": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.CandidateHandle.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"candidate_handle\"") + } + case "need": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Need.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"need\"") + } + case "state": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "expiry_reason": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.ExpiryReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expiry_reason\"") + } + case "version": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + case "terms_version": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.TermsVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms_version\"") + } + case "role_title": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.RoleTitle.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"role_title\"") + } + case "salary": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.Salary.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"salary\"") + } + case "response_deadline_at": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.ResponseDeadlineAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"response_deadline_at\"") + } + case "contact_access": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.ContactAccess.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"contact_access\"") + } + case "created_at": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + if err := s.CreatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"created_at\"") + } + case "updated_at": + requiredBitSet[1] |= 1 << 4 + if err := func() error { + if err := s.UpdatedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"updated_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode OrganizationInvitationSummary") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b00011111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfOrganizationInvitationSummary) { + name = jsonFieldsNameOfOrganizationInvitationSummary[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *OrganizationInvitationSummary) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OrganizationInvitationSummary) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *OrganizationInvitationUpdate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *OrganizationInvitationUpdate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + if s.Need.Set { + e.FieldStart("need") + s.Need.Encode(e) + } + } + { + if s.ResponsePeriodDays.Set { + e.FieldStart("response_period_days") + s.ResponsePeriodDays.Encode(e) + } + } + { + if s.Terms.Set { + e.FieldStart("terms") + s.Terms.Encode(e) + } + } +} + +var jsonFieldsNameOfOrganizationInvitationUpdate = [4]string{ + 0: "expected_version", + 1: "need", + 2: "response_period_days", + 3: "terms", +} + +// Decode decodes OrganizationInvitationUpdate from json. +func (s *OrganizationInvitationUpdate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode OrganizationInvitationUpdate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "need": + if err := func() error { + s.Need.Reset() + if err := s.Need.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"need\"") + } + case "response_period_days": + if err := func() error { + s.ResponsePeriodDays.Reset() + if err := s.ResponsePeriodDays.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"response_period_days\"") + } + case "terms": + if err := func() error { + s.Terms.Reset() + if err := s.Terms.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"terms\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode OrganizationInvitationUpdate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfOrganizationInvitationUpdate) { + name = jsonFieldsNameOfOrganizationInvitationUpdate[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *OrganizationInvitationUpdate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OrganizationInvitationUpdate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *PageInfo) Encode(e *jx.Encoder) { e.ObjStart() @@ -19451,6 +27399,272 @@ func (s *QuestionnaireVersion) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes RaiseOrganizationInvitationSalaryBadRequest as json. +func (s *RaiseOrganizationInvitationSalaryBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RaiseOrganizationInvitationSalaryBadRequest from json. +func (s *RaiseOrganizationInvitationSalaryBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RaiseOrganizationInvitationSalaryBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RaiseOrganizationInvitationSalaryBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RaiseOrganizationInvitationSalaryBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RaiseOrganizationInvitationSalaryBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RaiseOrganizationInvitationSalaryConflict as json. +func (s *RaiseOrganizationInvitationSalaryConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RaiseOrganizationInvitationSalaryConflict from json. +func (s *RaiseOrganizationInvitationSalaryConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RaiseOrganizationInvitationSalaryConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RaiseOrganizationInvitationSalaryConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RaiseOrganizationInvitationSalaryConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RaiseOrganizationInvitationSalaryConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RaiseOrganizationInvitationSalaryForbidden as json. +func (s *RaiseOrganizationInvitationSalaryForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RaiseOrganizationInvitationSalaryForbidden from json. +func (s *RaiseOrganizationInvitationSalaryForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RaiseOrganizationInvitationSalaryForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RaiseOrganizationInvitationSalaryForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RaiseOrganizationInvitationSalaryForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RaiseOrganizationInvitationSalaryForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RaiseOrganizationInvitationSalaryNotFound as json. +func (s *RaiseOrganizationInvitationSalaryNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RaiseOrganizationInvitationSalaryNotFound from json. +func (s *RaiseOrganizationInvitationSalaryNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RaiseOrganizationInvitationSalaryNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RaiseOrganizationInvitationSalaryNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RaiseOrganizationInvitationSalaryNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RaiseOrganizationInvitationSalaryNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RaiseOrganizationInvitationSalaryPreconditionFailed as json. +func (s *RaiseOrganizationInvitationSalaryPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RaiseOrganizationInvitationSalaryPreconditionFailed from json. +func (s *RaiseOrganizationInvitationSalaryPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RaiseOrganizationInvitationSalaryPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RaiseOrganizationInvitationSalaryPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RaiseOrganizationInvitationSalaryPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RaiseOrganizationInvitationSalaryPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RaiseOrganizationInvitationSalaryUnauthorized as json. +func (s *RaiseOrganizationInvitationSalaryUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RaiseOrganizationInvitationSalaryUnauthorized from json. +func (s *RaiseOrganizationInvitationSalaryUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RaiseOrganizationInvitationSalaryUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RaiseOrganizationInvitationSalaryUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RaiseOrganizationInvitationSalaryUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RaiseOrganizationInvitationSalaryUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes RaiseOrganizationInvitationSalaryUnprocessableEntity as json. +func (s *RaiseOrganizationInvitationSalaryUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes RaiseOrganizationInvitationSalaryUnprocessableEntity from json. +func (s *RaiseOrganizationInvitationSalaryUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode RaiseOrganizationInvitationSalaryUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = RaiseOrganizationInvitationSalaryUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *RaiseOrganizationInvitationSalaryUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *RaiseOrganizationInvitationSalaryUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes RegisterAccountBadRequest as json. func (s *RegisterAccountBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -20242,6 +28456,272 @@ func (s *SaveMyQuestionnaireUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes SendOrganizationInvitationBadRequest as json. +func (s *SendOrganizationInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SendOrganizationInvitationBadRequest from json. +func (s *SendOrganizationInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SendOrganizationInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SendOrganizationInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SendOrganizationInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SendOrganizationInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SendOrganizationInvitationConflict as json. +func (s *SendOrganizationInvitationConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SendOrganizationInvitationConflict from json. +func (s *SendOrganizationInvitationConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SendOrganizationInvitationConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SendOrganizationInvitationConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SendOrganizationInvitationConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SendOrganizationInvitationConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SendOrganizationInvitationForbidden as json. +func (s *SendOrganizationInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SendOrganizationInvitationForbidden from json. +func (s *SendOrganizationInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SendOrganizationInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SendOrganizationInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SendOrganizationInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SendOrganizationInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SendOrganizationInvitationNotFound as json. +func (s *SendOrganizationInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SendOrganizationInvitationNotFound from json. +func (s *SendOrganizationInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SendOrganizationInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SendOrganizationInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SendOrganizationInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SendOrganizationInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SendOrganizationInvitationPreconditionFailed as json. +func (s *SendOrganizationInvitationPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SendOrganizationInvitationPreconditionFailed from json. +func (s *SendOrganizationInvitationPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SendOrganizationInvitationPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SendOrganizationInvitationPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SendOrganizationInvitationPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SendOrganizationInvitationPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SendOrganizationInvitationUnauthorized as json. +func (s *SendOrganizationInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SendOrganizationInvitationUnauthorized from json. +func (s *SendOrganizationInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SendOrganizationInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SendOrganizationInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SendOrganizationInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SendOrganizationInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SendOrganizationInvitationUnprocessableEntity as json. +func (s *SendOrganizationInvitationUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SendOrganizationInvitationUnprocessableEntity from json. +func (s *SendOrganizationInvitationUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SendOrganizationInvitationUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SendOrganizationInvitationUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SendOrganizationInvitationUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SendOrganizationInvitationUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *Session) Encode(e *jx.Encoder) { e.ObjStart() @@ -24799,6 +33279,234 @@ func (s *Timestamp) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes UpdateOrganizationInvitationBadRequest as json. +func (s *UpdateOrganizationInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes UpdateOrganizationInvitationBadRequest from json. +func (s *UpdateOrganizationInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode UpdateOrganizationInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = UpdateOrganizationInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *UpdateOrganizationInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *UpdateOrganizationInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes UpdateOrganizationInvitationConflict as json. +func (s *UpdateOrganizationInvitationConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes UpdateOrganizationInvitationConflict from json. +func (s *UpdateOrganizationInvitationConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode UpdateOrganizationInvitationConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = UpdateOrganizationInvitationConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *UpdateOrganizationInvitationConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *UpdateOrganizationInvitationConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes UpdateOrganizationInvitationForbidden as json. +func (s *UpdateOrganizationInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes UpdateOrganizationInvitationForbidden from json. +func (s *UpdateOrganizationInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode UpdateOrganizationInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = UpdateOrganizationInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *UpdateOrganizationInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *UpdateOrganizationInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes UpdateOrganizationInvitationNotFound as json. +func (s *UpdateOrganizationInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes UpdateOrganizationInvitationNotFound from json. +func (s *UpdateOrganizationInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode UpdateOrganizationInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = UpdateOrganizationInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *UpdateOrganizationInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *UpdateOrganizationInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes UpdateOrganizationInvitationPreconditionFailed as json. +func (s *UpdateOrganizationInvitationPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes UpdateOrganizationInvitationPreconditionFailed from json. +func (s *UpdateOrganizationInvitationPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode UpdateOrganizationInvitationPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = UpdateOrganizationInvitationPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *UpdateOrganizationInvitationPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *UpdateOrganizationInvitationPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes UpdateOrganizationInvitationUnauthorized as json. +func (s *UpdateOrganizationInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes UpdateOrganizationInvitationUnauthorized from json. +func (s *UpdateOrganizationInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode UpdateOrganizationInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = UpdateOrganizationInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *UpdateOrganizationInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *UpdateOrganizationInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes UpdateOrganizationNeedBadRequest as json. func (s *UpdateOrganizationNeedBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -25029,6 +33737,424 @@ func (s *VerificationToken) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ViewMyInvitationBadRequest as json. +func (s *ViewMyInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ViewMyInvitationBadRequest from json. +func (s *ViewMyInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ViewMyInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ViewMyInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ViewMyInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ViewMyInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ViewMyInvitationForbidden as json. +func (s *ViewMyInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ViewMyInvitationForbidden from json. +func (s *ViewMyInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ViewMyInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ViewMyInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ViewMyInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ViewMyInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ViewMyInvitationNotFound as json. +func (s *ViewMyInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ViewMyInvitationNotFound from json. +func (s *ViewMyInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ViewMyInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ViewMyInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ViewMyInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ViewMyInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ViewMyInvitationUnauthorized as json. +func (s *ViewMyInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ViewMyInvitationUnauthorized from json. +func (s *ViewMyInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ViewMyInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ViewMyInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ViewMyInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ViewMyInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes WithdrawOrganizationInvitationBadRequest as json. +func (s *WithdrawOrganizationInvitationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes WithdrawOrganizationInvitationBadRequest from json. +func (s *WithdrawOrganizationInvitationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode WithdrawOrganizationInvitationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = WithdrawOrganizationInvitationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *WithdrawOrganizationInvitationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *WithdrawOrganizationInvitationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes WithdrawOrganizationInvitationConflict as json. +func (s *WithdrawOrganizationInvitationConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes WithdrawOrganizationInvitationConflict from json. +func (s *WithdrawOrganizationInvitationConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode WithdrawOrganizationInvitationConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = WithdrawOrganizationInvitationConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *WithdrawOrganizationInvitationConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *WithdrawOrganizationInvitationConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes WithdrawOrganizationInvitationForbidden as json. +func (s *WithdrawOrganizationInvitationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes WithdrawOrganizationInvitationForbidden from json. +func (s *WithdrawOrganizationInvitationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode WithdrawOrganizationInvitationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = WithdrawOrganizationInvitationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *WithdrawOrganizationInvitationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *WithdrawOrganizationInvitationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes WithdrawOrganizationInvitationNotFound as json. +func (s *WithdrawOrganizationInvitationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes WithdrawOrganizationInvitationNotFound from json. +func (s *WithdrawOrganizationInvitationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode WithdrawOrganizationInvitationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = WithdrawOrganizationInvitationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *WithdrawOrganizationInvitationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *WithdrawOrganizationInvitationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes WithdrawOrganizationInvitationPreconditionFailed as json. +func (s *WithdrawOrganizationInvitationPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes WithdrawOrganizationInvitationPreconditionFailed from json. +func (s *WithdrawOrganizationInvitationPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode WithdrawOrganizationInvitationPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = WithdrawOrganizationInvitationPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *WithdrawOrganizationInvitationPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *WithdrawOrganizationInvitationPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes WithdrawOrganizationInvitationUnauthorized as json. +func (s *WithdrawOrganizationInvitationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes WithdrawOrganizationInvitationUnauthorized from json. +func (s *WithdrawOrganizationInvitationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode WithdrawOrganizationInvitationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = WithdrawOrganizationInvitationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *WithdrawOrganizationInvitationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *WithdrawOrganizationInvitationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes WithdrawOrganizationInvitationUnprocessableEntity as json. +func (s *WithdrawOrganizationInvitationUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes WithdrawOrganizationInvitationUnprocessableEntity from json. +func (s *WithdrawOrganizationInvitationUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode WithdrawOrganizationInvitationUnprocessableEntity to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = WithdrawOrganizationInvitationUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *WithdrawOrganizationInvitationUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *WithdrawOrganizationInvitationUnprocessableEntity) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *WorkContext) Encode(e *jx.Encoder) { e.ObjStart() diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index 85c7585..f693f4c 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -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" ) diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go index 9ea7843..8598d34 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -15,6 +15,306 @@ import ( "github.com/ogen-go/ogen/validate" ) +// AcceptMyInvitationParams is parameters of AcceptMyInvitation operation. +type AcceptMyInvitationParams struct { + // 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. + InvitationID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackAcceptMyInvitationParams(packed middleware.Parameters) (params AcceptMyInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeAcceptMyInvitationParams(args [1]string, argsEscaped bool, r *http.Request) (params AcceptMyInvitationParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: invitation_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} + +// CancelMyInvitationParams is parameters of CancelMyInvitation operation. +type CancelMyInvitationParams struct { + // 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. + InvitationID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackCancelMyInvitationParams(packed middleware.Parameters) (params CancelMyInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeCancelMyInvitationParams(args [1]string, argsEscaped bool, r *http.Request) (params CancelMyInvitationParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: invitation_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} + // CreateMyAssessmentAttemptParams is parameters of CreateMyAssessmentAttempt operation. type CreateMyAssessmentAttemptParams struct { // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value @@ -203,6 +503,157 @@ func decodeCreateMySupportCaseParams(args [0]string, argsEscaped bool, r *http.R return params, nil } +// CreateOrganizationInvitationParams is parameters of CreateOrganizationInvitation operation. +type CreateOrganizationInvitationParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackCreateOrganizationInvitationParams(packed middleware.Parameters) (params CreateOrganizationInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeCreateOrganizationInvitationParams(args [1]string, argsEscaped bool, r *http.Request) (params CreateOrganizationInvitationParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} + // CreateOrganizationNeedParams is parameters of CreateOrganizationNeed operation. type CreateOrganizationNeedParams struct { // Identifier of an organization. Access comes only from an active membership of the session account in @@ -354,6 +805,156 @@ func decodeCreateOrganizationNeedParams(args [1]string, argsEscaped bool, r *htt return params, nil } +// DeclineMyInvitationParams is parameters of DeclineMyInvitation operation. +type DeclineMyInvitationParams struct { + // 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. + InvitationID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackDeclineMyInvitationParams(packed middleware.Parameters) (params DeclineMyInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeDeclineMyInvitationParams(args [1]string, argsEscaped bool, r *http.Request) (params DeclineMyInvitationParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: invitation_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} + // FinalizeMyAssessmentAttemptParams is parameters of FinalizeMyAssessmentAttempt operation. type FinalizeMyAssessmentAttemptParams struct { // Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an @@ -711,6 +1312,74 @@ func decodeGetMyAssessmentResultParams(args [1]string, argsEscaped bool, r *http return params, nil } +// GetMyInvitationParams is parameters of GetMyInvitation operation. +type GetMyInvitationParams struct { + // 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. + InvitationID uuid.UUID +} + +func unpackGetMyInvitationParams(packed middleware.Parameters) (params GetMyInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + return params +} + +func decodeGetMyInvitationParams(args [1]string, argsEscaped bool, r *http.Request) (params GetMyInvitationParams, _ error) { + // Decode path: invitation_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + return params, nil +} + // GetMySupportCaseParams is parameters of GetMySupportCase operation. type GetMySupportCaseParams struct { // Identifier of a case of the current account. A case of another account and an unknown identifier @@ -778,6 +1447,254 @@ func decodeGetMySupportCaseParams(args [1]string, argsEscaped bool, r *http.Requ return params, nil } +// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation. +type GetOrganizationInvitationParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Identifier of an invitation of the organization in the path. An invitation of another organization + // and an unknown identifier both answer 404 not_found. + InvitationID uuid.UUID +} + +func unpackGetOrganizationInvitationParams(packed middleware.Parameters) (params GetOrganizationInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + return params +} + +func decodeGetOrganizationInvitationParams(args [2]string, argsEscaped bool, r *http.Request) (params GetOrganizationInvitationParams, _ error) { + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Decode path: invitation_id. + if err := func() error { + param := args[1] + if argsEscaped { + unescaped, err := url.PathUnescape(args[1]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + return params, nil +} + +// GetOrganizationInvitationContactsParams is parameters of GetOrganizationInvitationContacts operation. +type GetOrganizationInvitationContactsParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Identifier of an invitation of the organization in the path. An invitation of another organization + // and an unknown identifier both answer 404 not_found. + InvitationID uuid.UUID +} + +func unpackGetOrganizationInvitationContactsParams(packed middleware.Parameters) (params GetOrganizationInvitationContactsParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + return params +} + +func decodeGetOrganizationInvitationContactsParams(args [2]string, argsEscaped bool, r *http.Request) (params GetOrganizationInvitationContactsParams, _ error) { + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Decode path: invitation_id. + if err := func() error { + param := args[1] + if argsEscaped { + unescaped, err := url.PathUnescape(args[1]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + return params, nil +} + // GetOrganizationNeedParams is parameters of GetOrganizationNeed operation. type GetOrganizationNeedParams struct { // Identifier of an organization. Access comes only from an active membership of the session account in @@ -902,6 +1819,182 @@ func decodeGetOrganizationNeedParams(args [2]string, argsEscaped bool, r *http.R return params, nil } +// ListMyInvitationsParams is parameters of ListMyInvitations operation. +type ListMyInvitationsParams struct { + // Maximum number of items in the page. The server may return fewer items even when more remain; use + // `page.has_more` to detect the end. + Limit OptInt32 `json:",omitempty,omitzero"` + // Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the + // first page. A malformed or foreign cursor returns 400 with code validation_failed. + Cursor OptString `json:",omitempty,omitzero"` +} + +func unpackListMyInvitationsParams(packed middleware.Parameters) (params ListMyInvitationsParams) { + { + key := middleware.ParameterKey{ + Name: "limit", + In: "query", + } + if v, ok := packed[key]; ok { + params.Limit = v.(OptInt32) + } + } + { + key := middleware.ParameterKey{ + Name: "cursor", + In: "query", + } + if v, ok := packed[key]; ok { + params.Cursor = v.(OptString) + } + } + return params +} + +func decodeListMyInvitationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyInvitationsParams, _ error) { + q := uri.NewQueryDecoder(r.URL.Query()) + // Set default value for query: limit. + { + val := int32(20) + params.Limit.SetTo(val) + } + // Decode query: limit. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "limit", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotLimitVal int32 + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt32(val) + if err != nil { + return err + } + + paramsDotLimitVal = c + return nil + }(); err != nil { + return err + } + params.Limit.SetTo(paramsDotLimitVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Limit.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 100, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "limit", + In: "query", + Err: err, + } + } + // Decode query: cursor. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "cursor", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotCursorVal string + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + paramsDotCursorVal = c + return nil + }(); err != nil { + return err + } + params.Cursor.SetTo(paramsDotCursorVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Cursor.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 512, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "cursor", + In: "query", + Err: err, + } + } + return params, nil +} + // ListMySupportCasesParams is parameters of ListMySupportCases operation. type ListMySupportCasesParams struct { // Maximum number of items in the page. The server may return fewer items even when more remain; use @@ -1078,6 +2171,239 @@ func decodeListMySupportCasesParams(args [0]string, argsEscaped bool, r *http.Re return params, nil } +// ListOrganizationInvitationsParams is parameters of ListOrganizationInvitations operation. +type ListOrganizationInvitationsParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Maximum number of items in the page. The server may return fewer items even when more remain; use + // `page.has_more` to detect the end. + Limit OptInt32 `json:",omitempty,omitzero"` + // Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the + // first page. A malformed or foreign cursor returns 400 with code validation_failed. + Cursor OptString `json:",omitempty,omitzero"` +} + +func unpackListOrganizationInvitationsParams(packed middleware.Parameters) (params ListOrganizationInvitationsParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "limit", + In: "query", + } + if v, ok := packed[key]; ok { + params.Limit = v.(OptInt32) + } + } + { + key := middleware.ParameterKey{ + Name: "cursor", + In: "query", + } + if v, ok := packed[key]; ok { + params.Cursor = v.(OptString) + } + } + return params +} + +func decodeListOrganizationInvitationsParams(args [1]string, argsEscaped bool, r *http.Request) (params ListOrganizationInvitationsParams, _ error) { + q := uri.NewQueryDecoder(r.URL.Query()) + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Set default value for query: limit. + { + val := int32(20) + params.Limit.SetTo(val) + } + // Decode query: limit. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "limit", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotLimitVal int32 + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt32(val) + if err != nil { + return err + } + + paramsDotLimitVal = c + return nil + }(); err != nil { + return err + } + params.Limit.SetTo(paramsDotLimitVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Limit.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 100, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "limit", + In: "query", + Err: err, + } + } + // Decode query: cursor. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "cursor", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotCursorVal string + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + paramsDotCursorVal = c + return nil + }(); err != nil { + return err + } + params.Cursor.SetTo(paramsDotCursorVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Cursor.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 512, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "cursor", + In: "query", + Err: err, + } + } + return params, nil +} + // ListOrganizationNeedsParams is parameters of ListOrganizationNeeds operation. type ListOrganizationNeedsParams struct { // Identifier of an organization. Access comes only from an active membership of the session account in @@ -1311,6 +2637,212 @@ func decodeListOrganizationNeedsParams(args [1]string, argsEscaped bool, r *http return params, nil } +// RaiseOrganizationInvitationSalaryParams is parameters of RaiseOrganizationInvitationSalary operation. +type RaiseOrganizationInvitationSalaryParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Identifier of an invitation of the organization in the path. An invitation of another organization + // and an unknown identifier both answer 404 not_found. + InvitationID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackRaiseOrganizationInvitationSalaryParams(packed middleware.Parameters) (params RaiseOrganizationInvitationSalaryParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeRaiseOrganizationInvitationSalaryParams(args [2]string, argsEscaped bool, r *http.Request) (params RaiseOrganizationInvitationSalaryParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Decode path: invitation_id. + if err := func() error { + param := args[1] + if argsEscaped { + unescaped, err := url.PathUnescape(args[1]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} + // RegisterAccountParams is parameters of RegisterAccount operation. type RegisterAccountParams struct { // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value @@ -1405,6 +2937,212 @@ func decodeRegisterAccountParams(args [0]string, argsEscaped bool, r *http.Reque return params, nil } +// SendOrganizationInvitationParams is parameters of SendOrganizationInvitation operation. +type SendOrganizationInvitationParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Identifier of an invitation of the organization in the path. An invitation of another organization + // and an unknown identifier both answer 404 not_found. + InvitationID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackSendOrganizationInvitationParams(packed middleware.Parameters) (params SendOrganizationInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeSendOrganizationInvitationParams(args [2]string, argsEscaped bool, r *http.Request) (params SendOrganizationInvitationParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Decode path: invitation_id. + if err := func() error { + param := args[1] + if argsEscaped { + unescaped, err := url.PathUnescape(args[1]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} + // SubmitMyAssessmentAnswerParams is parameters of SubmitMyAssessmentAnswer operation. type SubmitMyAssessmentAnswerParams struct { // Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an @@ -1554,6 +3292,130 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h return params, nil } +// UpdateOrganizationInvitationParams is parameters of UpdateOrganizationInvitation operation. +type UpdateOrganizationInvitationParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Identifier of an invitation of the organization in the path. An invitation of another organization + // and an unknown identifier both answer 404 not_found. + InvitationID uuid.UUID +} + +func unpackUpdateOrganizationInvitationParams(packed middleware.Parameters) (params UpdateOrganizationInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + return params +} + +func decodeUpdateOrganizationInvitationParams(args [2]string, argsEscaped bool, r *http.Request) (params UpdateOrganizationInvitationParams, _ error) { + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Decode path: invitation_id. + if err := func() error { + param := args[1] + if argsEscaped { + unescaped, err := url.PathUnescape(args[1]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + return params, nil +} + // UpdateOrganizationNeedParams is parameters of UpdateOrganizationNeed operation. type UpdateOrganizationNeedParams struct { // Identifier of an organization. Access comes only from an active membership of the session account in @@ -1677,3 +3539,277 @@ func decodeUpdateOrganizationNeedParams(args [2]string, argsEscaped bool, r *htt } return params, nil } + +// ViewMyInvitationParams is parameters of ViewMyInvitation operation. +type ViewMyInvitationParams struct { + // 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. + InvitationID uuid.UUID +} + +func unpackViewMyInvitationParams(packed middleware.Parameters) (params ViewMyInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + return params +} + +func decodeViewMyInvitationParams(args [1]string, argsEscaped bool, r *http.Request) (params ViewMyInvitationParams, _ error) { + // Decode path: invitation_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + return params, nil +} + +// WithdrawOrganizationInvitationParams is parameters of WithdrawOrganizationInvitation operation. +type WithdrawOrganizationInvitationParams struct { + // Identifier of an organization. Access comes only from an active membership of the session account in + // this organization, checked by the server on every request; the identifier itself grants nothing. An + // organization without such a membership and an unknown identifier both answer 404 not_found, so + // organizations cannot be enumerated. + OrgID uuid.UUID + // Identifier of an invitation of the organization in the path. An invitation of another organization + // and an unknown identifier both answer 404 not_found. + InvitationID uuid.UUID + // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value + // is sent without quotes. The server scopes the key by caller and operation and fingerprints the + // request by method, path, and body. + // + // Stored for 24 hours after the first request and replayed with the same status, headers, and body: + // the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 + // not_found or 409 state_conflict. A replay does not repeat the side effect. + // + // Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for + // the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 + // precondition_required (nothing changed; read the resource again and retry), 422 + // idempotency_key_reused, 429, and every 5xx. + // + // Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then + // the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused + // before any other key check; a running request with the same fingerprint returns 409 + // idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that + // does the server check If-Match, so a retry of a completed change replays its outcome instead of + // failing on the version it has just changed. After 24 hours the key may be accepted as new. + IdempotencyKey string +} + +func unpackWithdrawOrganizationInvitationParams(packed middleware.Parameters) (params WithdrawOrganizationInvitationParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "invitation_id", + In: "path", + } + params.InvitationID = packed[key].(uuid.UUID) + } + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeWithdrawOrganizationInvitationParams(args [2]string, argsEscaped bool, r *http.Request) (params WithdrawOrganizationInvitationParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode path: org_id. + if err := func() error { + param := args[0] + if argsEscaped { + unescaped, err := url.PathUnescape(args[0]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "org_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.OrgID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "org_id", + In: "path", + Err: err, + } + } + // Decode path: invitation_id. + if err := func() error { + param := args[1] + if argsEscaped { + unescaped, err := url.PathUnescape(args[1]) + if err != nil { + return errors.Wrap(err, "unescape path") + } + param = unescaped + } + if len(param) > 0 { + d := uri.NewPathDecoder(uri.PathDecoderConfig{ + Param: "invitation_id", + Value: param, + Style: uri.PathStyleSimple, + Explode: false, + }) + + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToUUID(val) + if err != nil { + return err + } + + params.InvitationID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "invitation_id", + In: "path", + Err: err, + } + } + // Decode header: Idempotency-Key. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Idempotency-Key", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + params.IdempotencyKey = c + return nil + }); err != nil { + return err + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 255, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9._:-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(params.IdempotencyKey)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } else { + return err + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Idempotency-Key", + In: "header", + Err: err, + } + } + return params, nil +} diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index 39a08c9..1c28003 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -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) + } +} diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index b34c2f9..771867f 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -14,6 +14,308 @@ import ( "go.opentelemetry.io/otel/trace" ) +func encodeAcceptMyInvitationResponse(response AcceptMyInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CandidateInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcceptMyInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcceptMyInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcceptMyInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcceptMyInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcceptMyInvitationConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcceptMyInvitationPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcceptMyInvitationUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeCancelMyInvitationResponse(response CancelMyInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CandidateInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CancelMyInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CancelMyInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CancelMyInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CancelMyInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CancelMyInvitationConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CancelMyInvitationPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CancelMyInvitationUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeConfirmEmailResponse(response ConfirmEmailRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *EmailVerificationResult: @@ -355,6 +657,145 @@ func encodeCreateMySupportCaseResponse(response CreateMySupportCaseRes, w http.R } } +func encodeCreateOrganizationInvitationResponse(response CreateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *OrganizationInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(201) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateOrganizationInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateOrganizationInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateOrganizationInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateOrganizationInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateOrganizationInvitationConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *CreateOrganizationInvitationUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeCreateOrganizationNeedResponse(response CreateOrganizationNeedRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *NeedHeaders: @@ -494,6 +935,157 @@ func encodeCreateOrganizationNeedResponse(response CreateOrganizationNeedRes, w } } +func encodeDeclineMyInvitationResponse(response DeclineMyInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CandidateInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *DeclineMyInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *DeclineMyInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *DeclineMyInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *DeclineMyInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *DeclineMyInvitationConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *DeclineMyInvitationPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *DeclineMyInvitationUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeFinalizeMyAssessmentAttemptResponse(response FinalizeMyAssessmentAttemptRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *AssessmentAttemptHeaders: @@ -964,6 +1556,89 @@ func encodeGetMyAssessmentResultResponse(response GetMyAssessmentResultRes, w ht } } +func encodeGetMyInvitationResponse(response GetMyInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CandidateInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeGetMyQuestionnaireResponse(response GetMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CandidateQuestionnaireHeaders: @@ -1094,6 +1769,172 @@ func encodeGetMySupportCaseResponse(response GetMySupportCaseRes, w http.Respons } } +func encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *OrganizationInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetOrganizationInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetOrganizationInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetOrganizationInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetOrganizationInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeGetOrganizationInvitationContactsResponse(response GetOrganizationInvitationContactsRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *ContactDisclosureHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetOrganizationInvitationContactsBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetOrganizationInvitationContactsUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetOrganizationInvitationContactsForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetOrganizationInvitationContactsNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeGetOrganizationNeedResponse(response GetOrganizationNeedRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *NeedHeaders: @@ -1190,6 +2031,77 @@ func encodeGetSpecializationCatalogResponse(response *SpecializationCatalog, w h return nil } +func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CandidateInvitationListHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListMyInvitationsBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListMyInvitationsUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListMyInvitationsForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeListMySupportCasesResponse(response ListMySupportCasesRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *SupportCaseListHeaders: @@ -1249,6 +2161,89 @@ func encodeListMySupportCasesResponse(response ListMySupportCasesRes, w http.Res } } +func encodeListOrganizationInvitationsResponse(response ListOrganizationInvitationsRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *OrganizationInvitationListHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListOrganizationInvitationsBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListOrganizationInvitationsUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListOrganizationInvitationsForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListOrganizationInvitationsNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeListOrganizationNeedsResponse(response ListOrganizationNeedsRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *NeedListHeaders: @@ -1518,6 +2513,157 @@ func encodeLogoutResponse(response LogoutRes, w http.ResponseWriter, span trace. } } +func encodeRaiseOrganizationInvitationSalaryResponse(response RaiseOrganizationInvitationSalaryRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *OrganizationInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RaiseOrganizationInvitationSalaryBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RaiseOrganizationInvitationSalaryUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RaiseOrganizationInvitationSalaryForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RaiseOrganizationInvitationSalaryNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RaiseOrganizationInvitationSalaryConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RaiseOrganizationInvitationSalaryPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *RaiseOrganizationInvitationSalaryUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *IdentityRequestAccepted: @@ -1775,6 +2921,157 @@ func encodeSaveMyQuestionnaireResponse(response SaveMyQuestionnaireRes, w http.R } } +func encodeSendOrganizationInvitationResponse(response SendOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *OrganizationInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SendOrganizationInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SendOrganizationInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SendOrganizationInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SendOrganizationInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SendOrganizationInvitationConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SendOrganizationInvitationPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SendOrganizationInvitationUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *AssessmentAttemptHeaders: @@ -1926,6 +3223,145 @@ func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes } } +func encodeUpdateOrganizationInvitationResponse(response UpdateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *OrganizationInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *UpdateOrganizationInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *UpdateOrganizationInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *UpdateOrganizationInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *UpdateOrganizationInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *UpdateOrganizationInvitationConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *UpdateOrganizationInvitationPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeUpdateOrganizationNeedResponse(response UpdateOrganizationNeedRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *NeedHeaders: @@ -2053,6 +3489,272 @@ func encodeUpdateOrganizationNeedResponse(response UpdateOrganizationNeedRes, w } } +func encodeViewMyInvitationResponse(response ViewMyInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CandidateInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ViewMyInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ViewMyInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ViewMyInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ViewMyInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeWithdrawOrganizationInvitationResponse(response WithdrawOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *OrganizationInvitationHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *WithdrawOrganizationInvitationBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *WithdrawOrganizationInvitationUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *WithdrawOrganizationInvitationForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *WithdrawOrganizationInvitationNotFound: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(404) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *WithdrawOrganizationInvitationConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *WithdrawOrganizationInvitationPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *WithdrawOrganizationInvitationUnprocessableEntity: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(422) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error { w.Header().Set("Content-Type", "application/problem+json") code := response.StatusCode diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index 2f04cca..f13025d 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,40 +11,67 @@ import ( ) var ( - rn31AllowedHeaders = map[string]string{ + rn45AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn1AllowedHeaders = map[string]string{ + rn7AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn29AllowedHeaders = map[string]string{ + rn43AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn28AllowedHeaders = map[string]string{ + rn40AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn16AllowedHeaders = map[string]string{ + rn24AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } + rn9AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn48AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn19AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } rn3AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn32AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn11AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn22AllowedHeaders = map[string]string{ - "PUT": "Content-Type,X-Csrf-Token", - } rn5AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn8AllowedHeaders = map[string]string{ + rn16AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn26AllowedHeaders = map[string]string{ + rn49AllowedHeaders = map[string]string{ + "POST": "X-Csrf-Token", + } + rn30AllowedHeaders = map[string]string{ + "PUT": "Content-Type,X-Csrf-Token", + } + rn10AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn13AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn34AllowedHeaders = map[string]string{ + "PATCH": "Content-Type,X-Csrf-Token", + } + rn42AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn47AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn50AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn15AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn37AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } ) @@ -201,7 +228,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn31AllowedHeaders, + allowedHeaders: rn45AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -226,7 +253,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn1AllowedHeaders, + allowedHeaders: rn7AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -278,7 +305,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn29AllowedHeaders, + allowedHeaders: rn43AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -302,7 +329,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn28AllowedHeaders, + allowedHeaders: rn40AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -329,7 +356,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,GET", - allowedHeaders: rn16AllowedHeaders, + allowedHeaders: rn24AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -381,7 +408,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn3AllowedHeaders, + allowedHeaders: rn9AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -455,7 +482,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn32AllowedHeaders, + allowedHeaders: rn48AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -482,7 +509,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn11AllowedHeaders, + allowedHeaders: rn19AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -551,6 +578,191 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } + case 'i': // Prefix: "invitations" + + if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleListMyInvitationsRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "invitation_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleGetMyInvitationRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'a': // Prefix: "accept" + + if l := len("accept"); len(elem) >= l && elem[0:l] == "accept" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleAcceptMyInvitationRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn3AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 'c': // Prefix: "cancel" + + if l := len("cancel"); len(elem) >= l && elem[0:l] == "cancel" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleCancelMyInvitationRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn5AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 'd': // Prefix: "decline" + + if l := len("decline"); len(elem) >= l && elem[0:l] == "decline" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleDeclineMyInvitationRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn16AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 'v': // Prefix: "view" + + if l := len("view"); len(elem) >= l && elem[0:l] == "view" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleViewMyInvitationRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn49AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + } + + } + case 'q': // Prefix: "questionnaire" if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" { @@ -569,7 +781,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn22AllowedHeaders, + allowedHeaders: rn30AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -595,7 +807,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn5AllowedHeaders, + allowedHeaders: rn10AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -665,77 +877,306 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } switch elem[0] { - case '/': // Prefix: "/needs" + case '/': // Prefix: "/" - if l := len("/needs"); len(elem) >= l && elem[0:l] == "/needs" { + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { elem = elem[l:] } else { break } if len(elem) == 0 { - switch r.Method { - case "GET": - s.handleListOrganizationNeedsRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - case "POST": - s.handleCreateOrganizationNeedRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET,POST", - allowedHeaders: rn8AllowedHeaders, - acceptPost: "application/json", - acceptPatch: "", - }) - } - - return + break } switch elem[0] { - case '/': // Prefix: "/" + case 'i': // Prefix: "invitations" - if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" { elem = elem[l:] } else { break } - // Param: "need_id" - // Leaf parameter, slashes are prohibited - idx := strings.IndexByte(elem, '/') - if idx >= 0 { - break - } - args[1] = elem - elem = "" - if len(elem) == 0 { - // Leaf node. switch r.Method { case "GET": - s.handleGetOrganizationNeedRequest([2]string{ + s.handleListOrganizationInvitationsRequest([1]string{ args[0], - args[1], }, elemIsEscaped, w, r) - case "PATCH": - s.handleUpdateOrganizationNeedRequest([2]string{ + case "POST": + s.handleCreateOrganizationInvitationRequest([1]string{ args[0], - args[1], }, elemIsEscaped, w, r) default: s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET,PATCH", - allowedHeaders: rn26AllowedHeaders, - acceptPost: "", - acceptPatch: "application/json", + allowedMethods: "GET,POST", + allowedHeaders: rn13AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", }) } return } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "invitation_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[1] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleGetOrganizationInvitationRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + case "PATCH": + s.handleUpdateOrganizationInvitationRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,PATCH", + allowedHeaders: rn34AllowedHeaders, + acceptPost: "", + acceptPatch: "application/json", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'c': // Prefix: "contacts" + + if l := len("contacts"); len(elem) >= l && elem[0:l] == "contacts" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetOrganizationInvitationContactsRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 's': // Prefix: "s" + + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'a': // Prefix: "alary-raise" + + if l := len("alary-raise"); len(elem) >= l && elem[0:l] == "alary-raise" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleRaiseOrganizationInvitationSalaryRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn42AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 'e': // Prefix: "end" + + if l := len("end"); len(elem) >= l && elem[0:l] == "end" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleSendOrganizationInvitationRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn47AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + } + + case 'w': // Prefix: "withdraw" + + if l := len("withdraw"); len(elem) >= l && elem[0:l] == "withdraw" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleWithdrawOrganizationInvitationRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn50AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + } + + } + + } + + case 'n': // Prefix: "needs" + + if l := len("needs"); len(elem) >= l && elem[0:l] == "needs" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleListOrganizationNeedsRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + case "POST": + s.handleCreateOrganizationNeedRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,POST", + allowedHeaders: rn15AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "need_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[1] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetOrganizationNeedRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + case "PATCH": + s.handleUpdateOrganizationNeedRequest([2]string{ + args[0], + args[1], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,PATCH", + allowedHeaders: rn37AllowedHeaders, + acceptPost: "", + acceptPatch: "application/json", + }) + } + + return + } + + } } @@ -1314,6 +1755,181 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } + case 'i': // Prefix: "invitations" + + if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "GET": + r.name = ListMyInvitationsOperation + r.summary = "List the invitations addressed to the current candidate." + r.operationID = "ListMyInvitations" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/invitations" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "invitation_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + switch method { + case "GET": + r.name = GetMyInvitationOperation + r.summary = "Open the terms of an invitation addressed to the current candidate." + r.operationID = "GetMyInvitation" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/invitations/{invitation_id}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'a': // Prefix: "accept" + + if l := len("accept"); len(elem) >= l && elem[0:l] == "accept" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = AcceptMyInvitationOperation + r.summary = "Accept the current terms and disclose the selected contacts." + r.operationID = "AcceptMyInvitation" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/invitations/{invitation_id}/accept" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 'c': // Prefix: "cancel" + + if l := len("cancel"); len(elem) >= l && elem[0:l] == "cancel" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = CancelMyInvitationOperation + r.summary = "Cancel the participation in an invitation and revoke its contact grant." + r.operationID = "CancelMyInvitation" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/invitations/{invitation_id}/cancel" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 'd': // Prefix: "decline" + + if l := len("decline"); len(elem) >= l && elem[0:l] == "decline" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = DeclineMyInvitationOperation + r.summary = "Decline an invitation with a structured reason." + r.operationID = "DeclineMyInvitation" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/invitations/{invitation_id}/decline" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 'v': // Prefix: "view" + + if l := len("view"); len(elem) >= l && elem[0:l] == "view" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = ViewMyInvitationOperation + r.summary = "Record that the current candidate opened the terms of an invitation." + r.operationID = "ViewMyInvitation" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/invitations/{invitation_id}/view" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + } + + } + + } + case 'q': // Prefix: "questionnaire" if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" { @@ -1440,81 +2056,302 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } switch elem[0] { - case '/': // Prefix: "/needs" + case '/': // Prefix: "/" - if l := len("/needs"); len(elem) >= l && elem[0:l] == "/needs" { + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { elem = elem[l:] } else { break } if len(elem) == 0 { - switch method { - case "GET": - r.name = ListOrganizationNeedsOperation - r.summary = "List the needs of an organization." - r.operationID = "ListOrganizationNeeds" - r.operationGroup = "" - r.pathPattern = "/api/v1/organizations/{org_id}/needs" - r.args = args - r.count = 1 - return r, true - case "POST": - r.name = CreateOrganizationNeedOperation - r.summary = "Create a need of an organization from a form, a text, or both." - r.operationID = "CreateOrganizationNeed" - r.operationGroup = "" - r.pathPattern = "/api/v1/organizations/{org_id}/needs" - r.args = args - r.count = 1 - return r, true - default: - return - } + break } switch elem[0] { - case '/': // Prefix: "/" + case 'i': // Prefix: "invitations" - if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" { elem = elem[l:] } else { break } - // Param: "need_id" - // Leaf parameter, slashes are prohibited - idx := strings.IndexByte(elem, '/') - if idx >= 0 { - break - } - args[1] = elem - elem = "" - if len(elem) == 0 { - // Leaf node. switch method { case "GET": - r.name = GetOrganizationNeedOperation - r.summary = "Read the current version of a need of an organization." - r.operationID = "GetOrganizationNeed" + r.name = ListOrganizationInvitationsOperation + r.summary = "List the invitations of an organization." + r.operationID = "ListOrganizationInvitations" r.operationGroup = "" - r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}" + r.pathPattern = "/api/v1/organizations/{org_id}/invitations" r.args = args - r.count = 2 + r.count = 1 return r, true - case "PATCH": - r.name = UpdateOrganizationNeedOperation - r.summary = "Confirm, change, or delete requirements of a need." - r.operationID = "UpdateOrganizationNeed" + case "POST": + r.name = CreateOrganizationInvitationOperation + r.summary = "Create an invitation draft for one candidate." + r.operationID = "CreateOrganizationInvitation" r.operationGroup = "" - r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}" + r.pathPattern = "/api/v1/organizations/{org_id}/invitations" r.args = args - r.count = 2 + r.count = 1 return r, true default: return } } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "invitation_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[1] = elem[:idx] + elem = elem[idx:] + + if len(elem) == 0 { + switch method { + case "GET": + r.name = GetOrganizationInvitationOperation + r.summary = "Read an invitation of an organization." + r.operationID = "GetOrganizationInvitation" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/invitations/{invitation_id}" + r.args = args + r.count = 2 + return r, true + case "PATCH": + r.name = UpdateOrganizationInvitationOperation + r.summary = "Change the terms, the need link, or the response period of a draft." + r.operationID = "UpdateOrganizationInvitation" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/invitations/{invitation_id}" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'c': // Prefix: "contacts" + + if l := len("contacts"); len(elem) >= l && elem[0:l] == "contacts" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetOrganizationInvitationContactsOperation + r.summary = "Read the contacts that the candidate disclosed to the organization." + r.operationID = "GetOrganizationInvitationContacts" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + case 's': // Prefix: "s" + + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'a': // Prefix: "alary-raise" + + if l := len("alary-raise"); len(elem) >= l && elem[0:l] == "alary-raise" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = RaiseOrganizationInvitationSalaryOperation + r.summary = "Raise the upper salary bound of a sent invitation once." + r.operationID = "RaiseOrganizationInvitationSalary" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + case 'e': // Prefix: "end" + + if l := len("end"); len(elem) >= l && elem[0:l] == "end" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = SendOrganizationInvitationOperation + r.summary = "Send a draft to the candidate's inbox." + r.operationID = "SendOrganizationInvitation" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/invitations/{invitation_id}/send" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + } + + case 'w': // Prefix: "withdraw" + + if l := len("withdraw"); len(elem) >= l && elem[0:l] == "withdraw" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = WithdrawOrganizationInvitationOperation + r.summary = "Withdraw an invitation." + r.operationID = "WithdrawOrganizationInvitation" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + } + + } + + } + + case 'n': // Prefix: "needs" + + if l := len("needs"); len(elem) >= l && elem[0:l] == "needs" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "GET": + r.name = ListOrganizationNeedsOperation + r.summary = "List the needs of an organization." + r.operationID = "ListOrganizationNeeds" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/needs" + r.args = args + r.count = 1 + return r, true + case "POST": + r.name = CreateOrganizationNeedOperation + r.summary = "Create a need of an organization from a form, a text, or both." + r.operationID = "CreateOrganizationNeed" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/needs" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "need_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[1] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetOrganizationNeedOperation + r.summary = "Read the current version of a need of an organization." + r.operationID = "GetOrganizationNeed" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}" + r.args = args + r.count = 2 + return r, true + case "PATCH": + r.name = UpdateOrganizationNeedOperation + r.summary = "Confirm, change, or delete requirements of a need." + r.operationID = "UpdateOrganizationNeed" + r.operationGroup = "" + r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}" + r.args = args + r.count = 2 + return r, true + default: + return + } + } + + } } diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 4c976a4..1ed1d03 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -14,6 +14,34 @@ func (s *ProblemStatusCode) Error() string { return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response) } +type AcceptMyInvitationBadRequest Problem + +func (*AcceptMyInvitationBadRequest) acceptMyInvitationRes() {} + +type AcceptMyInvitationConflict Problem + +func (*AcceptMyInvitationConflict) acceptMyInvitationRes() {} + +type AcceptMyInvitationForbidden Problem + +func (*AcceptMyInvitationForbidden) acceptMyInvitationRes() {} + +type AcceptMyInvitationNotFound Problem + +func (*AcceptMyInvitationNotFound) acceptMyInvitationRes() {} + +type AcceptMyInvitationPreconditionFailed Problem + +func (*AcceptMyInvitationPreconditionFailed) acceptMyInvitationRes() {} + +type AcceptMyInvitationUnauthorized Problem + +func (*AcceptMyInvitationUnauthorized) acceptMyInvitationRes() {} + +type AcceptMyInvitationUnprocessableEntity Problem + +func (*AcceptMyInvitationUnprocessableEntity) acceptMyInvitationRes() {} + // Current account view. It never contains password hashes, token hashes, session identifiers, or other // storage secrets. // Ref: #/components/schemas/Account @@ -2284,6 +2312,34 @@ func (s *CalibrationStatus) UnmarshalText(data []byte) error { } } +type CancelMyInvitationBadRequest Problem + +func (*CancelMyInvitationBadRequest) cancelMyInvitationRes() {} + +type CancelMyInvitationConflict Problem + +func (*CancelMyInvitationConflict) cancelMyInvitationRes() {} + +type CancelMyInvitationForbidden Problem + +func (*CancelMyInvitationForbidden) cancelMyInvitationRes() {} + +type CancelMyInvitationNotFound Problem + +func (*CancelMyInvitationNotFound) cancelMyInvitationRes() {} + +type CancelMyInvitationPreconditionFailed Problem + +func (*CancelMyInvitationPreconditionFailed) cancelMyInvitationRes() {} + +type CancelMyInvitationUnauthorized Problem + +func (*CancelMyInvitationUnauthorized) cancelMyInvitationRes() {} + +type CancelMyInvitationUnprocessableEntity Problem + +func (*CancelMyInvitationUnprocessableEntity) cancelMyInvitationRes() {} + // Experience that the candidate states for one specialization, in whole months. It is self-reported // context: it never adds assessment points and never confirms a grade. // Ref: #/components/schemas/CandidateExperience @@ -2314,6 +2370,431 @@ func (s *CandidateExperience) SetAcademicMonths(val int32) { s.AcademicMonths = val } +type CandidateHandle string + +// 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. +// Ref: #/components/schemas/CandidateInvitation +type CandidateInvitation struct { + // Identifier of the invitation. + ID uuid.UUID `json:"id"` + Organization InvitationOrganization `json:"organization"` + State InvitationState `json:"state"` + ExpiryReason NilInvitationExpiryReason `json:"expiry_reason"` + Version InvitationVersion `json:"version"` + TermsVersion InvitationTermsVersion `json:"terms_version"` + Terms InvitationTerms `json:"terms"` + ResponseDeadlineAt Timestamp `json:"response_deadline_at"` + DeliveredAt Timestamp `json:"delivered_at"` + // Moment of the first view recorded by ViewMyInvitation, or null when the candidate has not opened the + // terms. + ViewedAt NilTimestamp `json:"viewed_at"` + RespondedAt NilTimestamp `json:"responded_at"` + UpdatedAt Timestamp `json:"updated_at"` + // 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. + ContactConsent NilContactConsentOffer `json:"contact_consent"` + // The candidate's decline, or null unless `state` is `declined`. + Decline NilInvitationDeclineRecord `json:"decline"` + // 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. + ContactGrant NilContactGrant `json:"contact_grant"` +} + +// GetID returns the value of ID. +func (s *CandidateInvitation) GetID() uuid.UUID { + return s.ID +} + +// GetOrganization returns the value of Organization. +func (s *CandidateInvitation) GetOrganization() InvitationOrganization { + return s.Organization +} + +// GetState returns the value of State. +func (s *CandidateInvitation) GetState() InvitationState { + return s.State +} + +// GetExpiryReason returns the value of ExpiryReason. +func (s *CandidateInvitation) GetExpiryReason() NilInvitationExpiryReason { + return s.ExpiryReason +} + +// GetVersion returns the value of Version. +func (s *CandidateInvitation) GetVersion() InvitationVersion { + return s.Version +} + +// GetTermsVersion returns the value of TermsVersion. +func (s *CandidateInvitation) GetTermsVersion() InvitationTermsVersion { + return s.TermsVersion +} + +// GetTerms returns the value of Terms. +func (s *CandidateInvitation) GetTerms() InvitationTerms { + return s.Terms +} + +// GetResponseDeadlineAt returns the value of ResponseDeadlineAt. +func (s *CandidateInvitation) GetResponseDeadlineAt() Timestamp { + return s.ResponseDeadlineAt +} + +// GetDeliveredAt returns the value of DeliveredAt. +func (s *CandidateInvitation) GetDeliveredAt() Timestamp { + return s.DeliveredAt +} + +// GetViewedAt returns the value of ViewedAt. +func (s *CandidateInvitation) GetViewedAt() NilTimestamp { + return s.ViewedAt +} + +// GetRespondedAt returns the value of RespondedAt. +func (s *CandidateInvitation) GetRespondedAt() NilTimestamp { + return s.RespondedAt +} + +// GetUpdatedAt returns the value of UpdatedAt. +func (s *CandidateInvitation) GetUpdatedAt() Timestamp { + return s.UpdatedAt +} + +// GetContactConsent returns the value of ContactConsent. +func (s *CandidateInvitation) GetContactConsent() NilContactConsentOffer { + return s.ContactConsent +} + +// GetDecline returns the value of Decline. +func (s *CandidateInvitation) GetDecline() NilInvitationDeclineRecord { + return s.Decline +} + +// GetContactGrant returns the value of ContactGrant. +func (s *CandidateInvitation) GetContactGrant() NilContactGrant { + return s.ContactGrant +} + +// SetID sets the value of ID. +func (s *CandidateInvitation) SetID(val uuid.UUID) { + s.ID = val +} + +// SetOrganization sets the value of Organization. +func (s *CandidateInvitation) SetOrganization(val InvitationOrganization) { + s.Organization = val +} + +// SetState sets the value of State. +func (s *CandidateInvitation) SetState(val InvitationState) { + s.State = val +} + +// SetExpiryReason sets the value of ExpiryReason. +func (s *CandidateInvitation) SetExpiryReason(val NilInvitationExpiryReason) { + s.ExpiryReason = val +} + +// SetVersion sets the value of Version. +func (s *CandidateInvitation) SetVersion(val InvitationVersion) { + s.Version = val +} + +// SetTermsVersion sets the value of TermsVersion. +func (s *CandidateInvitation) SetTermsVersion(val InvitationTermsVersion) { + s.TermsVersion = val +} + +// SetTerms sets the value of Terms. +func (s *CandidateInvitation) SetTerms(val InvitationTerms) { + s.Terms = val +} + +// SetResponseDeadlineAt sets the value of ResponseDeadlineAt. +func (s *CandidateInvitation) SetResponseDeadlineAt(val Timestamp) { + s.ResponseDeadlineAt = val +} + +// SetDeliveredAt sets the value of DeliveredAt. +func (s *CandidateInvitation) SetDeliveredAt(val Timestamp) { + s.DeliveredAt = val +} + +// SetViewedAt sets the value of ViewedAt. +func (s *CandidateInvitation) SetViewedAt(val NilTimestamp) { + s.ViewedAt = val +} + +// SetRespondedAt sets the value of RespondedAt. +func (s *CandidateInvitation) SetRespondedAt(val NilTimestamp) { + s.RespondedAt = val +} + +// SetUpdatedAt sets the value of UpdatedAt. +func (s *CandidateInvitation) SetUpdatedAt(val Timestamp) { + s.UpdatedAt = val +} + +// SetContactConsent sets the value of ContactConsent. +func (s *CandidateInvitation) SetContactConsent(val NilContactConsentOffer) { + s.ContactConsent = val +} + +// SetDecline sets the value of Decline. +func (s *CandidateInvitation) SetDecline(val NilInvitationDeclineRecord) { + s.Decline = val +} + +// SetContactGrant sets the value of ContactGrant. +func (s *CandidateInvitation) SetContactGrant(val NilContactGrant) { + s.ContactGrant = val +} + +// CandidateInvitationHeaders wraps CandidateInvitation with response headers. +type CandidateInvitationHeaders struct { + CacheControl CacheControlNoStore + Response CandidateInvitation +} + +// GetCacheControl returns the value of CacheControl. +func (s *CandidateInvitationHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *CandidateInvitationHeaders) GetResponse() CandidateInvitation { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *CandidateInvitationHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *CandidateInvitationHeaders) SetResponse(val CandidateInvitation) { + s.Response = val +} + +func (*CandidateInvitationHeaders) acceptMyInvitationRes() {} +func (*CandidateInvitationHeaders) cancelMyInvitationRes() {} +func (*CandidateInvitationHeaders) declineMyInvitationRes() {} +func (*CandidateInvitationHeaders) getMyInvitationRes() {} +func (*CandidateInvitationHeaders) viewMyInvitationRes() {} + +// One page of the candidate's invitations, newest first by delivery time. +// Ref: #/components/schemas/CandidateInvitationList +type CandidateInvitationList struct { + // Invitations of the page. + Items []CandidateInvitationSummary `json:"items"` + Page PageInfo `json:"page"` +} + +// GetItems returns the value of Items. +func (s *CandidateInvitationList) GetItems() []CandidateInvitationSummary { + return s.Items +} + +// GetPage returns the value of Page. +func (s *CandidateInvitationList) GetPage() PageInfo { + return s.Page +} + +// SetItems sets the value of Items. +func (s *CandidateInvitationList) SetItems(val []CandidateInvitationSummary) { + s.Items = val +} + +// SetPage sets the value of Page. +func (s *CandidateInvitationList) SetPage(val PageInfo) { + s.Page = val +} + +// CandidateInvitationListHeaders wraps CandidateInvitationList with response headers. +type CandidateInvitationListHeaders struct { + CacheControl CacheControlNoStore + Response CandidateInvitationList +} + +// GetCacheControl returns the value of CacheControl. +func (s *CandidateInvitationListHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *CandidateInvitationListHeaders) GetResponse() CandidateInvitationList { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *CandidateInvitationListHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *CandidateInvitationListHeaders) SetResponse(val CandidateInvitationList) { + s.Response = val +} + +func (*CandidateInvitationListHeaders) listMyInvitationsRes() {} + +// 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. +// Ref: #/components/schemas/CandidateInvitationSummary +type CandidateInvitationSummary struct { + // Identifier of the invitation. + ID uuid.UUID `json:"id"` + Organization InvitationOrganization `json:"organization"` + State InvitationState `json:"state"` + ExpiryReason NilInvitationExpiryReason `json:"expiry_reason"` + Version InvitationVersion `json:"version"` + TermsVersion InvitationTermsVersion `json:"terms_version"` + RoleTitle InvitationRoleTitle `json:"role_title"` + Salary SalaryRange `json:"salary"` + WorkFormats []WorkFormat `json:"work_formats"` + ResponseDeadlineAt Timestamp `json:"response_deadline_at"` + DeliveredAt Timestamp `json:"delivered_at"` + ViewedAt NilTimestamp `json:"viewed_at"` + UpdatedAt Timestamp `json:"updated_at"` +} + +// GetID returns the value of ID. +func (s *CandidateInvitationSummary) GetID() uuid.UUID { + return s.ID +} + +// GetOrganization returns the value of Organization. +func (s *CandidateInvitationSummary) GetOrganization() InvitationOrganization { + return s.Organization +} + +// GetState returns the value of State. +func (s *CandidateInvitationSummary) GetState() InvitationState { + return s.State +} + +// GetExpiryReason returns the value of ExpiryReason. +func (s *CandidateInvitationSummary) GetExpiryReason() NilInvitationExpiryReason { + return s.ExpiryReason +} + +// GetVersion returns the value of Version. +func (s *CandidateInvitationSummary) GetVersion() InvitationVersion { + return s.Version +} + +// GetTermsVersion returns the value of TermsVersion. +func (s *CandidateInvitationSummary) GetTermsVersion() InvitationTermsVersion { + return s.TermsVersion +} + +// GetRoleTitle returns the value of RoleTitle. +func (s *CandidateInvitationSummary) GetRoleTitle() InvitationRoleTitle { + return s.RoleTitle +} + +// GetSalary returns the value of Salary. +func (s *CandidateInvitationSummary) GetSalary() SalaryRange { + return s.Salary +} + +// GetWorkFormats returns the value of WorkFormats. +func (s *CandidateInvitationSummary) GetWorkFormats() []WorkFormat { + return s.WorkFormats +} + +// GetResponseDeadlineAt returns the value of ResponseDeadlineAt. +func (s *CandidateInvitationSummary) GetResponseDeadlineAt() Timestamp { + return s.ResponseDeadlineAt +} + +// GetDeliveredAt returns the value of DeliveredAt. +func (s *CandidateInvitationSummary) GetDeliveredAt() Timestamp { + return s.DeliveredAt +} + +// GetViewedAt returns the value of ViewedAt. +func (s *CandidateInvitationSummary) GetViewedAt() NilTimestamp { + return s.ViewedAt +} + +// GetUpdatedAt returns the value of UpdatedAt. +func (s *CandidateInvitationSummary) GetUpdatedAt() Timestamp { + return s.UpdatedAt +} + +// SetID sets the value of ID. +func (s *CandidateInvitationSummary) SetID(val uuid.UUID) { + s.ID = val +} + +// SetOrganization sets the value of Organization. +func (s *CandidateInvitationSummary) SetOrganization(val InvitationOrganization) { + s.Organization = val +} + +// SetState sets the value of State. +func (s *CandidateInvitationSummary) SetState(val InvitationState) { + s.State = val +} + +// SetExpiryReason sets the value of ExpiryReason. +func (s *CandidateInvitationSummary) SetExpiryReason(val NilInvitationExpiryReason) { + s.ExpiryReason = val +} + +// SetVersion sets the value of Version. +func (s *CandidateInvitationSummary) SetVersion(val InvitationVersion) { + s.Version = val +} + +// SetTermsVersion sets the value of TermsVersion. +func (s *CandidateInvitationSummary) SetTermsVersion(val InvitationTermsVersion) { + s.TermsVersion = val +} + +// SetRoleTitle sets the value of RoleTitle. +func (s *CandidateInvitationSummary) SetRoleTitle(val InvitationRoleTitle) { + s.RoleTitle = val +} + +// SetSalary sets the value of Salary. +func (s *CandidateInvitationSummary) SetSalary(val SalaryRange) { + s.Salary = val +} + +// SetWorkFormats sets the value of WorkFormats. +func (s *CandidateInvitationSummary) SetWorkFormats(val []WorkFormat) { + s.WorkFormats = val +} + +// SetResponseDeadlineAt sets the value of ResponseDeadlineAt. +func (s *CandidateInvitationSummary) SetResponseDeadlineAt(val Timestamp) { + s.ResponseDeadlineAt = val +} + +// SetDeliveredAt sets the value of DeliveredAt. +func (s *CandidateInvitationSummary) SetDeliveredAt(val Timestamp) { + s.DeliveredAt = val +} + +// SetViewedAt sets the value of ViewedAt. +func (s *CandidateInvitationSummary) SetViewedAt(val NilTimestamp) { + s.ViewedAt = val +} + +// SetUpdatedAt sets the value of UpdatedAt. +func (s *CandidateInvitationSummary) SetUpdatedAt(val Timestamp) { + s.UpdatedAt = val +} + // Questionnaire of the current candidate: the chosen specializations with self-assessed grades and the // working context. It never contains a confirmed grade or a category; those come only from assessment // results. A candidate who has not saved the questionnaire yet gets version 0, no specializations, and @@ -2965,6 +3446,615 @@ func (*ConsentText) getConsentTextRes() {} type ConsentTextVersion string +// 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. +// +// Ref: #/components/schemas/ContactAccessBlock +type ContactAccessBlock string + +const ( + ContactAccessBlockVisibility ContactAccessBlock = "visibility" +) + +// AllValues returns all ContactAccessBlock values. +func (ContactAccessBlock) AllValues() []ContactAccessBlock { + return []ContactAccessBlock{ + ContactAccessBlockVisibility, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ContactAccessBlock) MarshalText() ([]byte, error) { + switch s { + case ContactAccessBlockVisibility: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ContactAccessBlock) UnmarshalText(data []byte) error { + switch ContactAccessBlock(data) { + case ContactAccessBlockVisibility: + *s = ContactAccessBlockVisibility + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// 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. +// Ref: #/components/schemas/ContactConsentAcceptance +type ContactConsentAcceptance struct { + TextVersion ConsentTextVersion `json:"text_version"` + // Explicit consent. Only true is valid. + Accepted ContactConsentAcceptanceAccepted `json:"accepted"` + // Contact fields the organization may read after the acceptance. The grant covers exactly these fields + // and no other. + Fields []ContactFieldKind `json:"fields"` +} + +// GetTextVersion returns the value of TextVersion. +func (s *ContactConsentAcceptance) GetTextVersion() ConsentTextVersion { + return s.TextVersion +} + +// GetAccepted returns the value of Accepted. +func (s *ContactConsentAcceptance) GetAccepted() ContactConsentAcceptanceAccepted { + return s.Accepted +} + +// GetFields returns the value of Fields. +func (s *ContactConsentAcceptance) GetFields() []ContactFieldKind { + return s.Fields +} + +// SetTextVersion sets the value of TextVersion. +func (s *ContactConsentAcceptance) SetTextVersion(val ConsentTextVersion) { + s.TextVersion = val +} + +// SetAccepted sets the value of Accepted. +func (s *ContactConsentAcceptance) SetAccepted(val ContactConsentAcceptanceAccepted) { + s.Accepted = val +} + +// SetFields sets the value of Fields. +func (s *ContactConsentAcceptance) SetFields(val []ContactFieldKind) { + s.Fields = val +} + +// Explicit consent. Only true is valid. +type ContactConsentAcceptanceAccepted bool + +const ( + ContactConsentAcceptanceAcceptedTrue ContactConsentAcceptanceAccepted = true +) + +// AllValues returns all ContactConsentAcceptanceAccepted values. +func (ContactConsentAcceptanceAccepted) AllValues() []ContactConsentAcceptanceAccepted { + return []ContactConsentAcceptanceAccepted{ + ContactConsentAcceptanceAcceptedTrue, + } +} + +// 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. +// Ref: #/components/schemas/ContactConsentOffer +type ContactConsentOffer struct { + Text ContactConsentText `json:"text"` + // Kinds of contact that the profile holds and that an acceptance may select. A kind outside this list + // answers 400 in an acceptance. + AvailableFields []ContactFieldKind `json:"available_fields"` +} + +// GetText returns the value of Text. +func (s *ContactConsentOffer) GetText() ContactConsentText { + return s.Text +} + +// GetAvailableFields returns the value of AvailableFields. +func (s *ContactConsentOffer) GetAvailableFields() []ContactFieldKind { + return s.AvailableFields +} + +// SetText sets the value of Text. +func (s *ContactConsentOffer) SetText(val ContactConsentText) { + s.Text = val +} + +// SetAvailableFields sets the value of AvailableFields. +func (s *ContactConsentOffer) SetAvailableFields(val []ContactFieldKind) { + s.AvailableFields = val +} + +// 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). +// Ref: #/components/schemas/ContactConsentText +type ContactConsentText struct { + TextVersion ConsentTextVersion `json:"text_version"` + // 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. + Text string `json:"text"` +} + +// GetTextVersion returns the value of TextVersion. +func (s *ContactConsentText) GetTextVersion() ConsentTextVersion { + return s.TextVersion +} + +// GetText returns the value of Text. +func (s *ContactConsentText) GetText() string { + return s.Text +} + +// SetTextVersion sets the value of TextVersion. +func (s *ContactConsentText) SetTextVersion(val ConsentTextVersion) { + s.TextVersion = val +} + +// SetText sets the value of Text. +func (s *ContactConsentText) SetText(val string) { + s.Text = val +} + +// 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. +// Ref: #/components/schemas/ContactDisclosure +type ContactDisclosure struct { + // Invitation whose acceptance created the grant. + InvitationID uuid.UUID `json:"invitation_id"` + // Grant that allows the read. + GrantID uuid.UUID `json:"grant_id"` + // Contact fields that the grant covers. + Fields []ContactFieldKind `json:"fields"` + GrantedAt Timestamp `json:"granted_at"` + FullName NilContactFullName `json:"full_name"` + Email NilEmailAddress `json:"email"` + Phone NilContactPhoneNumber `json:"phone"` + Telegram NilContactTelegramUsername `json:"telegram"` +} + +// GetInvitationID returns the value of InvitationID. +func (s *ContactDisclosure) GetInvitationID() uuid.UUID { + return s.InvitationID +} + +// GetGrantID returns the value of GrantID. +func (s *ContactDisclosure) GetGrantID() uuid.UUID { + return s.GrantID +} + +// GetFields returns the value of Fields. +func (s *ContactDisclosure) GetFields() []ContactFieldKind { + return s.Fields +} + +// GetGrantedAt returns the value of GrantedAt. +func (s *ContactDisclosure) GetGrantedAt() Timestamp { + return s.GrantedAt +} + +// GetFullName returns the value of FullName. +func (s *ContactDisclosure) GetFullName() NilContactFullName { + return s.FullName +} + +// GetEmail returns the value of Email. +func (s *ContactDisclosure) GetEmail() NilEmailAddress { + return s.Email +} + +// GetPhone returns the value of Phone. +func (s *ContactDisclosure) GetPhone() NilContactPhoneNumber { + return s.Phone +} + +// GetTelegram returns the value of Telegram. +func (s *ContactDisclosure) GetTelegram() NilContactTelegramUsername { + return s.Telegram +} + +// SetInvitationID sets the value of InvitationID. +func (s *ContactDisclosure) SetInvitationID(val uuid.UUID) { + s.InvitationID = val +} + +// SetGrantID sets the value of GrantID. +func (s *ContactDisclosure) SetGrantID(val uuid.UUID) { + s.GrantID = val +} + +// SetFields sets the value of Fields. +func (s *ContactDisclosure) SetFields(val []ContactFieldKind) { + s.Fields = val +} + +// SetGrantedAt sets the value of GrantedAt. +func (s *ContactDisclosure) SetGrantedAt(val Timestamp) { + s.GrantedAt = val +} + +// SetFullName sets the value of FullName. +func (s *ContactDisclosure) SetFullName(val NilContactFullName) { + s.FullName = val +} + +// SetEmail sets the value of Email. +func (s *ContactDisclosure) SetEmail(val NilEmailAddress) { + s.Email = val +} + +// SetPhone sets the value of Phone. +func (s *ContactDisclosure) SetPhone(val NilContactPhoneNumber) { + s.Phone = val +} + +// SetTelegram sets the value of Telegram. +func (s *ContactDisclosure) SetTelegram(val NilContactTelegramUsername) { + s.Telegram = val +} + +// ContactDisclosureHeaders wraps ContactDisclosure with response headers. +type ContactDisclosureHeaders struct { + CacheControl CacheControlNoStore + Response ContactDisclosure +} + +// GetCacheControl returns the value of CacheControl. +func (s *ContactDisclosureHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *ContactDisclosureHeaders) GetResponse() ContactDisclosure { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *ContactDisclosureHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *ContactDisclosureHeaders) SetResponse(val ContactDisclosure) { + s.Response = val +} + +func (*ContactDisclosureHeaders) getOrganizationInvitationContactsRes() {} + +// 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. +// Ref: #/components/schemas/ContactFieldKind +type ContactFieldKind string + +const ( + ContactFieldKindFullName ContactFieldKind = "full_name" + ContactFieldKindEmail ContactFieldKind = "email" + ContactFieldKindPhone ContactFieldKind = "phone" + ContactFieldKindTelegram ContactFieldKind = "telegram" +) + +// AllValues returns all ContactFieldKind values. +func (ContactFieldKind) AllValues() []ContactFieldKind { + return []ContactFieldKind{ + ContactFieldKindFullName, + ContactFieldKindEmail, + ContactFieldKindPhone, + ContactFieldKindTelegram, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ContactFieldKind) MarshalText() ([]byte, error) { + switch s { + case ContactFieldKindFullName: + return []byte(s), nil + case ContactFieldKindEmail: + return []byte(s), nil + case ContactFieldKindPhone: + return []byte(s), nil + case ContactFieldKindTelegram: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ContactFieldKind) UnmarshalText(data []byte) error { + switch ContactFieldKind(data) { + case ContactFieldKindFullName: + *s = ContactFieldKindFullName + return nil + case ContactFieldKindEmail: + *s = ContactFieldKindEmail + return nil + case ContactFieldKindPhone: + *s = ContactFieldKindPhone + return nil + case ContactFieldKindTelegram: + *s = ContactFieldKindTelegram + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type ContactFullName string + +// 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. +// Ref: #/components/schemas/ContactGrant +type ContactGrant struct { + // Identifier of the grant. + ID uuid.UUID `json:"id"` + // Contact fields that the grant covers. + Fields []ContactFieldKind `json:"fields"` + Status ContactGrantState `json:"status"` + // 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. + Readable bool `json:"readable"` + // Why an active grant is not readable now, or null when it is readable or revoked; a revoked grant has + // `revocation_reason` instead. + BlockedBy NilContactAccessBlock `json:"blocked_by"` + // Terms version of the invitation that the acceptance accepted. + TermsVersion InvitationTermsVersion `json:"terms_version"` + // Version of the consent C4 text that the candidate accepted. + ConsentTextVersion ConsentTextVersion `json:"consent_text_version"` + GrantedAt Timestamp `json:"granted_at"` + // Moment of the revocation, or null while the grant is active. + RevokedAt NilTimestamp `json:"revoked_at"` + // Reason of the revocation, or null while the grant is active. + RevocationReason NilContactRevocationReason `json:"revocation_reason"` +} + +// GetID returns the value of ID. +func (s *ContactGrant) GetID() uuid.UUID { + return s.ID +} + +// GetFields returns the value of Fields. +func (s *ContactGrant) GetFields() []ContactFieldKind { + return s.Fields +} + +// GetStatus returns the value of Status. +func (s *ContactGrant) GetStatus() ContactGrantState { + return s.Status +} + +// GetReadable returns the value of Readable. +func (s *ContactGrant) GetReadable() bool { + return s.Readable +} + +// GetBlockedBy returns the value of BlockedBy. +func (s *ContactGrant) GetBlockedBy() NilContactAccessBlock { + return s.BlockedBy +} + +// GetTermsVersion returns the value of TermsVersion. +func (s *ContactGrant) GetTermsVersion() InvitationTermsVersion { + return s.TermsVersion +} + +// GetConsentTextVersion returns the value of ConsentTextVersion. +func (s *ContactGrant) GetConsentTextVersion() ConsentTextVersion { + return s.ConsentTextVersion +} + +// GetGrantedAt returns the value of GrantedAt. +func (s *ContactGrant) GetGrantedAt() Timestamp { + return s.GrantedAt +} + +// GetRevokedAt returns the value of RevokedAt. +func (s *ContactGrant) GetRevokedAt() NilTimestamp { + return s.RevokedAt +} + +// GetRevocationReason returns the value of RevocationReason. +func (s *ContactGrant) GetRevocationReason() NilContactRevocationReason { + return s.RevocationReason +} + +// SetID sets the value of ID. +func (s *ContactGrant) SetID(val uuid.UUID) { + s.ID = val +} + +// SetFields sets the value of Fields. +func (s *ContactGrant) SetFields(val []ContactFieldKind) { + s.Fields = val +} + +// SetStatus sets the value of Status. +func (s *ContactGrant) SetStatus(val ContactGrantState) { + s.Status = val +} + +// SetReadable sets the value of Readable. +func (s *ContactGrant) SetReadable(val bool) { + s.Readable = val +} + +// SetBlockedBy sets the value of BlockedBy. +func (s *ContactGrant) SetBlockedBy(val NilContactAccessBlock) { + s.BlockedBy = val +} + +// SetTermsVersion sets the value of TermsVersion. +func (s *ContactGrant) SetTermsVersion(val InvitationTermsVersion) { + s.TermsVersion = val +} + +// SetConsentTextVersion sets the value of ConsentTextVersion. +func (s *ContactGrant) SetConsentTextVersion(val ConsentTextVersion) { + s.ConsentTextVersion = val +} + +// SetGrantedAt sets the value of GrantedAt. +func (s *ContactGrant) SetGrantedAt(val Timestamp) { + s.GrantedAt = val +} + +// SetRevokedAt sets the value of RevokedAt. +func (s *ContactGrant) SetRevokedAt(val NilTimestamp) { + s.RevokedAt = val +} + +// SetRevocationReason sets the value of RevocationReason. +func (s *ContactGrant) SetRevocationReason(val NilContactRevocationReason) { + s.RevocationReason = val +} + +// 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. +// +// Ref: #/components/schemas/ContactGrantState +type ContactGrantState string + +const ( + ContactGrantStateActive ContactGrantState = "active" + ContactGrantStateRevoked ContactGrantState = "revoked" +) + +// AllValues returns all ContactGrantState values. +func (ContactGrantState) AllValues() []ContactGrantState { + return []ContactGrantState{ + ContactGrantStateActive, + ContactGrantStateRevoked, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ContactGrantState) MarshalText() ([]byte, error) { + switch s { + case ContactGrantStateActive: + return []byte(s), nil + case ContactGrantStateRevoked: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ContactGrantState) UnmarshalText(data []byte) error { + switch ContactGrantState(data) { + case ContactGrantStateActive: + *s = ContactGrantStateActive + return nil + case ContactGrantStateRevoked: + *s = ContactGrantStateRevoked + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type ContactPhoneNumber string + +// 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. +// Ref: #/components/schemas/ContactRevocationReason +type ContactRevocationReason string + +const ( + ContactRevocationReasonConsentRevoked ContactRevocationReason = "consent_revoked" + ContactRevocationReasonParticipationCancelled ContactRevocationReason = "participation_cancelled" + ContactRevocationReasonVisibilityClosed ContactRevocationReason = "visibility_closed" +) + +// AllValues returns all ContactRevocationReason values. +func (ContactRevocationReason) AllValues() []ContactRevocationReason { + return []ContactRevocationReason{ + ContactRevocationReasonConsentRevoked, + ContactRevocationReasonParticipationCancelled, + ContactRevocationReasonVisibilityClosed, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s ContactRevocationReason) MarshalText() ([]byte, error) { + switch s { + case ContactRevocationReasonConsentRevoked: + return []byte(s), nil + case ContactRevocationReasonParticipationCancelled: + return []byte(s), nil + case ContactRevocationReasonVisibilityClosed: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *ContactRevocationReason) UnmarshalText(data []byte) error { + switch ContactRevocationReason(data) { + case ContactRevocationReasonConsentRevoked: + *s = ContactRevocationReasonConsentRevoked + return nil + case ContactRevocationReasonParticipationCancelled: + *s = ContactRevocationReasonParticipationCancelled + return nil + case ContactRevocationReasonVisibilityClosed: + *s = ContactRevocationReasonVisibilityClosed + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type ContactTelegramUsername string + type CreateMyAssessmentAttemptBadRequest Problem func (*CreateMyAssessmentAttemptBadRequest) createMyAssessmentAttemptRes() {} @@ -3009,6 +4099,30 @@ type CreateMySupportCaseUnprocessableEntity Problem func (*CreateMySupportCaseUnprocessableEntity) createMySupportCaseRes() {} +type CreateOrganizationInvitationBadRequest Problem + +func (*CreateOrganizationInvitationBadRequest) createOrganizationInvitationRes() {} + +type CreateOrganizationInvitationConflict Problem + +func (*CreateOrganizationInvitationConflict) createOrganizationInvitationRes() {} + +type CreateOrganizationInvitationForbidden Problem + +func (*CreateOrganizationInvitationForbidden) createOrganizationInvitationRes() {} + +type CreateOrganizationInvitationNotFound Problem + +func (*CreateOrganizationInvitationNotFound) createOrganizationInvitationRes() {} + +type CreateOrganizationInvitationUnauthorized Problem + +func (*CreateOrganizationInvitationUnauthorized) createOrganizationInvitationRes() {} + +type CreateOrganizationInvitationUnprocessableEntity Problem + +func (*CreateOrganizationInvitationUnprocessableEntity) createOrganizationInvitationRes() {} + type CreateOrganizationNeedBadRequest Problem func (*CreateOrganizationNeedBadRequest) createOrganizationNeedRes() {} @@ -3071,6 +4185,34 @@ func (s *CurrencyCode) UnmarshalText(data []byte) error { } } +type DeclineMyInvitationBadRequest Problem + +func (*DeclineMyInvitationBadRequest) declineMyInvitationRes() {} + +type DeclineMyInvitationConflict Problem + +func (*DeclineMyInvitationConflict) declineMyInvitationRes() {} + +type DeclineMyInvitationForbidden Problem + +func (*DeclineMyInvitationForbidden) declineMyInvitationRes() {} + +type DeclineMyInvitationNotFound Problem + +func (*DeclineMyInvitationNotFound) declineMyInvitationRes() {} + +type DeclineMyInvitationPreconditionFailed Problem + +func (*DeclineMyInvitationPreconditionFailed) declineMyInvitationRes() {} + +type DeclineMyInvitationUnauthorized Problem + +func (*DeclineMyInvitationUnauthorized) declineMyInvitationRes() {} + +type DeclineMyInvitationUnprocessableEntity Problem + +func (*DeclineMyInvitationUnprocessableEntity) declineMyInvitationRes() {} + // Stable code of a professional direction, the group that a specialization belongs to. // // - development: Development. @@ -3475,6 +4617,22 @@ type GetMyAssessmentResultUnauthorized Problem func (*GetMyAssessmentResultUnauthorized) getMyAssessmentResultRes() {} +type GetMyInvitationBadRequest Problem + +func (*GetMyInvitationBadRequest) getMyInvitationRes() {} + +type GetMyInvitationForbidden Problem + +func (*GetMyInvitationForbidden) getMyInvitationRes() {} + +type GetMyInvitationNotFound Problem + +func (*GetMyInvitationNotFound) getMyInvitationRes() {} + +type GetMyInvitationUnauthorized Problem + +func (*GetMyInvitationUnauthorized) getMyInvitationRes() {} + type GetMyQuestionnaireForbidden Problem func (*GetMyQuestionnaireForbidden) getMyQuestionnaireRes() {} @@ -3495,6 +4653,38 @@ type GetMySupportCaseUnauthorized Problem func (*GetMySupportCaseUnauthorized) getMySupportCaseRes() {} +type GetOrganizationInvitationBadRequest Problem + +func (*GetOrganizationInvitationBadRequest) getOrganizationInvitationRes() {} + +type GetOrganizationInvitationContactsBadRequest Problem + +func (*GetOrganizationInvitationContactsBadRequest) getOrganizationInvitationContactsRes() {} + +type GetOrganizationInvitationContactsForbidden Problem + +func (*GetOrganizationInvitationContactsForbidden) getOrganizationInvitationContactsRes() {} + +type GetOrganizationInvitationContactsNotFound Problem + +func (*GetOrganizationInvitationContactsNotFound) getOrganizationInvitationContactsRes() {} + +type GetOrganizationInvitationContactsUnauthorized Problem + +func (*GetOrganizationInvitationContactsUnauthorized) getOrganizationInvitationContactsRes() {} + +type GetOrganizationInvitationForbidden Problem + +func (*GetOrganizationInvitationForbidden) getOrganizationInvitationRes() {} + +type GetOrganizationInvitationNotFound Problem + +func (*GetOrganizationInvitationNotFound) getOrganizationInvitationRes() {} + +type GetOrganizationInvitationUnauthorized Problem + +func (*GetOrganizationInvitationUnauthorized) getOrganizationInvitationRes() {} + type GetOrganizationNeedBadRequest Problem func (*GetOrganizationNeedBadRequest) getOrganizationNeedRes() {} @@ -3675,6 +4865,1306 @@ func (s *IdentityRequestAcceptedStatus) UnmarshalText(data []byte) error { } } +// 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. +// Ref: #/components/schemas/InvitationAcceptance +type InvitationAcceptance struct { + ExpectedVersion InvitationVersion `json:"expected_version"` + // Terms version that the candidate read and accepts. A version that is not the current one answers 412 + // version_conflict. + TermsVersion InvitationTermsVersion `json:"terms_version"` + ConsentC4 ContactConsentAcceptance `json:"consent_c4"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *InvitationAcceptance) GetExpectedVersion() InvitationVersion { + return s.ExpectedVersion +} + +// GetTermsVersion returns the value of TermsVersion. +func (s *InvitationAcceptance) GetTermsVersion() InvitationTermsVersion { + return s.TermsVersion +} + +// GetConsentC4 returns the value of ConsentC4. +func (s *InvitationAcceptance) GetConsentC4() ContactConsentAcceptance { + return s.ConsentC4 +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *InvitationAcceptance) SetExpectedVersion(val InvitationVersion) { + s.ExpectedVersion = val +} + +// SetTermsVersion sets the value of TermsVersion. +func (s *InvitationAcceptance) SetTermsVersion(val InvitationTermsVersion) { + s.TermsVersion = val +} + +// SetConsentC4 sets the value of ConsentC4. +func (s *InvitationAcceptance) SetConsentC4(val ContactConsentAcceptance) { + s.ConsentC4 = val +} + +// Command without parameters over the invitation version the client read: send, withdraw, or cancel. +// Unknown fields are rejected. +// Ref: #/components/schemas/InvitationCommand +type InvitationCommand struct { + ExpectedVersion InvitationVersion `json:"expected_version"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *InvitationCommand) GetExpectedVersion() InvitationVersion { + return s.ExpectedVersion +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *InvitationCommand) SetExpectedVersion(val InvitationVersion) { + s.ExpectedVersion = val +} + +// 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. +// Ref: #/components/schemas/InvitationCommunicationChannel +type InvitationCommunicationChannel string + +const ( + InvitationCommunicationChannelEmail InvitationCommunicationChannel = "email" + InvitationCommunicationChannelPhone InvitationCommunicationChannel = "phone" + InvitationCommunicationChannelTelegram InvitationCommunicationChannel = "telegram" + InvitationCommunicationChannelVideoCall InvitationCommunicationChannel = "video_call" +) + +// AllValues returns all InvitationCommunicationChannel values. +func (InvitationCommunicationChannel) AllValues() []InvitationCommunicationChannel { + return []InvitationCommunicationChannel{ + InvitationCommunicationChannelEmail, + InvitationCommunicationChannelPhone, + InvitationCommunicationChannelTelegram, + InvitationCommunicationChannelVideoCall, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s InvitationCommunicationChannel) MarshalText() ([]byte, error) { + switch s { + case InvitationCommunicationChannelEmail: + return []byte(s), nil + case InvitationCommunicationChannelPhone: + return []byte(s), nil + case InvitationCommunicationChannelTelegram: + return []byte(s), nil + case InvitationCommunicationChannelVideoCall: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *InvitationCommunicationChannel) UnmarshalText(data []byte) error { + switch InvitationCommunicationChannel(data) { + case InvitationCommunicationChannelEmail: + *s = InvitationCommunicationChannelEmail + return nil + case InvitationCommunicationChannelPhone: + *s = InvitationCommunicationChannelPhone + return nil + case InvitationCommunicationChannelTelegram: + *s = InvitationCommunicationChannelTelegram + return nil + case InvitationCommunicationChannelVideoCall: + *s = InvitationCommunicationChannelVideoCall + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// 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. +// Ref: #/components/schemas/InvitationCommunicationMethod +type InvitationCommunicationMethod struct { + Channel InvitationCommunicationChannel `json:"channel"` + // 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. + Details NilInvitationCommunicationNote `json:"details"` +} + +// GetChannel returns the value of Channel. +func (s *InvitationCommunicationMethod) GetChannel() InvitationCommunicationChannel { + return s.Channel +} + +// GetDetails returns the value of Details. +func (s *InvitationCommunicationMethod) GetDetails() NilInvitationCommunicationNote { + return s.Details +} + +// SetChannel sets the value of Channel. +func (s *InvitationCommunicationMethod) SetChannel(val InvitationCommunicationChannel) { + s.Channel = val +} + +// SetDetails sets the value of Details. +func (s *InvitationCommunicationMethod) SetDetails(val NilInvitationCommunicationNote) { + s.Details = val +} + +type InvitationCommunicationNote string + +// Contact access of the organization through this invitation, without any contact value. The values +// come only from GetOrganizationInvitationContacts. +// Ref: #/components/schemas/InvitationContactAccess +type InvitationContactAccess struct { + Status InvitationContactAccessState `json:"status"` + // Kinds of contact that the read returns while `status` is `available`; empty otherwise. + Fields []ContactFieldKind `json:"fields"` +} + +// GetStatus returns the value of Status. +func (s *InvitationContactAccess) GetStatus() InvitationContactAccessState { + return s.Status +} + +// GetFields returns the value of Fields. +func (s *InvitationContactAccess) GetFields() []ContactFieldKind { + return s.Fields +} + +// SetStatus sets the value of Status. +func (s *InvitationContactAccess) SetStatus(val InvitationContactAccessState) { + s.Status = val +} + +// SetFields sets the value of Fields. +func (s *InvitationContactAccess) SetFields(val []ContactFieldKind) { + s.Fields = val +} + +// 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. +// +// Ref: #/components/schemas/InvitationContactAccessState +type InvitationContactAccessState string + +const ( + InvitationContactAccessStateNotGranted InvitationContactAccessState = "not_granted" + InvitationContactAccessStateAvailable InvitationContactAccessState = "available" + InvitationContactAccessStateClosed InvitationContactAccessState = "closed" +) + +// AllValues returns all InvitationContactAccessState values. +func (InvitationContactAccessState) AllValues() []InvitationContactAccessState { + return []InvitationContactAccessState{ + InvitationContactAccessStateNotGranted, + InvitationContactAccessStateAvailable, + InvitationContactAccessStateClosed, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s InvitationContactAccessState) MarshalText() ([]byte, error) { + switch s { + case InvitationContactAccessStateNotGranted: + return []byte(s), nil + case InvitationContactAccessStateAvailable: + return []byte(s), nil + case InvitationContactAccessStateClosed: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *InvitationContactAccessState) UnmarshalText(data []byte) error { + switch InvitationContactAccessState(data) { + case InvitationContactAccessStateNotGranted: + *s = InvitationContactAccessStateNotGranted + return nil + case InvitationContactAccessStateAvailable: + *s = InvitationContactAccessStateAvailable + return nil + case InvitationContactAccessStateClosed: + *s = InvitationContactAccessStateClosed + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type InvitationDeclineComment string + +// 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. +// Ref: #/components/schemas/InvitationDeclineReason +type InvitationDeclineReason string + +const ( + InvitationDeclineReasonSalary InvitationDeclineReason = "salary" + InvitationDeclineReasonTasks InvitationDeclineReason = "tasks" + InvitationDeclineReasonStack InvitationDeclineReason = "stack" + InvitationDeclineReasonWorkFormat InvitationDeclineReason = "work_format" + InvitationDeclineReasonPackage InvitationDeclineReason = "package" + InvitationDeclineReasonCompany InvitationDeclineReason = "company" + InvitationDeclineReasonNotLooking InvitationDeclineReason = "not_looking" + InvitationDeclineReasonOtherOffer InvitationDeclineReason = "other_offer" + InvitationDeclineReasonOther InvitationDeclineReason = "other" +) + +// AllValues returns all InvitationDeclineReason values. +func (InvitationDeclineReason) AllValues() []InvitationDeclineReason { + return []InvitationDeclineReason{ + InvitationDeclineReasonSalary, + InvitationDeclineReasonTasks, + InvitationDeclineReasonStack, + InvitationDeclineReasonWorkFormat, + InvitationDeclineReasonPackage, + InvitationDeclineReasonCompany, + InvitationDeclineReasonNotLooking, + InvitationDeclineReasonOtherOffer, + InvitationDeclineReasonOther, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s InvitationDeclineReason) MarshalText() ([]byte, error) { + switch s { + case InvitationDeclineReasonSalary: + return []byte(s), nil + case InvitationDeclineReasonTasks: + return []byte(s), nil + case InvitationDeclineReasonStack: + return []byte(s), nil + case InvitationDeclineReasonWorkFormat: + return []byte(s), nil + case InvitationDeclineReasonPackage: + return []byte(s), nil + case InvitationDeclineReasonCompany: + return []byte(s), nil + case InvitationDeclineReasonNotLooking: + return []byte(s), nil + case InvitationDeclineReasonOtherOffer: + return []byte(s), nil + case InvitationDeclineReasonOther: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *InvitationDeclineReason) UnmarshalText(data []byte) error { + switch InvitationDeclineReason(data) { + case InvitationDeclineReasonSalary: + *s = InvitationDeclineReasonSalary + return nil + case InvitationDeclineReasonTasks: + *s = InvitationDeclineReasonTasks + return nil + case InvitationDeclineReasonStack: + *s = InvitationDeclineReasonStack + return nil + case InvitationDeclineReasonWorkFormat: + *s = InvitationDeclineReasonWorkFormat + return nil + case InvitationDeclineReasonPackage: + *s = InvitationDeclineReasonPackage + return nil + case InvitationDeclineReasonCompany: + *s = InvitationDeclineReasonCompany + return nil + case InvitationDeclineReasonNotLooking: + *s = InvitationDeclineReasonNotLooking + return nil + case InvitationDeclineReasonOtherOffer: + *s = InvitationDeclineReasonOtherOffer + return nil + case InvitationDeclineReasonOther: + *s = InvitationDeclineReasonOther + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// The candidate's own decline, as the candidate reads it back. +// Ref: #/components/schemas/InvitationDeclineRecord +type InvitationDeclineRecord struct { + Reason InvitationDeclineReason `json:"reason"` + Comment NilInvitationDeclineComment `json:"comment"` + DeclinedAt Timestamp `json:"declined_at"` +} + +// GetReason returns the value of Reason. +func (s *InvitationDeclineRecord) GetReason() InvitationDeclineReason { + return s.Reason +} + +// GetComment returns the value of Comment. +func (s *InvitationDeclineRecord) GetComment() NilInvitationDeclineComment { + return s.Comment +} + +// GetDeclinedAt returns the value of DeclinedAt. +func (s *InvitationDeclineRecord) GetDeclinedAt() Timestamp { + return s.DeclinedAt +} + +// SetReason sets the value of Reason. +func (s *InvitationDeclineRecord) SetReason(val InvitationDeclineReason) { + s.Reason = val +} + +// SetComment sets the value of Comment. +func (s *InvitationDeclineRecord) SetComment(val NilInvitationDeclineComment) { + s.Comment = val +} + +// SetDeclinedAt sets the value of DeclinedAt. +func (s *InvitationDeclineRecord) SetDeclinedAt(val Timestamp) { + s.DeclinedAt = val +} + +// Structured decline: a reason and an optional comment. Unknown fields are rejected. +// Ref: #/components/schemas/InvitationDeclineRequest +type InvitationDeclineRequest struct { + ExpectedVersion InvitationVersion `json:"expected_version"` + Reason InvitationDeclineReason `json:"reason"` + // Optional comment for any reason, including `other`; absent or null means none. + Comment OptNilInvitationDeclineComment `json:"comment"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *InvitationDeclineRequest) GetExpectedVersion() InvitationVersion { + return s.ExpectedVersion +} + +// GetReason returns the value of Reason. +func (s *InvitationDeclineRequest) GetReason() InvitationDeclineReason { + return s.Reason +} + +// GetComment returns the value of Comment. +func (s *InvitationDeclineRequest) GetComment() OptNilInvitationDeclineComment { + return s.Comment +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *InvitationDeclineRequest) SetExpectedVersion(val InvitationVersion) { + s.ExpectedVersion = val +} + +// SetReason sets the value of Reason. +func (s *InvitationDeclineRequest) SetReason(val InvitationDeclineReason) { + s.Reason = val +} + +// SetComment sets the value of Comment. +func (s *InvitationDeclineRequest) SetComment(val OptNilInvitationDeclineComment) { + s.Comment = val +} + +// 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. +// +// Ref: #/components/schemas/InvitationExpiryReason +type InvitationExpiryReason string + +const ( + InvitationExpiryReasonInvitationTimeout InvitationExpiryReason = "invitation_timeout" + InvitationExpiryReasonNegotiationTimeout InvitationExpiryReason = "negotiation_timeout" +) + +// AllValues returns all InvitationExpiryReason values. +func (InvitationExpiryReason) AllValues() []InvitationExpiryReason { + return []InvitationExpiryReason{ + InvitationExpiryReasonInvitationTimeout, + InvitationExpiryReasonNegotiationTimeout, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s InvitationExpiryReason) MarshalText() ([]byte, error) { + switch s { + case InvitationExpiryReasonInvitationTimeout: + return []byte(s), nil + case InvitationExpiryReasonNegotiationTimeout: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *InvitationExpiryReason) UnmarshalText(data []byte) error { + switch InvitationExpiryReason(data) { + case InvitationExpiryReasonInvitationTimeout: + *s = InvitationExpiryReasonInvitationTimeout + return nil + case InvitationExpiryReasonNegotiationTimeout: + *s = InvitationExpiryReasonNegotiationTimeout + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// 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. +// Ref: #/components/schemas/InvitationNeedReference +type InvitationNeedReference struct { + // Identifier of a need of the organization in the path. + NeedID uuid.UUID `json:"need_id"` + // `requirements_version` of the need that the invitation refers to; it must be a version that the need + // has had. + RequirementsVersion NeedVersion `json:"requirements_version"` +} + +// GetNeedID returns the value of NeedID. +func (s *InvitationNeedReference) GetNeedID() uuid.UUID { + return s.NeedID +} + +// GetRequirementsVersion returns the value of RequirementsVersion. +func (s *InvitationNeedReference) GetRequirementsVersion() NeedVersion { + return s.RequirementsVersion +} + +// SetNeedID sets the value of NeedID. +func (s *InvitationNeedReference) SetNeedID(val uuid.UUID) { + s.NeedID = val +} + +// SetRequirementsVersion sets the value of RequirementsVersion. +func (s *InvitationNeedReference) SetRequirementsVersion(val NeedVersion) { + s.RequirementsVersion = val +} + +// 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. +// Ref: #/components/schemas/InvitationOfferType +type InvitationOfferType string + +const ( + InvitationOfferTypeFullTime InvitationOfferType = "full_time" + InvitationOfferTypePartTime InvitationOfferType = "part_time" + InvitationOfferTypeContract InvitationOfferType = "contract" + InvitationOfferTypeInternship InvitationOfferType = "internship" +) + +// AllValues returns all InvitationOfferType values. +func (InvitationOfferType) AllValues() []InvitationOfferType { + return []InvitationOfferType{ + InvitationOfferTypeFullTime, + InvitationOfferTypePartTime, + InvitationOfferTypeContract, + InvitationOfferTypeInternship, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s InvitationOfferType) MarshalText() ([]byte, error) { + switch s { + case InvitationOfferTypeFullTime: + return []byte(s), nil + case InvitationOfferTypePartTime: + return []byte(s), nil + case InvitationOfferTypeContract: + return []byte(s), nil + case InvitationOfferTypeInternship: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *InvitationOfferType) UnmarshalText(data []byte) error { + switch InvitationOfferType(data) { + case InvitationOfferTypeFullTime: + *s = InvitationOfferTypeFullTime + return nil + case InvitationOfferTypePartTime: + *s = InvitationOfferTypePartTime + return nil + case InvitationOfferTypeContract: + *s = InvitationOfferTypeContract + return nil + case InvitationOfferTypeInternship: + *s = InvitationOfferTypeInternship + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// 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. +// Ref: #/components/schemas/InvitationOrganization +type InvitationOrganization struct { + // Identifier of the organization. + ID uuid.UUID `json:"id"` + // Public name of the organization. Plain text; clients show it as text, never as HTML. + Name string `json:"name"` +} + +// GetID returns the value of ID. +func (s *InvitationOrganization) GetID() uuid.UUID { + return s.ID +} + +// GetName returns the value of Name. +func (s *InvitationOrganization) GetName() string { + return s.Name +} + +// SetID sets the value of ID. +func (s *InvitationOrganization) SetID(val uuid.UUID) { + s.ID = val +} + +// SetName sets the value of Name. +func (s *InvitationOrganization) SetName(val string) { + s.Name = val +} + +// 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. +// Ref: #/components/schemas/InvitationPackage +type InvitationPackage struct { + Bonus InvitationPackageItem `json:"bonus"` + Equipment InvitationPackageItem `json:"equipment"` + Training InvitationPackageItem `json:"training"` + HealthInsurance InvitationPackageItem `json:"health_insurance"` +} + +// GetBonus returns the value of Bonus. +func (s *InvitationPackage) GetBonus() InvitationPackageItem { + return s.Bonus +} + +// GetEquipment returns the value of Equipment. +func (s *InvitationPackage) GetEquipment() InvitationPackageItem { + return s.Equipment +} + +// GetTraining returns the value of Training. +func (s *InvitationPackage) GetTraining() InvitationPackageItem { + return s.Training +} + +// GetHealthInsurance returns the value of HealthInsurance. +func (s *InvitationPackage) GetHealthInsurance() InvitationPackageItem { + return s.HealthInsurance +} + +// SetBonus sets the value of Bonus. +func (s *InvitationPackage) SetBonus(val InvitationPackageItem) { + s.Bonus = val +} + +// SetEquipment sets the value of Equipment. +func (s *InvitationPackage) SetEquipment(val InvitationPackageItem) { + s.Equipment = val +} + +// SetTraining sets the value of Training. +func (s *InvitationPackage) SetTraining(val InvitationPackageItem) { + s.Training = val +} + +// SetHealthInsurance sets the value of HealthInsurance. +func (s *InvitationPackage) SetHealthInsurance(val InvitationPackageItem) { + s.HealthInsurance = val +} + +// 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`. +// Ref: #/components/schemas/InvitationPackageItem +// InvitationPackageItem represents sum type. +type InvitationPackageItem struct { + // Type selects the active sum variant, switch on this field. + Type InvitationPackageItemType + InvitationPackageItemProvided InvitationPackageItemProvided + InvitationPackageItemNotProvided InvitationPackageItemNotProvided +} + +// InvitationPackageItemType is oneOf type of InvitationPackageItem. +type InvitationPackageItemType string + +// Possible values for InvitationPackageItemType. +const ( + InvitationPackageItemProvidedInvitationPackageItem InvitationPackageItemType = "InvitationPackageItemProvided" + InvitationPackageItemNotProvidedInvitationPackageItem InvitationPackageItemType = "InvitationPackageItemNotProvided" +) + +// IsInvitationPackageItemProvided reports whether InvitationPackageItem is InvitationPackageItemProvided. +func (s InvitationPackageItem) IsInvitationPackageItemProvided() bool { + return s.Type == InvitationPackageItemProvidedInvitationPackageItem +} + +// IsInvitationPackageItemNotProvided reports whether InvitationPackageItem is InvitationPackageItemNotProvided. +func (s InvitationPackageItem) IsInvitationPackageItemNotProvided() bool { + return s.Type == InvitationPackageItemNotProvidedInvitationPackageItem +} + +// SetInvitationPackageItemProvided sets InvitationPackageItem to InvitationPackageItemProvided. +func (s *InvitationPackageItem) SetInvitationPackageItemProvided(v InvitationPackageItemProvided) { + s.Type = InvitationPackageItemProvidedInvitationPackageItem + s.InvitationPackageItemProvided = v +} + +// GetInvitationPackageItemProvided returns InvitationPackageItemProvided and true boolean if InvitationPackageItem is InvitationPackageItemProvided. +func (s InvitationPackageItem) GetInvitationPackageItemProvided() (v InvitationPackageItemProvided, ok bool) { + if !s.IsInvitationPackageItemProvided() { + return v, false + } + return s.InvitationPackageItemProvided, true +} + +// NewInvitationPackageItemProvidedInvitationPackageItem returns new InvitationPackageItem from InvitationPackageItemProvided. +func NewInvitationPackageItemProvidedInvitationPackageItem(v InvitationPackageItemProvided) InvitationPackageItem { + var s InvitationPackageItem + s.SetInvitationPackageItemProvided(v) + return s +} + +// SetInvitationPackageItemNotProvided sets InvitationPackageItem to InvitationPackageItemNotProvided. +func (s *InvitationPackageItem) SetInvitationPackageItemNotProvided(v InvitationPackageItemNotProvided) { + s.Type = InvitationPackageItemNotProvidedInvitationPackageItem + s.InvitationPackageItemNotProvided = v +} + +// GetInvitationPackageItemNotProvided returns InvitationPackageItemNotProvided and true boolean if InvitationPackageItem is InvitationPackageItemNotProvided. +func (s InvitationPackageItem) GetInvitationPackageItemNotProvided() (v InvitationPackageItemNotProvided, ok bool) { + if !s.IsInvitationPackageItemNotProvided() { + return v, false + } + return s.InvitationPackageItemNotProvided, true +} + +// NewInvitationPackageItemNotProvidedInvitationPackageItem returns new InvitationPackageItem from InvitationPackageItemNotProvided. +func NewInvitationPackageItemNotProvidedInvitationPackageItem(v InvitationPackageItemNotProvided) InvitationPackageItem { + var s InvitationPackageItem + s.SetInvitationPackageItemNotProvided(v) + return s +} + +// The organization states explicitly that the offer does not include the condition ("Не +// предусмотрено" in the interface). It has no description. +// Ref: #/components/schemas/InvitationPackageItemNotProvided +type InvitationPackageItemNotProvided struct { + Status InvitationPackageItemNotProvidedStatus `json:"status"` +} + +// GetStatus returns the value of Status. +func (s *InvitationPackageItemNotProvided) GetStatus() InvitationPackageItemNotProvidedStatus { + return s.Status +} + +// SetStatus sets the value of Status. +func (s *InvitationPackageItemNotProvided) SetStatus(val InvitationPackageItemNotProvidedStatus) { + s.Status = val +} + +type InvitationPackageItemNotProvidedStatus string + +const ( + InvitationPackageItemNotProvidedStatusNotProvided InvitationPackageItemNotProvidedStatus = "not_provided" +) + +// AllValues returns all InvitationPackageItemNotProvidedStatus values. +func (InvitationPackageItemNotProvidedStatus) AllValues() []InvitationPackageItemNotProvidedStatus { + return []InvitationPackageItemNotProvidedStatus{ + InvitationPackageItemNotProvidedStatusNotProvided, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s InvitationPackageItemNotProvidedStatus) MarshalText() ([]byte, error) { + switch s { + case InvitationPackageItemNotProvidedStatusNotProvided: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *InvitationPackageItemNotProvidedStatus) UnmarshalText(data []byte) error { + switch InvitationPackageItemNotProvidedStatus(data) { + case InvitationPackageItemNotProvidedStatusNotProvided: + *s = InvitationPackageItemNotProvidedStatusNotProvided + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// The condition is part of the offer, with its description. +// Ref: #/components/schemas/InvitationPackageItemProvided +type InvitationPackageItemProvided struct { + Status InvitationPackageItemProvidedStatus `json:"status"` + Description InvitationPackageItemText `json:"description"` +} + +// GetStatus returns the value of Status. +func (s *InvitationPackageItemProvided) GetStatus() InvitationPackageItemProvidedStatus { + return s.Status +} + +// GetDescription returns the value of Description. +func (s *InvitationPackageItemProvided) GetDescription() InvitationPackageItemText { + return s.Description +} + +// SetStatus sets the value of Status. +func (s *InvitationPackageItemProvided) SetStatus(val InvitationPackageItemProvidedStatus) { + s.Status = val +} + +// SetDescription sets the value of Description. +func (s *InvitationPackageItemProvided) SetDescription(val InvitationPackageItemText) { + s.Description = val +} + +type InvitationPackageItemProvidedStatus string + +const ( + InvitationPackageItemProvidedStatusProvided InvitationPackageItemProvidedStatus = "provided" +) + +// AllValues returns all InvitationPackageItemProvidedStatus values. +func (InvitationPackageItemProvidedStatus) AllValues() []InvitationPackageItemProvidedStatus { + return []InvitationPackageItemProvidedStatus{ + InvitationPackageItemProvidedStatusProvided, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s InvitationPackageItemProvidedStatus) MarshalText() ([]byte, error) { + switch s { + case InvitationPackageItemProvidedStatusProvided: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *InvitationPackageItemProvidedStatus) UnmarshalText(data []byte) error { + switch InvitationPackageItemProvidedStatus(data) { + case InvitationPackageItemProvidedStatusProvided: + *s = InvitationPackageItemProvidedStatusProvided + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type InvitationPackageItemText string + +// 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. +// Ref: #/components/schemas/InvitationResponsePeriod +type InvitationResponsePeriod int32 + +const ( + InvitationResponsePeriod3 InvitationResponsePeriod = 3 + InvitationResponsePeriod7 InvitationResponsePeriod = 7 + InvitationResponsePeriod14 InvitationResponsePeriod = 14 +) + +// AllValues returns all InvitationResponsePeriod values. +func (InvitationResponsePeriod) AllValues() []InvitationResponsePeriod { + return []InvitationResponsePeriod{ + InvitationResponsePeriod3, + InvitationResponsePeriod7, + InvitationResponsePeriod14, + } +} + +type InvitationRoleTitle string + +// 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. +// Ref: #/components/schemas/InvitationSalaryFit +type InvitationSalaryFit string + +const ( + InvitationSalaryFitWithinRange InvitationSalaryFit = "within_range" + InvitationSalaryFitUpTo10PercentAbove InvitationSalaryFit = "up_to_10_percent_above" + InvitationSalaryFitAbove InvitationSalaryFit = "above" + InvitationSalaryFitWithheld InvitationSalaryFit = "withheld" + InvitationSalaryFitNotAvailable InvitationSalaryFit = "not_available" +) + +// AllValues returns all InvitationSalaryFit values. +func (InvitationSalaryFit) AllValues() []InvitationSalaryFit { + return []InvitationSalaryFit{ + InvitationSalaryFitWithinRange, + InvitationSalaryFitUpTo10PercentAbove, + InvitationSalaryFitAbove, + InvitationSalaryFitWithheld, + InvitationSalaryFitNotAvailable, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s InvitationSalaryFit) MarshalText() ([]byte, error) { + switch s { + case InvitationSalaryFitWithinRange: + return []byte(s), nil + case InvitationSalaryFitUpTo10PercentAbove: + return []byte(s), nil + case InvitationSalaryFitAbove: + return []byte(s), nil + case InvitationSalaryFitWithheld: + return []byte(s), nil + case InvitationSalaryFitNotAvailable: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *InvitationSalaryFit) UnmarshalText(data []byte) error { + switch InvitationSalaryFit(data) { + case InvitationSalaryFitWithinRange: + *s = InvitationSalaryFitWithinRange + return nil + case InvitationSalaryFitUpTo10PercentAbove: + *s = InvitationSalaryFitUpTo10PercentAbove + return nil + case InvitationSalaryFitAbove: + *s = InvitationSalaryFitAbove + return nil + case InvitationSalaryFitWithheld: + *s = InvitationSalaryFitWithheld + return nil + case InvitationSalaryFitNotAvailable: + *s = InvitationSalaryFitNotAvailable + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// 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. +// Ref: #/components/schemas/InvitationSalaryRaise +type InvitationSalaryRaise struct { + ExpectedVersion InvitationVersion `json:"expected_version"` + // New upper bound, above the current one, with a width of the range from 10% to 40% of its midpoint. + SalaryTo RubAmount `json:"salary_to"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *InvitationSalaryRaise) GetExpectedVersion() InvitationVersion { + return s.ExpectedVersion +} + +// GetSalaryTo returns the value of SalaryTo. +func (s *InvitationSalaryRaise) GetSalaryTo() RubAmount { + return s.SalaryTo +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *InvitationSalaryRaise) SetExpectedVersion(val InvitationVersion) { + s.ExpectedVersion = val +} + +// SetSalaryTo sets the value of SalaryTo. +func (s *InvitationSalaryRaise) SetSalaryTo(val RubAmount) { + s.SalaryTo = val +} + +// 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. +// Ref: #/components/schemas/InvitationState +type InvitationState string + +const ( + InvitationStateDraft InvitationState = "draft" + InvitationStateDelivered InvitationState = "delivered" + InvitationStateViewed InvitationState = "viewed" + InvitationStateCounter InvitationState = "counter" + InvitationStateAccepted InvitationState = "accepted" + InvitationStateInterviewScheduled InvitationState = "interview_scheduled" + InvitationStateInterviewed InvitationState = "interviewed" + InvitationStateNegotiation InvitationState = "negotiation" + InvitationStateTermsAgreed InvitationState = "terms_agreed" + InvitationStateNoDeal InvitationState = "no_deal" + InvitationStateDeclined InvitationState = "declined" + InvitationStateExpired InvitationState = "expired" + InvitationStateWithdrawn InvitationState = "withdrawn" + InvitationStateCancelledByCandidate InvitationState = "cancelled_by_candidate" +) + +// AllValues returns all InvitationState values. +func (InvitationState) AllValues() []InvitationState { + return []InvitationState{ + InvitationStateDraft, + InvitationStateDelivered, + InvitationStateViewed, + InvitationStateCounter, + InvitationStateAccepted, + InvitationStateInterviewScheduled, + InvitationStateInterviewed, + InvitationStateNegotiation, + InvitationStateTermsAgreed, + InvitationStateNoDeal, + InvitationStateDeclined, + InvitationStateExpired, + InvitationStateWithdrawn, + InvitationStateCancelledByCandidate, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s InvitationState) MarshalText() ([]byte, error) { + switch s { + case InvitationStateDraft: + return []byte(s), nil + case InvitationStateDelivered: + return []byte(s), nil + case InvitationStateViewed: + return []byte(s), nil + case InvitationStateCounter: + return []byte(s), nil + case InvitationStateAccepted: + return []byte(s), nil + case InvitationStateInterviewScheduled: + return []byte(s), nil + case InvitationStateInterviewed: + return []byte(s), nil + case InvitationStateNegotiation: + return []byte(s), nil + case InvitationStateTermsAgreed: + return []byte(s), nil + case InvitationStateNoDeal: + return []byte(s), nil + case InvitationStateDeclined: + return []byte(s), nil + case InvitationStateExpired: + return []byte(s), nil + case InvitationStateWithdrawn: + return []byte(s), nil + case InvitationStateCancelledByCandidate: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *InvitationState) UnmarshalText(data []byte) error { + switch InvitationState(data) { + case InvitationStateDraft: + *s = InvitationStateDraft + return nil + case InvitationStateDelivered: + *s = InvitationStateDelivered + return nil + case InvitationStateViewed: + *s = InvitationStateViewed + return nil + case InvitationStateCounter: + *s = InvitationStateCounter + return nil + case InvitationStateAccepted: + *s = InvitationStateAccepted + return nil + case InvitationStateInterviewScheduled: + *s = InvitationStateInterviewScheduled + return nil + case InvitationStateInterviewed: + *s = InvitationStateInterviewed + return nil + case InvitationStateNegotiation: + *s = InvitationStateNegotiation + return nil + case InvitationStateTermsAgreed: + *s = InvitationStateTermsAgreed + return nil + case InvitationStateNoDeal: + *s = InvitationStateNoDeal + return nil + case InvitationStateDeclined: + *s = InvitationStateDeclined + return nil + case InvitationStateExpired: + *s = InvitationStateExpired + return nil + case InvitationStateWithdrawn: + *s = InvitationStateWithdrawn + return nil + case InvitationStateCancelledByCandidate: + *s = InvitationStateCancelledByCandidate + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type InvitationTeamDescription string + +// 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. +// Ref: #/components/schemas/InvitationTerms +type InvitationTerms struct { + RoleTitle InvitationRoleTitle `json:"role_title"` + Specialization SpecializationCode `json:"specialization"` + Grade GradeCode `json:"grade"` + OfferType InvitationOfferType `json:"offer_type"` + // Work tasks of the role in the order given. + Tasks []NeedTaskText `json:"tasks"` + Team InvitationTeamDescription `json:"team"` + // Technologies of the role. The server compares names without regard to letter case. + TechStack []SkillName `json:"tech_stack"` + // Work formats the organization offers; the candidate may choose any of them. + WorkFormats []WorkFormat `json:"work_formats"` + // 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. + Location NilNeedLocationName `json:"location"` + CommunicationMethod InvitationCommunicationMethod `json:"communication_method"` + Salary SalaryRange `json:"salary"` + Package InvitationPackage `json:"package"` +} + +// GetRoleTitle returns the value of RoleTitle. +func (s *InvitationTerms) GetRoleTitle() InvitationRoleTitle { + return s.RoleTitle +} + +// GetSpecialization returns the value of Specialization. +func (s *InvitationTerms) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetGrade returns the value of Grade. +func (s *InvitationTerms) GetGrade() GradeCode { + return s.Grade +} + +// GetOfferType returns the value of OfferType. +func (s *InvitationTerms) GetOfferType() InvitationOfferType { + return s.OfferType +} + +// GetTasks returns the value of Tasks. +func (s *InvitationTerms) GetTasks() []NeedTaskText { + return s.Tasks +} + +// GetTeam returns the value of Team. +func (s *InvitationTerms) GetTeam() InvitationTeamDescription { + return s.Team +} + +// GetTechStack returns the value of TechStack. +func (s *InvitationTerms) GetTechStack() []SkillName { + return s.TechStack +} + +// GetWorkFormats returns the value of WorkFormats. +func (s *InvitationTerms) GetWorkFormats() []WorkFormat { + return s.WorkFormats +} + +// GetLocation returns the value of Location. +func (s *InvitationTerms) GetLocation() NilNeedLocationName { + return s.Location +} + +// GetCommunicationMethod returns the value of CommunicationMethod. +func (s *InvitationTerms) GetCommunicationMethod() InvitationCommunicationMethod { + return s.CommunicationMethod +} + +// GetSalary returns the value of Salary. +func (s *InvitationTerms) GetSalary() SalaryRange { + return s.Salary +} + +// GetPackage returns the value of Package. +func (s *InvitationTerms) GetPackage() InvitationPackage { + return s.Package +} + +// SetRoleTitle sets the value of RoleTitle. +func (s *InvitationTerms) SetRoleTitle(val InvitationRoleTitle) { + s.RoleTitle = val +} + +// SetSpecialization sets the value of Specialization. +func (s *InvitationTerms) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetGrade sets the value of Grade. +func (s *InvitationTerms) SetGrade(val GradeCode) { + s.Grade = val +} + +// SetOfferType sets the value of OfferType. +func (s *InvitationTerms) SetOfferType(val InvitationOfferType) { + s.OfferType = val +} + +// SetTasks sets the value of Tasks. +func (s *InvitationTerms) SetTasks(val []NeedTaskText) { + s.Tasks = val +} + +// SetTeam sets the value of Team. +func (s *InvitationTerms) SetTeam(val InvitationTeamDescription) { + s.Team = val +} + +// SetTechStack sets the value of TechStack. +func (s *InvitationTerms) SetTechStack(val []SkillName) { + s.TechStack = val +} + +// SetWorkFormats sets the value of WorkFormats. +func (s *InvitationTerms) SetWorkFormats(val []WorkFormat) { + s.WorkFormats = val +} + +// SetLocation sets the value of Location. +func (s *InvitationTerms) SetLocation(val NilNeedLocationName) { + s.Location = val +} + +// SetCommunicationMethod sets the value of CommunicationMethod. +func (s *InvitationTerms) SetCommunicationMethod(val InvitationCommunicationMethod) { + s.CommunicationMethod = val +} + +// SetSalary sets the value of Salary. +func (s *InvitationTerms) SetSalary(val SalaryRange) { + s.Salary = val +} + +// SetPackage sets the value of Package. +func (s *InvitationTerms) SetPackage(val InvitationPackage) { + s.Package = val +} + +type InvitationTermsVersion int64 + +type InvitationVersion int64 + // Format-specific part of an item, selected by `format`. It holds only what the candidate needs to // answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a // hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or @@ -3877,6 +6367,18 @@ func NewPracticeItemContentItemContent(v PracticeItemContent) ItemContent { return s } +type ListMyInvitationsBadRequest Problem + +func (*ListMyInvitationsBadRequest) listMyInvitationsRes() {} + +type ListMyInvitationsForbidden Problem + +func (*ListMyInvitationsForbidden) listMyInvitationsRes() {} + +type ListMyInvitationsUnauthorized Problem + +func (*ListMyInvitationsUnauthorized) listMyInvitationsRes() {} + type ListMySupportCasesBadRequest Problem func (*ListMySupportCasesBadRequest) listMySupportCasesRes() {} @@ -3885,6 +6387,22 @@ type ListMySupportCasesUnauthorized Problem func (*ListMySupportCasesUnauthorized) listMySupportCasesRes() {} +type ListOrganizationInvitationsBadRequest Problem + +func (*ListOrganizationInvitationsBadRequest) listOrganizationInvitationsRes() {} + +type ListOrganizationInvitationsForbidden Problem + +func (*ListOrganizationInvitationsForbidden) listOrganizationInvitationsRes() {} + +type ListOrganizationInvitationsNotFound Problem + +func (*ListOrganizationInvitationsNotFound) listOrganizationInvitationsRes() {} + +type ListOrganizationInvitationsUnauthorized Problem + +func (*ListOrganizationInvitationsUnauthorized) listOrganizationInvitationsRes() {} + type ListOrganizationNeedsBadRequest Problem func (*ListOrganizationNeedsBadRequest) listOrganizationNeedsRes() {} @@ -6587,6 +9105,366 @@ func (o NilCandidateExperience) Or(d CandidateExperience) CandidateExperience { return d } +// NewNilContactAccessBlock returns new NilContactAccessBlock with value set to v. +func NewNilContactAccessBlock(v ContactAccessBlock) NilContactAccessBlock { + return NilContactAccessBlock{ + Value: v, + } +} + +// NilContactAccessBlock is nullable ContactAccessBlock. +type NilContactAccessBlock struct { + Value ContactAccessBlock + Null bool +} + +// SetTo sets value to v. +func (o *NilContactAccessBlock) SetTo(v ContactAccessBlock) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilContactAccessBlock) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilContactAccessBlock) SetToNull() { + o.Null = true + var v ContactAccessBlock + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilContactAccessBlock) Get() (v ContactAccessBlock, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilContactAccessBlock) Or(d ContactAccessBlock) ContactAccessBlock { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilContactConsentOffer returns new NilContactConsentOffer with value set to v. +func NewNilContactConsentOffer(v ContactConsentOffer) NilContactConsentOffer { + return NilContactConsentOffer{ + Value: v, + } +} + +// NilContactConsentOffer is nullable ContactConsentOffer. +type NilContactConsentOffer struct { + Value ContactConsentOffer + Null bool +} + +// SetTo sets value to v. +func (o *NilContactConsentOffer) SetTo(v ContactConsentOffer) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilContactConsentOffer) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilContactConsentOffer) SetToNull() { + o.Null = true + var v ContactConsentOffer + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilContactConsentOffer) Get() (v ContactConsentOffer, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilContactConsentOffer) Or(d ContactConsentOffer) ContactConsentOffer { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilContactFullName returns new NilContactFullName with value set to v. +func NewNilContactFullName(v ContactFullName) NilContactFullName { + return NilContactFullName{ + Value: v, + } +} + +// NilContactFullName is nullable ContactFullName. +type NilContactFullName struct { + Value ContactFullName + Null bool +} + +// SetTo sets value to v. +func (o *NilContactFullName) SetTo(v ContactFullName) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilContactFullName) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilContactFullName) SetToNull() { + o.Null = true + var v ContactFullName + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilContactFullName) Get() (v ContactFullName, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilContactFullName) Or(d ContactFullName) ContactFullName { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilContactGrant returns new NilContactGrant with value set to v. +func NewNilContactGrant(v ContactGrant) NilContactGrant { + return NilContactGrant{ + Value: v, + } +} + +// NilContactGrant is nullable ContactGrant. +type NilContactGrant struct { + Value ContactGrant + Null bool +} + +// SetTo sets value to v. +func (o *NilContactGrant) SetTo(v ContactGrant) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilContactGrant) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilContactGrant) SetToNull() { + o.Null = true + var v ContactGrant + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilContactGrant) Get() (v ContactGrant, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilContactGrant) Or(d ContactGrant) ContactGrant { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilContactPhoneNumber returns new NilContactPhoneNumber with value set to v. +func NewNilContactPhoneNumber(v ContactPhoneNumber) NilContactPhoneNumber { + return NilContactPhoneNumber{ + Value: v, + } +} + +// NilContactPhoneNumber is nullable ContactPhoneNumber. +type NilContactPhoneNumber struct { + Value ContactPhoneNumber + Null bool +} + +// SetTo sets value to v. +func (o *NilContactPhoneNumber) SetTo(v ContactPhoneNumber) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilContactPhoneNumber) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilContactPhoneNumber) SetToNull() { + o.Null = true + var v ContactPhoneNumber + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilContactPhoneNumber) Get() (v ContactPhoneNumber, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilContactPhoneNumber) Or(d ContactPhoneNumber) ContactPhoneNumber { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilContactRevocationReason returns new NilContactRevocationReason with value set to v. +func NewNilContactRevocationReason(v ContactRevocationReason) NilContactRevocationReason { + return NilContactRevocationReason{ + Value: v, + } +} + +// NilContactRevocationReason is nullable ContactRevocationReason. +type NilContactRevocationReason struct { + Value ContactRevocationReason + Null bool +} + +// SetTo sets value to v. +func (o *NilContactRevocationReason) SetTo(v ContactRevocationReason) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilContactRevocationReason) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilContactRevocationReason) SetToNull() { + o.Null = true + var v ContactRevocationReason + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilContactRevocationReason) Get() (v ContactRevocationReason, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilContactRevocationReason) Or(d ContactRevocationReason) ContactRevocationReason { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilContactTelegramUsername returns new NilContactTelegramUsername with value set to v. +func NewNilContactTelegramUsername(v ContactTelegramUsername) NilContactTelegramUsername { + return NilContactTelegramUsername{ + Value: v, + } +} + +// NilContactTelegramUsername is nullable ContactTelegramUsername. +type NilContactTelegramUsername struct { + Value ContactTelegramUsername + Null bool +} + +// SetTo sets value to v. +func (o *NilContactTelegramUsername) SetTo(v ContactTelegramUsername) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilContactTelegramUsername) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilContactTelegramUsername) SetToNull() { + o.Null = true + var v ContactTelegramUsername + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilContactTelegramUsername) Get() (v ContactTelegramUsername, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilContactTelegramUsername) Or(d ContactTelegramUsername) ContactTelegramUsername { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilEmailAddress returns new NilEmailAddress with value set to v. +func NewNilEmailAddress(v EmailAddress) NilEmailAddress { + return NilEmailAddress{ + Value: v, + } +} + +// NilEmailAddress is nullable EmailAddress. +type NilEmailAddress struct { + Value EmailAddress + Null bool +} + +// SetTo sets value to v. +func (o *NilEmailAddress) SetTo(v EmailAddress) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilEmailAddress) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilEmailAddress) SetToNull() { + o.Null = true + var v EmailAddress + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilEmailAddress) Get() (v EmailAddress, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilEmailAddress) Or(d EmailAddress) EmailAddress { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilFloat64 returns new NilFloat64 with value set to v. func NewNilFloat64(v float64) NilFloat64 { return NilFloat64{ @@ -6722,6 +9600,231 @@ func (o NilInt32) Or(d int32) int32 { return d } +// NewNilInvitationCommunicationNote returns new NilInvitationCommunicationNote with value set to v. +func NewNilInvitationCommunicationNote(v InvitationCommunicationNote) NilInvitationCommunicationNote { + return NilInvitationCommunicationNote{ + Value: v, + } +} + +// NilInvitationCommunicationNote is nullable InvitationCommunicationNote. +type NilInvitationCommunicationNote struct { + Value InvitationCommunicationNote + Null bool +} + +// SetTo sets value to v. +func (o *NilInvitationCommunicationNote) SetTo(v InvitationCommunicationNote) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilInvitationCommunicationNote) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilInvitationCommunicationNote) SetToNull() { + o.Null = true + var v InvitationCommunicationNote + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilInvitationCommunicationNote) Get() (v InvitationCommunicationNote, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilInvitationCommunicationNote) Or(d InvitationCommunicationNote) InvitationCommunicationNote { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilInvitationDeclineComment returns new NilInvitationDeclineComment with value set to v. +func NewNilInvitationDeclineComment(v InvitationDeclineComment) NilInvitationDeclineComment { + return NilInvitationDeclineComment{ + Value: v, + } +} + +// NilInvitationDeclineComment is nullable InvitationDeclineComment. +type NilInvitationDeclineComment struct { + Value InvitationDeclineComment + Null bool +} + +// SetTo sets value to v. +func (o *NilInvitationDeclineComment) SetTo(v InvitationDeclineComment) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilInvitationDeclineComment) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilInvitationDeclineComment) SetToNull() { + o.Null = true + var v InvitationDeclineComment + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilInvitationDeclineComment) Get() (v InvitationDeclineComment, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilInvitationDeclineComment) Or(d InvitationDeclineComment) InvitationDeclineComment { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilInvitationDeclineRecord returns new NilInvitationDeclineRecord with value set to v. +func NewNilInvitationDeclineRecord(v InvitationDeclineRecord) NilInvitationDeclineRecord { + return NilInvitationDeclineRecord{ + Value: v, + } +} + +// NilInvitationDeclineRecord is nullable InvitationDeclineRecord. +type NilInvitationDeclineRecord struct { + Value InvitationDeclineRecord + Null bool +} + +// SetTo sets value to v. +func (o *NilInvitationDeclineRecord) SetTo(v InvitationDeclineRecord) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilInvitationDeclineRecord) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilInvitationDeclineRecord) SetToNull() { + o.Null = true + var v InvitationDeclineRecord + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilInvitationDeclineRecord) Get() (v InvitationDeclineRecord, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilInvitationDeclineRecord) Or(d InvitationDeclineRecord) InvitationDeclineRecord { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilInvitationExpiryReason returns new NilInvitationExpiryReason with value set to v. +func NewNilInvitationExpiryReason(v InvitationExpiryReason) NilInvitationExpiryReason { + return NilInvitationExpiryReason{ + Value: v, + } +} + +// NilInvitationExpiryReason is nullable InvitationExpiryReason. +type NilInvitationExpiryReason struct { + Value InvitationExpiryReason + Null bool +} + +// SetTo sets value to v. +func (o *NilInvitationExpiryReason) SetTo(v InvitationExpiryReason) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilInvitationExpiryReason) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilInvitationExpiryReason) SetToNull() { + o.Null = true + var v InvitationExpiryReason + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilInvitationExpiryReason) Get() (v InvitationExpiryReason, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilInvitationExpiryReason) Or(d InvitationExpiryReason) InvitationExpiryReason { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilInvitationNeedReference returns new NilInvitationNeedReference with value set to v. +func NewNilInvitationNeedReference(v InvitationNeedReference) NilInvitationNeedReference { + return NilInvitationNeedReference{ + Value: v, + } +} + +// NilInvitationNeedReference is nullable InvitationNeedReference. +type NilInvitationNeedReference struct { + Value InvitationNeedReference + Null bool +} + +// SetTo sets value to v. +func (o *NilInvitationNeedReference) SetTo(v InvitationNeedReference) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilInvitationNeedReference) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilInvitationNeedReference) SetToNull() { + o.Null = true + var v InvitationNeedReference + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilInvitationNeedReference) Get() (v InvitationNeedReference, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilInvitationNeedReference) Or(d InvitationNeedReference) InvitationNeedReference { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilNeedDomainName returns new NilNeedDomainName with value set to v. func NewNilNeedDomainName(v NeedDomainName) NilNeedDomainName { return NilNeedDomainName{ @@ -8057,6 +11160,98 @@ func (o OptInt32) Or(d int32) int32 { return d } +// NewOptInvitationResponsePeriod returns new OptInvitationResponsePeriod with value set to v. +func NewOptInvitationResponsePeriod(v InvitationResponsePeriod) OptInvitationResponsePeriod { + return OptInvitationResponsePeriod{ + Value: v, + Set: true, + } +} + +// OptInvitationResponsePeriod is optional InvitationResponsePeriod. +type OptInvitationResponsePeriod struct { + Value InvitationResponsePeriod + Set bool +} + +// IsSet returns true if OptInvitationResponsePeriod was set. +func (o OptInvitationResponsePeriod) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptInvitationResponsePeriod) Reset() { + var v InvitationResponsePeriod + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptInvitationResponsePeriod) SetTo(v InvitationResponsePeriod) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptInvitationResponsePeriod) Get() (v InvitationResponsePeriod, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptInvitationResponsePeriod) Or(d InvitationResponsePeriod) InvitationResponsePeriod { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptInvitationTerms returns new OptInvitationTerms with value set to v. +func NewOptInvitationTerms(v InvitationTerms) OptInvitationTerms { + return OptInvitationTerms{ + Value: v, + Set: true, + } +} + +// OptInvitationTerms is optional InvitationTerms. +type OptInvitationTerms struct { + Value InvitationTerms + Set bool +} + +// IsSet returns true if OptInvitationTerms was set. +func (o OptInvitationTerms) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptInvitationTerms) Reset() { + var v InvitationTerms + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptInvitationTerms) SetTo(v InvitationTerms) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptInvitationTerms) Get() (v InvitationTerms, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptInvitationTerms) Or(d InvitationTerms) InvitationTerms { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewOptNeedTitle returns new OptNeedTitle with value set to v. func NewOptNeedTitle(v NeedTitle) OptNeedTitle { return OptNeedTitle{ @@ -8103,6 +11298,142 @@ func (o OptNeedTitle) Or(d NeedTitle) NeedTitle { return d } +// NewOptNilInvitationDeclineComment returns new OptNilInvitationDeclineComment with value set to v. +func NewOptNilInvitationDeclineComment(v InvitationDeclineComment) OptNilInvitationDeclineComment { + return OptNilInvitationDeclineComment{ + Value: v, + Set: true, + } +} + +// OptNilInvitationDeclineComment is optional nullable InvitationDeclineComment. +type OptNilInvitationDeclineComment struct { + Value InvitationDeclineComment + Set bool + Null bool +} + +// IsSet returns true if OptNilInvitationDeclineComment was set. +func (o OptNilInvitationDeclineComment) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptNilInvitationDeclineComment) Reset() { + var v InvitationDeclineComment + o.Value = v + o.Set = false + o.Null = false +} + +// SetTo sets value to v. +func (o *OptNilInvitationDeclineComment) SetTo(v InvitationDeclineComment) { + o.Set = true + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o OptNilInvitationDeclineComment) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *OptNilInvitationDeclineComment) SetToNull() { + o.Set = true + o.Null = true + var v InvitationDeclineComment + o.Value = v +} + +// IsEmpty returns true if the field was omitted from the payload (not Set and not Null). +func (o OptNilInvitationDeclineComment) IsEmpty() bool { + return !o.Set && !o.Null +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptNilInvitationDeclineComment) Get() (v InvitationDeclineComment, ok bool) { + if o.Null { + return v, false + } + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptNilInvitationDeclineComment) Or(d InvitationDeclineComment) InvitationDeclineComment { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptNilInvitationNeedReference returns new OptNilInvitationNeedReference with value set to v. +func NewOptNilInvitationNeedReference(v InvitationNeedReference) OptNilInvitationNeedReference { + return OptNilInvitationNeedReference{ + Value: v, + Set: true, + } +} + +// OptNilInvitationNeedReference is optional nullable InvitationNeedReference. +type OptNilInvitationNeedReference struct { + Value InvitationNeedReference + Set bool + Null bool +} + +// IsSet returns true if OptNilInvitationNeedReference was set. +func (o OptNilInvitationNeedReference) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptNilInvitationNeedReference) Reset() { + var v InvitationNeedReference + o.Value = v + o.Set = false + o.Null = false +} + +// SetTo sets value to v. +func (o *OptNilInvitationNeedReference) SetTo(v InvitationNeedReference) { + o.Set = true + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o OptNilInvitationNeedReference) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *OptNilInvitationNeedReference) SetToNull() { + o.Set = true + o.Null = true + var v InvitationNeedReference + o.Value = v +} + +// IsEmpty returns true if the field was omitted from the payload (not Set and not Null). +func (o OptNilInvitationNeedReference) IsEmpty() bool { + return !o.Set && !o.Null +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptNilInvitationNeedReference) Get() (v InvitationNeedReference, ok bool) { + if o.Null { + return v, false + } + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptNilInvitationNeedReference) Or(d InvitationNeedReference) InvitationNeedReference { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewOptNilNeedDomainInput returns new OptNilNeedDomainInput with value set to v. func NewOptNilNeedDomainInput(v NeedDomainInput) OptNilNeedDomainInput { return OptNilNeedDomainInput{ @@ -8955,6 +12286,581 @@ func (s *OrderItemContentFormat) UnmarshalText(data []byte) error { } } +// 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. +// Ref: #/components/schemas/OrganizationInvitation +type OrganizationInvitation struct { + // Identifier of the invitation. + ID uuid.UUID `json:"id"` + // Organization that owns the invitation, equal to `org_id` of the path. It never changes. + OrganizationID uuid.UUID `json:"organization_id"` + CandidateHandle CandidateHandle `json:"candidate_handle"` + // Need the invitation was built from, or null for a direct invitation. + Need NilInvitationNeedReference `json:"need"` + State InvitationState `json:"state"` + // Reason of an expiry, or null unless `state` is `expired`. + ExpiryReason NilInvitationExpiryReason `json:"expiry_reason"` + Version InvitationVersion `json:"version"` + TermsVersion InvitationTermsVersion `json:"terms_version"` + Terms InvitationTerms `json:"terms"` + ResponsePeriodDays InvitationResponsePeriod `json:"response_period_days"` + // 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. + ResponseDeadlineAt NilTimestamp `json:"response_deadline_at"` + // Whether the one raise of the upper salary bound after sending (PRD FR13) has been used. It counts + // the whole history of the invitation. + SalaryRaiseUsed bool `json:"salary_raise_used"` + SalaryFit InvitationSalaryFit `json:"salary_fit"` + ContactAccess InvitationContactAccess `json:"contact_access"` + CreatedAt Timestamp `json:"created_at"` + UpdatedAt Timestamp `json:"updated_at"` + // Moment of delivery to the candidate's inbox, or null for a draft. + DeliveredAt NilTimestamp `json:"delivered_at"` + // Moment when the candidate first opened the terms, or null. + ViewedAt NilTimestamp `json:"viewed_at"` + // Moment of the candidate's acceptance or decline, or null. + RespondedAt NilTimestamp `json:"responded_at"` +} + +// GetID returns the value of ID. +func (s *OrganizationInvitation) GetID() uuid.UUID { + return s.ID +} + +// GetOrganizationID returns the value of OrganizationID. +func (s *OrganizationInvitation) GetOrganizationID() uuid.UUID { + return s.OrganizationID +} + +// GetCandidateHandle returns the value of CandidateHandle. +func (s *OrganizationInvitation) GetCandidateHandle() CandidateHandle { + return s.CandidateHandle +} + +// GetNeed returns the value of Need. +func (s *OrganizationInvitation) GetNeed() NilInvitationNeedReference { + return s.Need +} + +// GetState returns the value of State. +func (s *OrganizationInvitation) GetState() InvitationState { + return s.State +} + +// GetExpiryReason returns the value of ExpiryReason. +func (s *OrganizationInvitation) GetExpiryReason() NilInvitationExpiryReason { + return s.ExpiryReason +} + +// GetVersion returns the value of Version. +func (s *OrganizationInvitation) GetVersion() InvitationVersion { + return s.Version +} + +// GetTermsVersion returns the value of TermsVersion. +func (s *OrganizationInvitation) GetTermsVersion() InvitationTermsVersion { + return s.TermsVersion +} + +// GetTerms returns the value of Terms. +func (s *OrganizationInvitation) GetTerms() InvitationTerms { + return s.Terms +} + +// GetResponsePeriodDays returns the value of ResponsePeriodDays. +func (s *OrganizationInvitation) GetResponsePeriodDays() InvitationResponsePeriod { + return s.ResponsePeriodDays +} + +// GetResponseDeadlineAt returns the value of ResponseDeadlineAt. +func (s *OrganizationInvitation) GetResponseDeadlineAt() NilTimestamp { + return s.ResponseDeadlineAt +} + +// GetSalaryRaiseUsed returns the value of SalaryRaiseUsed. +func (s *OrganizationInvitation) GetSalaryRaiseUsed() bool { + return s.SalaryRaiseUsed +} + +// GetSalaryFit returns the value of SalaryFit. +func (s *OrganizationInvitation) GetSalaryFit() InvitationSalaryFit { + return s.SalaryFit +} + +// GetContactAccess returns the value of ContactAccess. +func (s *OrganizationInvitation) GetContactAccess() InvitationContactAccess { + return s.ContactAccess +} + +// GetCreatedAt returns the value of CreatedAt. +func (s *OrganizationInvitation) GetCreatedAt() Timestamp { + return s.CreatedAt +} + +// GetUpdatedAt returns the value of UpdatedAt. +func (s *OrganizationInvitation) GetUpdatedAt() Timestamp { + return s.UpdatedAt +} + +// GetDeliveredAt returns the value of DeliveredAt. +func (s *OrganizationInvitation) GetDeliveredAt() NilTimestamp { + return s.DeliveredAt +} + +// GetViewedAt returns the value of ViewedAt. +func (s *OrganizationInvitation) GetViewedAt() NilTimestamp { + return s.ViewedAt +} + +// GetRespondedAt returns the value of RespondedAt. +func (s *OrganizationInvitation) GetRespondedAt() NilTimestamp { + return s.RespondedAt +} + +// SetID sets the value of ID. +func (s *OrganizationInvitation) SetID(val uuid.UUID) { + s.ID = val +} + +// SetOrganizationID sets the value of OrganizationID. +func (s *OrganizationInvitation) SetOrganizationID(val uuid.UUID) { + s.OrganizationID = val +} + +// SetCandidateHandle sets the value of CandidateHandle. +func (s *OrganizationInvitation) SetCandidateHandle(val CandidateHandle) { + s.CandidateHandle = val +} + +// SetNeed sets the value of Need. +func (s *OrganizationInvitation) SetNeed(val NilInvitationNeedReference) { + s.Need = val +} + +// SetState sets the value of State. +func (s *OrganizationInvitation) SetState(val InvitationState) { + s.State = val +} + +// SetExpiryReason sets the value of ExpiryReason. +func (s *OrganizationInvitation) SetExpiryReason(val NilInvitationExpiryReason) { + s.ExpiryReason = val +} + +// SetVersion sets the value of Version. +func (s *OrganizationInvitation) SetVersion(val InvitationVersion) { + s.Version = val +} + +// SetTermsVersion sets the value of TermsVersion. +func (s *OrganizationInvitation) SetTermsVersion(val InvitationTermsVersion) { + s.TermsVersion = val +} + +// SetTerms sets the value of Terms. +func (s *OrganizationInvitation) SetTerms(val InvitationTerms) { + s.Terms = val +} + +// SetResponsePeriodDays sets the value of ResponsePeriodDays. +func (s *OrganizationInvitation) SetResponsePeriodDays(val InvitationResponsePeriod) { + s.ResponsePeriodDays = val +} + +// SetResponseDeadlineAt sets the value of ResponseDeadlineAt. +func (s *OrganizationInvitation) SetResponseDeadlineAt(val NilTimestamp) { + s.ResponseDeadlineAt = val +} + +// SetSalaryRaiseUsed sets the value of SalaryRaiseUsed. +func (s *OrganizationInvitation) SetSalaryRaiseUsed(val bool) { + s.SalaryRaiseUsed = val +} + +// SetSalaryFit sets the value of SalaryFit. +func (s *OrganizationInvitation) SetSalaryFit(val InvitationSalaryFit) { + s.SalaryFit = val +} + +// SetContactAccess sets the value of ContactAccess. +func (s *OrganizationInvitation) SetContactAccess(val InvitationContactAccess) { + s.ContactAccess = val +} + +// SetCreatedAt sets the value of CreatedAt. +func (s *OrganizationInvitation) SetCreatedAt(val Timestamp) { + s.CreatedAt = val +} + +// SetUpdatedAt sets the value of UpdatedAt. +func (s *OrganizationInvitation) SetUpdatedAt(val Timestamp) { + s.UpdatedAt = val +} + +// SetDeliveredAt sets the value of DeliveredAt. +func (s *OrganizationInvitation) SetDeliveredAt(val NilTimestamp) { + s.DeliveredAt = val +} + +// SetViewedAt sets the value of ViewedAt. +func (s *OrganizationInvitation) SetViewedAt(val NilTimestamp) { + s.ViewedAt = val +} + +// SetRespondedAt sets the value of RespondedAt. +func (s *OrganizationInvitation) SetRespondedAt(val NilTimestamp) { + s.RespondedAt = val +} + +// 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. +// Ref: #/components/schemas/OrganizationInvitationCreate +type OrganizationInvitationCreate struct { + CandidateHandle CandidateHandle `json:"candidate_handle"` + // Need of the organization the invitation is built from, or null or absent for a direct invitation. + Need OptNilInvitationNeedReference `json:"need"` + // Days to answer; absent means 7, the default of the product policy. + ResponsePeriodDays OptInvitationResponsePeriod `json:"response_period_days"` + Terms InvitationTerms `json:"terms"` +} + +// GetCandidateHandle returns the value of CandidateHandle. +func (s *OrganizationInvitationCreate) GetCandidateHandle() CandidateHandle { + return s.CandidateHandle +} + +// GetNeed returns the value of Need. +func (s *OrganizationInvitationCreate) GetNeed() OptNilInvitationNeedReference { + return s.Need +} + +// GetResponsePeriodDays returns the value of ResponsePeriodDays. +func (s *OrganizationInvitationCreate) GetResponsePeriodDays() OptInvitationResponsePeriod { + return s.ResponsePeriodDays +} + +// GetTerms returns the value of Terms. +func (s *OrganizationInvitationCreate) GetTerms() InvitationTerms { + return s.Terms +} + +// SetCandidateHandle sets the value of CandidateHandle. +func (s *OrganizationInvitationCreate) SetCandidateHandle(val CandidateHandle) { + s.CandidateHandle = val +} + +// SetNeed sets the value of Need. +func (s *OrganizationInvitationCreate) SetNeed(val OptNilInvitationNeedReference) { + s.Need = val +} + +// SetResponsePeriodDays sets the value of ResponsePeriodDays. +func (s *OrganizationInvitationCreate) SetResponsePeriodDays(val OptInvitationResponsePeriod) { + s.ResponsePeriodDays = val +} + +// SetTerms sets the value of Terms. +func (s *OrganizationInvitationCreate) SetTerms(val InvitationTerms) { + s.Terms = val +} + +// OrganizationInvitationHeaders wraps OrganizationInvitation with response headers. +type OrganizationInvitationHeaders struct { + CacheControl CacheControlNoStore + Response OrganizationInvitation +} + +// GetCacheControl returns the value of CacheControl. +func (s *OrganizationInvitationHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *OrganizationInvitationHeaders) GetResponse() OrganizationInvitation { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *OrganizationInvitationHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *OrganizationInvitationHeaders) SetResponse(val OrganizationInvitation) { + s.Response = val +} + +func (*OrganizationInvitationHeaders) createOrganizationInvitationRes() {} +func (*OrganizationInvitationHeaders) getOrganizationInvitationRes() {} +func (*OrganizationInvitationHeaders) raiseOrganizationInvitationSalaryRes() {} +func (*OrganizationInvitationHeaders) sendOrganizationInvitationRes() {} +func (*OrganizationInvitationHeaders) updateOrganizationInvitationRes() {} +func (*OrganizationInvitationHeaders) withdrawOrganizationInvitationRes() {} + +// One page of the invitations of an organization, newest first by creation time. +// Ref: #/components/schemas/OrganizationInvitationList +type OrganizationInvitationList struct { + // Invitations of the page. + Items []OrganizationInvitationSummary `json:"items"` + Page PageInfo `json:"page"` +} + +// GetItems returns the value of Items. +func (s *OrganizationInvitationList) GetItems() []OrganizationInvitationSummary { + return s.Items +} + +// GetPage returns the value of Page. +func (s *OrganizationInvitationList) GetPage() PageInfo { + return s.Page +} + +// SetItems sets the value of Items. +func (s *OrganizationInvitationList) SetItems(val []OrganizationInvitationSummary) { + s.Items = val +} + +// SetPage sets the value of Page. +func (s *OrganizationInvitationList) SetPage(val PageInfo) { + s.Page = val +} + +// OrganizationInvitationListHeaders wraps OrganizationInvitationList with response headers. +type OrganizationInvitationListHeaders struct { + CacheControl CacheControlNoStore + Response OrganizationInvitationList +} + +// GetCacheControl returns the value of CacheControl. +func (s *OrganizationInvitationListHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *OrganizationInvitationListHeaders) GetResponse() OrganizationInvitationList { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *OrganizationInvitationListHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *OrganizationInvitationListHeaders) SetResponse(val OrganizationInvitationList) { + s.Response = val +} + +func (*OrganizationInvitationListHeaders) listOrganizationInvitationsRes() {} + +// 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. +// Ref: #/components/schemas/OrganizationInvitationSummary +type OrganizationInvitationSummary struct { + // Identifier of the invitation. + ID uuid.UUID `json:"id"` + CandidateHandle CandidateHandle `json:"candidate_handle"` + Need NilInvitationNeedReference `json:"need"` + State InvitationState `json:"state"` + ExpiryReason NilInvitationExpiryReason `json:"expiry_reason"` + Version InvitationVersion `json:"version"` + TermsVersion InvitationTermsVersion `json:"terms_version"` + RoleTitle InvitationRoleTitle `json:"role_title"` + Salary SalaryRange `json:"salary"` + ResponseDeadlineAt NilTimestamp `json:"response_deadline_at"` + ContactAccess InvitationContactAccess `json:"contact_access"` + CreatedAt Timestamp `json:"created_at"` + UpdatedAt Timestamp `json:"updated_at"` +} + +// GetID returns the value of ID. +func (s *OrganizationInvitationSummary) GetID() uuid.UUID { + return s.ID +} + +// GetCandidateHandle returns the value of CandidateHandle. +func (s *OrganizationInvitationSummary) GetCandidateHandle() CandidateHandle { + return s.CandidateHandle +} + +// GetNeed returns the value of Need. +func (s *OrganizationInvitationSummary) GetNeed() NilInvitationNeedReference { + return s.Need +} + +// GetState returns the value of State. +func (s *OrganizationInvitationSummary) GetState() InvitationState { + return s.State +} + +// GetExpiryReason returns the value of ExpiryReason. +func (s *OrganizationInvitationSummary) GetExpiryReason() NilInvitationExpiryReason { + return s.ExpiryReason +} + +// GetVersion returns the value of Version. +func (s *OrganizationInvitationSummary) GetVersion() InvitationVersion { + return s.Version +} + +// GetTermsVersion returns the value of TermsVersion. +func (s *OrganizationInvitationSummary) GetTermsVersion() InvitationTermsVersion { + return s.TermsVersion +} + +// GetRoleTitle returns the value of RoleTitle. +func (s *OrganizationInvitationSummary) GetRoleTitle() InvitationRoleTitle { + return s.RoleTitle +} + +// GetSalary returns the value of Salary. +func (s *OrganizationInvitationSummary) GetSalary() SalaryRange { + return s.Salary +} + +// GetResponseDeadlineAt returns the value of ResponseDeadlineAt. +func (s *OrganizationInvitationSummary) GetResponseDeadlineAt() NilTimestamp { + return s.ResponseDeadlineAt +} + +// GetContactAccess returns the value of ContactAccess. +func (s *OrganizationInvitationSummary) GetContactAccess() InvitationContactAccess { + return s.ContactAccess +} + +// GetCreatedAt returns the value of CreatedAt. +func (s *OrganizationInvitationSummary) GetCreatedAt() Timestamp { + return s.CreatedAt +} + +// GetUpdatedAt returns the value of UpdatedAt. +func (s *OrganizationInvitationSummary) GetUpdatedAt() Timestamp { + return s.UpdatedAt +} + +// SetID sets the value of ID. +func (s *OrganizationInvitationSummary) SetID(val uuid.UUID) { + s.ID = val +} + +// SetCandidateHandle sets the value of CandidateHandle. +func (s *OrganizationInvitationSummary) SetCandidateHandle(val CandidateHandle) { + s.CandidateHandle = val +} + +// SetNeed sets the value of Need. +func (s *OrganizationInvitationSummary) SetNeed(val NilInvitationNeedReference) { + s.Need = val +} + +// SetState sets the value of State. +func (s *OrganizationInvitationSummary) SetState(val InvitationState) { + s.State = val +} + +// SetExpiryReason sets the value of ExpiryReason. +func (s *OrganizationInvitationSummary) SetExpiryReason(val NilInvitationExpiryReason) { + s.ExpiryReason = val +} + +// SetVersion sets the value of Version. +func (s *OrganizationInvitationSummary) SetVersion(val InvitationVersion) { + s.Version = val +} + +// SetTermsVersion sets the value of TermsVersion. +func (s *OrganizationInvitationSummary) SetTermsVersion(val InvitationTermsVersion) { + s.TermsVersion = val +} + +// SetRoleTitle sets the value of RoleTitle. +func (s *OrganizationInvitationSummary) SetRoleTitle(val InvitationRoleTitle) { + s.RoleTitle = val +} + +// SetSalary sets the value of Salary. +func (s *OrganizationInvitationSummary) SetSalary(val SalaryRange) { + s.Salary = val +} + +// SetResponseDeadlineAt sets the value of ResponseDeadlineAt. +func (s *OrganizationInvitationSummary) SetResponseDeadlineAt(val NilTimestamp) { + s.ResponseDeadlineAt = val +} + +// SetContactAccess sets the value of ContactAccess. +func (s *OrganizationInvitationSummary) SetContactAccess(val InvitationContactAccess) { + s.ContactAccess = val +} + +// SetCreatedAt sets the value of CreatedAt. +func (s *OrganizationInvitationSummary) SetCreatedAt(val Timestamp) { + s.CreatedAt = val +} + +// SetUpdatedAt sets the value of UpdatedAt. +func (s *OrganizationInvitationSummary) SetUpdatedAt(val Timestamp) { + s.UpdatedAt = val +} + +// 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. +// Ref: #/components/schemas/OrganizationInvitationUpdate +type OrganizationInvitationUpdate struct { + ExpectedVersion InvitationVersion `json:"expected_version"` + Need OptNilInvitationNeedReference `json:"need"` + ResponsePeriodDays OptInvitationResponsePeriod `json:"response_period_days"` + Terms OptInvitationTerms `json:"terms"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *OrganizationInvitationUpdate) GetExpectedVersion() InvitationVersion { + return s.ExpectedVersion +} + +// GetNeed returns the value of Need. +func (s *OrganizationInvitationUpdate) GetNeed() OptNilInvitationNeedReference { + return s.Need +} + +// GetResponsePeriodDays returns the value of ResponsePeriodDays. +func (s *OrganizationInvitationUpdate) GetResponsePeriodDays() OptInvitationResponsePeriod { + return s.ResponsePeriodDays +} + +// GetTerms returns the value of Terms. +func (s *OrganizationInvitationUpdate) GetTerms() OptInvitationTerms { + return s.Terms +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *OrganizationInvitationUpdate) SetExpectedVersion(val InvitationVersion) { + s.ExpectedVersion = val +} + +// SetNeed sets the value of Need. +func (s *OrganizationInvitationUpdate) SetNeed(val OptNilInvitationNeedReference) { + s.Need = val +} + +// SetResponsePeriodDays sets the value of ResponsePeriodDays. +func (s *OrganizationInvitationUpdate) SetResponsePeriodDays(val OptInvitationResponsePeriod) { + s.ResponsePeriodDays = val +} + +// SetTerms sets the value of Terms. +func (s *OrganizationInvitationUpdate) SetTerms(val OptInvitationTerms) { + s.Terms = val +} + // 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`. // Ref: #/components/schemas/PageInfo @@ -10008,6 +13914,34 @@ func (s *QuestionnaireSpecialization) SetExperience(val NilCandidateExperience) type QuestionnaireVersion int64 +type RaiseOrganizationInvitationSalaryBadRequest Problem + +func (*RaiseOrganizationInvitationSalaryBadRequest) raiseOrganizationInvitationSalaryRes() {} + +type RaiseOrganizationInvitationSalaryConflict Problem + +func (*RaiseOrganizationInvitationSalaryConflict) raiseOrganizationInvitationSalaryRes() {} + +type RaiseOrganizationInvitationSalaryForbidden Problem + +func (*RaiseOrganizationInvitationSalaryForbidden) raiseOrganizationInvitationSalaryRes() {} + +type RaiseOrganizationInvitationSalaryNotFound Problem + +func (*RaiseOrganizationInvitationSalaryNotFound) raiseOrganizationInvitationSalaryRes() {} + +type RaiseOrganizationInvitationSalaryPreconditionFailed Problem + +func (*RaiseOrganizationInvitationSalaryPreconditionFailed) raiseOrganizationInvitationSalaryRes() {} + +type RaiseOrganizationInvitationSalaryUnauthorized Problem + +func (*RaiseOrganizationInvitationSalaryUnauthorized) raiseOrganizationInvitationSalaryRes() {} + +type RaiseOrganizationInvitationSalaryUnprocessableEntity Problem + +func (*RaiseOrganizationInvitationSalaryUnprocessableEntity) raiseOrganizationInvitationSalaryRes() {} + type RegisterAccountBadRequest Problem func (*RegisterAccountBadRequest) registerAccountRes() {} @@ -10247,6 +14181,34 @@ type SaveMyQuestionnaireUnauthorized Problem func (*SaveMyQuestionnaireUnauthorized) saveMyQuestionnaireRes() {} +type SendOrganizationInvitationBadRequest Problem + +func (*SendOrganizationInvitationBadRequest) sendOrganizationInvitationRes() {} + +type SendOrganizationInvitationConflict Problem + +func (*SendOrganizationInvitationConflict) sendOrganizationInvitationRes() {} + +type SendOrganizationInvitationForbidden Problem + +func (*SendOrganizationInvitationForbidden) sendOrganizationInvitationRes() {} + +type SendOrganizationInvitationNotFound Problem + +func (*SendOrganizationInvitationNotFound) sendOrganizationInvitationRes() {} + +type SendOrganizationInvitationPreconditionFailed Problem + +func (*SendOrganizationInvitationPreconditionFailed) sendOrganizationInvitationRes() {} + +type SendOrganizationInvitationUnauthorized Problem + +func (*SendOrganizationInvitationUnauthorized) sendOrganizationInvitationRes() {} + +type SendOrganizationInvitationUnprocessableEntity Problem + +func (*SendOrganizationInvitationUnprocessableEntity) sendOrganizationInvitationRes() {} + // Current session as the client may see it: the account and the CSRF token. The session identifier // itself travels only in the HttpOnly session cookie and never appears in a body. // Ref: #/components/schemas/Session @@ -12136,8 +16098,8 @@ func (s *SupportCaseObjectReference) SetID(val uuid.UUID) { // // - 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. // @@ -12781,15 +16743,48 @@ func (s *TooManyRequestsHeaders) SetResponse(val Problem) { s.Response = val } -func (*TooManyRequestsHeaders) confirmEmailRes() {} -func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {} -func (*TooManyRequestsHeaders) createMySupportCaseRes() {} -func (*TooManyRequestsHeaders) createOrganizationNeedRes() {} -func (*TooManyRequestsHeaders) loginRes() {} -func (*TooManyRequestsHeaders) registerAccountRes() {} -func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} -func (*TooManyRequestsHeaders) submitMyAssessmentAnswerRes() {} -func (*TooManyRequestsHeaders) updateOrganizationNeedRes() {} +func (*TooManyRequestsHeaders) acceptMyInvitationRes() {} +func (*TooManyRequestsHeaders) cancelMyInvitationRes() {} +func (*TooManyRequestsHeaders) confirmEmailRes() {} +func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {} +func (*TooManyRequestsHeaders) createMySupportCaseRes() {} +func (*TooManyRequestsHeaders) createOrganizationInvitationRes() {} +func (*TooManyRequestsHeaders) createOrganizationNeedRes() {} +func (*TooManyRequestsHeaders) declineMyInvitationRes() {} +func (*TooManyRequestsHeaders) loginRes() {} +func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {} +func (*TooManyRequestsHeaders) registerAccountRes() {} +func (*TooManyRequestsHeaders) resendEmailVerificationRes() {} +func (*TooManyRequestsHeaders) sendOrganizationInvitationRes() {} +func (*TooManyRequestsHeaders) submitMyAssessmentAnswerRes() {} +func (*TooManyRequestsHeaders) updateOrganizationInvitationRes() {} +func (*TooManyRequestsHeaders) updateOrganizationNeedRes() {} +func (*TooManyRequestsHeaders) viewMyInvitationRes() {} +func (*TooManyRequestsHeaders) withdrawOrganizationInvitationRes() {} + +type UpdateOrganizationInvitationBadRequest Problem + +func (*UpdateOrganizationInvitationBadRequest) updateOrganizationInvitationRes() {} + +type UpdateOrganizationInvitationConflict Problem + +func (*UpdateOrganizationInvitationConflict) updateOrganizationInvitationRes() {} + +type UpdateOrganizationInvitationForbidden Problem + +func (*UpdateOrganizationInvitationForbidden) updateOrganizationInvitationRes() {} + +type UpdateOrganizationInvitationNotFound Problem + +func (*UpdateOrganizationInvitationNotFound) updateOrganizationInvitationRes() {} + +type UpdateOrganizationInvitationPreconditionFailed Problem + +func (*UpdateOrganizationInvitationPreconditionFailed) updateOrganizationInvitationRes() {} + +type UpdateOrganizationInvitationUnauthorized Problem + +func (*UpdateOrganizationInvitationUnauthorized) updateOrganizationInvitationRes() {} type UpdateOrganizationNeedBadRequest Problem @@ -12813,6 +16808,50 @@ func (*UpdateOrganizationNeedUnauthorized) updateOrganizationNeedRes() {} type VerificationToken string +type ViewMyInvitationBadRequest Problem + +func (*ViewMyInvitationBadRequest) viewMyInvitationRes() {} + +type ViewMyInvitationForbidden Problem + +func (*ViewMyInvitationForbidden) viewMyInvitationRes() {} + +type ViewMyInvitationNotFound Problem + +func (*ViewMyInvitationNotFound) viewMyInvitationRes() {} + +type ViewMyInvitationUnauthorized Problem + +func (*ViewMyInvitationUnauthorized) viewMyInvitationRes() {} + +type WithdrawOrganizationInvitationBadRequest Problem + +func (*WithdrawOrganizationInvitationBadRequest) withdrawOrganizationInvitationRes() {} + +type WithdrawOrganizationInvitationConflict Problem + +func (*WithdrawOrganizationInvitationConflict) withdrawOrganizationInvitationRes() {} + +type WithdrawOrganizationInvitationForbidden Problem + +func (*WithdrawOrganizationInvitationForbidden) withdrawOrganizationInvitationRes() {} + +type WithdrawOrganizationInvitationNotFound Problem + +func (*WithdrawOrganizationInvitationNotFound) withdrawOrganizationInvitationRes() {} + +type WithdrawOrganizationInvitationPreconditionFailed Problem + +func (*WithdrawOrganizationInvitationPreconditionFailed) withdrawOrganizationInvitationRes() {} + +type WithdrawOrganizationInvitationUnauthorized Problem + +func (*WithdrawOrganizationInvitationUnauthorized) withdrawOrganizationInvitationRes() {} + +type WithdrawOrganizationInvitationUnprocessableEntity Problem + +func (*WithdrawOrganizationInvitationUnprocessableEntity) withdrawOrganizationInvitationRes() {} + // Working context of the candidate's search. It holds no personal data such as an address or a city; // location, relocation, and salary expectations belong to the candidate profile. // Ref: #/components/schemas/WorkContext diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index dc1029d..071d6f5 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -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. diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index 44009ab..d13d6d2 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -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. diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index c47019a..1f99eac 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -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. diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index c45842f..5d1d22b 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -9,6 +9,62 @@ import ( "github.com/ogen-go/ogen/validate" ) +func (s *AcceptMyInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *AcceptMyInvitationConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *AcceptMyInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *AcceptMyInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *AcceptMyInvitationPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *AcceptMyInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *AcceptMyInvitationUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *Account) Validate() error { if s == nil { return validate.ErrNilPointer @@ -2087,6 +2143,62 @@ func (s CalibrationStatus) Validate() error { } } +func (s *CancelMyInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CancelMyInvitationConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CancelMyInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CancelMyInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CancelMyInvitationPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CancelMyInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CancelMyInvitationUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *CandidateExperience) Validate() error { if s == nil { return validate.ErrNilPointer @@ -2141,6 +2253,427 @@ func (s *CandidateExperience) Validate() error { return nil } +func (s CandidateHandle) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *CandidateInvitation) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Organization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "organization", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ExpiryReason.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expiry_reason", + Error: err, + }) + } + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if err := s.TermsVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms_version", + Error: err, + }) + } + if err := func() error { + if err := s.Terms.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ContactConsent.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "contact_consent", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Decline.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "decline", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ContactGrant.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "contact_grant", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CandidateInvitationHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CandidateInvitationList) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Items == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Items)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Items { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "items", + Error: err, + }) + } + if err := func() error { + if err := s.Page.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "page", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CandidateInvitationListHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CandidateInvitationSummary) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Organization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "organization", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ExpiryReason.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expiry_reason", + Error: err, + }) + } + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if err := s.TermsVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms_version", + Error: err, + }) + } + if err := func() error { + if err := s.RoleTitle.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "role_title", + Error: err, + }) + } + if err := func() error { + if err := s.Salary.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "salary", + Error: err, + }) + } + if err := func() error { + if s.WorkFormats == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 3, + MaxLengthSet: true, + }).ValidateLength(len(s.WorkFormats)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.WorkFormats); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.WorkFormats { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "work_formats", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *CandidateQuestionnaire) Validate() error { if s == nil { return validate.ErrNilPointer @@ -2958,6 +3491,581 @@ func (s ConsentTextVersion) Validate() error { return nil } +func (s ContactAccessBlock) Validate() error { + switch s { + case "visibility": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ContactConsentAcceptance) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.TextVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text_version", + Error: err, + }) + } + if err := func() error { + if err := s.Accepted.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "accepted", + Error: err, + }) + } + if err := func() error { + if s.Fields == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.Fields)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Fields); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Fields { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "fields", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ContactConsentAcceptanceAccepted) Validate() error { + switch s { + case true: + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *ContactConsentOffer) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Text.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text", + Error: err, + }) + } + if err := func() error { + if s.AvailableFields == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.AvailableFields)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.AvailableFields); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.AvailableFields { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "available_fields", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ContactConsentText) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.TextVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text_version", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 100000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Text)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "text", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ContactDisclosure) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Fields == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.Fields)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Fields); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Fields { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "fields", + Error: err, + }) + } + if err := func() error { + if value, ok := s.FullName.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "full_name", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Email.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "email", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Phone.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "phone", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Telegram.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "telegram", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *ContactDisclosureHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ContactFieldKind) Validate() error { + switch s { + case "full_name": + return nil + case "email": + return nil + case "phone": + return nil + case "telegram": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s ContactFullName) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *ContactGrant) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Fields == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.Fields)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Fields); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Fields { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "fields", + Error: err, + }) + } + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.BlockedBy.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "blocked_by", + Error: err, + }) + } + if err := func() error { + if err := s.TermsVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms_version", + Error: err, + }) + } + if err := func() error { + if err := s.ConsentTextVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "consent_text_version", + Error: err, + }) + } + if err := func() error { + if value, ok := s.RevocationReason.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "revocation_reason", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s ContactGrantState) Validate() error { + switch s { + case "active": + return nil + case "revoked": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s ContactPhoneNumber) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 8, + MinLengthSet: true, + MaxLength: 16, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\+[1-9][0-9]{6,14}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s ContactRevocationReason) Validate() error { + switch s { + case "consent_revoked": + return nil + case "participation_cancelled": + return nil + case "visibility_closed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s ContactTelegramUsername) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 6, + MinLengthSet: true, + MaxLength: 33, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^@[A-Za-z0-9_]{5,32}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + func (s *CreateMyAssessmentAttemptBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -3046,6 +4154,54 @@ func (s *CreateMySupportCaseUnprocessableEntity) Validate() error { return nil } +func (s *CreateOrganizationInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateOrganizationInvitationConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateOrganizationInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateOrganizationInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateOrganizationInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateOrganizationInvitationUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *CreateOrganizationNeedBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -3123,6 +4279,62 @@ func (s CurrencyCode) Validate() error { } } +func (s *DeclineMyInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *DeclineMyInvitationConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *DeclineMyInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *DeclineMyInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *DeclineMyInvitationPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *DeclineMyInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *DeclineMyInvitationUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s DirectionCode) Validate() error { switch s { case "development": @@ -3622,6 +4834,38 @@ func (s *GetMyAssessmentResultUnauthorized) Validate() error { return nil } +func (s *GetMyInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetMyQuestionnaireForbidden) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -3662,6 +4906,70 @@ func (s *GetMySupportCaseUnauthorized) Validate() error { return nil } +func (s *GetOrganizationInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationInvitationContactsBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationInvitationContactsForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationInvitationContactsNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationInvitationContactsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetOrganizationInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetOrganizationNeedBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -3773,6 +5081,1022 @@ func (s IdentityRequestAcceptedStatus) Validate() error { } } +func (s *InvitationAcceptance) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if err := s.TermsVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms_version", + Error: err, + }) + } + if err := func() error { + if err := s.ConsentC4.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "consent_c4", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *InvitationCommand) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationCommunicationChannel) Validate() error { + switch s { + case "email": + return nil + case "phone": + return nil + case "telegram": + return nil + case "video_call": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *InvitationCommunicationMethod) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Channel.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "channel", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Details.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "details", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationCommunicationNote) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 300, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *InvitationContactAccess) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if s.Fields == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 4, + MaxLengthSet: true, + }).ValidateLength(len(s.Fields)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.Fields); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Fields { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "fields", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationContactAccessState) Validate() error { + switch s { + case "not_granted": + return nil + case "available": + return nil + case "closed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s InvitationDeclineComment) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 500, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["\\S"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s InvitationDeclineReason) Validate() error { + switch s { + case "salary": + return nil + case "tasks": + return nil + case "stack": + return nil + case "work_format": + return nil + case "package": + return nil + case "company": + return nil + case "not_looking": + return nil + case "other_offer": + return nil + case "other": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *InvitationDeclineRecord) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Reason.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "reason", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Comment.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "comment", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *InvitationDeclineRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if err := s.Reason.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "reason", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Comment.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "comment", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationExpiryReason) Validate() error { + switch s { + case "invitation_timeout": + return nil + case "negotiation_timeout": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *InvitationNeedReference) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.RequirementsVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "requirements_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationOfferType) Validate() error { + switch s { + case "full_time": + return nil + case "part_time": + return nil + case "contract": + return nil + case "internship": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *InvitationOrganization) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Name)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "name", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *InvitationPackage) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Bonus.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "bonus", + Error: err, + }) + } + if err := func() error { + if err := s.Equipment.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "equipment", + Error: err, + }) + } + if err := func() error { + if err := s.Training.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "training", + Error: err, + }) + } + if err := func() error { + if err := s.HealthInsurance.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "health_insurance", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationPackageItem) Validate() error { + switch s.Type { + case InvitationPackageItemProvidedInvitationPackageItem: + if err := s.InvitationPackageItemProvided.Validate(); err != nil { + return err + } + return nil + case InvitationPackageItemNotProvidedInvitationPackageItem: + if err := s.InvitationPackageItemNotProvided.Validate(); err != nil { + return err + } + return nil + default: + return errors.Errorf("invalid type %q", s.Type) + } +} + +func (s *InvitationPackageItemNotProvided) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationPackageItemNotProvidedStatus) Validate() error { + switch s { + case "not_provided": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *InvitationPackageItemProvided) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if err := s.Description.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "description", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationPackageItemProvidedStatus) Validate() error { + switch s { + case "provided": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s InvitationPackageItemText) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 300, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s InvitationResponsePeriod) Validate() error { + switch s { + case 3: + return nil + case 7: + return nil + case 14: + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s InvitationRoleTitle) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s InvitationSalaryFit) Validate() error { + switch s { + case "within_range": + return nil + case "up_to_10_percent_above": + return nil + case "above": + return nil + case "withheld": + return nil + case "not_available": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *InvitationSalaryRaise) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if err := s.SalaryTo.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "salary_to", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationState) Validate() error { + switch s { + case "draft": + return nil + case "delivered": + return nil + case "viewed": + return nil + case "counter": + return nil + case "accepted": + return nil + case "interview_scheduled": + return nil + case "interviewed": + return nil + case "negotiation": + return nil + case "terms_agreed": + return nil + case "no_deal": + return nil + case "declined": + return nil + case "expired": + return nil + case "withdrawn": + return nil + case "cancelled_by_candidate": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s InvitationTeamDescription) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 1000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["\\S"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *InvitationTerms) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.RoleTitle.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "role_title", + Error: err, + }) + } + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + Error: err, + }) + } + if err := func() error { + if err := s.Grade.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "grade", + Error: err, + }) + } + if err := func() error { + if err := s.OfferType.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "offer_type", + Error: err, + }) + } + if err := func() error { + if s.Tasks == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 20, + MaxLengthSet: true, + }).ValidateLength(len(s.Tasks)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Tasks { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "tasks", + Error: err, + }) + } + if err := func() error { + if err := s.Team.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "team", + Error: err, + }) + } + if err := func() error { + if s.TechStack == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 30, + MaxLengthSet: true, + }).ValidateLength(len(s.TechStack)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.TechStack); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.TechStack { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "tech_stack", + Error: err, + }) + } + if err := func() error { + if s.WorkFormats == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 3, + MaxLengthSet: true, + }).ValidateLength(len(s.WorkFormats)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(s.WorkFormats); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.WorkFormats { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "work_formats", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Location.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "location", + Error: err, + }) + } + if err := func() error { + if err := s.CommunicationMethod.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "communication_method", + Error: err, + }) + } + if err := func() error { + if err := s.Salary.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "salary", + Error: err, + }) + } + if err := func() error { + if err := s.Package.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "package", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s InvitationTermsVersion) Validate() error { + alias := (int64)(s) + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(alias)); err != nil { + return errors.Wrap(err, "int") + } + return nil +} + +func (s InvitationVersion) Validate() error { + alias := (int64)(s) + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(alias)); err != nil { + return errors.Wrap(err, "int") + } + return nil +} + func (s ItemContent) Validate() error { switch s.Type { case ChoiceItemContentItemContent: @@ -3815,6 +6139,30 @@ func (s ItemContent) Validate() error { } } +func (s *ListMyInvitationsBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyInvitationsForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyInvitationsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ListMySupportCasesBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -3831,6 +6179,38 @@ func (s *ListMySupportCasesUnauthorized) Validate() error { return nil } +func (s *ListOrganizationInvitationsBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListOrganizationInvitationsForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListOrganizationInvitationsNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListOrganizationInvitationsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ListOrganizationNeedsBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -6893,6 +9273,541 @@ func (s OrderItemContentFormat) Validate() error { } } +func (s *OrganizationInvitation) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CandidateHandle.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "candidate_handle", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Need.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "need", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ExpiryReason.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expiry_reason", + Error: err, + }) + } + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if err := s.TermsVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms_version", + Error: err, + }) + } + if err := func() error { + if err := s.Terms.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms", + Error: err, + }) + } + if err := func() error { + if err := s.ResponsePeriodDays.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "response_period_days", + Error: err, + }) + } + if err := func() error { + if err := s.SalaryFit.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "salary_fit", + Error: err, + }) + } + if err := func() error { + if err := s.ContactAccess.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "contact_access", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *OrganizationInvitationCreate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CandidateHandle.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "candidate_handle", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Need.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "need", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ResponsePeriodDays.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "response_period_days", + Error: err, + }) + } + if err := func() error { + if err := s.Terms.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *OrganizationInvitationHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *OrganizationInvitationList) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Items == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 100, + MaxLengthSet: true, + }).ValidateLength(len(s.Items)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Items { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "items", + Error: err, + }) + } + if err := func() error { + if err := s.Page.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "page", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *OrganizationInvitationListHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *OrganizationInvitationSummary) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CandidateHandle.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "candidate_handle", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Need.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "need", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ExpiryReason.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expiry_reason", + Error: err, + }) + } + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if err := func() error { + if err := s.TermsVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms_version", + Error: err, + }) + } + if err := func() error { + if err := s.RoleTitle.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "role_title", + Error: err, + }) + } + if err := func() error { + if err := s.Salary.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "salary", + Error: err, + }) + } + if err := func() error { + if err := s.ContactAccess.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "contact_access", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *OrganizationInvitationUpdate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Need.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "need", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ResponsePeriodDays.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "response_period_days", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Terms.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "terms", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *PageInfo) Validate() error { if s == nil { return validate.ErrNilPointer @@ -7986,6 +10901,62 @@ func (s QuestionnaireVersion) Validate() error { return nil } +func (s *RaiseOrganizationInvitationSalaryBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RaiseOrganizationInvitationSalaryConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RaiseOrganizationInvitationSalaryForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RaiseOrganizationInvitationSalaryNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RaiseOrganizationInvitationSalaryPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RaiseOrganizationInvitationSalaryUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *RaiseOrganizationInvitationSalaryUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *RegisterAccountBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -8227,6 +11198,62 @@ func (s *SaveMyQuestionnaireUnauthorized) Validate() error { return nil } +func (s *SendOrganizationInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SendOrganizationInvitationConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SendOrganizationInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SendOrganizationInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SendOrganizationInvitationPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SendOrganizationInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SendOrganizationInvitationUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *Session) Validate() error { if s == nil { return validate.ErrNilPointer @@ -10180,6 +13207,54 @@ func (s *TooManyRequestsHeaders) Validate() error { return nil } +func (s *UpdateOrganizationInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *UpdateOrganizationInvitationConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *UpdateOrganizationInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *UpdateOrganizationInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *UpdateOrganizationInvitationPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *UpdateOrganizationInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *UpdateOrganizationNeedBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -10240,6 +13315,94 @@ func (s VerificationToken) Validate() error { return nil } +func (s *ViewMyInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ViewMyInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ViewMyInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ViewMyInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *WithdrawOrganizationInvitationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *WithdrawOrganizationInvitationConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *WithdrawOrganizationInvitationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *WithdrawOrganizationInvitationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *WithdrawOrganizationInvitationPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *WithdrawOrganizationInvitationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *WithdrawOrganizationInvitationUnprocessableEntity) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *WorkContext) Validate() error { if s == nil { return validate.ErrNilPointer diff --git a/backend/internal/adapter/primary/http/problem/responder.go b/backend/internal/adapter/primary/http/problem/responder.go index 148b98f..2e63f4b 100644 --- a/backend/internal/adapter/primary/http/problem/responder.go +++ b/backend/internal/adapter/primary/http/problem/responder.go @@ -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 ` 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 ""` 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 { diff --git a/backend/internal/adapter/primary/http/problem/responder_test.go b/backend/internal/adapter/primary/http/problem/responder_test.go index 47b8d7d..3f5c588 100644 --- a/backend/internal/adapter/primary/http/problem/responder_test.go +++ b/backend/internal/adapter/primary/http/problem/responder_test.go @@ -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+`"`) +} diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index 12c2d69..bc7cdcb 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -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)) diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 362c34a..85444bc 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -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. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 5ebb4c3..41d42ee 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -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. diff --git a/frontend/src/shared/api/endpoints/index.msw.ts b/frontend/src/shared/api/endpoints/index.msw.ts index 9b0a3d9..00bf551 100644 --- a/frontend/src/shared/api/endpoints/index.msw.ts +++ b/frontend/src/shared/api/endpoints/index.msw.ts @@ -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' diff --git a/frontend/src/shared/api/endpoints/index.ts b/frontend/src/shared/api/endpoints/index.ts index 58f69af..3a78856 100644 --- a/frontend/src/shared/api/endpoints/index.ts +++ b/frontend/src/shared/api/endpoints/index.ts @@ -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'; diff --git a/frontend/src/shared/api/endpoints/invitation/invitation.msw.ts b/frontend/src/shared/api/endpoints/invitation/invitation.msw.ts new file mode 100644 index 0000000..cf12362 --- /dev/null +++ b/frontend/src/shared/api/endpoints/invitation/invitation.msw.ts @@ -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 => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse}); + +export const getListOrganizationInvitationsResponseMock = (overrideResponse: Partial> = {}): 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 => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse}); + +export const getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getCreateOrganizationInvitationResponseMock = (overrideResponse: Partial> = {}): 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 => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse}); + +export const getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getGetOrganizationInvitationResponseMock = (overrideResponse: Partial> = {}): 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 => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse}); + +export const getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getUpdateOrganizationInvitationResponseMock = (overrideResponse: Partial> = {}): 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 => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse}); + +export const getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getSendOrganizationInvitationResponseMock = (overrideResponse: Partial> = {}): 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 => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse}); + +export const getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getRaiseOrganizationInvitationSalaryResponseMock = (overrideResponse: Partial> = {}): 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 => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse}); + +export const getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemProvided => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getWithdrawOrganizationInvitationResponseMock = (overrideResponse: Partial> = {}): 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> = {}): 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> = {}): 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 => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getGetMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getGetMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial = {}): 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 => ({...{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 => ({...{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> = {}): 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 => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getViewMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getViewMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial = {}): 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 => ({...{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 => ({...{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> = {}): 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 => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getAcceptMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getAcceptMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial = {}): 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 => ({...{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 => ({...{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> = {}): 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 => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getDeclineMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getDeclineMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial = {}): 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 => ({...{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 => ({...{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> = {}): 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 => ({...{status: faker.helpers.arrayElement(['provided'] as const), description: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300})}, ...overrideResponse}); + +export const getCancelMyInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse}); + +export const getCancelMyInvitationResponseContactConsentOfferMock = (overrideResponse: Partial = {}): 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 => ({...{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 => ({...{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> = {}): 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[1]>[0]) => Promise | OrganizationInvitationList), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/organizations/:orgId/invitations', async (info: Parameters[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[1]>[0]) => Promise | OrganizationInvitation), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/organizations/:orgId/invitations', async (info: Parameters[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[1]>[0]) => Promise | OrganizationInvitation), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/organizations/:orgId/invitations/:invitationId', async (info: Parameters[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[1]>[0]) => Promise | OrganizationInvitation), options?: RequestHandlerOptions) => { + return http.patch('*/api/v1/organizations/:orgId/invitations/:invitationId', async (info: Parameters[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[1]>[0]) => Promise | OrganizationInvitation), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/organizations/:orgId/invitations/:invitationId/send', async (info: Parameters[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[1]>[0]) => Promise | OrganizationInvitation), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/organizations/:orgId/invitations/:invitationId/salary-raise', async (info: Parameters[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[1]>[0]) => Promise | OrganizationInvitation), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/organizations/:orgId/invitations/:invitationId/withdraw', async (info: Parameters[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[1]>[0]) => Promise | ContactDisclosure), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/organizations/:orgId/invitations/:invitationId/contacts', async (info: Parameters[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[1]>[0]) => Promise | CandidateInvitationList), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/invitations', async (info: Parameters[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[1]>[0]) => Promise | CandidateInvitation), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/invitations/:invitationId', async (info: Parameters[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[1]>[0]) => Promise | CandidateInvitation), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/invitations/:invitationId/view', async (info: Parameters[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[1]>[0]) => Promise | CandidateInvitation), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/invitations/:invitationId/accept', async (info: Parameters[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[1]>[0]) => Promise | CandidateInvitation), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/invitations/:invitationId/decline', async (info: Parameters[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[1]>[0]) => Promise | CandidateInvitation), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/invitations/:invitationId/cancel', async (info: Parameters[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() +] diff --git a/frontend/src/shared/api/endpoints/invitation/invitation.ts b/frontend/src/shared/api/endpoints/invitation/invitation.ts new file mode 100644 index 0000000..f1803bc --- /dev/null +++ b/frontend/src/shared/api/endpoints/invitation/invitation.ts @@ -0,0 +1,1520 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + AcceptMyInvitationHeaders, + CancelMyInvitationHeaders, + CandidateInvitation, + CandidateInvitationList, + ContactDisclosure, + CreateOrganizationInvitationHeaders, + DeclineMyInvitationHeaders, + InvitationAcceptance, + InvitationCommand, + InvitationDeclineRequest, + InvitationSalaryRaise, + ListMyInvitationsParams, + ListOrganizationInvitationsParams, + OrganizationInvitation, + OrganizationInvitationCreate, + OrganizationInvitationList, + OrganizationInvitationUpdate, + Problem, + RaiseOrganizationInvitationSalaryHeaders, + SendOrganizationInvitationHeaders, + WithdrawOrganizationInvitationHeaders +} from '../../schemas'; + +import { apiRequest } from '../../client'; +import type { ErrorType } from '../../client'; + + +type SecondParameter unknown> = Parameters[1]; + + + +const withQueryKey = (query: T, queryKey: K): T & { queryKey: K } => { + const result = { queryKey } as T & { queryKey: K }; + for (const key of Object.keys(query)) { + // The explicit queryKey always wins, matching the previous + // `{ ...query, queryKey }` spread where it was set last. + if (key === 'queryKey') continue; + Object.defineProperty(result, key, { + enumerable: true, + configurable: true, + get: () => (query as Record)[key], + }); + } + return result; +}; + +export const getListOrganizationInvitationsUrl = (orgId: string, + params?: ListOrganizationInvitationsParams,) => { + const normalizedParams = new URLSearchParams(); + + Object.entries(params || {}).forEach(([key, value]) => { + + if (value !== undefined) { + normalizedParams.append(key, value === null ? 'null' : String(value)) + } + }); + + const stringifiedParams = normalizedParams.toString(); + + return stringifiedParams.length > 0 ? `/api/v1/organizations/${orgId}/invitations?${stringifiedParams}` : `/api/v1/organizations/${orgId}/invitations` +} + +/** + * 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. + * @summary List the invitations of an organization. + */ +export const listOrganizationInvitations = async (orgId: string, + params?: ListOrganizationInvitationsParams, options?: Parameters[1]): Promise => { + + return apiRequest(getListOrganizationInvitationsUrl(orgId,params), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getListOrganizationInvitationsQueryKey = (orgId: string, + params?: ListOrganizationInvitationsParams,) => { + return [ + `/api/v1/organizations/${orgId}/invitations`, ...(params ? [params] : []) + ] as const; + } + + +export const getListOrganizationInvitationsQueryOptions = >, TError = ErrorType>(orgId: string, + params?: ListOrganizationInvitationsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListOrganizationInvitationsQueryKey(orgId,params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listOrganizationInvitations(orgId,params, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: orgId !== null && orgId !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListOrganizationInvitationsQueryResult = NonNullable>> +export type ListOrganizationInvitationsQueryError = ErrorType + + +export function useListOrganizationInvitations>, TError = ErrorType>( + orgId: string, + params: undefined | ListOrganizationInvitationsParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListOrganizationInvitations>, TError = ErrorType>( + orgId: string, + params?: ListOrganizationInvitationsParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListOrganizationInvitations>, TError = ErrorType>( + orgId: string, + params?: ListOrganizationInvitationsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary List the invitations of an organization. + */ + +export function useListOrganizationInvitations>, TError = ErrorType>( + orgId: string, + params?: ListOrganizationInvitationsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListOrganizationInvitationsQueryOptions(orgId,params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getCreateOrganizationInvitationUrl = (orgId: string,) => { + + + + + return `/api/v1/organizations/${orgId}/invitations` +} + +/** + * 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. + * @summary Create an invitation draft for one candidate. + */ +export const createOrganizationInvitation = async (orgId: string, + organizationInvitationCreate: OrganizationInvitationCreate, + headers: CreateOrganizationInvitationHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getCreateOrganizationInvitationUrl(orgId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(organizationInvitationCreate) + } +);} + + + + + +export const getCreateOrganizationInvitationMutationKey = () => ['createOrganizationInvitation'] as const; + +export const getCreateOrganizationInvitationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateOrganizationInvitationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,CreateOrganizationInvitationMutationVariables, TContext> => { + +const mutationKey = getCreateOrganizationInvitationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, CreateOrganizationInvitationMutationVariables> = (props) => { + const {orgId,data,headers} = props ?? {}; + + return createOrganizationInvitation(orgId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type CreateOrganizationInvitationMutationResult = NonNullable>> + export type CreateOrganizationInvitationMutationBody = OrganizationInvitationCreate + export type CreateOrganizationInvitationMutationError = ErrorType + export type CreateOrganizationInvitationMutationVariables = {orgId: string;data: OrganizationInvitationCreate;headers: CreateOrganizationInvitationHeaders} + + /** + * @summary Create an invitation draft for one candidate. + */ +export const useCreateOrganizationInvitation = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateOrganizationInvitationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + CreateOrganizationInvitationMutationVariables, + TContext + > => { + return useMutation(getCreateOrganizationInvitationMutationOptions(options), queryClient); + } + export const getGetOrganizationInvitationUrl = (orgId: string, + invitationId: string,) => { + + + + + return `/api/v1/organizations/${orgId}/invitations/${invitationId}` +} + +/** + * 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. + * @summary Read an invitation of an organization. + */ +export const getOrganizationInvitation = async (orgId: string, + invitationId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getGetOrganizationInvitationUrl(orgId,invitationId), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetOrganizationInvitationQueryKey = (orgId: string, + invitationId: string,) => { + return [ + `/api/v1/organizations/${orgId}/invitations/${invitationId}` + ] as const; + } + + +export const getGetOrganizationInvitationQueryOptions = >, TError = ErrorType>(orgId: string, + invitationId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetOrganizationInvitationQueryKey(orgId,invitationId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getOrganizationInvitation(orgId,invitationId, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: orgId !== null && orgId !== undefined && invitationId !== null && invitationId !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetOrganizationInvitationQueryResult = NonNullable>> +export type GetOrganizationInvitationQueryError = ErrorType + + +export function useGetOrganizationInvitation>, TError = ErrorType>( + orgId: string, + invitationId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetOrganizationInvitation>, TError = ErrorType>( + orgId: string, + invitationId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetOrganizationInvitation>, TError = ErrorType>( + orgId: string, + invitationId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read an invitation of an organization. + */ + +export function useGetOrganizationInvitation>, TError = ErrorType>( + orgId: string, + invitationId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetOrganizationInvitationQueryOptions(orgId,invitationId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getUpdateOrganizationInvitationUrl = (orgId: string, + invitationId: string,) => { + + + + + return `/api/v1/organizations/${orgId}/invitations/${invitationId}` +} + +/** + * 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). + * @summary Change the terms, the need link, or the response period of a draft. + */ +export const updateOrganizationInvitation = async (orgId: string, + invitationId: string, + organizationInvitationUpdate: OrganizationInvitationUpdate, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getUpdateOrganizationInvitationUrl(orgId,invitationId), + { + ...options, + method: 'PATCH', + headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) }, + body: JSON.stringify(organizationInvitationUpdate) + } +);} + + + + + +export const getUpdateOrganizationInvitationMutationKey = () => ['updateOrganizationInvitation'] as const; + +export const getUpdateOrganizationInvitationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,UpdateOrganizationInvitationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,UpdateOrganizationInvitationMutationVariables, TContext> => { + +const mutationKey = getUpdateOrganizationInvitationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, UpdateOrganizationInvitationMutationVariables> = (props) => { + const {orgId,invitationId,data} = props ?? {}; + + return updateOrganizationInvitation(orgId,invitationId,data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type UpdateOrganizationInvitationMutationResult = NonNullable>> + export type UpdateOrganizationInvitationMutationBody = OrganizationInvitationUpdate + export type UpdateOrganizationInvitationMutationError = ErrorType + export type UpdateOrganizationInvitationMutationVariables = {orgId: string;invitationId: string;data: OrganizationInvitationUpdate} + + /** + * @summary Change the terms, the need link, or the response period of a draft. + */ +export const useUpdateOrganizationInvitation = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,UpdateOrganizationInvitationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + UpdateOrganizationInvitationMutationVariables, + TContext + > => { + return useMutation(getUpdateOrganizationInvitationMutationOptions(options), queryClient); + } + export const getSendOrganizationInvitationUrl = (orgId: string, + invitationId: string,) => { + + + + + return `/api/v1/organizations/${orgId}/invitations/${invitationId}/send` +} + +/** + * 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. + * @summary Send a draft to the candidate's inbox. + */ +export const sendOrganizationInvitation = async (orgId: string, + invitationId: string, + invitationCommand: InvitationCommand, + headers: SendOrganizationInvitationHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getSendOrganizationInvitationUrl(orgId,invitationId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(invitationCommand) + } +);} + + + + + +export const getSendOrganizationInvitationMutationKey = () => ['sendOrganizationInvitation'] as const; + +export const getSendOrganizationInvitationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SendOrganizationInvitationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,SendOrganizationInvitationMutationVariables, TContext> => { + +const mutationKey = getSendOrganizationInvitationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, SendOrganizationInvitationMutationVariables> = (props) => { + const {orgId,invitationId,data,headers} = props ?? {}; + + return sendOrganizationInvitation(orgId,invitationId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type SendOrganizationInvitationMutationResult = NonNullable>> + export type SendOrganizationInvitationMutationBody = InvitationCommand + export type SendOrganizationInvitationMutationError = ErrorType + export type SendOrganizationInvitationMutationVariables = {orgId: string;invitationId: string;data: InvitationCommand;headers: SendOrganizationInvitationHeaders} + + /** + * @summary Send a draft to the candidate's inbox. + */ +export const useSendOrganizationInvitation = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SendOrganizationInvitationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + SendOrganizationInvitationMutationVariables, + TContext + > => { + return useMutation(getSendOrganizationInvitationMutationOptions(options), queryClient); + } + export const getRaiseOrganizationInvitationSalaryUrl = (orgId: string, + invitationId: string,) => { + + + + + return `/api/v1/organizations/${orgId}/invitations/${invitationId}/salary-raise` +} + +/** + * 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. + * @summary Raise the upper salary bound of a sent invitation once. + */ +export const raiseOrganizationInvitationSalary = async (orgId: string, + invitationId: string, + invitationSalaryRaise: InvitationSalaryRaise, + headers: RaiseOrganizationInvitationSalaryHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getRaiseOrganizationInvitationSalaryUrl(orgId,invitationId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(invitationSalaryRaise) + } +);} + + + + + +export const getRaiseOrganizationInvitationSalaryMutationKey = () => ['raiseOrganizationInvitationSalary'] as const; + +export const getRaiseOrganizationInvitationSalaryMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,RaiseOrganizationInvitationSalaryMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,RaiseOrganizationInvitationSalaryMutationVariables, TContext> => { + +const mutationKey = getRaiseOrganizationInvitationSalaryMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, RaiseOrganizationInvitationSalaryMutationVariables> = (props) => { + const {orgId,invitationId,data,headers} = props ?? {}; + + return raiseOrganizationInvitationSalary(orgId,invitationId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type RaiseOrganizationInvitationSalaryMutationResult = NonNullable>> + export type RaiseOrganizationInvitationSalaryMutationBody = InvitationSalaryRaise + export type RaiseOrganizationInvitationSalaryMutationError = ErrorType + export type RaiseOrganizationInvitationSalaryMutationVariables = {orgId: string;invitationId: string;data: InvitationSalaryRaise;headers: RaiseOrganizationInvitationSalaryHeaders} + + /** + * @summary Raise the upper salary bound of a sent invitation once. + */ +export const useRaiseOrganizationInvitationSalary = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,RaiseOrganizationInvitationSalaryMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + RaiseOrganizationInvitationSalaryMutationVariables, + TContext + > => { + return useMutation(getRaiseOrganizationInvitationSalaryMutationOptions(options), queryClient); + } + export const getWithdrawOrganizationInvitationUrl = (orgId: string, + invitationId: string,) => { + + + + + return `/api/v1/organizations/${orgId}/invitations/${invitationId}/withdraw` +} + +/** + * 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. + * @summary Withdraw an invitation. + */ +export const withdrawOrganizationInvitation = async (orgId: string, + invitationId: string, + invitationCommand: InvitationCommand, + headers: WithdrawOrganizationInvitationHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getWithdrawOrganizationInvitationUrl(orgId,invitationId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(invitationCommand) + } +);} + + + + + +export const getWithdrawOrganizationInvitationMutationKey = () => ['withdrawOrganizationInvitation'] as const; + +export const getWithdrawOrganizationInvitationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,WithdrawOrganizationInvitationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,WithdrawOrganizationInvitationMutationVariables, TContext> => { + +const mutationKey = getWithdrawOrganizationInvitationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, WithdrawOrganizationInvitationMutationVariables> = (props) => { + const {orgId,invitationId,data,headers} = props ?? {}; + + return withdrawOrganizationInvitation(orgId,invitationId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type WithdrawOrganizationInvitationMutationResult = NonNullable>> + export type WithdrawOrganizationInvitationMutationBody = InvitationCommand + export type WithdrawOrganizationInvitationMutationError = ErrorType + export type WithdrawOrganizationInvitationMutationVariables = {orgId: string;invitationId: string;data: InvitationCommand;headers: WithdrawOrganizationInvitationHeaders} + + /** + * @summary Withdraw an invitation. + */ +export const useWithdrawOrganizationInvitation = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,WithdrawOrganizationInvitationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + WithdrawOrganizationInvitationMutationVariables, + TContext + > => { + return useMutation(getWithdrawOrganizationInvitationMutationOptions(options), queryClient); + } + export const getGetOrganizationInvitationContactsUrl = (orgId: string, + invitationId: string,) => { + + + + + return `/api/v1/organizations/${orgId}/invitations/${invitationId}/contacts` +} + +/** + * 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. + * @summary Read the contacts that the candidate disclosed to the organization. + */ +export const getOrganizationInvitationContacts = async (orgId: string, + invitationId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getGetOrganizationInvitationContactsUrl(orgId,invitationId), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetOrganizationInvitationContactsQueryKey = (orgId: string, + invitationId: string,) => { + return [ + `/api/v1/organizations/${orgId}/invitations/${invitationId}/contacts` + ] as const; + } + + +export const getGetOrganizationInvitationContactsQueryOptions = >, TError = ErrorType>(orgId: string, + invitationId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetOrganizationInvitationContactsQueryKey(orgId,invitationId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getOrganizationInvitationContacts(orgId,invitationId, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: orgId !== null && orgId !== undefined && invitationId !== null && invitationId !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetOrganizationInvitationContactsQueryResult = NonNullable>> +export type GetOrganizationInvitationContactsQueryError = ErrorType + + +export function useGetOrganizationInvitationContacts>, TError = ErrorType>( + orgId: string, + invitationId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetOrganizationInvitationContacts>, TError = ErrorType>( + orgId: string, + invitationId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetOrganizationInvitationContacts>, TError = ErrorType>( + orgId: string, + invitationId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the contacts that the candidate disclosed to the organization. + */ + +export function useGetOrganizationInvitationContacts>, TError = ErrorType>( + orgId: string, + invitationId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetOrganizationInvitationContactsQueryOptions(orgId,invitationId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getListMyInvitationsUrl = (params?: ListMyInvitationsParams,) => { + const normalizedParams = new URLSearchParams(); + + Object.entries(params || {}).forEach(([key, value]) => { + + if (value !== undefined) { + normalizedParams.append(key, value === null ? 'null' : String(value)) + } + }); + + const stringifiedParams = normalizedParams.toString(); + + return stringifiedParams.length > 0 ? `/api/v1/me/invitations?${stringifiedParams}` : `/api/v1/me/invitations` +} + +/** + * 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. + * @summary List the invitations addressed to the current candidate. + */ +export const listMyInvitations = async (params?: ListMyInvitationsParams, options?: Parameters[1]): Promise => { + + return apiRequest(getListMyInvitationsUrl(params), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getListMyInvitationsQueryKey = (params?: ListMyInvitationsParams,) => { + return [ + `/api/v1/me/invitations`, ...(params ? [params] : []) + ] as const; + } + + +export const getListMyInvitationsQueryOptions = >, TError = ErrorType>(params?: ListMyInvitationsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListMyInvitationsQueryKey(params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listMyInvitations(params, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListMyInvitationsQueryResult = NonNullable>> +export type ListMyInvitationsQueryError = ErrorType + + +export function useListMyInvitations>, TError = ErrorType>( + params: undefined | ListMyInvitationsParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListMyInvitations>, TError = ErrorType>( + params?: ListMyInvitationsParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListMyInvitations>, TError = ErrorType>( + params?: ListMyInvitationsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary List the invitations addressed to the current candidate. + */ + +export function useListMyInvitations>, TError = ErrorType>( + params?: ListMyInvitationsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListMyInvitationsQueryOptions(params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getGetMyInvitationUrl = (invitationId: string,) => { + + + + + return `/api/v1/me/invitations/${invitationId}` +} + +/** + * 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. + * @summary Open the terms of an invitation addressed to the current candidate. + */ +export const getMyInvitation = async (invitationId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyInvitationUrl(invitationId), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyInvitationQueryKey = (invitationId: string,) => { + return [ + `/api/v1/me/invitations/${invitationId}` + ] as const; + } + + +export const getGetMyInvitationQueryOptions = >, TError = ErrorType>(invitationId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyInvitationQueryKey(invitationId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyInvitation(invitationId, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: invitationId !== null && invitationId !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyInvitationQueryResult = NonNullable>> +export type GetMyInvitationQueryError = ErrorType + + +export function useGetMyInvitation>, TError = ErrorType>( + invitationId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyInvitation>, TError = ErrorType>( + invitationId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyInvitation>, TError = ErrorType>( + invitationId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Open the terms of an invitation addressed to the current candidate. + */ + +export function useGetMyInvitation>, TError = ErrorType>( + invitationId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyInvitationQueryOptions(invitationId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getViewMyInvitationUrl = (invitationId: string,) => { + + + + + return `/api/v1/me/invitations/${invitationId}/view` +} + +/** + * 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. + * @summary Record that the current candidate opened the terms of an invitation. + */ +export const viewMyInvitation = async (invitationId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getViewMyInvitationUrl(invitationId), + { + ...options, + method: 'POST' + + + } +);} + + + + + +export const getViewMyInvitationMutationKey = () => ['viewMyInvitation'] as const; + +export const getViewMyInvitationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,ViewMyInvitationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,ViewMyInvitationMutationVariables, TContext> => { + +const mutationKey = getViewMyInvitationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, ViewMyInvitationMutationVariables> = (props) => { + const {invitationId} = props ?? {}; + + return viewMyInvitation(invitationId,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type ViewMyInvitationMutationResult = NonNullable>> + + export type ViewMyInvitationMutationError = ErrorType + export type ViewMyInvitationMutationVariables = {invitationId: string} + + /** + * @summary Record that the current candidate opened the terms of an invitation. + */ +export const useViewMyInvitation = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,ViewMyInvitationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + ViewMyInvitationMutationVariables, + TContext + > => { + return useMutation(getViewMyInvitationMutationOptions(options), queryClient); + } + export const getAcceptMyInvitationUrl = (invitationId: string,) => { + + + + + return `/api/v1/me/invitations/${invitationId}/accept` +} + +/** + * 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. + * @summary Accept the current terms and disclose the selected contacts. + */ +export const acceptMyInvitation = async (invitationId: string, + invitationAcceptance: InvitationAcceptance, + headers: AcceptMyInvitationHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getAcceptMyInvitationUrl(invitationId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(invitationAcceptance) + } +);} + + + + + +export const getAcceptMyInvitationMutationKey = () => ['acceptMyInvitation'] as const; + +export const getAcceptMyInvitationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,AcceptMyInvitationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,AcceptMyInvitationMutationVariables, TContext> => { + +const mutationKey = getAcceptMyInvitationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, AcceptMyInvitationMutationVariables> = (props) => { + const {invitationId,data,headers} = props ?? {}; + + return acceptMyInvitation(invitationId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type AcceptMyInvitationMutationResult = NonNullable>> + export type AcceptMyInvitationMutationBody = InvitationAcceptance + export type AcceptMyInvitationMutationError = ErrorType + export type AcceptMyInvitationMutationVariables = {invitationId: string;data: InvitationAcceptance;headers: AcceptMyInvitationHeaders} + + /** + * @summary Accept the current terms and disclose the selected contacts. + */ +export const useAcceptMyInvitation = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,AcceptMyInvitationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + AcceptMyInvitationMutationVariables, + TContext + > => { + return useMutation(getAcceptMyInvitationMutationOptions(options), queryClient); + } + export const getDeclineMyInvitationUrl = (invitationId: string,) => { + + + + + return `/api/v1/me/invitations/${invitationId}/decline` +} + +/** + * 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. + * @summary Decline an invitation with a structured reason. + */ +export const declineMyInvitation = async (invitationId: string, + invitationDeclineRequest: InvitationDeclineRequest, + headers: DeclineMyInvitationHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getDeclineMyInvitationUrl(invitationId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(invitationDeclineRequest) + } +);} + + + + + +export const getDeclineMyInvitationMutationKey = () => ['declineMyInvitation'] as const; + +export const getDeclineMyInvitationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,DeclineMyInvitationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,DeclineMyInvitationMutationVariables, TContext> => { + +const mutationKey = getDeclineMyInvitationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, DeclineMyInvitationMutationVariables> = (props) => { + const {invitationId,data,headers} = props ?? {}; + + return declineMyInvitation(invitationId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type DeclineMyInvitationMutationResult = NonNullable>> + export type DeclineMyInvitationMutationBody = InvitationDeclineRequest + export type DeclineMyInvitationMutationError = ErrorType + export type DeclineMyInvitationMutationVariables = {invitationId: string;data: InvitationDeclineRequest;headers: DeclineMyInvitationHeaders} + + /** + * @summary Decline an invitation with a structured reason. + */ +export const useDeclineMyInvitation = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,DeclineMyInvitationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + DeclineMyInvitationMutationVariables, + TContext + > => { + return useMutation(getDeclineMyInvitationMutationOptions(options), queryClient); + } + export const getCancelMyInvitationUrl = (invitationId: string,) => { + + + + + return `/api/v1/me/invitations/${invitationId}/cancel` +} + +/** + * 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. + * @summary Cancel the participation in an invitation and revoke its contact grant. + */ +export const cancelMyInvitation = async (invitationId: string, + invitationCommand: InvitationCommand, + headers: CancelMyInvitationHeaders, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getCancelMyInvitationUrl(invitationId), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(invitationCommand) + } +);} + + + + + +export const getCancelMyInvitationMutationKey = () => ['cancelMyInvitation'] as const; + +export const getCancelMyInvitationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CancelMyInvitationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,CancelMyInvitationMutationVariables, TContext> => { + +const mutationKey = getCancelMyInvitationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, CancelMyInvitationMutationVariables> = (props) => { + const {invitationId,data,headers} = props ?? {}; + + return cancelMyInvitation(invitationId,data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type CancelMyInvitationMutationResult = NonNullable>> + export type CancelMyInvitationMutationBody = InvitationCommand + export type CancelMyInvitationMutationError = ErrorType + export type CancelMyInvitationMutationVariables = {invitationId: string;data: InvitationCommand;headers: CancelMyInvitationHeaders} + + /** + * @summary Cancel the participation in an invitation and revoke its contact grant. + */ +export const useCancelMyInvitation = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CancelMyInvitationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + CancelMyInvitationMutationVariables, + TContext + > => { + return useMutation(getCancelMyInvitationMutationOptions(options), queryClient); + } diff --git a/frontend/src/shared/api/endpoints/support/support.ts b/frontend/src/shared/api/endpoints/support/support.ts index d6dabea..ae894b9 100644 --- a/frontend/src/shared/api/endpoints/support/support.ts +++ b/frontend/src/shared/api/endpoints/support/support.ts @@ -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. * diff --git a/frontend/src/shared/api/invitation-contract.test.ts b/frontend/src/shared/api/invitation-contract.test.ts new file mode 100644 index 0000000..0d1f5a5 --- /dev/null +++ b/frontend/src/shared/api/invitation-contract.test.ts @@ -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(value: T, key: K): Omit { + const copy: Partial = { ...value }; + delete copy[key]; + return copy as Omit; +} + +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/. + 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>().toEqualTypeOf(); + expectTypeOf< + Extract + >().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + Extract + >().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + Extract + >().toEqualTypeOf(); + // The organization never reads the reason or the comment of a decline. + expectTypeOf< + Extract + >().toEqualTypeOf(); + // Contact values travel only in the separate disclosure. + expectTypeOf>().toEqualTypeOf< + "email" | "phone" + >(); + expectTypeOf(getOrganizationInvitation).returns.resolves.toEqualTypeOf(); + expectTypeOf(getMyInvitation).returns.resolves.toEqualTypeOf(); + // The view is an explicit command without a body, a key, or a version. + expectTypeOf(viewMyInvitation).parameters.toEqualTypeOf< + [invitationId: string, options?: Parameters[1]] + >(); + expectTypeOf(viewMyInvitation).returns.resolves.toEqualTypeOf(); + expectTypeOf( + getOrganizationInvitationContacts, + ).returns.resolves.toEqualTypeOf(); +}); + +it("exposes request DTOs without client-set state, contacts, or a hidden C4 default", () => { + expectTypeOf< + Extract + >().toEqualTypeOf(); + expectTypeOf< + Extract + >().toEqualTypeOf(); + expectTypeOf< + Extract< + keyof InvitationAcceptance, + Exclude | ContactOrMinimumKey + > + >().toEqualTypeOf(); + expectTypeOf< + Extract + >().toEqualTypeOf(); + // The acceptance names the terms version and the field choice explicitly. + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf< + ("full_name" | "email" | "phone" | "telegram")[] + >(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf(createOrganizationInvitation) + .parameter(1) + .toEqualTypeOf(); + expectTypeOf(acceptMyInvitation).parameter(1).toEqualTypeOf(); +}); diff --git a/frontend/src/shared/api/schemas/identity/consentTextVersion.zod.ts b/frontend/src/shared/api/schemas/consentTextVersion.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/identity/consentTextVersion.zod.ts rename to frontend/src/shared/api/schemas/consentTextVersion.zod.ts diff --git a/frontend/src/shared/api/schemas/need/currencyCode.zod.ts b/frontend/src/shared/api/schemas/currencyCode.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/currencyCode.zod.ts rename to frontend/src/shared/api/schemas/currencyCode.zod.ts diff --git a/frontend/src/shared/api/schemas/identity/emailAddress.zod.ts b/frontend/src/shared/api/schemas/emailAddress.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/identity/emailAddress.zod.ts rename to frontend/src/shared/api/schemas/emailAddress.zod.ts diff --git a/frontend/src/shared/api/schemas/identity/index.ts b/frontend/src/shared/api/schemas/identity/index.ts index d4a7ad0..c3886d8 100644 --- a/frontend/src/shared/api/schemas/identity/index.ts +++ b/frontend/src/shared/api/schemas/identity/index.ts @@ -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'; diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index 7fde953..c0f63e4 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -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'; diff --git a/frontend/src/shared/api/schemas/invitation/acceptMyInvitationBody.zod.ts b/frontend/src/shared/api/schemas/invitation/acceptMyInvitationBody.zod.ts new file mode 100644 index 0000000..3475c6f --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/acceptMyInvitationBody.zod.ts @@ -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; +export type AcceptMyInvitationBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/acceptMyInvitationHeaders.zod.ts b/frontend/src/shared/api/schemas/invitation/acceptMyInvitationHeaders.zod.ts new file mode 100644 index 0000000..530c2df --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/acceptMyInvitationHeaders.zod.ts @@ -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; +export type AcceptMyInvitationHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/cancelMyInvitationBody.zod.ts b/frontend/src/shared/api/schemas/invitation/cancelMyInvitationBody.zod.ts new file mode 100644 index 0000000..53459d7 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/cancelMyInvitationBody.zod.ts @@ -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; +export type CancelMyInvitationBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/cancelMyInvitationHeaders.zod.ts b/frontend/src/shared/api/schemas/invitation/cancelMyInvitationHeaders.zod.ts new file mode 100644 index 0000000..bcff973 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/cancelMyInvitationHeaders.zod.ts @@ -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; +export type CancelMyInvitationHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/candidateHandle.zod.ts b/frontend/src/shared/api/schemas/invitation/candidateHandle.zod.ts new file mode 100644 index 0000000..dbf3a39 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/candidateHandle.zod.ts @@ -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; +export type CandidateHandleOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/candidateInvitation.zod.ts b/frontend/src/shared/api/schemas/invitation/candidateInvitation.zod.ts new file mode 100644 index 0000000..bc425b2 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/candidateInvitation.zod.ts @@ -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; +export type CandidateInvitationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/candidateInvitationList.zod.ts b/frontend/src/shared/api/schemas/invitation/candidateInvitationList.zod.ts new file mode 100644 index 0000000..f64284f --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/candidateInvitationList.zod.ts @@ -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; +export type CandidateInvitationListOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/candidateInvitationSummary.zod.ts b/frontend/src/shared/api/schemas/invitation/candidateInvitationSummary.zod.ts new file mode 100644 index 0000000..051bd2d --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/candidateInvitationSummary.zod.ts @@ -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; +export type CandidateInvitationSummaryOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactAccessBlock.zod.ts b/frontend/src/shared/api/schemas/invitation/contactAccessBlock.zod.ts new file mode 100644 index 0000000..546e5c0 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactAccessBlock.zod.ts @@ -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; +export type ContactAccessBlockOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactConsentAcceptance.zod.ts b/frontend/src/shared/api/schemas/invitation/contactConsentAcceptance.zod.ts new file mode 100644 index 0000000..c167dc5 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactConsentAcceptance.zod.ts @@ -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; +export type ContactConsentAcceptanceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactConsentOffer.zod.ts b/frontend/src/shared/api/schemas/invitation/contactConsentOffer.zod.ts new file mode 100644 index 0000000..1bc653a --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactConsentOffer.zod.ts @@ -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; +export type ContactConsentOfferOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactConsentText.zod.ts b/frontend/src/shared/api/schemas/invitation/contactConsentText.zod.ts new file mode 100644 index 0000000..2c39d94 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactConsentText.zod.ts @@ -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; +export type ContactConsentTextOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactDisclosure.zod.ts b/frontend/src/shared/api/schemas/invitation/contactDisclosure.zod.ts new file mode 100644 index 0000000..abfe0f6 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactDisclosure.zod.ts @@ -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; +export type ContactDisclosureOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactFieldKind.zod.ts b/frontend/src/shared/api/schemas/invitation/contactFieldKind.zod.ts new file mode 100644 index 0000000..541293a --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactFieldKind.zod.ts @@ -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; +export type ContactFieldKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactFullName.zod.ts b/frontend/src/shared/api/schemas/invitation/contactFullName.zod.ts new file mode 100644 index 0000000..4d2aac4 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactFullName.zod.ts @@ -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; +export type ContactFullNameOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactGrant.zod.ts b/frontend/src/shared/api/schemas/invitation/contactGrant.zod.ts new file mode 100644 index 0000000..dd713e6 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactGrant.zod.ts @@ -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; +export type ContactGrantOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactGrantState.zod.ts b/frontend/src/shared/api/schemas/invitation/contactGrantState.zod.ts new file mode 100644 index 0000000..26fa39e --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactGrantState.zod.ts @@ -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; +export type ContactGrantStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactPhoneNumber.zod.ts b/frontend/src/shared/api/schemas/invitation/contactPhoneNumber.zod.ts new file mode 100644 index 0000000..9c639a1 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactPhoneNumber.zod.ts @@ -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; +export type ContactPhoneNumberOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactRevocationReason.zod.ts b/frontend/src/shared/api/schemas/invitation/contactRevocationReason.zod.ts new file mode 100644 index 0000000..cf65439 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactRevocationReason.zod.ts @@ -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; +export type ContactRevocationReasonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/contactTelegramUsername.zod.ts b/frontend/src/shared/api/schemas/invitation/contactTelegramUsername.zod.ts new file mode 100644 index 0000000..2b72ef5 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/contactTelegramUsername.zod.ts @@ -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; +export type ContactTelegramUsernameOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationBody.zod.ts b/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationBody.zod.ts new file mode 100644 index 0000000..0715d8b --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationBody.zod.ts @@ -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; +export type CreateOrganizationInvitationBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationHeaders.zod.ts b/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationHeaders.zod.ts new file mode 100644 index 0000000..2d3a685 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/createOrganizationInvitationHeaders.zod.ts @@ -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; +export type CreateOrganizationInvitationHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/declineMyInvitationBody.zod.ts b/frontend/src/shared/api/schemas/invitation/declineMyInvitationBody.zod.ts new file mode 100644 index 0000000..7770850 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/declineMyInvitationBody.zod.ts @@ -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; +export type DeclineMyInvitationBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/declineMyInvitationHeaders.zod.ts b/frontend/src/shared/api/schemas/invitation/declineMyInvitationHeaders.zod.ts new file mode 100644 index 0000000..a8334af --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/declineMyInvitationHeaders.zod.ts @@ -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; +export type DeclineMyInvitationHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/index.ts b/frontend/src/shared/api/schemas/invitation/index.ts new file mode 100644 index 0000000..5ac0706 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/index.ts @@ -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'; diff --git a/frontend/src/shared/api/schemas/invitation/invitationAcceptance.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationAcceptance.zod.ts new file mode 100644 index 0000000..5f0b105 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationAcceptance.zod.ts @@ -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; +export type InvitationAcceptanceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationCommand.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationCommand.zod.ts new file mode 100644 index 0000000..471a931 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationCommand.zod.ts @@ -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; +export type InvitationCommandOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationCommunicationChannel.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationCommunicationChannel.zod.ts new file mode 100644 index 0000000..52633f6 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationCommunicationChannel.zod.ts @@ -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; +export type InvitationCommunicationChannelOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationCommunicationMethod.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationCommunicationMethod.zod.ts new file mode 100644 index 0000000..29b1479 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationCommunicationMethod.zod.ts @@ -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; +export type InvitationCommunicationMethodOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationCommunicationNote.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationCommunicationNote.zod.ts new file mode 100644 index 0000000..0129369 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationCommunicationNote.zod.ts @@ -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; +export type InvitationCommunicationNoteOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationContactAccess.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationContactAccess.zod.ts new file mode 100644 index 0000000..405bb66 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationContactAccess.zod.ts @@ -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; +export type InvitationContactAccessOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationContactAccessState.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationContactAccessState.zod.ts new file mode 100644 index 0000000..47815af --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationContactAccessState.zod.ts @@ -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; +export type InvitationContactAccessStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationDeclineComment.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationDeclineComment.zod.ts new file mode 100644 index 0000000..00413a1 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationDeclineComment.zod.ts @@ -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; +export type InvitationDeclineCommentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationDeclineReason.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationDeclineReason.zod.ts new file mode 100644 index 0000000..b263657 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationDeclineReason.zod.ts @@ -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; +export type InvitationDeclineReasonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationDeclineRecord.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationDeclineRecord.zod.ts new file mode 100644 index 0000000..0586f6f --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationDeclineRecord.zod.ts @@ -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; +export type InvitationDeclineRecordOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationDeclineRequest.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationDeclineRequest.zod.ts new file mode 100644 index 0000000..3d3f2b7 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationDeclineRequest.zod.ts @@ -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; +export type InvitationDeclineRequestOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationExpiryReason.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationExpiryReason.zod.ts new file mode 100644 index 0000000..6d324c9 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationExpiryReason.zod.ts @@ -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; +export type InvitationExpiryReasonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationNeedReference.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationNeedReference.zod.ts new file mode 100644 index 0000000..679797b --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationNeedReference.zod.ts @@ -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; +export type InvitationNeedReferenceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationOfferType.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationOfferType.zod.ts new file mode 100644 index 0000000..d584a1a --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationOfferType.zod.ts @@ -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; +export type InvitationOfferTypeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationOrganization.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationOrganization.zod.ts new file mode 100644 index 0000000..4ddf4cc --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationOrganization.zod.ts @@ -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; +export type InvitationOrganizationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationPackage.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationPackage.zod.ts new file mode 100644 index 0000000..3ca1fa2 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationPackage.zod.ts @@ -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; +export type InvitationPackageOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationPackageItem.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationPackageItem.zod.ts new file mode 100644 index 0000000..17bc47d --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationPackageItem.zod.ts @@ -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; +export type InvitationPackageItemOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationPackageItemNotProvided.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationPackageItemNotProvided.zod.ts new file mode 100644 index 0000000..104acac --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationPackageItemNotProvided.zod.ts @@ -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; +export type InvitationPackageItemNotProvidedOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationPackageItemProvided.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationPackageItemProvided.zod.ts new file mode 100644 index 0000000..4565ab1 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationPackageItemProvided.zod.ts @@ -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; +export type InvitationPackageItemProvidedOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationPackageItemText.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationPackageItemText.zod.ts new file mode 100644 index 0000000..87afb5e --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationPackageItemText.zod.ts @@ -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; +export type InvitationPackageItemTextOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationResponsePeriod.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationResponsePeriod.zod.ts new file mode 100644 index 0000000..6daf65b --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationResponsePeriod.zod.ts @@ -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 InvitationResponsePeriod = 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.') + +export type InvitationResponsePeriod = zod.input; +export type InvitationResponsePeriodOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationRoleTitle.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationRoleTitle.zod.ts new file mode 100644 index 0000000..b21eba1 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationRoleTitle.zod.ts @@ -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 InvitationRoleTitleMax = 200; + + +export const InvitationRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$'); + +export const InvitationRoleTitle = zod.string().min(1).max(InvitationRoleTitleMax).regex(InvitationRoleTitleRegExp).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.') + +export type InvitationRoleTitle = zod.input; +export type InvitationRoleTitleOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationSalaryFit.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationSalaryFit.zod.ts new file mode 100644 index 0000000..545e01e --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationSalaryFit.zod.ts @@ -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 InvitationSalaryFit = zod.enum(['within_range', 'up_to_10_percent_above', 'above', 'withheld', 'not_available']).describe('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.\n\n- within_range: the minimum is not above `B`.\n- up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`.\n- above: the minimum is more than 10% above `B`.\n- 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.\n- not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis.\n\nEvery 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.\n\nThe server never rejects or changes a range because of the minimum: a rejection would itself reveal it.') + +export type InvitationSalaryFit = zod.input; +export type InvitationSalaryFitOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationSalaryRaise.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationSalaryRaise.zod.ts new file mode 100644 index 0000000..99fe93d --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationSalaryRaise.zod.ts @@ -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 invitationSalaryRaiseSalaryToOneMin = 1000; +export const invitationSalaryRaiseSalaryToOneMax = 100000000; +export const invitationSalaryRaiseSalaryToOneMultipleOf = 1000; + + +export const InvitationSalaryRaise = 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.'), + "salary_to": zod.int().min(invitationSalaryRaiseSalaryToOneMin).max(invitationSalaryRaiseSalaryToOneMax).multipleOf(invitationSalaryRaiseSalaryToOneMultipleOf).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.').describe('New upper bound, above the current one, with a width of the range from 10% to 40% of its midpoint.') +}).describe('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.') + +export type InvitationSalaryRaise = zod.input; +export type InvitationSalaryRaiseOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationState.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationState.zod.ts new file mode 100644 index 0000000..1425339 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationState.zod.ts @@ -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 InvitationState = 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.') + +export type InvitationState = zod.input; +export type InvitationStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationTeamDescription.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationTeamDescription.zod.ts new file mode 100644 index 0000000..6130c43 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationTeamDescription.zod.ts @@ -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 InvitationTeamDescriptionMax = 1000; + + +export const InvitationTeamDescriptionRegExp = new RegExp('\\S'); + +export const InvitationTeamDescription = zod.string().min(1).max(InvitationTeamDescriptionMax).regex(InvitationTeamDescriptionRegExp).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.') + +export type InvitationTeamDescription = zod.input; +export type InvitationTeamDescriptionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationTerms.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationTerms.zod.ts new file mode 100644 index 0000000..74fc8c1 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationTerms.zod.ts @@ -0,0 +1,114 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const invitationTermsRoleTitleMax = 200; + + +export const invitationTermsRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const invitationTermsTasksItemMax = 300; + + +export const invitationTermsTasksItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const invitationTermsTasksMax = 20; + +export const invitationTermsTeamMax = 1000; + + +export const invitationTermsTeamRegExp = new RegExp('\\S'); +export const invitationTermsTechStackItemMax = 100; + + +export const invitationTermsTechStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const invitationTermsTechStackMax = 30; + +export const invitationTermsWorkFormatsMax = 3; + +export const invitationTermsLocationOneMax = 100; + + +export const invitationTermsLocationOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const invitationTermsCommunicationMethodDetailsOneMax = 300; + + +export const invitationTermsCommunicationMethodDetailsOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const invitationTermsSalarySalaryFromMin = 1000; +export const invitationTermsSalarySalaryFromMax = 100000000; +export const invitationTermsSalarySalaryFromMultipleOf = 1000; + +export const invitationTermsSalarySalaryToMin = 1000; +export const invitationTermsSalarySalaryToMax = 100000000; +export const invitationTermsSalarySalaryToMultipleOf = 1000; + +export const invitationTermsPackageBonusOneDescriptionMax = 300; + + +export const invitationTermsPackageBonusOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const invitationTermsPackageEquipmentOneDescriptionMax = 300; + + +export const invitationTermsPackageEquipmentOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const invitationTermsPackageTrainingOneDescriptionMax = 300; + + +export const invitationTermsPackageTrainingOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const invitationTermsPackageHealthInsuranceOneDescriptionMax = 300; + + +export const invitationTermsPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); + +export const InvitationTerms = zod.object({ + "role_title": zod.string().min(1).max(invitationTermsRoleTitleMax).regex(invitationTermsRoleTitleRegExp).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(invitationTermsTasksItemMax).regex(invitationTermsTasksItemRegExp).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(invitationTermsTasksMax).describe('Work tasks of the role in the order given.'), + "team": zod.string().min(1).max(invitationTermsTeamMax).regex(invitationTermsTeamRegExp).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(invitationTermsTechStackItemMax).regex(invitationTermsTechStackItemRegExp).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(invitationTermsTechStackMax).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(invitationTermsWorkFormatsMax).describe('Work formats the organization offers; the candidate may choose any of them.'), + "location": zod.union([zod.string().min(1).max(invitationTermsLocationOneMax).regex(invitationTermsLocationOneRegExp).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(invitationTermsCommunicationMethodDetailsOneMax).regex(invitationTermsCommunicationMethodDetailsOneRegExp).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(invitationTermsSalarySalaryFromMin).max(invitationTermsSalarySalaryFromMax).multipleOf(invitationTermsSalarySalaryFromMultipleOf).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(invitationTermsSalarySalaryToMin).max(invitationTermsSalarySalaryToMax).multipleOf(invitationTermsSalarySalaryToMultipleOf).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(invitationTermsPackageBonusOneDescriptionMax).regex(invitationTermsPackageBonusOneDescriptionRegExp).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(invitationTermsPackageEquipmentOneDescriptionMax).regex(invitationTermsPackageEquipmentOneDescriptionRegExp).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(invitationTermsPackageTrainingOneDescriptionMax).regex(invitationTermsPackageTrainingOneDescriptionRegExp).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(invitationTermsPackageHealthInsuranceOneDescriptionMax).regex(invitationTermsPackageHealthInsuranceOneDescriptionRegExp).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.') + +export type InvitationTerms = zod.input; +export type InvitationTermsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationTermsVersion.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationTermsVersion.zod.ts new file mode 100644 index 0000000..7eb891e --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationTermsVersion.zod.ts @@ -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 InvitationTermsVersion = 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.') + +export type InvitationTermsVersion = zod.input; +export type InvitationTermsVersionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/invitationVersion.zod.ts b/frontend/src/shared/api/schemas/invitation/invitationVersion.zod.ts new file mode 100644 index 0000000..d45631e --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/invitationVersion.zod.ts @@ -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 InvitationVersion = 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.') + +export type InvitationVersion = zod.input; +export type InvitationVersionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/listMyInvitationsParams.zod.ts b/frontend/src/shared/api/schemas/invitation/listMyInvitationsParams.zod.ts new file mode 100644 index 0000000..e1a767a --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/listMyInvitationsParams.zod.ts @@ -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 listMyInvitationsParamsLimitDefault = 20; +export const listMyInvitationsParamsLimitMax = 100; + +export const listMyInvitationsParamsCursorMax = 512; + + +export const listMyInvitationsParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const ListMyInvitationsParams = zod.object({ + "limit": zod.int().min(1).max(listMyInvitationsParamsLimitMax).default(listMyInvitationsParamsLimitDefault), + "cursor": zod.string().min(1).max(listMyInvitationsParamsCursorMax).regex(listMyInvitationsParamsCursorRegExp).exactOptional() +}) + +export type ListMyInvitationsParams = zod.input; +export type ListMyInvitationsParamsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/listOrganizationInvitationsParams.zod.ts b/frontend/src/shared/api/schemas/invitation/listOrganizationInvitationsParams.zod.ts new file mode 100644 index 0000000..df01111 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/listOrganizationInvitationsParams.zod.ts @@ -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 listOrganizationInvitationsParamsLimitDefault = 20; +export const listOrganizationInvitationsParamsLimitMax = 100; + +export const listOrganizationInvitationsParamsCursorMax = 512; + + +export const listOrganizationInvitationsParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const ListOrganizationInvitationsParams = zod.object({ + "limit": zod.int().min(1).max(listOrganizationInvitationsParamsLimitMax).default(listOrganizationInvitationsParamsLimitDefault), + "cursor": zod.string().min(1).max(listOrganizationInvitationsParamsCursorMax).regex(listOrganizationInvitationsParamsCursorRegExp).exactOptional() +}) + +export type ListOrganizationInvitationsParams = zod.input; +export type ListOrganizationInvitationsParamsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/organizationInvitation.zod.ts b/frontend/src/shared/api/schemas/invitation/organizationInvitation.zod.ts new file mode 100644 index 0000000..bb8cc52 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/organizationInvitation.zod.ts @@ -0,0 +1,149 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const organizationInvitationCandidateHandleMax = 128; + + +export const organizationInvitationCandidateHandleRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + + + +export const organizationInvitationTermsRoleTitleMax = 200; + + +export const organizationInvitationTermsRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationTermsTasksItemMax = 300; + + +export const organizationInvitationTermsTasksItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationTermsTasksMax = 20; + +export const organizationInvitationTermsTeamMax = 1000; + + +export const organizationInvitationTermsTeamRegExp = new RegExp('\\S'); +export const organizationInvitationTermsTechStackItemMax = 100; + + +export const organizationInvitationTermsTechStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationTermsTechStackMax = 30; + +export const organizationInvitationTermsWorkFormatsMax = 3; + +export const organizationInvitationTermsLocationOneMax = 100; + + +export const organizationInvitationTermsLocationOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationTermsCommunicationMethodDetailsOneMax = 300; + + +export const organizationInvitationTermsCommunicationMethodDetailsOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationTermsSalarySalaryFromMin = 1000; +export const organizationInvitationTermsSalarySalaryFromMax = 100000000; +export const organizationInvitationTermsSalarySalaryFromMultipleOf = 1000; + +export const organizationInvitationTermsSalarySalaryToMin = 1000; +export const organizationInvitationTermsSalarySalaryToMax = 100000000; +export const organizationInvitationTermsSalarySalaryToMultipleOf = 1000; + +export const organizationInvitationTermsPackageBonusOneDescriptionMax = 300; + + +export const organizationInvitationTermsPackageBonusOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationTermsPackageEquipmentOneDescriptionMax = 300; + + +export const organizationInvitationTermsPackageEquipmentOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationTermsPackageTrainingOneDescriptionMax = 300; + + +export const organizationInvitationTermsPackageTrainingOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationTermsPackageHealthInsuranceOneDescriptionMax = 300; + + +export const organizationInvitationTermsPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationContactAccessFieldsMax = 4; + + +export const OrganizationInvitation = zod.object({ + "id": zod.uuid().describe('Identifier of the invitation.'), + "organization_id": zod.uuid().describe('Organization that owns the invitation, equal to `org_id` of the path. It never changes.'), + "candidate_handle": zod.string().min(1).max(organizationInvitationCandidateHandleMax).regex(organizationInvitationCandidateHandleRegExp).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()]).describe('Need the invitation was built from, or null for a direct invitation.'), + "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()]).describe('Reason of an expiry, or null unless `state` is `expired`.'), + "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(organizationInvitationTermsRoleTitleMax).regex(organizationInvitationTermsRoleTitleRegExp).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(organizationInvitationTermsTasksItemMax).regex(organizationInvitationTermsTasksItemRegExp).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(organizationInvitationTermsTasksMax).describe('Work tasks of the role in the order given.'), + "team": zod.string().min(1).max(organizationInvitationTermsTeamMax).regex(organizationInvitationTermsTeamRegExp).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(organizationInvitationTermsTechStackItemMax).regex(organizationInvitationTermsTechStackItemRegExp).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(organizationInvitationTermsTechStackMax).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(organizationInvitationTermsWorkFormatsMax).describe('Work formats the organization offers; the candidate may choose any of them.'), + "location": zod.union([zod.string().min(1).max(organizationInvitationTermsLocationOneMax).regex(organizationInvitationTermsLocationOneRegExp).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(organizationInvitationTermsCommunicationMethodDetailsOneMax).regex(organizationInvitationTermsCommunicationMethodDetailsOneRegExp).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(organizationInvitationTermsSalarySalaryFromMin).max(organizationInvitationTermsSalarySalaryFromMax).multipleOf(organizationInvitationTermsSalarySalaryFromMultipleOf).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(organizationInvitationTermsSalarySalaryToMin).max(organizationInvitationTermsSalarySalaryToMax).multipleOf(organizationInvitationTermsSalarySalaryToMultipleOf).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(organizationInvitationTermsPackageBonusOneDescriptionMax).regex(organizationInvitationTermsPackageBonusOneDescriptionRegExp).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(organizationInvitationTermsPackageEquipmentOneDescriptionMax).regex(organizationInvitationTermsPackageEquipmentOneDescriptionRegExp).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(organizationInvitationTermsPackageTrainingOneDescriptionMax).regex(organizationInvitationTermsPackageTrainingOneDescriptionRegExp).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(organizationInvitationTermsPackageHealthInsuranceOneDescriptionMax).regex(organizationInvitationTermsPackageHealthInsuranceOneDescriptionRegExp).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_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.'), + "response_deadline_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 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.'), + "salary_raise_used": zod.boolean().describe('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": zod.enum(['within_range', 'up_to_10_percent_above', 'above', 'withheld', 'not_available']).describe('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.\n\n- within_range: the minimum is not above `B`.\n- up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`.\n- above: the minimum is more than 10% above `B`.\n- 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.\n- not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis.\n\nEvery 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.\n\nThe server never rejects or changes a range because of the minimum: a rejection would itself reveal it.'), + "contact_access": 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(organizationInvitationContactAccessFieldsMax).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.'), + "created_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.'), + "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.'), + "delivered_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 delivery to the candidate\'s inbox, or null for a draft.'), + "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 when the candidate first opened the terms, or null.'), + "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()]).describe('Moment of the candidate\'s acceptance or decline, or null.') +}).describe('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.') + +export type OrganizationInvitation = zod.input; +export type OrganizationInvitationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/organizationInvitationCreate.zod.ts b/frontend/src/shared/api/schemas/invitation/organizationInvitationCreate.zod.ts new file mode 100644 index 0000000..46f26ef --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/organizationInvitationCreate.zod.ts @@ -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 organizationInvitationCreateCandidateHandleMax = 128; + + +export const organizationInvitationCreateCandidateHandleRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const organizationInvitationCreateTermsRoleTitleMax = 200; + + +export const organizationInvitationCreateTermsRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationCreateTermsTasksItemMax = 300; + + +export const organizationInvitationCreateTermsTasksItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationCreateTermsTasksMax = 20; + +export const organizationInvitationCreateTermsTeamMax = 1000; + + +export const organizationInvitationCreateTermsTeamRegExp = new RegExp('\\S'); +export const organizationInvitationCreateTermsTechStackItemMax = 100; + + +export const organizationInvitationCreateTermsTechStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationCreateTermsTechStackMax = 30; + +export const organizationInvitationCreateTermsWorkFormatsMax = 3; + +export const organizationInvitationCreateTermsLocationOneMax = 100; + + +export const organizationInvitationCreateTermsLocationOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationCreateTermsCommunicationMethodDetailsOneMax = 300; + + +export const organizationInvitationCreateTermsCommunicationMethodDetailsOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationCreateTermsSalarySalaryFromMin = 1000; +export const organizationInvitationCreateTermsSalarySalaryFromMax = 100000000; +export const organizationInvitationCreateTermsSalarySalaryFromMultipleOf = 1000; + +export const organizationInvitationCreateTermsSalarySalaryToMin = 1000; +export const organizationInvitationCreateTermsSalarySalaryToMax = 100000000; +export const organizationInvitationCreateTermsSalarySalaryToMultipleOf = 1000; + +export const organizationInvitationCreateTermsPackageBonusOneDescriptionMax = 300; + + +export const organizationInvitationCreateTermsPackageBonusOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationCreateTermsPackageEquipmentOneDescriptionMax = 300; + + +export const organizationInvitationCreateTermsPackageEquipmentOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationCreateTermsPackageTrainingOneDescriptionMax = 300; + + +export const organizationInvitationCreateTermsPackageTrainingOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationCreateTermsPackageHealthInsuranceOneDescriptionMax = 300; + + +export const organizationInvitationCreateTermsPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); + +export const OrganizationInvitationCreate = zod.object({ + "candidate_handle": zod.string().min(1).max(organizationInvitationCreateCandidateHandleMax).regex(organizationInvitationCreateCandidateHandleRegExp).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(organizationInvitationCreateTermsRoleTitleMax).regex(organizationInvitationCreateTermsRoleTitleRegExp).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(organizationInvitationCreateTermsTasksItemMax).regex(organizationInvitationCreateTermsTasksItemRegExp).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(organizationInvitationCreateTermsTasksMax).describe('Work tasks of the role in the order given.'), + "team": zod.string().min(1).max(organizationInvitationCreateTermsTeamMax).regex(organizationInvitationCreateTermsTeamRegExp).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(organizationInvitationCreateTermsTechStackItemMax).regex(organizationInvitationCreateTermsTechStackItemRegExp).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(organizationInvitationCreateTermsTechStackMax).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(organizationInvitationCreateTermsWorkFormatsMax).describe('Work formats the organization offers; the candidate may choose any of them.'), + "location": zod.union([zod.string().min(1).max(organizationInvitationCreateTermsLocationOneMax).regex(organizationInvitationCreateTermsLocationOneRegExp).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(organizationInvitationCreateTermsCommunicationMethodDetailsOneMax).regex(organizationInvitationCreateTermsCommunicationMethodDetailsOneRegExp).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(organizationInvitationCreateTermsSalarySalaryFromMin).max(organizationInvitationCreateTermsSalarySalaryFromMax).multipleOf(organizationInvitationCreateTermsSalarySalaryFromMultipleOf).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(organizationInvitationCreateTermsSalarySalaryToMin).max(organizationInvitationCreateTermsSalarySalaryToMax).multipleOf(organizationInvitationCreateTermsSalarySalaryToMultipleOf).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(organizationInvitationCreateTermsPackageBonusOneDescriptionMax).regex(organizationInvitationCreateTermsPackageBonusOneDescriptionRegExp).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(organizationInvitationCreateTermsPackageEquipmentOneDescriptionMax).regex(organizationInvitationCreateTermsPackageEquipmentOneDescriptionRegExp).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(organizationInvitationCreateTermsPackageTrainingOneDescriptionMax).regex(organizationInvitationCreateTermsPackageTrainingOneDescriptionRegExp).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(organizationInvitationCreateTermsPackageHealthInsuranceOneDescriptionMax).regex(organizationInvitationCreateTermsPackageHealthInsuranceOneDescriptionRegExp).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 OrganizationInvitationCreate = zod.input; +export type OrganizationInvitationCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/organizationInvitationList.zod.ts b/frontend/src/shared/api/schemas/invitation/organizationInvitationList.zod.ts new file mode 100644 index 0000000..f80cc34 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/organizationInvitationList.zod.ts @@ -0,0 +1,72 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const organizationInvitationListItemsItemCandidateHandleMax = 128; + + +export const organizationInvitationListItemsItemCandidateHandleRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + + + +export const organizationInvitationListItemsItemRoleTitleMax = 200; + + +export const organizationInvitationListItemsItemRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationListItemsItemSalarySalaryFromMin = 1000; +export const organizationInvitationListItemsItemSalarySalaryFromMax = 100000000; +export const organizationInvitationListItemsItemSalarySalaryFromMultipleOf = 1000; + +export const organizationInvitationListItemsItemSalarySalaryToMin = 1000; +export const organizationInvitationListItemsItemSalarySalaryToMax = 100000000; +export const organizationInvitationListItemsItemSalarySalaryToMultipleOf = 1000; + +export const organizationInvitationListItemsItemContactAccessFieldsMax = 4; + +export const organizationInvitationListItemsMax = 100; + +export const organizationInvitationListPageNextCursorMax = 512; + + +export const organizationInvitationListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const OrganizationInvitationList = zod.object({ + "items": zod.array(zod.object({ + "id": zod.uuid().describe('Identifier of the invitation.'), + "candidate_handle": zod.string().min(1).max(organizationInvitationListItemsItemCandidateHandleMax).regex(organizationInvitationListItemsItemCandidateHandleRegExp).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()]), + "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(organizationInvitationListItemsItemRoleTitleMax).regex(organizationInvitationListItemsItemRoleTitleRegExp).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(organizationInvitationListItemsItemSalarySalaryFromMin).max(organizationInvitationListItemsItemSalarySalaryFromMax).multipleOf(organizationInvitationListItemsItemSalarySalaryFromMultipleOf).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(organizationInvitationListItemsItemSalarySalaryToMin).max(organizationInvitationListItemsItemSalarySalaryToMax).multipleOf(organizationInvitationListItemsItemSalarySalaryToMultipleOf).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.'), + "response_deadline_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()]), + "contact_access": 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(organizationInvitationListItemsItemContactAccessFieldsMax).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.'), + "created_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.'), + "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 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.')).max(organizationInvitationListItemsMax).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(organizationInvitationListPageNextCursorMax).regex(organizationInvitationListPageNextCursorRegExp).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 invitations of an organization, newest first by creation time.') + +export type OrganizationInvitationList = zod.input; +export type OrganizationInvitationListOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/organizationInvitationSummary.zod.ts b/frontend/src/shared/api/schemas/invitation/organizationInvitationSummary.zod.ts new file mode 100644 index 0000000..56b9c3e --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/organizationInvitationSummary.zod.ts @@ -0,0 +1,60 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const organizationInvitationSummaryCandidateHandleMax = 128; + + +export const organizationInvitationSummaryCandidateHandleRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + + + +export const organizationInvitationSummaryRoleTitleMax = 200; + + +export const organizationInvitationSummaryRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationSummarySalarySalaryFromMin = 1000; +export const organizationInvitationSummarySalarySalaryFromMax = 100000000; +export const organizationInvitationSummarySalarySalaryFromMultipleOf = 1000; + +export const organizationInvitationSummarySalarySalaryToMin = 1000; +export const organizationInvitationSummarySalarySalaryToMax = 100000000; +export const organizationInvitationSummarySalarySalaryToMultipleOf = 1000; + +export const organizationInvitationSummaryContactAccessFieldsMax = 4; + + +export const OrganizationInvitationSummary = zod.object({ + "id": zod.uuid().describe('Identifier of the invitation.'), + "candidate_handle": zod.string().min(1).max(organizationInvitationSummaryCandidateHandleMax).regex(organizationInvitationSummaryCandidateHandleRegExp).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()]), + "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(organizationInvitationSummaryRoleTitleMax).regex(organizationInvitationSummaryRoleTitleRegExp).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(organizationInvitationSummarySalarySalaryFromMin).max(organizationInvitationSummarySalarySalaryFromMax).multipleOf(organizationInvitationSummarySalarySalaryFromMultipleOf).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(organizationInvitationSummarySalarySalaryToMin).max(organizationInvitationSummarySalarySalaryToMax).multipleOf(organizationInvitationSummarySalarySalaryToMultipleOf).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.'), + "response_deadline_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()]), + "contact_access": 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(organizationInvitationSummaryContactAccessFieldsMax).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.'), + "created_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.'), + "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 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.') + +export type OrganizationInvitationSummary = zod.input; +export type OrganizationInvitationSummaryOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/organizationInvitationUpdate.zod.ts b/frontend/src/shared/api/schemas/invitation/organizationInvitationUpdate.zod.ts new file mode 100644 index 0000000..fa54565 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/organizationInvitationUpdate.zod.ts @@ -0,0 +1,124 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const organizationInvitationUpdateTermsRoleTitleMax = 200; + + +export const organizationInvitationUpdateTermsRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationUpdateTermsTasksItemMax = 300; + + +export const organizationInvitationUpdateTermsTasksItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationUpdateTermsTasksMax = 20; + +export const organizationInvitationUpdateTermsTeamMax = 1000; + + +export const organizationInvitationUpdateTermsTeamRegExp = new RegExp('\\S'); +export const organizationInvitationUpdateTermsTechStackItemMax = 100; + + +export const organizationInvitationUpdateTermsTechStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationUpdateTermsTechStackMax = 30; + +export const organizationInvitationUpdateTermsWorkFormatsMax = 3; + +export const organizationInvitationUpdateTermsLocationOneMax = 100; + + +export const organizationInvitationUpdateTermsLocationOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationUpdateTermsCommunicationMethodDetailsOneMax = 300; + + +export const organizationInvitationUpdateTermsCommunicationMethodDetailsOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationUpdateTermsSalarySalaryFromMin = 1000; +export const organizationInvitationUpdateTermsSalarySalaryFromMax = 100000000; +export const organizationInvitationUpdateTermsSalarySalaryFromMultipleOf = 1000; + +export const organizationInvitationUpdateTermsSalarySalaryToMin = 1000; +export const organizationInvitationUpdateTermsSalarySalaryToMax = 100000000; +export const organizationInvitationUpdateTermsSalarySalaryToMultipleOf = 1000; + +export const organizationInvitationUpdateTermsPackageBonusOneDescriptionMax = 300; + + +export const organizationInvitationUpdateTermsPackageBonusOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationUpdateTermsPackageEquipmentOneDescriptionMax = 300; + + +export const organizationInvitationUpdateTermsPackageEquipmentOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationUpdateTermsPackageTrainingOneDescriptionMax = 300; + + +export const organizationInvitationUpdateTermsPackageTrainingOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const organizationInvitationUpdateTermsPackageHealthInsuranceOneDescriptionMax = 300; + + +export const organizationInvitationUpdateTermsPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); + +export const OrganizationInvitationUpdate = 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.'), + "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(), + "response_period_days": zod.union([zod.literal(3),zod.literal(7),zod.literal(14)]).exactOptional().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.'), + "terms": zod.object({ + "role_title": zod.string().min(1).max(organizationInvitationUpdateTermsRoleTitleMax).regex(organizationInvitationUpdateTermsRoleTitleRegExp).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(organizationInvitationUpdateTermsTasksItemMax).regex(organizationInvitationUpdateTermsTasksItemRegExp).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(organizationInvitationUpdateTermsTasksMax).describe('Work tasks of the role in the order given.'), + "team": zod.string().min(1).max(organizationInvitationUpdateTermsTeamMax).regex(organizationInvitationUpdateTermsTeamRegExp).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(organizationInvitationUpdateTermsTechStackItemMax).regex(organizationInvitationUpdateTermsTechStackItemRegExp).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(organizationInvitationUpdateTermsTechStackMax).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(organizationInvitationUpdateTermsWorkFormatsMax).describe('Work formats the organization offers; the candidate may choose any of them.'), + "location": zod.union([zod.string().min(1).max(organizationInvitationUpdateTermsLocationOneMax).regex(organizationInvitationUpdateTermsLocationOneRegExp).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(organizationInvitationUpdateTermsCommunicationMethodDetailsOneMax).regex(organizationInvitationUpdateTermsCommunicationMethodDetailsOneRegExp).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(organizationInvitationUpdateTermsSalarySalaryFromMin).max(organizationInvitationUpdateTermsSalarySalaryFromMax).multipleOf(organizationInvitationUpdateTermsSalarySalaryFromMultipleOf).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(organizationInvitationUpdateTermsSalarySalaryToMin).max(organizationInvitationUpdateTermsSalarySalaryToMax).multipleOf(organizationInvitationUpdateTermsSalarySalaryToMultipleOf).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(organizationInvitationUpdateTermsPackageBonusOneDescriptionMax).regex(organizationInvitationUpdateTermsPackageBonusOneDescriptionRegExp).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(organizationInvitationUpdateTermsPackageEquipmentOneDescriptionMax).regex(organizationInvitationUpdateTermsPackageEquipmentOneDescriptionRegExp).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(organizationInvitationUpdateTermsPackageTrainingOneDescriptionMax).regex(organizationInvitationUpdateTermsPackageTrainingOneDescriptionRegExp).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(organizationInvitationUpdateTermsPackageHealthInsuranceOneDescriptionMax).regex(organizationInvitationUpdateTermsPackageHealthInsuranceOneDescriptionRegExp).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.') +}).exactOptional().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('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.') + +export type OrganizationInvitationUpdate = zod.input; +export type OrganizationInvitationUpdateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/raiseOrganizationInvitationSalaryBody.zod.ts b/frontend/src/shared/api/schemas/invitation/raiseOrganizationInvitationSalaryBody.zod.ts new file mode 100644 index 0000000..8905f13 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/raiseOrganizationInvitationSalaryBody.zod.ts @@ -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 raiseOrganizationInvitationSalaryBodySalaryToOneMin = 1000; +export const raiseOrganizationInvitationSalaryBodySalaryToOneMax = 100000000; +export const raiseOrganizationInvitationSalaryBodySalaryToOneMultipleOf = 1000; + + +export const RaiseOrganizationInvitationSalaryBody = 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.'), + "salary_to": zod.int().min(raiseOrganizationInvitationSalaryBodySalaryToOneMin).max(raiseOrganizationInvitationSalaryBodySalaryToOneMax).multipleOf(raiseOrganizationInvitationSalaryBodySalaryToOneMultipleOf).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.').describe('New upper bound, above the current one, with a width of the range from 10% to 40% of its midpoint.') +}).describe('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.') + +export type RaiseOrganizationInvitationSalaryBody = zod.input; +export type RaiseOrganizationInvitationSalaryBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/raiseOrganizationInvitationSalaryHeaders.zod.ts b/frontend/src/shared/api/schemas/invitation/raiseOrganizationInvitationSalaryHeaders.zod.ts new file mode 100644 index 0000000..40c9b8f --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/raiseOrganizationInvitationSalaryHeaders.zod.ts @@ -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 raiseOrganizationInvitationSalaryHeadersIdempotencyKeyMax = 255; + + +export const raiseOrganizationInvitationSalaryHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const RaiseOrganizationInvitationSalaryHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(raiseOrganizationInvitationSalaryHeadersIdempotencyKeyMax).regex(raiseOrganizationInvitationSalaryHeadersIdempotencyKeyRegExp) +}) + +export type RaiseOrganizationInvitationSalaryHeaders = zod.input; +export type RaiseOrganizationInvitationSalaryHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/sendOrganizationInvitationBody.zod.ts b/frontend/src/shared/api/schemas/invitation/sendOrganizationInvitationBody.zod.ts new file mode 100644 index 0000000..ddcb01a --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/sendOrganizationInvitationBody.zod.ts @@ -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 SendOrganizationInvitationBody = 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 SendOrganizationInvitationBody = zod.input; +export type SendOrganizationInvitationBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/sendOrganizationInvitationHeaders.zod.ts b/frontend/src/shared/api/schemas/invitation/sendOrganizationInvitationHeaders.zod.ts new file mode 100644 index 0000000..4041a54 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/sendOrganizationInvitationHeaders.zod.ts @@ -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 sendOrganizationInvitationHeadersIdempotencyKeyMax = 255; + + +export const sendOrganizationInvitationHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const SendOrganizationInvitationHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(sendOrganizationInvitationHeadersIdempotencyKeyMax).regex(sendOrganizationInvitationHeadersIdempotencyKeyRegExp) +}) + +export type SendOrganizationInvitationHeaders = zod.input; +export type SendOrganizationInvitationHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/updateOrganizationInvitationBody.zod.ts b/frontend/src/shared/api/schemas/invitation/updateOrganizationInvitationBody.zod.ts new file mode 100644 index 0000000..75721a6 --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/updateOrganizationInvitationBody.zod.ts @@ -0,0 +1,124 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + + + +export const updateOrganizationInvitationBodyTermsRoleTitleMax = 200; + + +export const updateOrganizationInvitationBodyTermsRoleTitleRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const updateOrganizationInvitationBodyTermsTasksItemMax = 300; + + +export const updateOrganizationInvitationBodyTermsTasksItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const updateOrganizationInvitationBodyTermsTasksMax = 20; + +export const updateOrganizationInvitationBodyTermsTeamMax = 1000; + + +export const updateOrganizationInvitationBodyTermsTeamRegExp = new RegExp('\\S'); +export const updateOrganizationInvitationBodyTermsTechStackItemMax = 100; + + +export const updateOrganizationInvitationBodyTermsTechStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const updateOrganizationInvitationBodyTermsTechStackMax = 30; + +export const updateOrganizationInvitationBodyTermsWorkFormatsMax = 3; + +export const updateOrganizationInvitationBodyTermsLocationOneMax = 100; + + +export const updateOrganizationInvitationBodyTermsLocationOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const updateOrganizationInvitationBodyTermsCommunicationMethodDetailsOneMax = 300; + + +export const updateOrganizationInvitationBodyTermsCommunicationMethodDetailsOneRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const updateOrganizationInvitationBodyTermsSalarySalaryFromMin = 1000; +export const updateOrganizationInvitationBodyTermsSalarySalaryFromMax = 100000000; +export const updateOrganizationInvitationBodyTermsSalarySalaryFromMultipleOf = 1000; + +export const updateOrganizationInvitationBodyTermsSalarySalaryToMin = 1000; +export const updateOrganizationInvitationBodyTermsSalarySalaryToMax = 100000000; +export const updateOrganizationInvitationBodyTermsSalarySalaryToMultipleOf = 1000; + +export const updateOrganizationInvitationBodyTermsPackageBonusOneDescriptionMax = 300; + + +export const updateOrganizationInvitationBodyTermsPackageBonusOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const updateOrganizationInvitationBodyTermsPackageEquipmentOneDescriptionMax = 300; + + +export const updateOrganizationInvitationBodyTermsPackageEquipmentOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const updateOrganizationInvitationBodyTermsPackageTrainingOneDescriptionMax = 300; + + +export const updateOrganizationInvitationBodyTermsPackageTrainingOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const updateOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescriptionMax = 300; + + +export const updateOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescriptionRegExp = new RegExp('^\\S(?:.*\\S)?$'); + +export const UpdateOrganizationInvitationBody = 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.'), + "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(), + "response_period_days": zod.union([zod.literal(3),zod.literal(7),zod.literal(14)]).exactOptional().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.'), + "terms": zod.object({ + "role_title": zod.string().min(1).max(updateOrganizationInvitationBodyTermsRoleTitleMax).regex(updateOrganizationInvitationBodyTermsRoleTitleRegExp).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(updateOrganizationInvitationBodyTermsTasksItemMax).regex(updateOrganizationInvitationBodyTermsTasksItemRegExp).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(updateOrganizationInvitationBodyTermsTasksMax).describe('Work tasks of the role in the order given.'), + "team": zod.string().min(1).max(updateOrganizationInvitationBodyTermsTeamMax).regex(updateOrganizationInvitationBodyTermsTeamRegExp).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(updateOrganizationInvitationBodyTermsTechStackItemMax).regex(updateOrganizationInvitationBodyTermsTechStackItemRegExp).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(updateOrganizationInvitationBodyTermsTechStackMax).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(updateOrganizationInvitationBodyTermsWorkFormatsMax).describe('Work formats the organization offers; the candidate may choose any of them.'), + "location": zod.union([zod.string().min(1).max(updateOrganizationInvitationBodyTermsLocationOneMax).regex(updateOrganizationInvitationBodyTermsLocationOneRegExp).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(updateOrganizationInvitationBodyTermsCommunicationMethodDetailsOneMax).regex(updateOrganizationInvitationBodyTermsCommunicationMethodDetailsOneRegExp).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(updateOrganizationInvitationBodyTermsSalarySalaryFromMin).max(updateOrganizationInvitationBodyTermsSalarySalaryFromMax).multipleOf(updateOrganizationInvitationBodyTermsSalarySalaryFromMultipleOf).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(updateOrganizationInvitationBodyTermsSalarySalaryToMin).max(updateOrganizationInvitationBodyTermsSalarySalaryToMax).multipleOf(updateOrganizationInvitationBodyTermsSalarySalaryToMultipleOf).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(updateOrganizationInvitationBodyTermsPackageBonusOneDescriptionMax).regex(updateOrganizationInvitationBodyTermsPackageBonusOneDescriptionRegExp).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(updateOrganizationInvitationBodyTermsPackageEquipmentOneDescriptionMax).regex(updateOrganizationInvitationBodyTermsPackageEquipmentOneDescriptionRegExp).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(updateOrganizationInvitationBodyTermsPackageTrainingOneDescriptionMax).regex(updateOrganizationInvitationBodyTermsPackageTrainingOneDescriptionRegExp).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(updateOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescriptionMax).regex(updateOrganizationInvitationBodyTermsPackageHealthInsuranceOneDescriptionRegExp).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.') +}).exactOptional().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('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.') + +export type UpdateOrganizationInvitationBody = zod.input; +export type UpdateOrganizationInvitationBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/withdrawOrganizationInvitationBody.zod.ts b/frontend/src/shared/api/schemas/invitation/withdrawOrganizationInvitationBody.zod.ts new file mode 100644 index 0000000..abaec6c --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/withdrawOrganizationInvitationBody.zod.ts @@ -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 WithdrawOrganizationInvitationBody = 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 WithdrawOrganizationInvitationBody = zod.input; +export type WithdrawOrganizationInvitationBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/invitation/withdrawOrganizationInvitationHeaders.zod.ts b/frontend/src/shared/api/schemas/invitation/withdrawOrganizationInvitationHeaders.zod.ts new file mode 100644 index 0000000..c8ecd1f --- /dev/null +++ b/frontend/src/shared/api/schemas/invitation/withdrawOrganizationInvitationHeaders.zod.ts @@ -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 withdrawOrganizationInvitationHeadersIdempotencyKeyMax = 255; + + +export const withdrawOrganizationInvitationHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const WithdrawOrganizationInvitationHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(withdrawOrganizationInvitationHeadersIdempotencyKeyMax).regex(withdrawOrganizationInvitationHeadersIdempotencyKeyRegExp) +}) + +export type WithdrawOrganizationInvitationHeaders = zod.input; +export type WithdrawOrganizationInvitationHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/need/index.ts b/frontend/src/shared/api/schemas/need/index.ts index 9b233bd..806bb5c 100644 --- a/frontend/src/shared/api/schemas/need/index.ts +++ b/frontend/src/shared/api/schemas/need/index.ts @@ -7,7 +7,6 @@ export * from './createOrganizationNeedBody.zod'; export * from './createOrganizationNeedHeaders.zod'; -export * from './currencyCode.zod'; export * from './listOrganizationNeedsParams.zod'; export * from './need.zod'; export * from './needCategoryRecommendation.zod'; @@ -23,7 +22,6 @@ export * from './needItemStatus.zod'; export * from './needList.zod'; export * from './needLocation.zod'; export * from './needLocationInput.zod'; -export * from './needLocationName.zod'; export * from './needMissingField.zod'; export * from './needMissingReason.zod'; export * from './needMoneyFit.zod'; @@ -45,20 +43,13 @@ export * from './needSummary.zod'; export * from './needSupplyBand.zod'; export * from './needTask.zod'; export * from './needTaskInput.zod'; -export * from './needTaskText.zod'; export * from './needTitle.zod'; export * from './needUpdate.zod'; export * from './needValueOrigin.zod'; export * from './needValueSource.zod'; export * from './needValueStatus.zod'; -export * from './needVersion.zod'; export * from './needVersionLabel.zod'; export * from './needWorkFormats.zod'; export * from './needWorkFormatsInput.zod'; -export * from './rubAmount.zod'; -export * from './salaryPeriod.zod'; -export * from './salaryRange.zod'; -export * from './salaryTaxBasis.zod'; -export * from './skillName.zod'; export * from './skillTaxonomyCode.zod'; export * from './updateOrganizationNeedBody.zod'; diff --git a/frontend/src/shared/api/schemas/need/needLocationName.zod.ts b/frontend/src/shared/api/schemas/needLocationName.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/needLocationName.zod.ts rename to frontend/src/shared/api/schemas/needLocationName.zod.ts diff --git a/frontend/src/shared/api/schemas/need/needTaskText.zod.ts b/frontend/src/shared/api/schemas/needTaskText.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/needTaskText.zod.ts rename to frontend/src/shared/api/schemas/needTaskText.zod.ts diff --git a/frontend/src/shared/api/schemas/need/needVersion.zod.ts b/frontend/src/shared/api/schemas/needVersion.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/needVersion.zod.ts rename to frontend/src/shared/api/schemas/needVersion.zod.ts diff --git a/frontend/src/shared/api/schemas/need/rubAmount.zod.ts b/frontend/src/shared/api/schemas/rubAmount.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/rubAmount.zod.ts rename to frontend/src/shared/api/schemas/rubAmount.zod.ts diff --git a/frontend/src/shared/api/schemas/need/salaryPeriod.zod.ts b/frontend/src/shared/api/schemas/salaryPeriod.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/salaryPeriod.zod.ts rename to frontend/src/shared/api/schemas/salaryPeriod.zod.ts diff --git a/frontend/src/shared/api/schemas/need/salaryRange.zod.ts b/frontend/src/shared/api/schemas/salaryRange.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/salaryRange.zod.ts rename to frontend/src/shared/api/schemas/salaryRange.zod.ts diff --git a/frontend/src/shared/api/schemas/need/salaryTaxBasis.zod.ts b/frontend/src/shared/api/schemas/salaryTaxBasis.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/salaryTaxBasis.zod.ts rename to frontend/src/shared/api/schemas/salaryTaxBasis.zod.ts diff --git a/frontend/src/shared/api/schemas/need/skillName.zod.ts b/frontend/src/shared/api/schemas/skillName.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/skillName.zod.ts rename to frontend/src/shared/api/schemas/skillName.zod.ts diff --git a/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts b/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts index 1470e0e..209d86b 100644 --- a/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts +++ b/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts @@ -31,7 +31,7 @@ export const CreateMySupportCaseBody = zod.union([zod.object({ "type": zod.enum(['support']), "description": zod.string().min(1).max(createMySupportCaseBodyOneDescriptionMax).regex(createMySupportCaseBodyOneDescriptionRegExp).describe('What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people\'s contact data into it. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.'), "object": zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are not in the contract yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- 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.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).exactOptional().describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'), "assessment_target": zod.object({ diff --git a/frontend/src/shared/api/schemas/support/supportCase.zod.ts b/frontend/src/shared/api/schemas/support/supportCase.zod.ts index a34f15b..94c170e 100644 --- a/frontend/src/shared/api/schemas/support/supportCase.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCase.zod.ts @@ -34,7 +34,7 @@ export const SupportCase = zod.object({ "status": zod.enum(['submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed']).describe('Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value.\n\n- submitted: the case was accepted and waits in its queue.\n- in_review: support or a moderator works on it.\n- waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status.\n- waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time.\n- resolved: terminal; a decision was made and `decision` holds its outcome and public reason.\n- closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why.'), "description": zod.string().min(1).max(supportCaseDescriptionMax).regex(supportCaseDescriptionRegExp).describe('What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people\'s contact data into it. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.'), "object": zod.union([zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are not in the contract yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- 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.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'),zod.null()]).describe('Object that the case is about, as sent on creation, or null when the case has none.'), "assessment_target": zod.union([zod.object({ diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts index 3c6c4f8..84bbf24 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts @@ -31,7 +31,7 @@ export const SupportCaseCreate = zod.union([zod.object({ "type": zod.enum(['support']), "description": zod.string().min(1).max(supportCaseCreateOneDescriptionMax).regex(supportCaseCreateOneDescriptionRegExp).describe('What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people\'s contact data into it. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.'), "object": zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are not in the contract yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- 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.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).exactOptional().describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'), "assessment_target": zod.object({ diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts index b9c3ee8..f9a2875 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts @@ -15,7 +15,7 @@ export const SupportCaseCreateSupport = zod.object({ "type": zod.enum(['support']), "description": zod.string().min(1).max(supportCaseCreateSupportDescriptionMax).regex(supportCaseCreateSupportDescriptionRegExp).describe('What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people\'s contact data into it. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.'), "object": zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are not in the contract yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- 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.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).exactOptional().describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'), "assessment_target": zod.object({ diff --git a/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts index f0186d6..0979403 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts @@ -28,7 +28,7 @@ export const SupportCaseList = zod.object({ "type": zod.enum(['support', 'complaint', 'grade_appeal', 'anticheat_appeal', 'manual_assessment']).describe('Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case.\n\n- support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts.\n- complaint: a complaint about an organization or an offer, including a breach of the salary terms or a disclosure of personal data (PRD FR18). Candidate accounts.\n- grade_appeal: an appeal of a category the caller received: the result of one own assessment attempt, or the outcome of one own resolved manual assessment case. An expert reviews it, and the original result stays in the history. Candidate accounts.\n- anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts.\n- manual_assessment: a request for a manual assessment of a category by a subject expert with the same rubric, the alternative to automated categorization (consent C3). Candidate accounts.'), "status": zod.enum(['submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed']).describe('Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value.\n\n- submitted: the case was accepted and waits in its queue.\n- in_review: support or a moderator works on it.\n- waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status.\n- waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time.\n- resolved: terminal; a decision was made and `decision` holds its outcome and public reason.\n- closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why.'), "object": zod.union([zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are not in the contract yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- 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.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'),zod.null()]).describe('Object that the case is about, or null.'), "assessment_target": zod.union([zod.object({ diff --git a/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts index f653be6..515acae 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts @@ -7,7 +7,7 @@ import * as zod from 'zod'; export const SupportCaseObjectReference = zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are not in the contract yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- 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.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.') diff --git a/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts index db78826..c86d0d9 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts @@ -6,7 +6,7 @@ */ import * as zod from 'zod'; -export const SupportCaseObjectType = zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are not in the contract yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.') +export const SupportCaseObjectType = zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- 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.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.') export type SupportCaseObjectType = zod.input; export type SupportCaseObjectTypeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts index d9fa66d..3ead3c9 100644 --- a/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts +++ b/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts @@ -21,7 +21,7 @@ export const SupportCaseSummary = zod.object({ "type": zod.enum(['support', 'complaint', 'grade_appeal', 'anticheat_appeal', 'manual_assessment']).describe('Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case.\n\n- support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts.\n- complaint: a complaint about an organization or an offer, including a breach of the salary terms or a disclosure of personal data (PRD FR18). Candidate accounts.\n- grade_appeal: an appeal of a category the caller received: the result of one own assessment attempt, or the outcome of one own resolved manual assessment case. An expert reviews it, and the original result stays in the history. Candidate accounts.\n- anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts.\n- manual_assessment: a request for a manual assessment of a category by a subject expert with the same rubric, the alternative to automated categorization (consent C3). Candidate accounts.'), "status": zod.enum(['submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed']).describe('Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value.\n\n- submitted: the case was accepted and waits in its queue.\n- in_review: support or a moderator works on it.\n- waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status.\n- waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time.\n- resolved: terminal; a decision was made and `decision` holds its outcome and public reason.\n- closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why.'), "object": zod.union([zod.object({ - "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- invitation: an invitation addressed to the caller. Invitations are not in the contract yet; until they are, every invitation reference answers 404 not_found.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), + "type": zod.enum(['assessment_attempt', 'organization', 'invitation', 'support_case']).describe('Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272.\n\n- assessment_attempt: an assessment attempt of the caller.\n- organization: an organization that the caller can see.\n- 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.\n- support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.'), "id": zod.uuid().describe('Identifier of the object.') }).describe('Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person\'s object exists. The case keeps only the type and the identifier, never a copy of the object.'),zod.null()]).describe('Object that the case is about, or null.'), "assessment_target": zod.union([zod.object({