diff --git a/api/README.en.md b/api/README.en.md index ccecbf4..e20643d 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, and `CreateOrganizationNeed` 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`, and `CreateMySupportCase` require Idempotency-Key, but no operation stores keys yet. ### Errors @@ -304,6 +304,72 @@ Recommendations: Planned, additive: reading and comparing versions, exclusions (TASK-182), the market range hint (P25-P75) of FR08, the check plan "vacancy -> tasks", a need status for archiving, list filters, and need assignments. +### Support cases + +The `support` tag covers the cases of the current account (PRD FR18, with the manual assessment of FR04 and C3): questions to support, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. 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/me/support-cases` | `ListMySupportCases` | session | 200 `SupportCaseList` of `SupportCaseSummary`, `Cache-Control: no-store` | 400 `validation_failed`, 401 | +| `POST /api/v1/me/support-cases` | `CreateMySupportCase` | session and CSRF, Idempotency-Key | 201 `SupportCase`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 404 `not_found`, 409 `state_conflict` or `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | +| `GET /api/v1/me/support-cases/{case_id}` | `GetMySupportCase` | session | 200 `SupportCase`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 404 `not_found` | + +Every operation also declares the `default` problem response. + +Access: + +- The author is the account of the session; no request has a user, account, or organization field. PRD FR18 lets both candidates and company employees contact support, so `/me` serves both scenarios: an employer account opens `support` cases, and the other types answer 403 `forbidden` for it. A case belongs to the account that created it, not to an organization: other members of the same organization never see it. +- Another account's case answers 404 `not_found`, the same as an unknown identifier. TASK-314 says "forbidden" for a foreign case URL; the contract answers 404 instead, so identifiers cannot be probed, and the client shows the same "not found" state for a foreign and an unknown case. The author reads the case whatever happened to the object since then, so a refused test or a revoked access never hides it. +- The moderation queues of TASK-316 are separate staff operations with their own DTOs; they add nothing to these operations. + +Types and object references: + +| Type | Accounts | Object reference | Other fields | Response target | +| --- | --- | --- | --- | --- | +| `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` | policy value | +| `complaint` | candidate | required; an `organization` the caller can see or an `invitation` addressed to the caller | required `complaint_reason` | policy value | +| `grade_appeal` | candidate | required; a terminal `assessment_attempt` of the caller, or a `support_case` of the caller of type `manual_assessment`, `resolved` with the outcome `assessed` | none | 10 business days | +| `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`). +- 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. +- `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. + +Content and fields the client never sets: + +- `description` is plain text of 1-4000 characters with at least one character that is not white space (`pattern: \S`); line breaks are allowed. ogen converts `\S` to the ECMAScript white space set, so the Go server and generated Zod both reject an empty text or one of spaces such as U+00A0 or U+3000 with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes, so the implementation adds a domain check: a description whose every character is `unicode.IsSpace` or U+FEFF answers 400 with the pointer `/description`; Zod accepts it and the server stays authoritative. The server stores the text as written and never writes it to logs or notifications. +- Every variant has `additionalProperties: false`. The client cannot set the status, the decision or its outcome, the priority, the response target, the rubric, the assignee, the moderator, or a contact: such fields, for example `status`, `decision`, `moderator_id`, `response_target`, `rubric_version`, or `reply_to`, answer 400 with the whole-body pointer. + +Case: + +- `number` is a human-readable number assigned on creation, `SC--` with at least six digits, for example `SC-2026-000123`. The sequence is global and never reused, so the number is unique and never changes. The API addresses a case only by its UUID `id`; the number is for letters and calls. A global sequence tells the approximate number of cases created so far, which is acceptable for the MVP. +- `status` is `submitted`, `in_review`, `waiting_for_user`, `waiting_expert`, `resolved` (terminal, with `decision`), or `closed` (terminal, without a decision on the merits, for example a duplicate). Only the server changes it. `waiting_for_user` is in the enum but not set yet: it starts with the planned operation that lets the author reply. An appeal and a manual assessment move to `waiting_expert` by a `system` event in the same transaction as their creation, so the 201 already shows it; they stay there until a person decides. +- `response_target` is the response deadline of FR18: `kind` `operational_goal` (a goal of the team, not a deadline set by law), `business_days`, `due_at` from the configured business calendar, `answered_at`, `late`, and `policy_version`. For `support` and `complaint` the first public reply, a decision, or a closure meets it; for the appeals and `manual_assessment` only a decision or a closure. Missing it never closes the case or changes a grade. +- `decision` is null until `resolved` and then holds `outcome` (`upheld`, `partially_upheld`, `not_upheld`, `answered` for support, `assessed` for a manual assessment), the public `reason`, and `decided_at`. An upheld grade appeal never rewrites the original result; the corrected result is a separate decision of the assessment. +- `history` lists every public event in order, starting with `created`: `kind` (`created`, `status_changed`, `reply`, `decision`), `actor` by kind only (`user`, `support`, `system`), `occurred_at`, the resulting `status`, and a public `message`. It is never truncated. Server invariant: a case holds at most 200 events, and the server rejects a staff reply or status change that would leave no room for the terminal event, so every case fits and can still be resolved or closed; further correspondence goes into a new case that references it as `support_case`. A truncation flag with paginated events was rejected: it would make the full case depend on a second read, while human staff cannot realistically produce 200 public events on one case. +- A case never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. +- Replies reach the user through the case. The server may also notify the verified email address of the account with the number and a link, never with the description, the reply, or assessment details; no request field names another address, so the operation cannot send mail to an address that the user typed. +- `ListMySupportCases` returns `SupportCaseSummary` items, newest first, with cursor pagination: the number, type, status, object reference, category, response target, `decision_outcome`, and timestamps, without the description and the history. The full case comes only from `GetMySupportCase`. + +Commands and limits: + +- Create requires Idempotency-Key with the 24-hour replay: a retry returns the 201 snapshot stored at creation, with the same case and number, following the repository convention; the client reads the current state with `GetMySupportCase`. 404 and 409 `state_conflict` are stored and replayed; 400, 403, and 429 are not. +- 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 one open complaint. A second one, and a grade appeal of an active attempt, answer 409 `state_conflict`. +- 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`. +- Order of checks for create: session (401), CSRF and Origin (403), request validation (400), account scenario (403 `forbidden`), the per-account case limit (429), the Idempotency-Key (422, 409 `idempotency_in_progress`, replay), domain rules (400), the object reference (404), then the state and the limits (409 `state_conflict`). The general rate limit can answer 429 before any check. +- No new problem code is added: the `ProblemCode` enum is copied byte-for-byte into the ML contract. An unavailable anti-cheat appeal and a repeated appeal both use 409 `state_conflict`, and the case or the attempt tells the client why. +- `TestSupportCaseSchemaValidationPrecedesImplementation` checks the schema rejections through the generated server, and `frontend/src/shared/api/support-contract.test.ts` pins the generated Zod rules, the absence of status, decision, moderator, and contact fields in the request types, and the absence of moderator identity and internal fields in the case and the summary. + +Open product question for TASK-315: whether repeated manual assessments of the same category follow the retest rules of FR04 (the same grade after 30 days, at most three attempts in 180 days) or their own rule. The contract only allows one open manual assessment per specialization and invents no interval. + +Planned, additive (a new operation or an optional field): replies of the author, attachments, withdrawal of a case, list filters by status and type, the resulting category of a manual assessment in the decision, a next step for the author (TASK-322), staff queues and decisions (TASK-316, TASK-317, TASK-323), and the pause rules of the response target. + +Planned 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`. + ### 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. @@ -335,7 +401,7 @@ Known generator limitations: #### Format unions - Format unions such as `ItemContent` and `AssessmentAnswer` are `oneOf` without a `discriminator` object. Redocly resolves `discriminator.mapping` values as references, and `scripts/merge-schemas.py` rewrites only `$ref`, so a mapping in a split schema file cannot resolve in the merged `components/schemas.yml`. Every variant fixes `format` with a one-value enum; ogen discriminates by that value and by the fields unique to a variant and rejects a body that matches several variants, and Orval generates a Zod union. -- Orval names the constants of an inline property ``, so a property name that repeats another schema name collides in `index.ts` (TS2308). The union of item formats is therefore `ItemContent`, not `AssessmentItemContent`, next to the `AssessmentItem.content` property, and the parts of `Need` are `NeedRequirementSet`, `NeedReadinessReport`, and `NeedCategoryRecommendations`, not `NeedRequirements`, `NeedReadiness`, and `NeedRecommendations`. +- Orval names the constants of an inline property ``, so a property name that repeats another schema name collides in `index.ts` (TS2308). The union of item formats is therefore `ItemContent`, not `AssessmentItemContent`, next to the `AssessmentItem.content` property, and the parts of `Need` are `NeedRequirementSet`, `NeedReadinessReport`, and `NeedCategoryRecommendations`, not `NeedRequirements`, `NeedReadiness`, and `NeedRecommendations`. The response target of a case is `SupportResponseTarget`, not `SupportCaseResponseTarget`, next to the `SupportCase.response_target` property. Generated Zod is not strict. A body that mixes the fields of two formats or carries an extra `score` or `seed` is accepted after unknown keys are silently stripped, and `uniqueItems` is not checked; only the server rejects such bodies. `frontend/src/shared/api/assessment-contract.test.ts` pins the accepted formats and that no answer or item DTO has a score, key, seed, or correctness field. diff --git a/api/README.md b/api/README.md index 0c48e71..92c24ba 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` требуют 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, но ни одна операция пока не хранит ключи. ### Ошибки @@ -304,6 +304,72 @@ ML-сервис отвечает на ошибки той же схемой `Pro Запланировано, добавляется без ломающих изменений: чтение и сравнение версий, исключения (TASK-182), подсказка рыночной вилки (P25-P75) из FR08, план проверки "вакансия -> задания", статус потребности для архивации, фильтры списка и назначения на потребность. +### Обращения + +Тег `support` описывает обращения текущего аккаунта (FR18 в PRD, с ручной оценкой из FR04 и C3): вопросы в поддержку, жалобы, апелляции грейда и античит-решения, запросы ручной оценки. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`). + +| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | +| --- | --- | --- | --- | --- | +| `GET /api/v1/me/support-cases` | `ListMySupportCases` | сессия | 200 `SupportCaseList` из `SupportCaseSummary`, `Cache-Control: no-store` | 400 `validation_failed`, 401 | +| `POST /api/v1/me/support-cases` | `CreateMySupportCase` | сессия и CSRF, Idempotency-Key | 201 `SupportCase`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 404 `not_found`, 409 `state_conflict` или `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | +| `GET /api/v1/me/support-cases/{case_id}` | `GetMySupportCase` | сессия | 200 `SupportCase`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 404 `not_found` | + +Каждая операция также объявляет problem-ответ `default`. + +Доступ: + +- Автор - аккаунт сессии; ни один запрос не содержит поля пользователя, аккаунта или организации. FR18 в PRD позволяет обращаться в поддержку и кандидату, и сотруднику компании, поэтому `/me` обслуживает оба сценария: аккаунт работодателя открывает обращения типа `support`, а остальные типы дают ему 403 `forbidden`. Обращение принадлежит создавшему его аккаунту, а не организации: другие участники той же организации его не видят. +- Обращение другого аккаунта дает 404 `not_found`, как и неизвестный идентификатор. TASK-314 говорит о "forbidden" для URL чужого обращения; контракт вместо этого отвечает 404, чтобы идентификаторы нельзя было перебрать, и клиент показывает одно и то же состояние "не найдено" для чужого и неизвестного обращения. Автор читает обращение независимо от того, что потом стало с объектом, поэтому отказ в тесте или отозванный доступ его не скрывают. +- Очереди модерации из TASK-316 - отдельные служебные операции со своими DTO; к этим операциям они ничего не добавляют. + +Типы и ссылки на объекты: + +| Тип | Аккаунты | Ссылка на объект | Другие поля | Срок ответа | +| --- | --- | --- | --- | --- | +| `support` | кандидат, работодатель | необязательна; `assessment_attempt` автора, `organization`, которую автор видит, `invitation`, адресованное автору, или другое `support_case` автора | необязательный `assessment_target` | значение политики | +| `complaint` | кандидат | обязательна; `organization`, которую автор видит, или `invitation`, адресованное автору | обязательный `complaint_reason` | значение политики | +| `grade_appeal` | кандидат | обязательна; завершенная `assessment_attempt` автора или `support_case` автора типа `manual_assessment` в статусе `resolved` с исходом `assessed` | нет | 10 рабочих дней | +| `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`). +- Категорию, присвоенную без попытки, тоже можно оспорить (FR18): апелляция грейда может ссылаться на собственное обращение ручной оценки, когда оно `resolved` с `assessed`. Неизвестное обращение и обращение другого аккаунта дают 404 `not_found`; собственное обращение другого типа, еще не решенное или решенное с другим исходом дает 409 `state_conflict`. +- Организацию видит кандидат, которого она пригласила или которому контракт организации (TASK-077) показывает ее профиль, и аккаунт работодателя с действующим членством в ней. Сервер сверяет каждую ссылку с аккаунтом сессии: неизвестный и чужой объект одинаково дают 404 `not_found`, поэтому ссылка не раскрывает, существует ли чужой объект. Обращение хранит только `{type, id}`. +- Приглашений и решений античит-проверки в контракте пока нет. До их появления любая ссылка `invitation` дает 404, а любая античит-апелляция - 409 `state_conflict`; форма запроса при их появлении не меняется. +- Жалобы `offer_content` и `salary_terms_violation` требуют приглашения; другой объект дает 400 с pointer `/object/type` (доменное правило после схемы). +- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; связь ручной оценки с согласием C3 решают TASK-064 и TASK-315. + +Содержание и поля, которые клиент не задает: + +- `description` - простой текст длиной 1-4000 символов, в котором есть хотя бы один непробельный символ (`pattern: \S`); переносы строк разрешены. ogen переводит `\S` в набор пробельных символов ECMAScript, поэтому и Go-сервер, и сгенерированный Zod отклоняют пустой текст или текст из пробелов вроде U+00A0 или U+3000 с pointer `/description`. В пробельные символы ECMAScript не входит U+0085 (NEL), который Go `unicode.IsSpace` считает пробелом, поэтому реализация добавляет доменную проверку: описание, в котором каждый символ - `unicode.IsSpace` или U+FEFF, дает 400 с pointer `/description`; Zod такой текст принимает, решает сервер. Сервер хранит текст как есть и никогда не пишет его в журналы и уведомления. +- У каждого варианта `additionalProperties: false`. Клиент не может задать статус, решение или его исход, приоритет, срок ответа, рубрику, исполнителя, модератора или контакт: такие поля, например `status`, `decision`, `moderator_id`, `response_target`, `rubric_version` или `reply_to`, дают 400 с pointer на все тело. + +Обращение: + +- `number` - понятный человеку номер, который присваивается при создании: `SC-<год UTC>-<порядковый номер>` минимум из шести цифр, например `SC-2026-000123`. Последовательность общая и не переиспользуется, поэтому номер уникален и не меняется. API адресует обращение только по UUID `id`; номер нужен для писем и звонков. Общая последовательность раскрывает примерное число созданных обращений, для MVP это допустимо. +- `status` - `submitted`, `in_review`, `waiting_for_user`, `waiting_expert`, `resolved` (терминальный, с `decision`) или `closed` (терминальный, без решения по существу, например дубликат). Меняет его только сервер. `waiting_for_user` есть в перечислении, но пока не выставляется: он появится вместе с запланированной операцией ответа автора. Апелляции и ручная оценка переходят в `waiting_expert` событием `system` в той же транзакции, что и создание, поэтому ответ 201 уже показывает этот статус; в нем они остаются, пока решение не примет человек. +- `response_target` - срок ответа из FR18: `kind` `operational_goal` (цель команды, а не срок, установленный законом), `business_days`, `due_at` по настроенному производственному календарю, `answered_at`, `late` и `policy_version`. Для `support` и `complaint` его выполняет первый публичный ответ, решение или закрытие; для апелляций и `manual_assessment` - только решение или закрытие. Пропуск срока не закрывает обращение и не меняет грейд. +- `decision` равно null до `resolved`, а затем содержит `outcome` (`upheld`, `partially_upheld`, `not_upheld`, `answered` для поддержки, `assessed` для ручной оценки), публичную причину `reason` и `decided_at`. Удовлетворенная апелляция грейда не переписывает исходный результат; исправленный результат - отдельное решение оценки. +- `history` перечисляет все публичные события по порядку, начиная с `created`: `kind` (`created`, `status_changed`, `reply`, `decision`), `actor` только по виду (`user`, `support`, `system`), `occurred_at`, итоговый `status` и публичный `message`. История никогда не обрезается. Инвариант сервера: в обращении не больше 200 событий, и сервер отклоняет ответ или смену статуса сотрудником, если после них не останется места для терминального события, поэтому любое обращение помещается в лимит и его всегда можно решить или закрыть; дальнейшая переписка идет в новом обращении со ссылкой `support_case` на это. Флаг обрезки с постраничными событиями отвергнут: полное обращение зависело бы от второго чтения, а сотрудники на практике не создают 200 публичных событий в одном обращении. +- Обращение никогда не содержит личность модератора, эксперта или сотрудника поддержки, внутренние заметки, доказательства, ответы теста, античит-сигналы и сигналы риска или контакты другого человека. +- Ответы доходят до пользователя через само обращение. Сервер может также уведомить подтвержденный email аккаунта номером и ссылкой, но не описанием, ответом или подробностями оценки; ни одно поле запроса не задает другой адрес, поэтому операция не может отправить письмо на адрес, введенный пользователем. +- `ListMySupportCases` возвращает элементы `SupportCaseSummary`, новые первыми, с курсорной пагинацией: номер, тип, статус, ссылку на объект, категорию, срок ответа, `decision_outcome` и отметки времени, без описания и истории. Полное обращение возвращает только `GetMySupportCase`. + +Команды и ограничения: + +- Создание требует Idempotency-Key с повтором в течение 24 часов: повтор возвращает снимок ответа 201, сохраненный при создании, с тем же обращением и номером, по соглашению репозитория; текущее состояние клиент читает через `GetMySupportCase`. 404 и 409 `state_conflict` сохраняются и повторяются; 400, 403 и 429 - нет. +- Попытка и решенная ручная оценка принимают не больше одной апелляции грейда каждая, а попытка - не больше одной античит-апелляции, в любом статусе; несогласие с решением оформляется обращением в поддержку со ссылкой `support_case` на апелляцию. Специализация принимает одну открытую ручную оценку, объект - одну открытую жалобу. Повторное обращение и апелляция грейда активной попытки дают 409 `state_conflict`. +- Каждое создание, прошедшее аутентификацию, проверку запроса и сценарий аккаунта, учитывается в лимите аккаунта из продуктовой политики, включая повторы, 404 и 409, поэтому лимит ограничивает и перебор ссылок; сверх лимита сервер отвечает 429 с `Retry-After`. +- Порядок проверок при создании: сессия (401), CSRF и Origin (403), проверка запроса (400), сценарий аккаунта (403 `forbidden`), лимит обращений аккаунта (429), Idempotency-Key (422, 409 `idempotency_in_progress`, повтор), доменные правила (400), ссылка на объект (404), затем состояние и ограничения (409 `state_conflict`). Общий лимит частоты может ответить 429 до любой проверки. +- Новый problem-код не добавляется: перечисление `ProblemCode` побайтно копируется в ML-контракт. Недоступная античит-апелляция и повторная апелляция используют 409 `state_conflict`, а причину клиент узнает из обращения или попытки. +- `TestSupportCaseSchemaValidationPrecedesImplementation` проверяет отказы схемы через сгенерированный сервер, а `frontend/src/shared/api/support-contract.test.ts` закрепляет правила сгенерированного Zod, отсутствие полей статуса, решения, модератора и контактов в типах запроса и отсутствие личности модератора и внутренних полей в обращении и в сводке. + +Открытый продуктовый вопрос к TASK-315: подчиняются ли повторные ручные оценки той же категории правилам пересдачи из FR04 (тот же грейд через 30 дней, не больше трех попыток за 180 дней) или собственному правилу. Контракт разрешает только одну открытую ручную оценку на специализацию и интервал не придумывает. + +Запланировано, добавляется без ломающих изменений (новая операция или необязательное поле): ответы автора, вложения, отзыв обращения, фильтры списка по статусу и типу, итоговая категория ручной оценки в решении, следующий шаг для автора (TASK-322), служебные очереди и решения (TASK-316, TASK-317, TASK-323) и правила паузы срока ответа. + +Запланированные изменения контракта (новые значения перечислений; как и коды каталога, сгенерированные клиенты отклоняют неизвестное значение, поэтому каждое выходит вместе с перегенерированными клиентами): типы объектов `vacancy` и `application` для вакансий и защищенных откликов из FR16 и тип объекта для замечаний к профилю из TASK-272. `waiting_for_user` и `support_case` уже есть в перечислениях, поэтому операции ответа и последующим обращениям такое изменение не нужно. Новых видов событий и участников не планируется: ответ автора - это `reply` с участником `user`, пересмотр решения (TASK-317) - еще одно событие `decision`, а эксперты и модераторы - это `support`. + ### Проверки генераторов `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. @@ -335,7 +401,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro #### Объединения форматов - Объединения форматов, например `ItemContent` и `AssessmentAnswer`, - это `oneOf` без объекта `discriminator`. Redocly разрешает значения `discriminator.mapping` как ссылки, а `scripts/merge-schemas.py` переписывает только `$ref`, поэтому mapping из отдельного файла схем не разрешается в объединенном `components/schemas.yml`. Каждый вариант фиксирует `format` перечислением из одного значения; ogen различает варианты по этому значению и по полям, уникальным для варианта, и отклоняет тело, подходящее под несколько вариантов, а Orval генерирует Zod-объединение. -- Orval называет константы встроенного свойства ``, поэтому имя свойства, повторяющее имя другой схемы, дает конфликт в `index.ts` (TS2308). Поэтому объединение форматов задания называется `ItemContent`, а не `AssessmentItemContent`, рядом со свойством `AssessmentItem.content`, а части `Need` называются `NeedRequirementSet`, `NeedReadinessReport` и `NeedCategoryRecommendations`, а не `NeedRequirements`, `NeedReadiness` и `NeedRecommendations`. +- Orval называет константы встроенного свойства ``, поэтому имя свойства, повторяющее имя другой схемы, дает конфликт в `index.ts` (TS2308). Поэтому объединение форматов задания называется `ItemContent`, а не `AssessmentItemContent`, рядом со свойством `AssessmentItem.content`, а части `Need` называются `NeedRequirementSet`, `NeedReadinessReport` и `NeedCategoryRecommendations`, а не `NeedRequirements`, `NeedReadiness` и `NeedRecommendations`. Срок ответа обращения называется `SupportResponseTarget`, а не `SupportCaseResponseTarget`, рядом со свойством `SupportCase.response_target`. Сгенерированный Zod не строгий. Тело, смешивающее поля двух форматов или содержащее лишние `score` или `seed`, принимается после молчаливого удаления неизвестных ключей, а `uniqueItems` не проверяется; такие тела отклоняет только сервер. `frontend/src/shared/api/assessment-contract.test.ts` закрепляет принимаемые форматы и отсутствие в DTO ответа и задания полей балла, ключа, seed или правильности. diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index daa4ad8..4d03267 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -2015,3 +2015,278 @@ NeedStaleVersion: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 0f1a2b3c-4d5e-4f6a-8b7c-8d9e0f1a2b3d +SupportCaseCreateManualAssessment: + summary: A manual assessment of a category instead of the automated one + value: + type: manual_assessment + description: Прошу провести ручную оценку по рубрике Backend Middle вместо автоматической категоризации. + assessment_target: + specialization: backend + grade: middle +SupportCaseCreateGradeAppeal: + summary: An appeal of the result of an own attempt + value: + type: grade_appeal + description: Практика не засчитана, хотя решение проходит публичные примеры. Прошу пересмотреть результат. + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b +SupportCaseCreateCategoryAppeal: + summary: An appeal of a category that a manual assessment assigned + description: The category came from an expert without an attempt, so the appeal references the resolved manual assessment case. + value: + type: grade_appeal + description: Эксперт подтвердил Junior, но в рубрике Middle я выполнил все обязательные пункты. Прошу пересмотреть. + object: + type: support_case + id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d +SupportCaseCreateTestUnavailable: + summary: A support case about a test that is not available + value: + type: support + description: Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. + assessment_target: + specialization: backend + grade: senior +SupportCaseCreateComplaint: + summary: A complaint about the salary terms of an offer + value: + type: complaint + description: После принятия приглашения компания предложила сумму ниже указанной вилки. + complaint_reason: salary_terms_violation + object: + type: invitation + id: 01928f7a-7f8a-7b9c-8d0e-1f2a3b4c5d6e +SupportCaseManualAssessmentCreated: + summary: A new manual assessment request with its rubric and response target + description: The server moves the case to waiting_expert in the same transaction as the creation, so the 201 already shows both events. + value: + id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + number: SC-2026-000123 + type: manual_assessment + status: waiting_expert + description: Прошу провести ручную оценку по рубрике Backend Middle вместо автоматической категоризации. + object: null + assessment_target: + specialization: backend + grade: middle + complaint_reason: null + rubric_version: 3 + response_target: + kind: operational_goal + business_days: 5 + due_at: "2026-10-13T09:00:00Z" + answered_at: null + late: false + policy_version: 1 + decision: null + history: + - sequence: 1 + kind: created + actor: user + occurred_at: "2026-10-06T09:00:00Z" + status: submitted + message: null + - sequence: 2 + kind: status_changed + actor: system + occurred_at: "2026-10-06T09:00:00Z" + status: waiting_expert + message: null + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:00:00Z" +SupportCaseGradeAppealResolved: + summary: An own grade appeal with a public decision + value: + id: 01928f7a-5d6e-7f8a-9b0c-1d2e3f4a5b6c + number: SC-2026-000097 + type: grade_appeal + status: resolved + description: Практика не засчитана, хотя решение проходит публичные примеры. Прошу пересмотреть результат. + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + assessment_target: null + complaint_reason: null + rubric_version: null + response_target: + kind: operational_goal + business_days: 10 + due_at: "2026-10-15T10:00:00Z" + answered_at: "2026-10-09T14:30:00Z" + late: false + policy_version: 1 + decision: + outcome: not_upheld + reason: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам. + decided_at: "2026-10-09T14:30:00Z" + history: + - sequence: 1 + kind: created + actor: user + occurred_at: "2026-10-01T10:00:00Z" + status: submitted + message: null + - sequence: 2 + kind: status_changed + actor: system + occurred_at: "2026-10-01T10:00:00Z" + status: waiting_expert + message: null + - sequence: 3 + kind: status_changed + actor: support + occurred_at: "2026-10-07T08:15:00Z" + status: in_review + message: null + - sequence: 4 + kind: decision + actor: support + occurred_at: "2026-10-09T14:30:00Z" + status: resolved + message: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам. + created_at: "2026-10-01T10:00:00Z" + updated_at: "2026-10-09T14:30:00Z" +SupportCaseListPage: + summary: The last page of the case summaries of the current account + value: + items: + - id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + number: SC-2026-000123 + type: manual_assessment + status: waiting_expert + object: null + assessment_target: + specialization: backend + grade: middle + response_target: + kind: operational_goal + business_days: 5 + due_at: "2026-10-13T09:00:00Z" + answered_at: null + late: false + policy_version: 1 + decision_outcome: null + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:00:00Z" + - id: 01928f7a-5d6e-7f8a-9b0c-1d2e3f4a5b6c + number: SC-2026-000097 + type: grade_appeal + status: resolved + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + assessment_target: null + response_target: + kind: operational_goal + business_days: 10 + due_at: "2026-10-15T10:00:00Z" + answered_at: "2026-10-09T14:30:00Z" + late: false + policy_version: 1 + decision_outcome: not_upheld + created_at: "2026-10-01T10:00:00Z" + updated_at: "2026-10-09T14:30:00Z" + - id: 01928f7a-4c5d-7e6f-8a9b-0c1d2e3f4a5b + number: SC-2026-000088 + type: support + status: in_review + object: null + assessment_target: + specialization: backend + grade: senior + response_target: + kind: operational_goal + business_days: 3 + due_at: "2026-10-02T12:00:00Z" + answered_at: "2026-10-01T09:20:00Z" + late: false + policy_version: 1 + decision_outcome: null + created_at: "2026-09-29T12:00:00Z" + updated_at: "2026-10-01T09:20:00Z" + page: + has_more: false + next_cursor: null +SupportCaseBlankDescription: + summary: The description is empty or contains only whitespace + 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: 5a6b7c8d-9e0f-4a1b-8c2d-3e4f5a6b7c8d + errors: + - in: body + pointer: /description + code: invalid + 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. + 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: 6b7c8d9e-0f1a-4b2c-9d3e-4f5a6b7c8d9e + errors: + - in: body + pointer: "" + code: invalid + 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. + 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: 7c8d9e0f-1a2b-4c3d-8e4f-5a6b7c8d9e0f + errors: + - in: body + pointer: "" + code: invalid + 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. + 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: 0f1a2b3c-4d5e-4f6a-9b7c-8d9e0f1a2b3c + errors: + - in: body + pointer: "" + code: invalid + message: The value does not match the contract. +SupportCaseComplaintNeedsInvitation: + summary: The complaint reason requires an invitation reference + 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: 8d9e0f1a-2b3c-4d4e-9f5a-6b7c8d9e0f1a + errors: + - in: body + pointer: /object/type + code: invalid + message: The value does not match the contract. +SupportCaseAppealExists: + summary: The attempt or the manual assessment already has an appeal of this type + 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: 9e0f1a2b-3c4d-4e5f-8a6b-7c8d9e0f1a2b diff --git a/api/core/components/parameters.yml b/api/core/components/parameters.yml index 1e8826d..938e03a 100644 --- a/api/core/components/parameters.yml +++ b/api/core/components/parameters.yml @@ -93,3 +93,15 @@ NeedId: type: string format: uuid example: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 +SupportCaseId: + name: case_id + in: path + required: true + description: >- + Identifier of a case of the current account. A case of another account + and an unknown identifier both answer 404 not_found, so identifiers + cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index 7d991d4..d13a447 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -419,3 +419,50 @@ NeedVersionConflict: examples: version_conflict: $ref: ./examples.yml#/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. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + blank_description: + $ref: ./examples.yml#/SupportCaseBlankDescription + unknown_type: + $ref: ./examples.yml#/SupportCaseUnknownType + decision_sent_by_client: + $ref: ./examples.yml#/SupportCaseUnknownField + malformed_object_id: + $ref: ./examples.yml#/SupportCaseMalformedReference + complaint_reason_needs_invitation: + $ref: ./examples.yml#/SupportCaseComplaintNeedsInvitation +SupportCaseCreateConflict: + description: >- + The referenced object does not allow this case now, code + state_conflict: the attempt of a grade appeal has no result yet, the + case referenced by a grade appeal is not a manual assessment resolved + with the outcome assessed, the attempt of an anti-cheat appeal has no + anti-cheat review decision, the attempt or the manual assessment + already has an appeal of the same type, or an open case of the same + type already exists for the category or the object. Or a request + with the same Idempotency-Key is still running, code + idempotency_in_progress. Nothing was created in either case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/SupportCaseAppealExists + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 5f8d57d..3427493 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -2824,3 +2824,552 @@ CandidateQuestionnaireUpdate: $ref: '#/QuestionnaireSpecialization' work_context: $ref: '#/WorkContext' +SupportCaseNumber: + type: string + minLength: 14 + maxLength: 18 + pattern: ^SC-[0-9]{4}-[0-9]{6,10}$ + description: 'Human-readable case number that the server assigns on creation, for example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, and a sequence number of at least six digits with leading zeros. The sequence is global and never reused, so the number is unique across every case and year and never changes. The user quotes it in letters and calls; the API addresses a case only by its `id`. Clients show the number as text and never parse it.' + examples: + - SC-2026-000123 +SupportCaseType: + type: string + description: 'Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case. + + + - support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts. + + - 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. + + - 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. + + - anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts. + + - 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.' + enum: + - support + - complaint + - grade_appeal + - anticheat_appeal + - manual_assessment +SupportCaseStatus: + type: string + description: '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. + + + - submitted: the case was accepted and waits in its queue. + + - in_review: support or a moderator works on it. + + - 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. + + - 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. + + - resolved: terminal; a decision was made and `decision` holds its outcome and public reason. + + - 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.' + enum: + - submitted + - in_review + - waiting_for_user + - waiting_expert + - resolved + - closed +SupportCaseObjectType: + type: string + description: 'Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272. + + + - 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. + + - support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.' + enum: + - assessment_attempt + - organization + - invitation + - support_case +SupportCaseObjectReference: + type: object + description: 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. + additionalProperties: false + required: + - type + - id + properties: + type: + $ref: '#/SupportCaseObjectType' + id: + type: string + format: uuid + description: Identifier of the object. +SupportCaseAttemptReference: + type: object + description: Reference to an assessment attempt of the caller. Any other object type fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + id: + type: string + format: uuid + description: Identifier of an assessment attempt of the caller. +SupportCaseGradeAppealReference: + type: object + description: 'Reference to the category that a grade appeal disputes: an assessment attempt of the caller in a terminal state, or a `manual_assessment` case of the caller that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt. Any other object type fails validation.' + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + - support_case + id: + type: string + format: uuid + description: Identifier of the attempt or the case. +SupportCaseComplaintReference: + type: object + description: 'Reference to the object of a complaint: an organization that the caller can see or an invitation addressed to the caller. Any other object type fails validation.' + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - organization + - invitation + id: + type: string + format: uuid + description: Identifier of the organization or the invitation. +SupportCaseAssessmentTarget: + type: object + description: 'Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.' + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' +SupportCaseComplaintReason: + type: string + description: 'Ground of a complaint (PRD FR18). + + + - organization_conduct: conduct of the organization, for example fraudulent or abusive messages. + + - offer_content: misleading or discriminatory content of an offer. Requires an invitation reference. + + - salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference. + + - data_disclosure: a disclosure of the caller''s personal data beyond what the caller granted. + + - other: another ground, explained in the description.' + enum: + - organization_conduct + - offer_content + - salary_terms_violation + - data_disclosure + - other +SupportCaseDescription: + type: string + minLength: 1 + maxLength: 4000 + pattern: \S + description: '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.' + examples: + - Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. +SupportCasePublicText: + type: string + minLength: 1 + maxLength: 4000 + description: 'Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.' +SupportCaseCreateSupport: + type: object + description: New support case. Both the object reference and the assessment target are optional context; omit what does not apply. + additionalProperties: false + required: + - type + - description + properties: + type: + type: string + enum: + - support + description: + $ref: '#/SupportCaseDescription' + object: + $ref: '#/SupportCaseObjectReference' + assessment_target: + $ref: '#/SupportCaseAssessmentTarget' +SupportCaseCreateComplaint: + type: object + description: New complaint about an organization or an offer. + additionalProperties: false + required: + - type + - description + - complaint_reason + - object + properties: + type: + type: string + enum: + - complaint + description: + $ref: '#/SupportCaseDescription' + complaint_reason: + $ref: '#/SupportCaseComplaintReason' + object: + $ref: '#/SupportCaseComplaintReference' +SupportCaseCreateGradeAppeal: + type: object + description: 'New appeal of a category the caller received: the result of an own assessment attempt, or the outcome of an own resolved manual assessment.' + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - grade_appeal + description: + $ref: '#/SupportCaseDescription' + object: + $ref: '#/SupportCaseGradeAppealReference' +SupportCaseCreateAnticheatAppeal: + type: object + description: New appeal of an anti-cheat review decision on an own assessment attempt. + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - anticheat_appeal + description: + $ref: '#/SupportCaseDescription' + object: + $ref: '#/SupportCaseAttemptReference' +SupportCaseCreateManualAssessment: + type: object + description: 'New request for a manual assessment of a category by a subject expert. A prior attempt of the same category is optional context: a failed first test or no attempt at all never blocks the request.' + additionalProperties: false + required: + - type + - description + - assessment_target + properties: + type: + type: string + enum: + - manual_assessment + description: + $ref: '#/SupportCaseDescription' + assessment_target: + $ref: '#/SupportCaseAssessmentTarget' + object: + $ref: '#/SupportCaseAttemptReference' +SupportCaseCreate: + description: 'New case, selected by `type`. Each type fixes its required fields and the object types it accepts. The body carries only what the user states: the request has no status, decision, outcome, priority, response target, assignee, moderator, rubric, or contact field, and every variant rejects unknown fields, so a client cannot set any of them. The user and the account come only from the session.' + oneOf: + - $ref: '#/SupportCaseCreateSupport' + - $ref: '#/SupportCaseCreateComplaint' + - $ref: '#/SupportCaseCreateGradeAppeal' + - $ref: '#/SupportCaseCreateAnticheatAppeal' + - $ref: '#/SupportCaseCreateManualAssessment' +SupportResponseTarget: + type: object + description: 'Operational target for the answer to the case (PRD FR18: a case gets a number, a status, and a response deadline). The server fixes it on creation from the product policy version and the configured business calendar; it is a goal of the team, not a deadline set by law. The target is met by the first public reply, a decision, or a closure for `support` and `complaint`, and only by a decision or a closure for the appeals and `manual_assessment`. Missing the target never closes the case, never decides it, and never changes a grade.' + additionalProperties: false + required: + - kind + - business_days + - due_at + - answered_at + - late + - policy_version + properties: + kind: + type: string + enum: + - operational_goal + description: Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as a legal deadline. + business_days: + type: integer + format: int32 + minimum: 1 + maximum: 60 + description: Length of the target in business days of the policy version, for example 5 for a manual assessment and 10 for an appeal. + due_at: + $ref: '#/Timestamp' + answered_at: + description: Time the target was met, or null while it is not. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + late: + type: boolean + description: 'Whether the target was missed: it was met after `due_at`, or it is not met and `due_at` has passed at the time of the response.' + policy_version: + type: integer + format: int32 + minimum: 1 + description: Number of the `product` policy version that fixed the target. +SupportCaseDecisionOutcome: + type: string + description: 'Outcome of a decision as the user sees it. The allowed outcomes depend on the case type. + + + - upheld: the appeal or the complaint is upheld in full. + + - partially_upheld: the appeal or the complaint is upheld in part. + + - not_upheld: the appeal or the complaint is not upheld. + + - answered: a support case was answered. + + - assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case.' + enum: + - upheld + - partially_upheld + - not_upheld + - answered + - assessed +SupportCaseDecision: + type: object + description: 'Decision visible to the user. It exists only once the case is `resolved`. It holds the outcome and the public reason; it never names the moderator or the expert and never contains internal notes, evidence, sanctions against another party, or risk signals. An upheld grade appeal never rewrites the original result: the corrected result is a separate decision of the assessment, and both stay in the history of that attempt.' + additionalProperties: false + required: + - outcome + - reason + - decided_at + properties: + outcome: + $ref: '#/SupportCaseDecisionOutcome' + reason: + $ref: '#/SupportCasePublicText' + decided_at: + $ref: '#/Timestamp' +SupportCaseActorKind: + type: string + description: 'Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change. + + + - user: the author of the case. + + - support: a person of the support, moderation, or expert staff. + + - system: the server, for example on creation or when it routes the case.' + enum: + - user + - support + - system +SupportCaseEventKind: + type: string + description: 'Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value. + + + - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. + + - status_changed: the status changed; `status` is the new status, and `message` may explain a closure. + + - reply: support replied; `message` holds the reply and `status` is null. + + - decision: a decision was made; `status` is `resolved` and `message` holds the public reason.' + enum: + - created + - status_changed + - reply + - decision +SupportCaseEvent: + type: object + description: One public event of the case history. Internal notes, assignments, evidence requests, and risk signals are never history events. + additionalProperties: false + required: + - sequence + - kind + - actor + - occurred_at + - status + - message + properties: + sequence: + type: integer + format: int32 + minimum: 1 + description: Position of the event in the history, starting at 1 and increasing by one. + kind: + $ref: '#/SupportCaseEventKind' + actor: + $ref: '#/SupportCaseActorKind' + occurred_at: + $ref: '#/Timestamp' + status: + description: Status of the case after the event, or null for a reply. + oneOf: + - $ref: '#/SupportCaseStatus' + - type: 'null' + message: + description: Public text of the event, or null. + oneOf: + - $ref: '#/SupportCasePublicText' + - type: 'null' +SupportCase: + type: object + description: Case of the current account. It contains what the author sent, the public processing state, and the public history. It never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers or anti-cheat signals, risk signals, or contact data of another person. Fields that do not apply to the type are null. + additionalProperties: false + required: + - id + - number + - type + - status + - description + - object + - assessment_target + - complaint_reason + - rubric_version + - response_target + - decision + - history + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: '#/SupportCaseNumber' + type: + $ref: '#/SupportCaseType' + status: + $ref: '#/SupportCaseStatus' + description: + $ref: '#/SupportCaseDescription' + object: + description: Object that the case is about, as sent on creation, or null when the case has none. + oneOf: + - $ref: '#/SupportCaseObjectReference' + - type: 'null' + assessment_target: + description: Category of a manual assessment, the optional category of a support case, or null. + oneOf: + - $ref: '#/SupportCaseAssessmentTarget' + - type: 'null' + complaint_reason: + description: Ground of a complaint, or null for other types. + oneOf: + - $ref: '#/SupportCaseComplaintReason' + - type: 'null' + rubric_version: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: 'For a manual assessment, the version of the published rubric of the category that the server fixed on creation; the expert assesses with it, the same rubric as the automated assessment. Null for other types, and null for a manual assessment whose category has no published rubric yet: the case then waits in `waiting_expert` and the client says so instead of promising a date.' + response_target: + $ref: '#/SupportResponseTarget' + decision: + description: Decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: '#/SupportCaseDecision' + - type: 'null' + history: + type: array + minItems: 1 + maxItems: 200 + description: 'Every public event in the order it happened, starting with `created`; the list is never truncated. The server keeps a case within 200 events: it rejects a staff reply or status change that would leave no room for the terminal event, so a case always fits and can always be resolved or closed. Further correspondence goes into a new case that references this one as `support_case`.' + items: + $ref: '#/SupportCaseEvent' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' +SupportCaseSummary: + type: object + description: 'Case in a list: the fields that a list of cases shows, without the description and the history. GetMySupportCase returns the full case.' + additionalProperties: false + required: + - id + - number + - type + - status + - object + - assessment_target + - response_target + - decision_outcome + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: '#/SupportCaseNumber' + type: + $ref: '#/SupportCaseType' + status: + $ref: '#/SupportCaseStatus' + object: + description: Object that the case is about, or null. + oneOf: + - $ref: '#/SupportCaseObjectReference' + - type: 'null' + assessment_target: + description: Category of the case, or null. + oneOf: + - $ref: '#/SupportCaseAssessmentTarget' + - type: 'null' + response_target: + $ref: '#/SupportResponseTarget' + decision_outcome: + description: Outcome of the decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: '#/SupportCaseDecisionOutcome' + - type: 'null' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' +SupportCaseList: + type: object + description: One page of the cases of the current account, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Case summaries of the page. + items: + $ref: '#/SupportCaseSummary' + page: + $ref: '#/PageInfo' diff --git a/api/core/components/schemas/support_schemas.yml b/api/core/components/schemas/support_schemas.yml new file mode 100644 index 0000000..762230a --- /dev/null +++ b/api/core/components/schemas/support_schemas.yml @@ -0,0 +1,630 @@ +schemas: + SupportCaseNumber: + type: string + minLength: 14 + maxLength: 18 + pattern: "^SC-[0-9]{4}-[0-9]{6,10}$" + description: >- + Human-readable case number that the server assigns on creation, for + example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, + and a sequence number of at least six digits with leading zeros. The + sequence is global and never reused, so the number is unique across + every case and year and never changes. The user quotes it in letters + and calls; the API addresses a case only by its `id`. Clients show the + number as text and never parse it. + examples: + - SC-2026-000123 + SupportCaseType: + type: string + description: |- + Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case. + + - support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts. + - 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. + - 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. + - anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts. + - 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. + enum: + - support + - complaint + - grade_appeal + - anticheat_appeal + - manual_assessment + SupportCaseStatus: + type: string + description: |- + 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. + + - submitted: the case was accepted and waits in its queue. + - in_review: support or a moderator works on it. + - 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. + - 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. + - resolved: terminal; a decision was made and `decision` holds its outcome and public reason. + - 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. + enum: + - submitted + - in_review + - waiting_for_user + - waiting_expert + - resolved + - closed + SupportCaseObjectType: + type: string + description: |- + Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272. + + - 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. + - support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes. + enum: + - assessment_attempt + - organization + - invitation + - support_case + SupportCaseObjectReference: + type: object + description: >- + 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. + additionalProperties: false + required: + - type + - id + properties: + type: + $ref: "#/schemas/SupportCaseObjectType" + id: + type: string + format: uuid + description: Identifier of the object. + SupportCaseAttemptReference: + type: object + description: >- + Reference to an assessment attempt of the caller. Any other object + type fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + id: + type: string + format: uuid + description: Identifier of an assessment attempt of the caller. + SupportCaseGradeAppealReference: + type: object + description: >- + Reference to the category that a grade appeal disputes: an assessment + attempt of the caller in a terminal state, or a `manual_assessment` + case of the caller that is `resolved` with the outcome `assessed`, for + a category that an expert assigned without an attempt. Any other object + type fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + - support_case + id: + type: string + format: uuid + description: Identifier of the attempt or the case. + SupportCaseComplaintReference: + type: object + description: >- + Reference to the object of a complaint: an organization that the caller + can see or an invitation addressed to the caller. Any other object type + fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - organization + - invitation + id: + type: string + format: uuid + description: Identifier of the organization or the invitation. + SupportCaseAssessmentTarget: + type: object + description: >- + Category that the case is about: a specialization and a grade of the + MVP scale. For a manual assessment it is the category to assess; for a + support case it is optional context, for example the category whose + test is not available. + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + SupportCaseComplaintReason: + type: string + description: |- + Ground of a complaint (PRD FR18). + + - organization_conduct: conduct of the organization, for example fraudulent or abusive messages. + - offer_content: misleading or discriminatory content of an offer. Requires an invitation reference. + - salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference. + - data_disclosure: a disclosure of the caller's personal data beyond what the caller granted. + - other: another ground, explained in the description. + enum: + - organization_conduct + - offer_content + - salary_terms_violation + - data_disclosure + - other + SupportCaseDescription: + type: string + minLength: 1 + maxLength: 4000 + pattern: \S + description: >- + 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. + examples: + - Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. + SupportCasePublicText: + type: string + minLength: 1 + maxLength: 4000 + description: >- + Text that support or a moderator wrote for the user: a public reply or + the public reason of a decision. Plain text; clients show it as text, + never as HTML. Internal notes of the staff are never public texts. + SupportCaseCreateSupport: + type: object + description: >- + New support case. Both the object reference and the assessment target + are optional context; omit what does not apply. + additionalProperties: false + required: + - type + - description + properties: + type: + type: string + enum: + - support + description: + $ref: "#/schemas/SupportCaseDescription" + object: + $ref: "#/schemas/SupportCaseObjectReference" + assessment_target: + $ref: "#/schemas/SupportCaseAssessmentTarget" + SupportCaseCreateComplaint: + type: object + description: New complaint about an organization or an offer. + additionalProperties: false + required: + - type + - description + - complaint_reason + - object + properties: + type: + type: string + enum: + - complaint + description: + $ref: "#/schemas/SupportCaseDescription" + complaint_reason: + $ref: "#/schemas/SupportCaseComplaintReason" + object: + $ref: "#/schemas/SupportCaseComplaintReference" + SupportCaseCreateGradeAppeal: + type: object + description: >- + New appeal of a category the caller received: the result of an own + assessment attempt, or the outcome of an own resolved manual + assessment. + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - grade_appeal + description: + $ref: "#/schemas/SupportCaseDescription" + object: + $ref: "#/schemas/SupportCaseGradeAppealReference" + SupportCaseCreateAnticheatAppeal: + type: object + description: New appeal of an anti-cheat review decision on an own assessment attempt. + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - anticheat_appeal + description: + $ref: "#/schemas/SupportCaseDescription" + object: + $ref: "#/schemas/SupportCaseAttemptReference" + SupportCaseCreateManualAssessment: + type: object + description: >- + New request for a manual assessment of a category by a subject expert. + A prior attempt of the same category is optional context: a failed + first test or no attempt at all never blocks the request. + additionalProperties: false + required: + - type + - description + - assessment_target + properties: + type: + type: string + enum: + - manual_assessment + description: + $ref: "#/schemas/SupportCaseDescription" + assessment_target: + $ref: "#/schemas/SupportCaseAssessmentTarget" + object: + $ref: "#/schemas/SupportCaseAttemptReference" + SupportCaseCreate: + description: >- + New case, selected by `type`. Each type fixes its required fields and + the object types it accepts. The body carries only what the user + states: the request has no status, decision, outcome, priority, + response target, assignee, moderator, rubric, or contact field, and + every variant rejects unknown fields, so a client cannot set any of + them. The user and the account come only from the session. + oneOf: + - $ref: "#/schemas/SupportCaseCreateSupport" + - $ref: "#/schemas/SupportCaseCreateComplaint" + - $ref: "#/schemas/SupportCaseCreateGradeAppeal" + - $ref: "#/schemas/SupportCaseCreateAnticheatAppeal" + - $ref: "#/schemas/SupportCaseCreateManualAssessment" + SupportResponseTarget: + type: object + description: >- + Operational target for the answer to the case (PRD FR18: a case gets a + number, a status, and a response deadline). The server fixes it on + creation from the product policy version and the configured business + calendar; it is a goal of the team, not a deadline set by law. The + target is met by the first public reply, a decision, or a closure for + `support` and `complaint`, and only by a decision or a closure for the + appeals and `manual_assessment`. Missing the target never closes the + case, never decides it, and never changes a grade. + additionalProperties: false + required: + - kind + - business_days + - due_at + - answered_at + - late + - policy_version + properties: + kind: + type: string + enum: + - operational_goal + description: >- + Nature of the target. `operational_goal` is a goal of the team + that clients label as such, never as a legal deadline. + business_days: + type: integer + format: int32 + minimum: 1 + maximum: 60 + description: >- + Length of the target in business days of the policy version, for + example 5 for a manual assessment and 10 for an appeal. + due_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + answered_at: + description: Time the target was met, or null while it is not. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + late: + type: boolean + description: >- + Whether the target was missed: it was met after `due_at`, or it is + not met and `due_at` has passed at the time of the response. + policy_version: + type: integer + format: int32 + minimum: 1 + description: Number of the `product` policy version that fixed the target. + SupportCaseDecisionOutcome: + type: string + description: |- + Outcome of a decision as the user sees it. The allowed outcomes depend on the case type. + + - upheld: the appeal or the complaint is upheld in full. + - partially_upheld: the appeal or the complaint is upheld in part. + - not_upheld: the appeal or the complaint is not upheld. + - answered: a support case was answered. + - assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case. + enum: + - upheld + - partially_upheld + - not_upheld + - answered + - assessed + SupportCaseDecision: + type: object + description: >- + Decision visible to the user. It exists only once the case is + `resolved`. It holds the outcome and the public reason; it never names + the moderator or the expert and never contains internal notes, + evidence, sanctions against another party, or risk signals. An upheld + grade appeal never rewrites the original result: the corrected result + is a separate decision of the assessment, and both stay in the history + of that attempt. + additionalProperties: false + required: + - outcome + - reason + - decided_at + properties: + outcome: + $ref: "#/schemas/SupportCaseDecisionOutcome" + reason: + $ref: "#/schemas/SupportCasePublicText" + decided_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + SupportCaseActorKind: + type: string + description: |- + Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change. + + - user: the author of the case. + - support: a person of the support, moderation, or expert staff. + - system: the server, for example on creation or when it routes the case. + enum: + - user + - support + - system + SupportCaseEventKind: + type: string + description: |- + Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value. + + - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. + - status_changed: the status changed; `status` is the new status, and `message` may explain a closure. + - reply: support replied; `message` holds the reply and `status` is null. + - decision: a decision was made; `status` is `resolved` and `message` holds the public reason. + enum: + - created + - status_changed + - reply + - decision + SupportCaseEvent: + type: object + description: >- + One public event of the case history. Internal notes, assignments, + evidence requests, and risk signals are never history events. + additionalProperties: false + required: + - sequence + - kind + - actor + - occurred_at + - status + - message + properties: + sequence: + type: integer + format: int32 + minimum: 1 + description: Position of the event in the history, starting at 1 and increasing by one. + kind: + $ref: "#/schemas/SupportCaseEventKind" + actor: + $ref: "#/schemas/SupportCaseActorKind" + occurred_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + status: + description: Status of the case after the event, or null for a reply. + oneOf: + - $ref: "#/schemas/SupportCaseStatus" + - type: "null" + message: + description: Public text of the event, or null. + oneOf: + - $ref: "#/schemas/SupportCasePublicText" + - type: "null" + SupportCase: + type: object + description: >- + Case of the current account. It contains what the author sent, the + public processing state, and the public history. It never contains + the identity of a moderator, an expert, or a support agent, internal + notes, evidence, assessment answers or anti-cheat signals, risk + signals, or contact data of another person. Fields that do not apply + to the type are null. + additionalProperties: false + required: + - id + - number + - type + - status + - description + - object + - assessment_target + - complaint_reason + - rubric_version + - response_target + - decision + - history + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: "#/schemas/SupportCaseNumber" + type: + $ref: "#/schemas/SupportCaseType" + status: + $ref: "#/schemas/SupportCaseStatus" + description: + $ref: "#/schemas/SupportCaseDescription" + object: + description: >- + Object that the case is about, as sent on creation, or null when + the case has none. + oneOf: + - $ref: "#/schemas/SupportCaseObjectReference" + - type: "null" + assessment_target: + description: >- + Category of a manual assessment, the optional category of a + support case, or null. + oneOf: + - $ref: "#/schemas/SupportCaseAssessmentTarget" + - type: "null" + complaint_reason: + description: Ground of a complaint, or null for other types. + oneOf: + - $ref: "#/schemas/SupportCaseComplaintReason" + - type: "null" + rubric_version: + type: + - integer + - "null" + format: int32 + minimum: 1 + description: >- + For a manual assessment, the version of the published rubric of the + category that the server fixed on creation; the expert assesses with + it, the same rubric as the automated assessment. Null for other + types, and null for a manual assessment whose category has no + published rubric yet: the case then waits in `waiting_expert` and + the client says so instead of promising a date. + response_target: + $ref: "#/schemas/SupportResponseTarget" + decision: + description: Decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: "#/schemas/SupportCaseDecision" + - type: "null" + history: + type: array + minItems: 1 + maxItems: 200 + description: >- + Every public event in the order it happened, starting with + `created`; the list is never truncated. The server keeps a case + within 200 events: it rejects a staff reply or status change that + would leave no room for the terminal event, so a case always fits + and can always be resolved or closed. Further correspondence goes + into a new case that references this one as `support_case`. + items: + $ref: "#/schemas/SupportCaseEvent" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + SupportCaseSummary: + type: object + description: >- + Case in a list: the fields that a list of cases shows, without the + description and the history. GetMySupportCase returns the full case. + additionalProperties: false + required: + - id + - number + - type + - status + - object + - assessment_target + - response_target + - decision_outcome + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: "#/schemas/SupportCaseNumber" + type: + $ref: "#/schemas/SupportCaseType" + status: + $ref: "#/schemas/SupportCaseStatus" + object: + description: Object that the case is about, or null. + oneOf: + - $ref: "#/schemas/SupportCaseObjectReference" + - type: "null" + assessment_target: + description: Category of the case, or null. + oneOf: + - $ref: "#/schemas/SupportCaseAssessmentTarget" + - type: "null" + response_target: + $ref: "#/schemas/SupportResponseTarget" + decision_outcome: + description: Outcome of the decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: "#/schemas/SupportCaseDecisionOutcome" + - type: "null" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + SupportCaseList: + type: object + description: One page of the cases of the current account, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Case summaries of the page. + items: + $ref: "#/schemas/SupportCaseSummary" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index a3d2081..e63c66f 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: 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: /api/v1/healthz: get: @@ -1040,6 +1042,167 @@ paths: $ref: '#/components/responses/TooManyRequests' default: $ref: '#/components/responses/Problem' + /api/v1/me/support-cases: + get: + operationId: ListMySupportCases + summary: List the support cases of the current account. + description: |- + Requires the session cookie of a candidate or an employer account. Returns a page of the cases that this account created, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. Each item is a summary with the number, type, status, object reference, category, response target, and decision outcome; it has no description and no history, which GetMySupportCase returns with the full case. Cases of other accounts are never listed, including cases of other members of the same organization. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit` or `cursor` answers 400 validation_failed. Filters by status and type are planned and add optional parameters. + security: + - sessionCookie: [] + tags: + - support + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the cases of the current account. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/SupportCaseList' + examples: + last_page: + $ref: '#/components/examples/SupportCaseListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + default: + $ref: '#/components/responses/Problem' + post: + operationId: CreateMySupportCase + summary: Open a support case, a complaint, an appeal, or a manual assessment request. + description: |- + Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The author is the account of the session; the body has no user, account, or organization field. A case is reachable from any screen, including a screen that denies access to an assessment: being refused an action never removes the path to a case about it. + + The client sends only what the user states: `type`, a non-blank `description`, and the fields of the type. It never sets the status, the decision, the outcome, the priority, the response target, the rubric, the assignee, or the moderator: every variant has `additionalProperties: false`, so such fields answer 400. Attachments are not part of the MVP; they are planned as an optional field and change no existing one. + + Types, accounts, and allowed references: + + | Type | Accounts | Object reference | Other fields | + | --- | --- | --- | --- | + | `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` that the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` | + | `complaint` | candidate | required; an `organization` that the caller can see or an `invitation` addressed to the caller | required `complaint_reason`; `offer_content` and `salary_terms_violation` require an invitation | + | `grade_appeal` | candidate | required; `assessment_attempt` of the caller in a terminal state, so it has a result, or a `support_case` of the caller of type `manual_assessment` that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt | none | + | `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. + + 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. + + 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. + + Description check: the schema pattern `\S` uses the ECMAScript white space set in both generated validators (ogen converts it for Go), so a description of spaces such as U+00A0 or U+3000 already fails validation with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes, so the server also applies a domain check: a description whose every character is `unicode.IsSpace` or U+FEFF answers 400 validation_failed with the pointer `/description`. This check comes with the implementation; generated Zod accepts a description of NEL, and the server stays authoritative. + + The new case gets a number and the status `submitted`. A grade appeal, an anti-cheat appeal, and a manual assessment are moved to `waiting_expert` by a `system` event in the same transaction, so the 201 already shows that status with both events; a support case and a complaint stay `submitted`. Each case gets a response target from the product policy version and the configured business calendar: 5 business days for a manual assessment and 10 for an appeal (PRD FR18 and C3), and a policy value for support and complaints. The target is an operational goal, not a deadline set by law. A manual assessment fixes the published rubric version of the category, or null when the category has none yet; the expert assesses with the same rubric as the automated assessment, and the request assigns no category by itself. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt. + + Replies: the case itself is the channel. Support replies and decisions appear in the public `history` and `decision`. The server may also notify the verified email address of the account that the case changed, with the case number and a link, never with the description, the reply, or assessment details. No request field names another address or contact, so the operation cannot send mail to an address that the user typed. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 with the same number and creates nothing, so a lost response never opens a second case. The replay is the snapshot stored at creation, following the repository convention; the client reads the current status and history with GetMySupportCase. 404 and 409 state_conflict are stored and replayed as well. A different body with the same key answers 422 idempotency_key_reused. 400, 403, 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 an employer account with a type other than `support`), the per-account case limit (429), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with the pointer `/description` for a text of only Unicode spaces or `/object/type` for a complaint reason that requires an invitation), the object reference (404 not_found), then the state of the object and the limits (409 state_conflict). The general rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - support + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SupportCaseCreate' + examples: + manual_assessment: + $ref: '#/components/examples/SupportCaseCreateManualAssessment' + own_grade_appeal: + $ref: '#/components/examples/SupportCaseCreateGradeAppeal' + appeal_of_manual_assessment: + $ref: '#/components/examples/SupportCaseCreateCategoryAppeal' + test_unavailable: + $ref: '#/components/examples/SupportCaseCreateTestUnavailable' + salary_terms_complaint: + $ref: '#/components/examples/SupportCaseCreateComplaint' + responses: + '201': + description: The case was created, with the status `submitted` or, for an appeal or a manual assessment, `waiting_expert`; or a retry with the same Idempotency-Key replayed the stored creation response. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/SupportCase' + examples: + manual_assessment: + $ref: '#/components/examples/SupportCaseManualAssessmentCreated' + '400': + $ref: '#/components/responses/SupportCaseValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/SupportCaseCreateConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/support-cases/{case_id}: + get: + operationId: GetMySupportCase + summary: Read a support case of the current account. + description: |- + Requires the session cookie of a candidate or an employer account. Returns the case with its number, type, object reference, status, response target, decision, and public history. The owner reads the case whatever happened to the object since then: a revoked access, a closed invitation, or a refused test never hides the case from its author. + + The case never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. `decision` is null until the case is `resolved`. + + The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one. + + The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - support + parameters: + - $ref: '#/components/parameters/SupportCaseId' + responses: + '200': + description: The case. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/SupportCase' + examples: + manual_assessment_created: + $ref: '#/components/examples/SupportCaseManualAssessmentCreated' + grade_appeal_resolved: + $ref: '#/components/examples/SupportCaseGradeAppealResolved' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' components: schemas: Problem: @@ -3777,6 +3940,529 @@ components: oneOf: - $ref: '#/components/schemas/NeedSalaryInput' - type: 'null' + SupportCaseNumber: + type: string + minLength: 14 + maxLength: 18 + pattern: ^SC-[0-9]{4}-[0-9]{6,10}$ + description: 'Human-readable case number that the server assigns on creation, for example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, and a sequence number of at least six digits with leading zeros. The sequence is global and never reused, so the number is unique across every case and year and never changes. The user quotes it in letters and calls; the API addresses a case only by its `id`. Clients show the number as text and never parse it.' + examples: + - SC-2026-000123 + SupportCaseType: + type: string + description: |- + Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case. + + - support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts. + - 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. + - 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. + - anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts. + - 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. + enum: + - support + - complaint + - grade_appeal + - anticheat_appeal + - manual_assessment + SupportCaseStatus: + type: string + description: |- + 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. + + - submitted: the case was accepted and waits in its queue. + - in_review: support or a moderator works on it. + - 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. + - 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. + - resolved: terminal; a decision was made and `decision` holds its outcome and public reason. + - 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. + enum: + - submitted + - in_review + - waiting_for_user + - waiting_expert + - resolved + - closed + SupportCaseObjectType: + type: string + description: |- + Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with TASK-272. + + - 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. + - support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes. + enum: + - assessment_attempt + - organization + - invitation + - support_case + SupportCaseObjectReference: + type: object + description: 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. + additionalProperties: false + required: + - type + - id + properties: + type: + $ref: '#/components/schemas/SupportCaseObjectType' + id: + type: string + format: uuid + description: Identifier of the object. + SupportCaseAttemptReference: + type: object + description: Reference to an assessment attempt of the caller. Any other object type fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + id: + type: string + format: uuid + description: Identifier of an assessment attempt of the caller. + SupportCaseGradeAppealReference: + type: object + description: 'Reference to the category that a grade appeal disputes: an assessment attempt of the caller in a terminal state, or a `manual_assessment` case of the caller that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt. Any other object type fails validation.' + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + - support_case + id: + type: string + format: uuid + description: Identifier of the attempt or the case. + SupportCaseComplaintReference: + type: object + description: 'Reference to the object of a complaint: an organization that the caller can see or an invitation addressed to the caller. Any other object type fails validation.' + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - organization + - invitation + id: + type: string + format: uuid + description: Identifier of the organization or the invitation. + SupportCaseAssessmentTarget: + type: object + description: 'Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.' + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + SupportCaseComplaintReason: + type: string + description: |- + Ground of a complaint (PRD FR18). + + - organization_conduct: conduct of the organization, for example fraudulent or abusive messages. + - offer_content: misleading or discriminatory content of an offer. Requires an invitation reference. + - salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference. + - data_disclosure: a disclosure of the caller's personal data beyond what the caller granted. + - other: another ground, explained in the description. + enum: + - organization_conduct + - offer_content + - salary_terms_violation + - data_disclosure + - other + SupportCaseDescription: + type: string + minLength: 1 + maxLength: 4000 + pattern: \S + description: '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.' + examples: + - Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. + SupportCasePublicText: + type: string + minLength: 1 + maxLength: 4000 + description: 'Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.' + SupportCaseCreateSupport: + type: object + description: New support case. Both the object reference and the assessment target are optional context; omit what does not apply. + additionalProperties: false + required: + - type + - description + properties: + type: + type: string + enum: + - support + description: + $ref: '#/components/schemas/SupportCaseDescription' + object: + $ref: '#/components/schemas/SupportCaseObjectReference' + assessment_target: + $ref: '#/components/schemas/SupportCaseAssessmentTarget' + SupportCaseCreateComplaint: + type: object + description: New complaint about an organization or an offer. + additionalProperties: false + required: + - type + - description + - complaint_reason + - object + properties: + type: + type: string + enum: + - complaint + description: + $ref: '#/components/schemas/SupportCaseDescription' + complaint_reason: + $ref: '#/components/schemas/SupportCaseComplaintReason' + object: + $ref: '#/components/schemas/SupportCaseComplaintReference' + SupportCaseCreateGradeAppeal: + type: object + description: 'New appeal of a category the caller received: the result of an own assessment attempt, or the outcome of an own resolved manual assessment.' + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - grade_appeal + description: + $ref: '#/components/schemas/SupportCaseDescription' + object: + $ref: '#/components/schemas/SupportCaseGradeAppealReference' + SupportCaseCreateAnticheatAppeal: + type: object + description: New appeal of an anti-cheat review decision on an own assessment attempt. + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - anticheat_appeal + description: + $ref: '#/components/schemas/SupportCaseDescription' + object: + $ref: '#/components/schemas/SupportCaseAttemptReference' + SupportCaseCreateManualAssessment: + type: object + description: 'New request for a manual assessment of a category by a subject expert. A prior attempt of the same category is optional context: a failed first test or no attempt at all never blocks the request.' + additionalProperties: false + required: + - type + - description + - assessment_target + properties: + type: + type: string + enum: + - manual_assessment + description: + $ref: '#/components/schemas/SupportCaseDescription' + assessment_target: + $ref: '#/components/schemas/SupportCaseAssessmentTarget' + object: + $ref: '#/components/schemas/SupportCaseAttemptReference' + SupportCaseCreate: + description: 'New case, selected by `type`. Each type fixes its required fields and the object types it accepts. The body carries only what the user states: the request has no status, decision, outcome, priority, response target, assignee, moderator, rubric, or contact field, and every variant rejects unknown fields, so a client cannot set any of them. The user and the account come only from the session.' + oneOf: + - $ref: '#/components/schemas/SupportCaseCreateSupport' + - $ref: '#/components/schemas/SupportCaseCreateComplaint' + - $ref: '#/components/schemas/SupportCaseCreateGradeAppeal' + - $ref: '#/components/schemas/SupportCaseCreateAnticheatAppeal' + - $ref: '#/components/schemas/SupportCaseCreateManualAssessment' + SupportResponseTarget: + type: object + description: 'Operational target for the answer to the case (PRD FR18: a case gets a number, a status, and a response deadline). The server fixes it on creation from the product policy version and the configured business calendar; it is a goal of the team, not a deadline set by law. The target is met by the first public reply, a decision, or a closure for `support` and `complaint`, and only by a decision or a closure for the appeals and `manual_assessment`. Missing the target never closes the case, never decides it, and never changes a grade.' + additionalProperties: false + required: + - kind + - business_days + - due_at + - answered_at + - late + - policy_version + properties: + kind: + type: string + enum: + - operational_goal + description: Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as a legal deadline. + business_days: + type: integer + format: int32 + minimum: 1 + maximum: 60 + description: Length of the target in business days of the policy version, for example 5 for a manual assessment and 10 for an appeal. + due_at: + $ref: '#/components/schemas/Timestamp' + answered_at: + description: Time the target was met, or null while it is not. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + late: + type: boolean + description: 'Whether the target was missed: it was met after `due_at`, or it is not met and `due_at` has passed at the time of the response.' + policy_version: + type: integer + format: int32 + minimum: 1 + description: Number of the `product` policy version that fixed the target. + SupportCaseDecisionOutcome: + type: string + description: |- + Outcome of a decision as the user sees it. The allowed outcomes depend on the case type. + + - upheld: the appeal or the complaint is upheld in full. + - partially_upheld: the appeal or the complaint is upheld in part. + - not_upheld: the appeal or the complaint is not upheld. + - answered: a support case was answered. + - assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case. + enum: + - upheld + - partially_upheld + - not_upheld + - answered + - assessed + SupportCaseDecision: + type: object + description: 'Decision visible to the user. It exists only once the case is `resolved`. It holds the outcome and the public reason; it never names the moderator or the expert and never contains internal notes, evidence, sanctions against another party, or risk signals. An upheld grade appeal never rewrites the original result: the corrected result is a separate decision of the assessment, and both stay in the history of that attempt.' + additionalProperties: false + required: + - outcome + - reason + - decided_at + properties: + outcome: + $ref: '#/components/schemas/SupportCaseDecisionOutcome' + reason: + $ref: '#/components/schemas/SupportCasePublicText' + decided_at: + $ref: '#/components/schemas/Timestamp' + SupportCaseActorKind: + type: string + description: |- + Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change. + + - user: the author of the case. + - support: a person of the support, moderation, or expert staff. + - system: the server, for example on creation or when it routes the case. + enum: + - user + - support + - system + SupportCaseEventKind: + type: string + description: |- + Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value. + + - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. + - status_changed: the status changed; `status` is the new status, and `message` may explain a closure. + - reply: support replied; `message` holds the reply and `status` is null. + - decision: a decision was made; `status` is `resolved` and `message` holds the public reason. + enum: + - created + - status_changed + - reply + - decision + SupportCaseEvent: + type: object + description: One public event of the case history. Internal notes, assignments, evidence requests, and risk signals are never history events. + additionalProperties: false + required: + - sequence + - kind + - actor + - occurred_at + - status + - message + properties: + sequence: + type: integer + format: int32 + minimum: 1 + description: Position of the event in the history, starting at 1 and increasing by one. + kind: + $ref: '#/components/schemas/SupportCaseEventKind' + actor: + $ref: '#/components/schemas/SupportCaseActorKind' + occurred_at: + $ref: '#/components/schemas/Timestamp' + status: + description: Status of the case after the event, or null for a reply. + oneOf: + - $ref: '#/components/schemas/SupportCaseStatus' + - type: 'null' + message: + description: Public text of the event, or null. + oneOf: + - $ref: '#/components/schemas/SupportCasePublicText' + - type: 'null' + SupportCase: + type: object + description: Case of the current account. It contains what the author sent, the public processing state, and the public history. It never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers or anti-cheat signals, risk signals, or contact data of another person. Fields that do not apply to the type are null. + additionalProperties: false + required: + - id + - number + - type + - status + - description + - object + - assessment_target + - complaint_reason + - rubric_version + - response_target + - decision + - history + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: '#/components/schemas/SupportCaseNumber' + type: + $ref: '#/components/schemas/SupportCaseType' + status: + $ref: '#/components/schemas/SupportCaseStatus' + description: + $ref: '#/components/schemas/SupportCaseDescription' + object: + description: Object that the case is about, as sent on creation, or null when the case has none. + oneOf: + - $ref: '#/components/schemas/SupportCaseObjectReference' + - type: 'null' + assessment_target: + description: Category of a manual assessment, the optional category of a support case, or null. + oneOf: + - $ref: '#/components/schemas/SupportCaseAssessmentTarget' + - type: 'null' + complaint_reason: + description: Ground of a complaint, or null for other types. + oneOf: + - $ref: '#/components/schemas/SupportCaseComplaintReason' + - type: 'null' + rubric_version: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: 'For a manual assessment, the version of the published rubric of the category that the server fixed on creation; the expert assesses with it, the same rubric as the automated assessment. Null for other types, and null for a manual assessment whose category has no published rubric yet: the case then waits in `waiting_expert` and the client says so instead of promising a date.' + response_target: + $ref: '#/components/schemas/SupportResponseTarget' + decision: + description: Decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: '#/components/schemas/SupportCaseDecision' + - type: 'null' + history: + type: array + minItems: 1 + maxItems: 200 + description: 'Every public event in the order it happened, starting with `created`; the list is never truncated. The server keeps a case within 200 events: it rejects a staff reply or status change that would leave no room for the terminal event, so a case always fits and can always be resolved or closed. Further correspondence goes into a new case that references this one as `support_case`.' + items: + $ref: '#/components/schemas/SupportCaseEvent' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + SupportCaseSummary: + type: object + description: 'Case in a list: the fields that a list of cases shows, without the description and the history. GetMySupportCase returns the full case.' + additionalProperties: false + required: + - id + - number + - type + - status + - object + - assessment_target + - response_target + - decision_outcome + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: '#/components/schemas/SupportCaseNumber' + type: + $ref: '#/components/schemas/SupportCaseType' + status: + $ref: '#/components/schemas/SupportCaseStatus' + object: + description: Object that the case is about, or null. + oneOf: + - $ref: '#/components/schemas/SupportCaseObjectReference' + - type: 'null' + assessment_target: + description: Category of the case, or null. + oneOf: + - $ref: '#/components/schemas/SupportCaseAssessmentTarget' + - type: 'null' + response_target: + $ref: '#/components/schemas/SupportResponseTarget' + decision_outcome: + description: Outcome of the decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: '#/components/schemas/SupportCaseDecisionOutcome' + - type: 'null' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + SupportCaseList: + type: object + description: One page of the cases of the current account, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Case summaries of the page. + items: + $ref: '#/components/schemas/SupportCaseSummary' + page: + $ref: '#/components/schemas/PageInfo' HealthResponse: type: object additionalProperties: false @@ -3868,6 +4554,15 @@ components: type: string format: uuid example: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + SupportCaseId: + name: case_id + in: path + required: true + description: Identifier of a case of the current account. A case of another account and an unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d headers: ETag: description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version. @@ -4224,6 +4919,34 @@ components: examples: 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.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + blank_description: + $ref: '#/components/examples/SupportCaseBlankDescription' + unknown_type: + $ref: '#/components/examples/SupportCaseUnknownType' + decision_sent_by_client: + $ref: '#/components/examples/SupportCaseUnknownField' + malformed_object_id: + $ref: '#/components/examples/SupportCaseMalformedReference' + complaint_reason_needs_invitation: + $ref: '#/components/examples/SupportCaseComplaintNeedsInvitation' + SupportCaseCreateConflict: + description: 'The referenced object does not allow this case now, code state_conflict: the attempt of a grade appeal has no result yet, the case referenced by a grade appeal is not a manual assessment resolved with the outcome assessed, the attempt of an anti-cheat appeal has no anti-cheat review decision, the attempt or the manual assessment already has an appeal of the same type, or an open case of the same type already exists for the category or the object. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was created in either case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/SupportCaseAppealExists' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' securitySchemes: sessionCookie: type: apiKey @@ -6198,6 +6921,281 @@ components: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 0f1a2b3c-4d5e-4f6a-8b7c-8d9e0f1a2b3d + SupportCaseListPage: + summary: The last page of the case summaries of the current account + value: + items: + - id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + number: SC-2026-000123 + type: manual_assessment + status: waiting_expert + object: null + assessment_target: + specialization: backend + grade: middle + response_target: + kind: operational_goal + business_days: 5 + due_at: '2026-10-13T09:00:00Z' + answered_at: null + late: false + policy_version: 1 + decision_outcome: null + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:00:00Z' + - id: 01928f7a-5d6e-7f8a-9b0c-1d2e3f4a5b6c + number: SC-2026-000097 + type: grade_appeal + status: resolved + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + assessment_target: null + response_target: + kind: operational_goal + business_days: 10 + due_at: '2026-10-15T10:00:00Z' + answered_at: '2026-10-09T14:30:00Z' + late: false + policy_version: 1 + decision_outcome: not_upheld + created_at: '2026-10-01T10:00:00Z' + updated_at: '2026-10-09T14:30:00Z' + - id: 01928f7a-4c5d-7e6f-8a9b-0c1d2e3f4a5b + number: SC-2026-000088 + type: support + status: in_review + object: null + assessment_target: + specialization: backend + grade: senior + response_target: + kind: operational_goal + business_days: 3 + due_at: '2026-10-02T12:00:00Z' + answered_at: '2026-10-01T09:20:00Z' + late: false + policy_version: 1 + decision_outcome: null + created_at: '2026-09-29T12:00:00Z' + updated_at: '2026-10-01T09:20:00Z' + page: + has_more: false + next_cursor: null + SupportCaseCreateManualAssessment: + summary: A manual assessment of a category instead of the automated one + value: + type: manual_assessment + description: Прошу провести ручную оценку по рубрике Backend Middle вместо автоматической категоризации. + assessment_target: + specialization: backend + grade: middle + SupportCaseCreateGradeAppeal: + summary: An appeal of the result of an own attempt + value: + type: grade_appeal + description: Практика не засчитана, хотя решение проходит публичные примеры. Прошу пересмотреть результат. + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + SupportCaseCreateCategoryAppeal: + summary: An appeal of a category that a manual assessment assigned + description: The category came from an expert without an attempt, so the appeal references the resolved manual assessment case. + value: + type: grade_appeal + description: Эксперт подтвердил Junior, но в рубрике Middle я выполнил все обязательные пункты. Прошу пересмотреть. + object: + type: support_case + id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + SupportCaseCreateTestUnavailable: + summary: A support case about a test that is not available + value: + type: support + description: Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. + assessment_target: + specialization: backend + grade: senior + SupportCaseCreateComplaint: + summary: A complaint about the salary terms of an offer + value: + type: complaint + description: После принятия приглашения компания предложила сумму ниже указанной вилки. + complaint_reason: salary_terms_violation + object: + type: invitation + id: 01928f7a-7f8a-7b9c-8d0e-1f2a3b4c5d6e + SupportCaseManualAssessmentCreated: + summary: A new manual assessment request with its rubric and response target + description: The server moves the case to waiting_expert in the same transaction as the creation, so the 201 already shows both events. + value: + id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + number: SC-2026-000123 + type: manual_assessment + status: waiting_expert + description: Прошу провести ручную оценку по рубрике Backend Middle вместо автоматической категоризации. + object: null + assessment_target: + specialization: backend + grade: middle + complaint_reason: null + rubric_version: 3 + response_target: + kind: operational_goal + business_days: 5 + due_at: '2026-10-13T09:00:00Z' + answered_at: null + late: false + policy_version: 1 + decision: null + history: + - sequence: 1 + kind: created + actor: user + occurred_at: '2026-10-06T09:00:00Z' + status: submitted + message: null + - sequence: 2 + kind: status_changed + actor: system + occurred_at: '2026-10-06T09:00:00Z' + status: waiting_expert + message: null + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:00:00Z' + SupportCaseBlankDescription: + summary: The description is empty or contains only whitespace + 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: 5a6b7c8d-9e0f-4a1b-8c2d-3e4f5a6b7c8d + errors: + - in: body + pointer: /description + code: invalid + 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. + 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: 6b7c8d9e-0f1a-4b2c-9d3e-4f5a6b7c8d9e + errors: + - in: body + pointer: '' + code: invalid + 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. + 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: 7c8d9e0f-1a2b-4c3d-8e4f-5a6b7c8d9e0f + errors: + - in: body + pointer: '' + code: invalid + 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. + 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: 0f1a2b3c-4d5e-4f6a-9b7c-8d9e0f1a2b3c + errors: + - in: body + pointer: '' + code: invalid + message: The value does not match the contract. + SupportCaseComplaintNeedsInvitation: + summary: The complaint reason requires an invitation reference + 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: 8d9e0f1a-2b3c-4d4e-9f5a-6b7c8d9e0f1a + errors: + - in: body + pointer: /object/type + code: invalid + message: The value does not match the contract. + SupportCaseAppealExists: + summary: The attempt or the manual assessment already has an appeal of this type + 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: 9e0f1a2b-3c4d-4e5f-8a6b-7c8d9e0f1a2b + SupportCaseGradeAppealResolved: + summary: An own grade appeal with a public decision + value: + id: 01928f7a-5d6e-7f8a-9b0c-1d2e3f4a5b6c + number: SC-2026-000097 + type: grade_appeal + status: resolved + description: Практика не засчитана, хотя решение проходит публичные примеры. Прошу пересмотреть результат. + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + assessment_target: null + complaint_reason: null + rubric_version: null + response_target: + kind: operational_goal + business_days: 10 + due_at: '2026-10-15T10:00:00Z' + answered_at: '2026-10-09T14:30:00Z' + late: false + policy_version: 1 + decision: + outcome: not_upheld + reason: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам. + decided_at: '2026-10-09T14:30:00Z' + history: + - sequence: 1 + kind: created + actor: user + occurred_at: '2026-10-01T10:00:00Z' + status: submitted + message: null + - sequence: 2 + kind: status_changed + actor: system + occurred_at: '2026-10-01T10:00:00Z' + status: waiting_expert + message: null + - sequence: 3 + kind: status_changed + actor: support + occurred_at: '2026-10-07T08:15:00Z' + status: in_review + message: null + - sequence: 4 + kind: decision + actor: support + occurred_at: '2026-10-09T14:30:00Z' + status: resolved + 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: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 81291c8..a1d44c9 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -32,6 +32,13 @@ 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: 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. # Operations require a session unless they declare `security: []`, so a new # operation that omits security is protected by default. security: @@ -73,6 +80,10 @@ paths: $ref: ./routes/organization_needs.yml /api/v1/organizations/{org_id}/needs/{need_id}: $ref: ./routes/organization_need.yml + /api/v1/me/support-cases: + $ref: ./routes/support_cases.yml + /api/v1/me/support-cases/{case_id}: + $ref: ./routes/support_case.yml components: schemas: Problem: @@ -381,6 +392,60 @@ components: $ref: ./components/schemas.yml#/NeedCreate NeedUpdate: $ref: ./components/schemas.yml#/NeedUpdate + SupportCaseNumber: + $ref: ./components/schemas.yml#/SupportCaseNumber + SupportCaseType: + $ref: ./components/schemas.yml#/SupportCaseType + SupportCaseStatus: + $ref: ./components/schemas.yml#/SupportCaseStatus + SupportCaseObjectType: + $ref: ./components/schemas.yml#/SupportCaseObjectType + SupportCaseObjectReference: + $ref: ./components/schemas.yml#/SupportCaseObjectReference + SupportCaseAttemptReference: + $ref: ./components/schemas.yml#/SupportCaseAttemptReference + SupportCaseGradeAppealReference: + $ref: ./components/schemas.yml#/SupportCaseGradeAppealReference + SupportCaseComplaintReference: + $ref: ./components/schemas.yml#/SupportCaseComplaintReference + SupportCaseAssessmentTarget: + $ref: ./components/schemas.yml#/SupportCaseAssessmentTarget + SupportCaseComplaintReason: + $ref: ./components/schemas.yml#/SupportCaseComplaintReason + SupportCaseDescription: + $ref: ./components/schemas.yml#/SupportCaseDescription + SupportCasePublicText: + $ref: ./components/schemas.yml#/SupportCasePublicText + SupportCaseCreateSupport: + $ref: ./components/schemas.yml#/SupportCaseCreateSupport + SupportCaseCreateComplaint: + $ref: ./components/schemas.yml#/SupportCaseCreateComplaint + SupportCaseCreateGradeAppeal: + $ref: ./components/schemas.yml#/SupportCaseCreateGradeAppeal + SupportCaseCreateAnticheatAppeal: + $ref: ./components/schemas.yml#/SupportCaseCreateAnticheatAppeal + SupportCaseCreateManualAssessment: + $ref: ./components/schemas.yml#/SupportCaseCreateManualAssessment + SupportCaseCreate: + $ref: ./components/schemas.yml#/SupportCaseCreate + SupportResponseTarget: + $ref: ./components/schemas.yml#/SupportResponseTarget + SupportCaseDecisionOutcome: + $ref: ./components/schemas.yml#/SupportCaseDecisionOutcome + SupportCaseDecision: + $ref: ./components/schemas.yml#/SupportCaseDecision + SupportCaseActorKind: + $ref: ./components/schemas.yml#/SupportCaseActorKind + SupportCaseEventKind: + $ref: ./components/schemas.yml#/SupportCaseEventKind + SupportCaseEvent: + $ref: ./components/schemas.yml#/SupportCaseEvent + SupportCase: + $ref: ./components/schemas.yml#/SupportCase + SupportCaseSummary: + $ref: ./components/schemas.yml#/SupportCaseSummary + SupportCaseList: + $ref: ./components/schemas.yml#/SupportCaseList parameters: IdempotencyKey: $ref: ./components/parameters.yml#/IdempotencyKey @@ -396,6 +461,8 @@ components: $ref: ./components/parameters.yml#/OrganizationId NeedId: $ref: ./components/parameters.yml#/NeedId + SupportCaseId: + $ref: ./components/parameters.yml#/SupportCaseId headers: ETag: $ref: ./components/headers.yml#/ETag @@ -468,6 +535,10 @@ components: $ref: ./components/responses.yml#/NeedValidationFailed NeedVersionConflict: $ref: ./components/responses.yml#/NeedVersionConflict + SupportCaseValidationFailed: + $ref: ./components/responses.yml#/SupportCaseValidationFailed + SupportCaseCreateConflict: + $ref: ./components/responses.yml#/SupportCaseCreateConflict securitySchemes: sessionCookie: type: apiKey diff --git a/api/core/routes/support_case.yml b/api/core/routes/support_case.yml new file mode 100644 index 0000000..2998471 --- /dev/null +++ b/api/core/routes/support_case.yml @@ -0,0 +1,40 @@ +get: + operationId: GetMySupportCase + summary: Read a support case of the current account. + description: |- + Requires the session cookie of a candidate or an employer account. Returns the case with its number, type, object reference, status, response target, decision, and public history. The owner reads the case whatever happened to the object since then: a revoked access, a closed invitation, or a refused test never hides the case from its author. + + The case never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. `decision` is null until the case is `resolved`. + + The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one. + + The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - support + parameters: + - $ref: ../components/parameters.yml#/SupportCaseId + responses: + "200": + description: The case. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SupportCase + examples: + manual_assessment_created: + $ref: ../components/examples.yml#/SupportCaseManualAssessmentCreated + grade_appeal_resolved: + $ref: ../components/examples.yml#/SupportCaseGradeAppealResolved + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/support_cases.yml b/api/core/routes/support_cases.yml new file mode 100644 index 0000000..6b24c61 --- /dev/null +++ b/api/core/routes/support_cases.yml @@ -0,0 +1,122 @@ +get: + operationId: ListMySupportCases + summary: List the support cases of the current account. + description: |- + Requires the session cookie of a candidate or an employer account. Returns a page of the cases that this account created, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. Each item is a summary with the number, type, status, object reference, category, response target, and decision outcome; it has no description and no history, which GetMySupportCase returns with the full case. Cases of other accounts are never listed, including cases of other members of the same organization. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit` or `cursor` answers 400 validation_failed. Filters by status and type are planned and add optional parameters. + security: + - sessionCookie: [] + tags: + - support + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the cases of the current account. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SupportCaseList + examples: + last_page: + $ref: ../components/examples.yml#/SupportCaseListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + default: + $ref: ../components/responses.yml#/Problem +post: + operationId: CreateMySupportCase + summary: Open a support case, a complaint, an appeal, or a manual assessment request. + description: |- + Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The author is the account of the session; the body has no user, account, or organization field. A case is reachable from any screen, including a screen that denies access to an assessment: being refused an action never removes the path to a case about it. + + The client sends only what the user states: `type`, a non-blank `description`, and the fields of the type. It never sets the status, the decision, the outcome, the priority, the response target, the rubric, the assignee, or the moderator: every variant has `additionalProperties: false`, so such fields answer 400. Attachments are not part of the MVP; they are planned as an optional field and change no existing one. + + Types, accounts, and allowed references: + + | Type | Accounts | Object reference | Other fields | + | --- | --- | --- | --- | + | `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` that the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` | + | `complaint` | candidate | required; an `organization` that the caller can see or an `invitation` addressed to the caller | required `complaint_reason`; `offer_content` and `salary_terms_violation` require an invitation | + | `grade_appeal` | candidate | required; `assessment_attempt` of the caller in a terminal state, so it has a result, or a `support_case` of the caller of type `manual_assessment` that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt | none | + | `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. + + 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. + + 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. + + Description check: the schema pattern `\S` uses the ECMAScript white space set in both generated validators (ogen converts it for Go), so a description of spaces such as U+00A0 or U+3000 already fails validation with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes, so the server also applies a domain check: a description whose every character is `unicode.IsSpace` or U+FEFF answers 400 validation_failed with the pointer `/description`. This check comes with the implementation; generated Zod accepts a description of NEL, and the server stays authoritative. + + The new case gets a number and the status `submitted`. A grade appeal, an anti-cheat appeal, and a manual assessment are moved to `waiting_expert` by a `system` event in the same transaction, so the 201 already shows that status with both events; a support case and a complaint stay `submitted`. Each case gets a response target from the product policy version and the configured business calendar: 5 business days for a manual assessment and 10 for an appeal (PRD FR18 and C3), and a policy value for support and complaints. The target is an operational goal, not a deadline set by law. A manual assessment fixes the published rubric version of the category, or null when the category has none yet; the expert assesses with the same rubric as the automated assessment, and the request assigns no category by itself. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt. + + Replies: the case itself is the channel. Support replies and decisions appear in the public `history` and `decision`. The server may also notify the verified email address of the account that the case changed, with the case number and a link, never with the description, the reply, or assessment details. No request field names another address or contact, so the operation cannot send mail to an address that the user typed. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 with the same number and creates nothing, so a lost response never opens a second case. The replay is the snapshot stored at creation, following the repository convention; the client reads the current status and history with GetMySupportCase. 404 and 409 state_conflict are stored and replayed as well. A different body with the same key answers 422 idempotency_key_reused. 400, 403, 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 an employer account with a type other than `support`), the per-account case limit (429), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with the pointer `/description` for a text of only Unicode spaces or `/object/type` for a complaint reason that requires an invitation), the object reference (404 not_found), then the state of the object and the limits (409 state_conflict). The general rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - support + parameters: + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SupportCaseCreate + examples: + manual_assessment: + $ref: ../components/examples.yml#/SupportCaseCreateManualAssessment + own_grade_appeal: + $ref: ../components/examples.yml#/SupportCaseCreateGradeAppeal + appeal_of_manual_assessment: + $ref: ../components/examples.yml#/SupportCaseCreateCategoryAppeal + test_unavailable: + $ref: ../components/examples.yml#/SupportCaseCreateTestUnavailable + salary_terms_complaint: + $ref: ../components/examples.yml#/SupportCaseCreateComplaint + responses: + "201": + description: >- + The case was created, with the status `submitted` or, for an appeal + or a manual assessment, `waiting_expert`; or a retry with the same + Idempotency-Key replayed the stored creation response. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SupportCase + examples: + manual_assessment: + $ref: ../components/examples.yml#/SupportCaseManualAssessmentCreated + "400": + $ref: ../components/responses.yml#/SupportCaseValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/SupportCaseCreateConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem 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 eb27608..a71f7db 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -17,7 +17,9 @@ import ( ) var regexMap = map[string]ogenregex.Regexp{ + "\\S": ogenregex.MustCompile("\\S"), "^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"), + "^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._:-]+$"), "^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"), 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 346a0b2..7109a4e 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -474,6 +474,324 @@ func (s *Server) handleCreateMyAssessmentAttemptRequest(args [0]string, argsEsca } } +// handleCreateMySupportCaseRequest handles CreateMySupportCase operation. +// +// Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and +// an Idempotency-Key. The author is the account of the session; the body has no user, account, or +// organization field. A case is reachable from any screen, including a screen that denies access to an +// assessment: being refused an action never removes the path to a case about it. +// +// The client sends only what the user states: `type`, a non-blank `description`, and the fields of the +// type. It never sets the status, the decision, the outcome, the priority, the response target, the +// rubric, the assignee, or the moderator: every variant has `additionalProperties: false`, so such +// fields answer 400. Attachments are not part of the MVP; they are planned as an optional field and +// change no existing one. +// +// Types, accounts, and allowed references: +// +// Type | Accounts | Object reference | Other fields +// --------------------+---------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------ +// `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` that the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` +// `complaint` | candidate | required; an `organization` that the caller can see or an `invitation` addressed to the caller | required `complaint_reason`; `offer_content` and `salary_terms_violation` require an invitation +// `grade_appeal` | candidate | required; `assessment_attempt` of the caller in a terminal state, so it has a result, or a `support_case` of the caller of type `manual_assessment` that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt | none +// `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. +// +// 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. +// +// 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. +// +// Description check: the schema pattern `\S` uses the ECMAScript white space set in both generated +// validators (ogen converts it for Go), so a description of spaces such as U+00A0 or U+3000 already +// fails validation with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which +// Go `unicode.IsSpace` includes, so the server also applies a domain check: a description whose every +// character is `unicode.IsSpace` or U+FEFF answers 400 validation_failed with the pointer +// `/description`. This check comes with the implementation; generated Zod accepts a description of +// NEL, and the server stays authoritative. +// +// The new case gets a number and the status `submitted`. A grade appeal, an anti-cheat appeal, and a +// manual assessment are moved to `waiting_expert` by a `system` event in the same transaction, so the +// 201 already shows that status with both events; a support case and a complaint stay `submitted`. +// Each case gets a response target from the product policy version and the configured business +// calendar: 5 business days for a manual assessment and 10 for an appeal (PRD FR18 and C3), and a +// policy value for support and complaints. The target is an operational goal, not a deadline set by +// law. A manual assessment fixes the published rubric version of the category, or null when the +// category has none yet; the expert assesses with the same rubric as the automated assessment, and the +// request assigns no category by itself. Creating a case never grants, revokes, or changes a consent, +// a grade, or an attempt. +// +// Replies: the case itself is the channel. Support replies and decisions appear in the public +// `history` and `decision`. The server may also notify the verified email address of the account that +// the case changed, with the case number and a link, never with the description, the reply, or +// assessment details. No request field names another address or contact, so the operation cannot send +// mail to an address that the user typed. +// +// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 with the same +// number and creates nothing, so a lost response never opens a second case. The replay is the snapshot +// stored at creation, following the repository convention; the client reads the current status and +// history with GetMySupportCase. 404 and 409 state_conflict are stored and replayed as well. A +// different body with the same key answers 422 idempotency_key_reused. 400, 403, 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 an employer account with a type other than `support`), the +// per-account case limit (429), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain +// rules (400 with the pointer `/description` for a text of only Unicode spaces or `/object/type` for a +// complaint reason that requires an invitation), the object reference (404 not_found), then the state +// of the object and the limits (409 state_conflict). The general rate limit can answer 429 with +// Retry-After before any check. +// +// POST /api/v1/me/support-cases +func (s *Server) handleCreateMySupportCaseRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("CreateMySupportCase"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/me/support-cases"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateMySupportCaseOperation, + 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: CreateMySupportCaseOperation, + ID: "CreateMySupportCase", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, CreateMySupportCaseOperation, 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, CreateMySupportCaseOperation, 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 := decodeCreateMySupportCaseParams(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.decodeCreateMySupportCaseRequest(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 CreateMySupportCaseRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CreateMySupportCaseOperation, + OperationSummary: "Open a support case, a complaint, an appeal, or a manual assessment request.", + OperationID: "CreateMySupportCase", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "Idempotency-Key", + In: "header", + }: params.IdempotencyKey, + }, + Raw: r, + } + + type ( + Request = SupportCaseCreate + Params = CreateMySupportCaseParams + Response = CreateMySupportCaseRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackCreateMySupportCaseParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.CreateMySupportCase(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.CreateMySupportCase(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 := encodeCreateMySupportCaseResponse(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 @@ -2530,6 +2848,222 @@ func (s *Server) handleGetMyQuestionnaireRequest(args [0]string, argsEscaped boo } } +// handleGetMySupportCaseRequest handles GetMySupportCase operation. +// +// Requires the session cookie of a candidate or an employer account. Returns the case with its number, +// type, object reference, status, response target, decision, and public history. The owner reads the +// case whatever happened to the object since then: a revoked access, a closed invitation, or a refused +// test never hides the case from its author. +// +// The case never contains the identity of a moderator, an expert, or a support agent, internal notes, +// evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. +// `decision` is null until the case is `resolved`. +// +// The history lists every public event and is never truncated: the server keeps a case within 200 +// events by rejecting a staff event that would leave no room for the terminal one. +// +// The case must belong to the account of the session: a case of another account, including another +// member of the same organization, answers 404 not_found, the same as an unknown identifier, so +// identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers +// 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A +// malformed `case_id` answers 400 validation_failed with the path pointer. +// +// GET /api/v1/me/support-cases/{case_id} +func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMySupportCase"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/support-cases/{case_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(), GetMySupportCaseOperation, + 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: GetMySupportCaseOperation, + ID: "GetMySupportCase", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMySupportCaseOperation, 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 := decodeGetMySupportCaseParams(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 GetMySupportCaseRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMySupportCaseOperation, + OperationSummary: "Read a support case of the current account.", + OperationID: "GetMySupportCase", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "case_id", + In: "path", + }: params.CaseID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = GetMySupportCaseParams + Response = GetMySupportCaseRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackGetMySupportCaseParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMySupportCase(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.GetMySupportCase(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 := encodeGetMySupportCaseResponse(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 @@ -2908,6 +3442,219 @@ func (s *Server) handleGetSpecializationCatalogRequest(args [0]string, argsEscap } } +// handleListMySupportCasesRequest handles ListMySupportCases operation. +// +// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that +// this account created, newest first by creation time with the identifier as the tie-breaker, with +// cursor pagination. Each item is a summary with the number, type, status, object reference, category, +// response target, and decision outcome; it has no description and no history, which GetMySupportCase +// returns with the full case. Cases of other accounts are never listed, including cases of other +// members of the same organization. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed +// `limit` or `cursor` answers 400 validation_failed. Filters by status and type are planned and add +// optional parameters. +// +// GET /api/v1/me/support-cases +func (s *Server) handleListMySupportCasesRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListMySupportCases"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/support-cases"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListMySupportCasesOperation, + 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: ListMySupportCasesOperation, + ID: "ListMySupportCases", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListMySupportCasesOperation, 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 := decodeListMySupportCasesParams(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 ListMySupportCasesRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListMySupportCasesOperation, + OperationSummary: "List the support cases of the current account.", + OperationID: "ListMySupportCases", + 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 = ListMySupportCasesParams + Response = ListMySupportCasesRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListMySupportCasesParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListMySupportCases(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListMySupportCases(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 := encodeListMySupportCasesResponse(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 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 4062f4b..fc7d652 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -9,6 +9,10 @@ type CreateMyAssessmentAttemptRes interface { createMyAssessmentAttemptRes() } +type CreateMySupportCaseRes interface { + createMySupportCaseRes() +} + type CreateOrganizationNeedRes interface { createOrganizationNeedRes() } @@ -45,10 +49,18 @@ type GetMyQuestionnaireRes interface { getMyQuestionnaireRes() } +type GetMySupportCaseRes interface { + getMySupportCaseRes() +} + type GetOrganizationNeedRes interface { getOrganizationNeedRes() } +type ListMySupportCasesRes interface { + listMySupportCasesRes() +} + type ListOrganizationNeedsRes interface { listOrganizationNeedsRes() } 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 3c20d14..2be1905 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -6285,6 +6285,234 @@ func (s *CreateMyAssessmentAttemptUnprocessableEntity) UnmarshalJSON(data []byte return s.Decode(d) } +// Encode encodes CreateMySupportCaseBadRequest as json. +func (s *CreateMySupportCaseBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMySupportCaseBadRequest from json. +func (s *CreateMySupportCaseBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMySupportCaseBadRequest 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 = CreateMySupportCaseBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMySupportCaseBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMySupportCaseBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMySupportCaseConflict as json. +func (s *CreateMySupportCaseConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMySupportCaseConflict from json. +func (s *CreateMySupportCaseConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMySupportCaseConflict 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 = CreateMySupportCaseConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMySupportCaseConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMySupportCaseConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMySupportCaseForbidden as json. +func (s *CreateMySupportCaseForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMySupportCaseForbidden from json. +func (s *CreateMySupportCaseForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMySupportCaseForbidden 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 = CreateMySupportCaseForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMySupportCaseForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMySupportCaseForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMySupportCaseNotFound as json. +func (s *CreateMySupportCaseNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMySupportCaseNotFound from json. +func (s *CreateMySupportCaseNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMySupportCaseNotFound 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 = CreateMySupportCaseNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMySupportCaseNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMySupportCaseNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMySupportCaseUnauthorized as json. +func (s *CreateMySupportCaseUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMySupportCaseUnauthorized from json. +func (s *CreateMySupportCaseUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMySupportCaseUnauthorized 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 = CreateMySupportCaseUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMySupportCaseUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMySupportCaseUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CreateMySupportCaseUnprocessableEntity as json. +func (s *CreateMySupportCaseUnprocessableEntity) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes CreateMySupportCaseUnprocessableEntity from json. +func (s *CreateMySupportCaseUnprocessableEntity) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CreateMySupportCaseUnprocessableEntity 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 = CreateMySupportCaseUnprocessableEntity(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CreateMySupportCaseUnprocessableEntity) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CreateMySupportCaseUnprocessableEntity) 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) @@ -8057,6 +8285,120 @@ func (s *GetMyQuestionnaireUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GetMySupportCaseBadRequest as json. +func (s *GetMySupportCaseBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMySupportCaseBadRequest from json. +func (s *GetMySupportCaseBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMySupportCaseBadRequest 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 = GetMySupportCaseBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMySupportCaseBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMySupportCaseBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMySupportCaseNotFound as json. +func (s *GetMySupportCaseNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMySupportCaseNotFound from json. +func (s *GetMySupportCaseNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMySupportCaseNotFound 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 = GetMySupportCaseNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMySupportCaseNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMySupportCaseNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMySupportCaseUnauthorized as json. +func (s *GetMySupportCaseUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMySupportCaseUnauthorized from json. +func (s *GetMySupportCaseUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMySupportCaseUnauthorized 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 = GetMySupportCaseUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMySupportCaseUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMySupportCaseUnauthorized) 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) @@ -8828,6 +9170,82 @@ func (s *ItemContent) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListMySupportCasesBadRequest as json. +func (s *ListMySupportCasesBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMySupportCasesBadRequest from json. +func (s *ListMySupportCasesBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMySupportCasesBadRequest 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 = ListMySupportCasesBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMySupportCasesBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMySupportCasesBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMySupportCasesUnauthorized as json. +func (s *ListMySupportCasesUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMySupportCasesUnauthorized from json. +func (s *ListMySupportCasesUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMySupportCasesUnauthorized 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 = ListMySupportCasesUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMySupportCasesUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMySupportCasesUnauthorized) 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) @@ -15506,6 +15924,314 @@ func (s *NilString) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes SupportCaseAssessmentTarget as json. +func (o NilSupportCaseAssessmentTarget) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes SupportCaseAssessmentTarget from json. +func (o *NilSupportCaseAssessmentTarget) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilSupportCaseAssessmentTarget to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v SupportCaseAssessmentTarget + 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 NilSupportCaseAssessmentTarget) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilSupportCaseAssessmentTarget) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseComplaintReason as json. +func (o NilSupportCaseComplaintReason) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes SupportCaseComplaintReason from json. +func (o *NilSupportCaseComplaintReason) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilSupportCaseComplaintReason to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v SupportCaseComplaintReason + 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 NilSupportCaseComplaintReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilSupportCaseComplaintReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseDecision as json. +func (o NilSupportCaseDecision) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes SupportCaseDecision from json. +func (o *NilSupportCaseDecision) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilSupportCaseDecision to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v SupportCaseDecision + 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 NilSupportCaseDecision) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilSupportCaseDecision) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseDecisionOutcome as json. +func (o NilSupportCaseDecisionOutcome) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes SupportCaseDecisionOutcome from json. +func (o *NilSupportCaseDecisionOutcome) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilSupportCaseDecisionOutcome to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v SupportCaseDecisionOutcome + 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 NilSupportCaseDecisionOutcome) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilSupportCaseDecisionOutcome) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseObjectReference as json. +func (o NilSupportCaseObjectReference) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes SupportCaseObjectReference from json. +func (o *NilSupportCaseObjectReference) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilSupportCaseObjectReference to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v SupportCaseObjectReference + 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 NilSupportCaseObjectReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilSupportCaseObjectReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCasePublicText as json. +func (o NilSupportCasePublicText) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes SupportCasePublicText from json. +func (o *NilSupportCasePublicText) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilSupportCasePublicText to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v SupportCasePublicText + 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 NilSupportCasePublicText) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilSupportCasePublicText) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseStatus as json. +func (o NilSupportCaseStatus) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes SupportCaseStatus from json. +func (o *NilSupportCaseStatus) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilSupportCaseStatus to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v SupportCaseStatus + 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 NilSupportCaseStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilSupportCaseStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes TaskLanguage as json. func (o NilTaskLanguage) Encode(e *jx.Encoder) { if o.Null { @@ -16490,6 +17216,105 @@ func (s *OptString) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes SupportCaseAssessmentTarget as json. +func (o OptSupportCaseAssessmentTarget) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes SupportCaseAssessmentTarget from json. +func (o *OptSupportCaseAssessmentTarget) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptSupportCaseAssessmentTarget to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptSupportCaseAssessmentTarget) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptSupportCaseAssessmentTarget) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseAttemptReference as json. +func (o OptSupportCaseAttemptReference) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes SupportCaseAttemptReference from json. +func (o *OptSupportCaseAttemptReference) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptSupportCaseAttemptReference to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptSupportCaseAttemptReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptSupportCaseAttemptReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseObjectReference as json. +func (o OptSupportCaseObjectReference) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes SupportCaseObjectReference from json. +func (o *OptSupportCaseObjectReference) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptSupportCaseObjectReference to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptSupportCaseObjectReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptSupportCaseObjectReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *OrderAnswer) Encode(e *jx.Encoder) { e.ObjStart() @@ -20397,6 +21222,3300 @@ func (s *SubmitMyAssessmentAnswerUnprocessableEntity) UnmarshalJSON(data []byte) return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *SupportCase) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCase) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("number") + s.Number.Encode(e) + } + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("description") + s.Description.Encode(e) + } + { + e.FieldStart("object") + s.Object.Encode(e) + } + { + e.FieldStart("assessment_target") + s.AssessmentTarget.Encode(e) + } + { + e.FieldStart("complaint_reason") + s.ComplaintReason.Encode(e) + } + { + e.FieldStart("rubric_version") + s.RubricVersion.Encode(e) + } + { + e.FieldStart("response_target") + s.ResponseTarget.Encode(e) + } + { + e.FieldStart("decision") + s.Decision.Encode(e) + } + { + e.FieldStart("history") + e.ArrStart() + for _, elem := range s.History { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("created_at") + s.CreatedAt.Encode(e) + } + { + e.FieldStart("updated_at") + s.UpdatedAt.Encode(e) + } +} + +var jsonFieldsNameOfSupportCase = [14]string{ + 0: "id", + 1: "number", + 2: "type", + 3: "status", + 4: "description", + 5: "object", + 6: "assessment_target", + 7: "complaint_reason", + 8: "rubric_version", + 9: "response_target", + 10: "decision", + 11: "history", + 12: "created_at", + 13: "updated_at", +} + +// Decode decodes SupportCase from json. +func (s *SupportCase) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCase 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 "number": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Number.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"number\"") + } + case "type": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "status": + requiredBitSet[0] |= 1 << 3 + 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 << 4 + 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\"") + } + case "object": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Object.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"object\"") + } + case "assessment_target": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.AssessmentTarget.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"assessment_target\"") + } + case "complaint_reason": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.ComplaintReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"complaint_reason\"") + } + case "rubric_version": + requiredBitSet[1] |= 1 << 0 + if err := func() error { + if err := s.RubricVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"rubric_version\"") + } + case "response_target": + requiredBitSet[1] |= 1 << 1 + if err := func() error { + if err := s.ResponseTarget.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"response_target\"") + } + case "decision": + requiredBitSet[1] |= 1 << 2 + if err := func() error { + if err := s.Decision.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"decision\"") + } + case "history": + requiredBitSet[1] |= 1 << 3 + if err := func() error { + s.History = make([]SupportCaseEvent, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem SupportCaseEvent + if err := elem.Decode(d); err != nil { + return err + } + s.History = append(s.History, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"history\"") + } + case "created_at": + requiredBitSet[1] |= 1 << 4 + 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 << 5 + 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 SupportCase") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [2]uint8{ + 0b11111111, + 0b00111111, + } { + 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(jsonFieldsNameOfSupportCase) { + name = jsonFieldsNameOfSupportCase[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 *SupportCase) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCase) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseActorKind as json. +func (s SupportCaseActorKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseActorKind from json. +func (s *SupportCaseActorKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseActorKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseActorKind(v) { + case SupportCaseActorKindUser: + *s = SupportCaseActorKindUser + case SupportCaseActorKindSupport: + *s = SupportCaseActorKindSupport + case SupportCaseActorKindSystem: + *s = SupportCaseActorKindSystem + default: + *s = SupportCaseActorKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseActorKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseActorKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseAssessmentTarget) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseAssessmentTarget) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("grade") + s.Grade.Encode(e) + } +} + +var jsonFieldsNameOfSupportCaseAssessmentTarget = [2]string{ + 0: "specialization", + 1: "grade", +} + +// Decode decodes SupportCaseAssessmentTarget from json. +func (s *SupportCaseAssessmentTarget) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseAssessmentTarget to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specialization": + requiredBitSet[0] |= 1 << 0 + 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 << 1 + 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\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseAssessmentTarget") + } + // 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(jsonFieldsNameOfSupportCaseAssessmentTarget) { + name = jsonFieldsNameOfSupportCaseAssessmentTarget[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 *SupportCaseAssessmentTarget) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseAssessmentTarget) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseAttemptReference) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseAttemptReference) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } +} + +var jsonFieldsNameOfSupportCaseAttemptReference = [2]string{ + 0: "type", + 1: "id", +} + +// Decode decodes SupportCaseAttemptReference from json. +func (s *SupportCaseAttemptReference) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseAttemptReference to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "id": + requiredBitSet[0] |= 1 << 1 + 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\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseAttemptReference") + } + // 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(jsonFieldsNameOfSupportCaseAttemptReference) { + name = jsonFieldsNameOfSupportCaseAttemptReference[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 *SupportCaseAttemptReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseAttemptReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseAttemptReferenceType as json. +func (s SupportCaseAttemptReferenceType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseAttemptReferenceType from json. +func (s *SupportCaseAttemptReferenceType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseAttemptReferenceType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseAttemptReferenceType(v) { + case SupportCaseAttemptReferenceTypeAssessmentAttempt: + *s = SupportCaseAttemptReferenceTypeAssessmentAttempt + default: + *s = SupportCaseAttemptReferenceType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseAttemptReferenceType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseAttemptReferenceType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseComplaintReason as json. +func (s SupportCaseComplaintReason) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseComplaintReason from json. +func (s *SupportCaseComplaintReason) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseComplaintReason to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseComplaintReason(v) { + case SupportCaseComplaintReasonOrganizationConduct: + *s = SupportCaseComplaintReasonOrganizationConduct + case SupportCaseComplaintReasonOfferContent: + *s = SupportCaseComplaintReasonOfferContent + case SupportCaseComplaintReasonSalaryTermsViolation: + *s = SupportCaseComplaintReasonSalaryTermsViolation + case SupportCaseComplaintReasonDataDisclosure: + *s = SupportCaseComplaintReasonDataDisclosure + case SupportCaseComplaintReasonOther: + *s = SupportCaseComplaintReasonOther + default: + *s = SupportCaseComplaintReason(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseComplaintReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseComplaintReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseComplaintReference) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseComplaintReference) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } +} + +var jsonFieldsNameOfSupportCaseComplaintReference = [2]string{ + 0: "type", + 1: "id", +} + +// Decode decodes SupportCaseComplaintReference from json. +func (s *SupportCaseComplaintReference) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseComplaintReference to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "id": + requiredBitSet[0] |= 1 << 1 + 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\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseComplaintReference") + } + // 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(jsonFieldsNameOfSupportCaseComplaintReference) { + name = jsonFieldsNameOfSupportCaseComplaintReference[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 *SupportCaseComplaintReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseComplaintReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseComplaintReferenceType as json. +func (s SupportCaseComplaintReferenceType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseComplaintReferenceType from json. +func (s *SupportCaseComplaintReferenceType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseComplaintReferenceType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseComplaintReferenceType(v) { + case SupportCaseComplaintReferenceTypeOrganization: + *s = SupportCaseComplaintReferenceTypeOrganization + case SupportCaseComplaintReferenceTypeInvitation: + *s = SupportCaseComplaintReferenceTypeInvitation + default: + *s = SupportCaseComplaintReferenceType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseComplaintReferenceType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseComplaintReferenceType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseCreate as json. +func (s SupportCaseCreate) Encode(e *jx.Encoder) { + switch s.Type { + case SupportCaseCreateSupportSupportCaseCreate: + s.SupportCaseCreateSupport.Encode(e) + case SupportCaseCreateComplaintSupportCaseCreate: + s.SupportCaseCreateComplaint.Encode(e) + case SupportCaseCreateGradeAppealSupportCaseCreate: + s.SupportCaseCreateGradeAppeal.Encode(e) + case SupportCaseCreateAnticheatAppealSupportCaseCreate: + s.SupportCaseCreateAnticheatAppeal.Encode(e) + case SupportCaseCreateManualAssessmentSupportCaseCreate: + s.SupportCaseCreateManualAssessment.Encode(e) + } +} + +func (s SupportCaseCreate) encodeFields(e *jx.Encoder) { + switch s.Type { + case SupportCaseCreateSupportSupportCaseCreate: + s.SupportCaseCreateSupport.encodeFields(e) + case SupportCaseCreateComplaintSupportCaseCreate: + s.SupportCaseCreateComplaint.encodeFields(e) + case SupportCaseCreateGradeAppealSupportCaseCreate: + s.SupportCaseCreateGradeAppeal.encodeFields(e) + case SupportCaseCreateAnticheatAppealSupportCaseCreate: + s.SupportCaseCreateAnticheatAppeal.encodeFields(e) + case SupportCaseCreateManualAssessmentSupportCaseCreate: + s.SupportCaseCreateManualAssessment.encodeFields(e) + } +} + +// Decode decodes SupportCaseCreate from json. +func (s *SupportCaseCreate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreate 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 "complaint_reason": + // 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 := SupportCaseCreateComplaintSupportCaseCreate + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "type": + // 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 "anticheat_appeal": + match := SupportCaseCreateAnticheatAppealSupportCaseCreate + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "complaint": + match := SupportCaseCreateComplaintSupportCaseCreate + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "grade_appeal": + match := SupportCaseCreateGradeAppealSupportCaseCreate + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "manual_assessment": + match := SupportCaseCreateManualAssessmentSupportCaseCreate + if found && s.Type != match { + s.Type = "" + return errors.Errorf("multiple oneOf matches: (%v, %v)", s.Type, match) + } + found = true + s.Type = match + case "support": + match := SupportCaseCreateSupportSupportCaseCreate + 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 SupportCaseCreateSupportSupportCaseCreate: + if err := s.SupportCaseCreateSupport.Decode(d); err != nil { + return err + } + case SupportCaseCreateComplaintSupportCaseCreate: + if err := s.SupportCaseCreateComplaint.Decode(d); err != nil { + return err + } + case SupportCaseCreateGradeAppealSupportCaseCreate: + if err := s.SupportCaseCreateGradeAppeal.Decode(d); err != nil { + return err + } + case SupportCaseCreateAnticheatAppealSupportCaseCreate: + if err := s.SupportCaseCreateAnticheatAppeal.Decode(d); err != nil { + return err + } + case SupportCaseCreateManualAssessmentSupportCaseCreate: + if err := s.SupportCaseCreateManualAssessment.Decode(d); err != nil { + return err + } + default: + return errors.Errorf("inferred invalid type: %s", s.Type) + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseCreate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseCreateAnticheatAppeal) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseCreateAnticheatAppeal) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("description") + s.Description.Encode(e) + } + { + e.FieldStart("object") + s.Object.Encode(e) + } +} + +var jsonFieldsNameOfSupportCaseCreateAnticheatAppeal = [3]string{ + 0: "type", + 1: "description", + 2: "object", +} + +// Decode decodes SupportCaseCreateAnticheatAppeal from json. +func (s *SupportCaseCreateAnticheatAppeal) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateAnticheatAppeal to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + 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\"") + } + case "object": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Object.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"object\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseCreateAnticheatAppeal") + } + // 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(jsonFieldsNameOfSupportCaseCreateAnticheatAppeal) { + name = jsonFieldsNameOfSupportCaseCreateAnticheatAppeal[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 *SupportCaseCreateAnticheatAppeal) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateAnticheatAppeal) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseCreateAnticheatAppealType as json. +func (s SupportCaseCreateAnticheatAppealType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseCreateAnticheatAppealType from json. +func (s *SupportCaseCreateAnticheatAppealType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateAnticheatAppealType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseCreateAnticheatAppealType(v) { + case SupportCaseCreateAnticheatAppealTypeAnticheatAppeal: + *s = SupportCaseCreateAnticheatAppealTypeAnticheatAppeal + default: + *s = SupportCaseCreateAnticheatAppealType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseCreateAnticheatAppealType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateAnticheatAppealType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseCreateComplaint) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseCreateComplaint) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("description") + s.Description.Encode(e) + } + { + e.FieldStart("complaint_reason") + s.ComplaintReason.Encode(e) + } + { + e.FieldStart("object") + s.Object.Encode(e) + } +} + +var jsonFieldsNameOfSupportCaseCreateComplaint = [4]string{ + 0: "type", + 1: "description", + 2: "complaint_reason", + 3: "object", +} + +// Decode decodes SupportCaseCreateComplaint from json. +func (s *SupportCaseCreateComplaint) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateComplaint to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + 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\"") + } + case "complaint_reason": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.ComplaintReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"complaint_reason\"") + } + case "object": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Object.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"object\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseCreateComplaint") + } + // 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(jsonFieldsNameOfSupportCaseCreateComplaint) { + name = jsonFieldsNameOfSupportCaseCreateComplaint[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 *SupportCaseCreateComplaint) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateComplaint) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseCreateComplaintType as json. +func (s SupportCaseCreateComplaintType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseCreateComplaintType from json. +func (s *SupportCaseCreateComplaintType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateComplaintType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseCreateComplaintType(v) { + case SupportCaseCreateComplaintTypeComplaint: + *s = SupportCaseCreateComplaintTypeComplaint + default: + *s = SupportCaseCreateComplaintType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseCreateComplaintType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateComplaintType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseCreateGradeAppeal) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseCreateGradeAppeal) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("description") + s.Description.Encode(e) + } + { + e.FieldStart("object") + s.Object.Encode(e) + } +} + +var jsonFieldsNameOfSupportCaseCreateGradeAppeal = [3]string{ + 0: "type", + 1: "description", + 2: "object", +} + +// Decode decodes SupportCaseCreateGradeAppeal from json. +func (s *SupportCaseCreateGradeAppeal) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateGradeAppeal to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + 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\"") + } + case "object": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Object.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"object\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseCreateGradeAppeal") + } + // 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(jsonFieldsNameOfSupportCaseCreateGradeAppeal) { + name = jsonFieldsNameOfSupportCaseCreateGradeAppeal[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 *SupportCaseCreateGradeAppeal) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateGradeAppeal) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseCreateGradeAppealType as json. +func (s SupportCaseCreateGradeAppealType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseCreateGradeAppealType from json. +func (s *SupportCaseCreateGradeAppealType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateGradeAppealType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseCreateGradeAppealType(v) { + case SupportCaseCreateGradeAppealTypeGradeAppeal: + *s = SupportCaseCreateGradeAppealTypeGradeAppeal + default: + *s = SupportCaseCreateGradeAppealType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseCreateGradeAppealType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateGradeAppealType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseCreateManualAssessment) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseCreateManualAssessment) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("description") + s.Description.Encode(e) + } + { + e.FieldStart("assessment_target") + s.AssessmentTarget.Encode(e) + } + { + if s.Object.Set { + e.FieldStart("object") + s.Object.Encode(e) + } + } +} + +var jsonFieldsNameOfSupportCaseCreateManualAssessment = [4]string{ + 0: "type", + 1: "description", + 2: "assessment_target", + 3: "object", +} + +// Decode decodes SupportCaseCreateManualAssessment from json. +func (s *SupportCaseCreateManualAssessment) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateManualAssessment to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + 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\"") + } + case "assessment_target": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.AssessmentTarget.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"assessment_target\"") + } + case "object": + if err := func() error { + s.Object.Reset() + if err := s.Object.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"object\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseCreateManualAssessment") + } + // 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(jsonFieldsNameOfSupportCaseCreateManualAssessment) { + name = jsonFieldsNameOfSupportCaseCreateManualAssessment[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 *SupportCaseCreateManualAssessment) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateManualAssessment) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseCreateManualAssessmentType as json. +func (s SupportCaseCreateManualAssessmentType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseCreateManualAssessmentType from json. +func (s *SupportCaseCreateManualAssessmentType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateManualAssessmentType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseCreateManualAssessmentType(v) { + case SupportCaseCreateManualAssessmentTypeManualAssessment: + *s = SupportCaseCreateManualAssessmentTypeManualAssessment + default: + *s = SupportCaseCreateManualAssessmentType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseCreateManualAssessmentType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateManualAssessmentType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseCreateSupport) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseCreateSupport) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("description") + s.Description.Encode(e) + } + { + if s.Object.Set { + e.FieldStart("object") + s.Object.Encode(e) + } + } + { + if s.AssessmentTarget.Set { + e.FieldStart("assessment_target") + s.AssessmentTarget.Encode(e) + } + } +} + +var jsonFieldsNameOfSupportCaseCreateSupport = [4]string{ + 0: "type", + 1: "description", + 2: "object", + 3: "assessment_target", +} + +// Decode decodes SupportCaseCreateSupport from json. +func (s *SupportCaseCreateSupport) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateSupport to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + 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\"") + } + case "object": + if err := func() error { + s.Object.Reset() + if err := s.Object.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"object\"") + } + case "assessment_target": + if err := func() error { + s.AssessmentTarget.Reset() + if err := s.AssessmentTarget.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"assessment_target\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseCreateSupport") + } + // 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(jsonFieldsNameOfSupportCaseCreateSupport) { + name = jsonFieldsNameOfSupportCaseCreateSupport[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 *SupportCaseCreateSupport) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateSupport) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseCreateSupportType as json. +func (s SupportCaseCreateSupportType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseCreateSupportType from json. +func (s *SupportCaseCreateSupportType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseCreateSupportType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseCreateSupportType(v) { + case SupportCaseCreateSupportTypeSupport: + *s = SupportCaseCreateSupportTypeSupport + default: + *s = SupportCaseCreateSupportType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseCreateSupportType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseCreateSupportType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseDecision) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseDecision) encodeFields(e *jx.Encoder) { + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("reason") + s.Reason.Encode(e) + } + { + e.FieldStart("decided_at") + s.DecidedAt.Encode(e) + } +} + +var jsonFieldsNameOfSupportCaseDecision = [3]string{ + 0: "outcome", + 1: "reason", + 2: "decided_at", +} + +// Decode decodes SupportCaseDecision from json. +func (s *SupportCaseDecision) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseDecision to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "outcome": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Outcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"outcome\"") + } + 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 "decided_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.DecidedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"decided_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseDecision") + } + // 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(jsonFieldsNameOfSupportCaseDecision) { + name = jsonFieldsNameOfSupportCaseDecision[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 *SupportCaseDecision) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseDecision) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseDecisionOutcome as json. +func (s SupportCaseDecisionOutcome) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseDecisionOutcome from json. +func (s *SupportCaseDecisionOutcome) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseDecisionOutcome to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseDecisionOutcome(v) { + case SupportCaseDecisionOutcomeUpheld: + *s = SupportCaseDecisionOutcomeUpheld + case SupportCaseDecisionOutcomePartiallyUpheld: + *s = SupportCaseDecisionOutcomePartiallyUpheld + case SupportCaseDecisionOutcomeNotUpheld: + *s = SupportCaseDecisionOutcomeNotUpheld + case SupportCaseDecisionOutcomeAnswered: + *s = SupportCaseDecisionOutcomeAnswered + case SupportCaseDecisionOutcomeAssessed: + *s = SupportCaseDecisionOutcomeAssessed + default: + *s = SupportCaseDecisionOutcome(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseDecisionOutcome) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseDecisionOutcome) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseDescription as json. +func (s SupportCaseDescription) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes SupportCaseDescription from json. +func (s *SupportCaseDescription) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseDescription 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 = SupportCaseDescription(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseDescription) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseDescription) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseEvent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseEvent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("sequence") + e.Int32(s.Sequence) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("actor") + s.Actor.Encode(e) + } + { + e.FieldStart("occurred_at") + s.OccurredAt.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("message") + s.Message.Encode(e) + } +} + +var jsonFieldsNameOfSupportCaseEvent = [6]string{ + 0: "sequence", + 1: "kind", + 2: "actor", + 3: "occurred_at", + 4: "status", + 5: "message", +} + +// Decode decodes SupportCaseEvent from json. +func (s *SupportCaseEvent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseEvent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "sequence": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := d.Int32() + s.Sequence = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"sequence\"") + } + case "kind": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "actor": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Actor.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"actor\"") + } + case "occurred_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.OccurredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"occurred_at\"") + } + case "status": + requiredBitSet[0] |= 1 << 4 + 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 "message": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Message.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"message\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseEvent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + 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(jsonFieldsNameOfSupportCaseEvent) { + name = jsonFieldsNameOfSupportCaseEvent[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 *SupportCaseEvent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseEvent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseEventKind as json. +func (s SupportCaseEventKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseEventKind from json. +func (s *SupportCaseEventKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseEventKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseEventKind(v) { + case SupportCaseEventKindCreated: + *s = SupportCaseEventKindCreated + case SupportCaseEventKindStatusChanged: + *s = SupportCaseEventKindStatusChanged + case SupportCaseEventKindReply: + *s = SupportCaseEventKindReply + case SupportCaseEventKindDecision: + *s = SupportCaseEventKindDecision + default: + *s = SupportCaseEventKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseEventKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseEventKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseGradeAppealReference) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseGradeAppealReference) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } +} + +var jsonFieldsNameOfSupportCaseGradeAppealReference = [2]string{ + 0: "type", + 1: "id", +} + +// Decode decodes SupportCaseGradeAppealReference from json. +func (s *SupportCaseGradeAppealReference) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseGradeAppealReference to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "id": + requiredBitSet[0] |= 1 << 1 + 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\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseGradeAppealReference") + } + // 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(jsonFieldsNameOfSupportCaseGradeAppealReference) { + name = jsonFieldsNameOfSupportCaseGradeAppealReference[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 *SupportCaseGradeAppealReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseGradeAppealReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseGradeAppealReferenceType as json. +func (s SupportCaseGradeAppealReferenceType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseGradeAppealReferenceType from json. +func (s *SupportCaseGradeAppealReferenceType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseGradeAppealReferenceType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseGradeAppealReferenceType(v) { + case SupportCaseGradeAppealReferenceTypeAssessmentAttempt: + *s = SupportCaseGradeAppealReferenceTypeAssessmentAttempt + case SupportCaseGradeAppealReferenceTypeSupportCase: + *s = SupportCaseGradeAppealReferenceTypeSupportCase + default: + *s = SupportCaseGradeAppealReferenceType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseGradeAppealReferenceType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseGradeAppealReferenceType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseList) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseList) 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 jsonFieldsNameOfSupportCaseList = [2]string{ + 0: "items", + 1: "page", +} + +// Decode decodes SupportCaseList from json. +func (s *SupportCaseList) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseList 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([]SupportCaseSummary, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem SupportCaseSummary + 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 SupportCaseList") + } + // 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(jsonFieldsNameOfSupportCaseList) { + name = jsonFieldsNameOfSupportCaseList[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 *SupportCaseList) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseList) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseNumber as json. +func (s SupportCaseNumber) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes SupportCaseNumber from json. +func (s *SupportCaseNumber) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseNumber 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 = SupportCaseNumber(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseNumber) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseNumber) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseObjectReference) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseObjectReference) encodeFields(e *jx.Encoder) { + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } +} + +var jsonFieldsNameOfSupportCaseObjectReference = [2]string{ + 0: "type", + 1: "id", +} + +// Decode decodes SupportCaseObjectReference from json. +func (s *SupportCaseObjectReference) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseObjectReference to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "type": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "id": + requiredBitSet[0] |= 1 << 1 + 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\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportCaseObjectReference") + } + // 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(jsonFieldsNameOfSupportCaseObjectReference) { + name = jsonFieldsNameOfSupportCaseObjectReference[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 *SupportCaseObjectReference) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseObjectReference) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseObjectType as json. +func (s SupportCaseObjectType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseObjectType from json. +func (s *SupportCaseObjectType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseObjectType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseObjectType(v) { + case SupportCaseObjectTypeAssessmentAttempt: + *s = SupportCaseObjectTypeAssessmentAttempt + case SupportCaseObjectTypeOrganization: + *s = SupportCaseObjectTypeOrganization + case SupportCaseObjectTypeInvitation: + *s = SupportCaseObjectTypeInvitation + case SupportCaseObjectTypeSupportCase: + *s = SupportCaseObjectTypeSupportCase + default: + *s = SupportCaseObjectType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseObjectType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseObjectType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCasePublicText as json. +func (s SupportCasePublicText) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes SupportCasePublicText from json. +func (s *SupportCasePublicText) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCasePublicText 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 = SupportCasePublicText(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCasePublicText) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCasePublicText) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseStatus as json. +func (s SupportCaseStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseStatus from json. +func (s *SupportCaseStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseStatus(v) { + case SupportCaseStatusSubmitted: + *s = SupportCaseStatusSubmitted + case SupportCaseStatusInReview: + *s = SupportCaseStatusInReview + case SupportCaseStatusWaitingForUser: + *s = SupportCaseStatusWaitingForUser + case SupportCaseStatusWaitingExpert: + *s = SupportCaseStatusWaitingExpert + case SupportCaseStatusResolved: + *s = SupportCaseStatusResolved + case SupportCaseStatusClosed: + *s = SupportCaseStatusClosed + default: + *s = SupportCaseStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportCaseSummary) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportCaseSummary) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("number") + s.Number.Encode(e) + } + { + e.FieldStart("type") + s.Type.Encode(e) + } + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("object") + s.Object.Encode(e) + } + { + e.FieldStart("assessment_target") + s.AssessmentTarget.Encode(e) + } + { + e.FieldStart("response_target") + s.ResponseTarget.Encode(e) + } + { + e.FieldStart("decision_outcome") + s.DecisionOutcome.Encode(e) + } + { + e.FieldStart("created_at") + s.CreatedAt.Encode(e) + } + { + e.FieldStart("updated_at") + s.UpdatedAt.Encode(e) + } +} + +var jsonFieldsNameOfSupportCaseSummary = [10]string{ + 0: "id", + 1: "number", + 2: "type", + 3: "status", + 4: "object", + 5: "assessment_target", + 6: "response_target", + 7: "decision_outcome", + 8: "created_at", + 9: "updated_at", +} + +// Decode decodes SupportCaseSummary from json. +func (s *SupportCaseSummary) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseSummary 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 "number": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Number.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"number\"") + } + case "type": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Type.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"type\"") + } + case "status": + requiredBitSet[0] |= 1 << 3 + 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 "object": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Object.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"object\"") + } + case "assessment_target": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.AssessmentTarget.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"assessment_target\"") + } + case "response_target": + requiredBitSet[0] |= 1 << 6 + if err := func() error { + if err := s.ResponseTarget.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"response_target\"") + } + case "decision_outcome": + requiredBitSet[0] |= 1 << 7 + if err := func() error { + if err := s.DecisionOutcome.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"decision_outcome\"") + } + case "created_at": + requiredBitSet[1] |= 1 << 0 + 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 << 1 + 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 SupportCaseSummary") + } + // 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(jsonFieldsNameOfSupportCaseSummary) { + name = jsonFieldsNameOfSupportCaseSummary[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 *SupportCaseSummary) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseSummary) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportCaseType as json. +func (s SupportCaseType) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportCaseType from json. +func (s *SupportCaseType) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportCaseType to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportCaseType(v) { + case SupportCaseTypeSupport: + *s = SupportCaseTypeSupport + case SupportCaseTypeComplaint: + *s = SupportCaseTypeComplaint + case SupportCaseTypeGradeAppeal: + *s = SupportCaseTypeGradeAppeal + case SupportCaseTypeAnticheatAppeal: + *s = SupportCaseTypeAnticheatAppeal + case SupportCaseTypeManualAssessment: + *s = SupportCaseTypeManualAssessment + default: + *s = SupportCaseType(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportCaseType) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportCaseType) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SupportResponseTarget) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SupportResponseTarget) encodeFields(e *jx.Encoder) { + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("business_days") + e.Int32(s.BusinessDays) + } + { + e.FieldStart("due_at") + s.DueAt.Encode(e) + } + { + e.FieldStart("answered_at") + s.AnsweredAt.Encode(e) + } + { + e.FieldStart("late") + e.Bool(s.Late) + } + { + e.FieldStart("policy_version") + e.Int32(s.PolicyVersion) + } +} + +var jsonFieldsNameOfSupportResponseTarget = [6]string{ + 0: "kind", + 1: "business_days", + 2: "due_at", + 3: "answered_at", + 4: "late", + 5: "policy_version", +} + +// Decode decodes SupportResponseTarget from json. +func (s *SupportResponseTarget) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportResponseTarget to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "kind": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "business_days": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Int32() + s.BusinessDays = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"business_days\"") + } + case "due_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.DueAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"due_at\"") + } + case "answered_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.AnsweredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"answered_at\"") + } + case "late": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + v, err := d.Bool() + s.Late = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"late\"") + } + case "policy_version": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + v, err := d.Int32() + s.PolicyVersion = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"policy_version\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SupportResponseTarget") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + 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(jsonFieldsNameOfSupportResponseTarget) { + name = jsonFieldsNameOfSupportResponseTarget[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 *SupportResponseTarget) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportResponseTarget) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SupportResponseTargetKind as json. +func (s SupportResponseTargetKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SupportResponseTargetKind from json. +func (s *SupportResponseTargetKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SupportResponseTargetKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SupportResponseTargetKind(v) { + case SupportResponseTargetKindOperationalGoal: + *s = SupportResponseTargetKindOperationalGoal + default: + *s = SupportResponseTargetKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SupportResponseTargetKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SupportResponseTargetKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes TaskLanguage as json. func (s TaskLanguage) Encode(e *jx.Encoder) { e.Str(string(s)) 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 df69798..85c7585 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -8,6 +8,7 @@ type OperationName = string const ( ConfirmEmailOperation OperationName = "ConfirmEmail" CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt" + CreateMySupportCaseOperation OperationName = "CreateMySupportCase" CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed" FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt" GetConsentTextOperation OperationName = "GetConsentText" @@ -18,8 +19,10 @@ const ( 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" 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 e4f2b4a..9ea7843 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -109,6 +109,100 @@ func decodeCreateMyAssessmentAttemptParams(args [0]string, argsEscaped bool, r * return params, nil } +// CreateMySupportCaseParams is parameters of CreateMySupportCase operation. +type CreateMySupportCaseParams struct { + // 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 unpackCreateMySupportCaseParams(packed middleware.Parameters) (params CreateMySupportCaseParams) { + { + key := middleware.ParameterKey{ + Name: "Idempotency-Key", + In: "header", + } + params.IdempotencyKey = packed[key].(string) + } + return params +} + +func decodeCreateMySupportCaseParams(args [0]string, argsEscaped bool, r *http.Request) (params CreateMySupportCaseParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // 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 @@ -617,6 +711,73 @@ func decodeGetMyAssessmentResultParams(args [1]string, argsEscaped bool, r *http 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 + // both answer 404 not_found, so identifiers cannot be enumerated. + CaseID uuid.UUID +} + +func unpackGetMySupportCaseParams(packed middleware.Parameters) (params GetMySupportCaseParams) { + { + key := middleware.ParameterKey{ + Name: "case_id", + In: "path", + } + params.CaseID = packed[key].(uuid.UUID) + } + return params +} + +func decodeGetMySupportCaseParams(args [1]string, argsEscaped bool, r *http.Request) (params GetMySupportCaseParams, _ error) { + // Decode path: case_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: "case_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.CaseID = c + return nil + }(); err != nil { + return err + } + } else { + return validate.ErrFieldRequired + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "case_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 @@ -741,6 +902,182 @@ func decodeGetOrganizationNeedParams(args [2]string, argsEscaped bool, r *http.R 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 + // `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 unpackListMySupportCasesParams(packed middleware.Parameters) (params ListMySupportCasesParams) { + { + 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 decodeListMySupportCasesParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMySupportCasesParams, _ 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 +} + // 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 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 339dc2a..39a08c9 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 @@ -172,6 +172,85 @@ func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) ( } } +func (s *Server) decodeCreateMySupportCaseRequest(r *http.Request) ( + req SupportCaseCreate, + 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 SupportCaseCreate + 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, 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 cbbffc3..b34c2f9 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 @@ -216,6 +216,145 @@ func encodeCreateMyAssessmentAttemptResponse(response CreateMyAssessmentAttemptR } } +func encodeCreateMySupportCaseResponse(response CreateMySupportCaseRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *SupportCaseHeaders: + 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 *CreateMySupportCaseBadRequest: + 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 *CreateMySupportCaseUnauthorized: + 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 *CreateMySupportCaseForbidden: + 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 *CreateMySupportCaseNotFound: + 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 *CreateMySupportCaseConflict: + 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 *CreateMySupportCaseUnprocessableEntity: + 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: @@ -884,6 +1023,77 @@ func encodeGetMyQuestionnaireResponse(response GetMyQuestionnaireRes, w http.Res } } +func encodeGetMySupportCaseResponse(response GetMySupportCaseRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *SupportCaseHeaders: + 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 *GetMySupportCaseBadRequest: + 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 *GetMySupportCaseUnauthorized: + 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 *GetMySupportCaseNotFound: + 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: @@ -980,6 +1190,65 @@ func encodeGetSpecializationCatalogResponse(response *SpecializationCatalog, w h return nil } +func encodeListMySupportCasesResponse(response ListMySupportCasesRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *SupportCaseListHeaders: + 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 *ListMySupportCasesBadRequest: + 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 *ListMySupportCasesUnauthorized: + 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 + + 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: 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 741f7ab..2f04cca 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,37 +11,40 @@ import ( ) var ( - rn28AllowedHeaders = map[string]string{ + rn31AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn1AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn26AllowedHeaders = map[string]string{ + rn29AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn25AllowedHeaders = map[string]string{ + rn28AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn14AllowedHeaders = map[string]string{ + rn16AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } rn3AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn29AllowedHeaders = map[string]string{ + rn32AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn9AllowedHeaders = map[string]string{ + rn11AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn21AllowedHeaders = map[string]string{ + rn22AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn6AllowedHeaders = map[string]string{ + rn5AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn23AllowedHeaders = map[string]string{ + rn8AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn26AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } ) @@ -198,7 +201,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn28AllowedHeaders, + allowedHeaders: rn31AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -275,7 +278,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn26AllowedHeaders, + allowedHeaders: rn29AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -299,7 +302,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn25AllowedHeaders, + allowedHeaders: rn28AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -326,7 +329,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,GET", - allowedHeaders: rn14AllowedHeaders, + allowedHeaders: rn16AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -452,7 +455,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn29AllowedHeaders, + allowedHeaders: rn32AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -479,7 +482,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn9AllowedHeaders, + allowedHeaders: rn11AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -566,7 +569,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn21AllowedHeaders, + allowedHeaders: rn22AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -575,6 +578,70 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + case 's': // Prefix: "support-cases" + + if l := len("support-cases"); len(elem) >= l && elem[0:l] == "support-cases" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleListMySupportCasesRequest([0]string{}, elemIsEscaped, w, r) + case "POST": + s.handleCreateMySupportCaseRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,POST", + allowedHeaders: rn5AllowedHeaders, + 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: "case_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMySupportCaseRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + } case 'o': // Prefix: "organizations/" @@ -619,7 +686,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn6AllowedHeaders, + allowedHeaders: rn8AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -661,7 +728,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn23AllowedHeaders, + allowedHeaders: rn26AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -1281,6 +1348,75 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } + case 's': // Prefix: "support-cases" + + if l := len("support-cases"); len(elem) >= l && elem[0:l] == "support-cases" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "GET": + r.name = ListMySupportCasesOperation + r.summary = "List the support cases of the current account." + r.operationID = "ListMySupportCases" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/support-cases" + r.args = args + r.count = 0 + return r, true + case "POST": + r.name = CreateMySupportCaseOperation + r.summary = "Open a support case, a complaint, an appeal, or a manual assessment request." + r.operationID = "CreateMySupportCase" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/support-cases" + 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: "case_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMySupportCaseOperation + r.summary = "Read a support case of the current account." + r.operationID = "GetMySupportCase" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/support-cases/{case_id}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + } + } case 'o': // Prefix: "organizations/" 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 3027254..4c976a4 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -2985,6 +2985,30 @@ type CreateMyAssessmentAttemptUnprocessableEntity Problem func (*CreateMyAssessmentAttemptUnprocessableEntity) createMyAssessmentAttemptRes() {} +type CreateMySupportCaseBadRequest Problem + +func (*CreateMySupportCaseBadRequest) createMySupportCaseRes() {} + +type CreateMySupportCaseConflict Problem + +func (*CreateMySupportCaseConflict) createMySupportCaseRes() {} + +type CreateMySupportCaseForbidden Problem + +func (*CreateMySupportCaseForbidden) createMySupportCaseRes() {} + +type CreateMySupportCaseNotFound Problem + +func (*CreateMySupportCaseNotFound) createMySupportCaseRes() {} + +type CreateMySupportCaseUnauthorized Problem + +func (*CreateMySupportCaseUnauthorized) createMySupportCaseRes() {} + +type CreateMySupportCaseUnprocessableEntity Problem + +func (*CreateMySupportCaseUnprocessableEntity) createMySupportCaseRes() {} + type CreateOrganizationNeedBadRequest Problem func (*CreateOrganizationNeedBadRequest) createOrganizationNeedRes() {} @@ -3459,6 +3483,18 @@ type GetMyQuestionnaireUnauthorized Problem func (*GetMyQuestionnaireUnauthorized) getMyQuestionnaireRes() {} +type GetMySupportCaseBadRequest Problem + +func (*GetMySupportCaseBadRequest) getMySupportCaseRes() {} + +type GetMySupportCaseNotFound Problem + +func (*GetMySupportCaseNotFound) getMySupportCaseRes() {} + +type GetMySupportCaseUnauthorized Problem + +func (*GetMySupportCaseUnauthorized) getMySupportCaseRes() {} + type GetOrganizationNeedBadRequest Problem func (*GetOrganizationNeedBadRequest) getOrganizationNeedRes() {} @@ -3841,6 +3877,14 @@ func NewPracticeItemContentItemContent(v PracticeItemContent) ItemContent { return s } +type ListMySupportCasesBadRequest Problem + +func (*ListMySupportCasesBadRequest) listMySupportCasesRes() {} + +type ListMySupportCasesUnauthorized Problem + +func (*ListMySupportCasesUnauthorized) listMySupportCasesRes() {} + type ListOrganizationNeedsBadRequest Problem func (*ListOrganizationNeedsBadRequest) listOrganizationNeedsRes() {} @@ -7263,6 +7307,321 @@ func (o NilString) Or(d string) string { return d } +// NewNilSupportCaseAssessmentTarget returns new NilSupportCaseAssessmentTarget with value set to v. +func NewNilSupportCaseAssessmentTarget(v SupportCaseAssessmentTarget) NilSupportCaseAssessmentTarget { + return NilSupportCaseAssessmentTarget{ + Value: v, + } +} + +// NilSupportCaseAssessmentTarget is nullable SupportCaseAssessmentTarget. +type NilSupportCaseAssessmentTarget struct { + Value SupportCaseAssessmentTarget + Null bool +} + +// SetTo sets value to v. +func (o *NilSupportCaseAssessmentTarget) SetTo(v SupportCaseAssessmentTarget) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilSupportCaseAssessmentTarget) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilSupportCaseAssessmentTarget) SetToNull() { + o.Null = true + var v SupportCaseAssessmentTarget + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilSupportCaseAssessmentTarget) Get() (v SupportCaseAssessmentTarget, 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 NilSupportCaseAssessmentTarget) Or(d SupportCaseAssessmentTarget) SupportCaseAssessmentTarget { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilSupportCaseComplaintReason returns new NilSupportCaseComplaintReason with value set to v. +func NewNilSupportCaseComplaintReason(v SupportCaseComplaintReason) NilSupportCaseComplaintReason { + return NilSupportCaseComplaintReason{ + Value: v, + } +} + +// NilSupportCaseComplaintReason is nullable SupportCaseComplaintReason. +type NilSupportCaseComplaintReason struct { + Value SupportCaseComplaintReason + Null bool +} + +// SetTo sets value to v. +func (o *NilSupportCaseComplaintReason) SetTo(v SupportCaseComplaintReason) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilSupportCaseComplaintReason) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilSupportCaseComplaintReason) SetToNull() { + o.Null = true + var v SupportCaseComplaintReason + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilSupportCaseComplaintReason) Get() (v SupportCaseComplaintReason, 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 NilSupportCaseComplaintReason) Or(d SupportCaseComplaintReason) SupportCaseComplaintReason { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilSupportCaseDecision returns new NilSupportCaseDecision with value set to v. +func NewNilSupportCaseDecision(v SupportCaseDecision) NilSupportCaseDecision { + return NilSupportCaseDecision{ + Value: v, + } +} + +// NilSupportCaseDecision is nullable SupportCaseDecision. +type NilSupportCaseDecision struct { + Value SupportCaseDecision + Null bool +} + +// SetTo sets value to v. +func (o *NilSupportCaseDecision) SetTo(v SupportCaseDecision) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilSupportCaseDecision) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilSupportCaseDecision) SetToNull() { + o.Null = true + var v SupportCaseDecision + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilSupportCaseDecision) Get() (v SupportCaseDecision, 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 NilSupportCaseDecision) Or(d SupportCaseDecision) SupportCaseDecision { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilSupportCaseDecisionOutcome returns new NilSupportCaseDecisionOutcome with value set to v. +func NewNilSupportCaseDecisionOutcome(v SupportCaseDecisionOutcome) NilSupportCaseDecisionOutcome { + return NilSupportCaseDecisionOutcome{ + Value: v, + } +} + +// NilSupportCaseDecisionOutcome is nullable SupportCaseDecisionOutcome. +type NilSupportCaseDecisionOutcome struct { + Value SupportCaseDecisionOutcome + Null bool +} + +// SetTo sets value to v. +func (o *NilSupportCaseDecisionOutcome) SetTo(v SupportCaseDecisionOutcome) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilSupportCaseDecisionOutcome) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilSupportCaseDecisionOutcome) SetToNull() { + o.Null = true + var v SupportCaseDecisionOutcome + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilSupportCaseDecisionOutcome) Get() (v SupportCaseDecisionOutcome, 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 NilSupportCaseDecisionOutcome) Or(d SupportCaseDecisionOutcome) SupportCaseDecisionOutcome { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilSupportCaseObjectReference returns new NilSupportCaseObjectReference with value set to v. +func NewNilSupportCaseObjectReference(v SupportCaseObjectReference) NilSupportCaseObjectReference { + return NilSupportCaseObjectReference{ + Value: v, + } +} + +// NilSupportCaseObjectReference is nullable SupportCaseObjectReference. +type NilSupportCaseObjectReference struct { + Value SupportCaseObjectReference + Null bool +} + +// SetTo sets value to v. +func (o *NilSupportCaseObjectReference) SetTo(v SupportCaseObjectReference) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilSupportCaseObjectReference) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilSupportCaseObjectReference) SetToNull() { + o.Null = true + var v SupportCaseObjectReference + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilSupportCaseObjectReference) Get() (v SupportCaseObjectReference, 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 NilSupportCaseObjectReference) Or(d SupportCaseObjectReference) SupportCaseObjectReference { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilSupportCasePublicText returns new NilSupportCasePublicText with value set to v. +func NewNilSupportCasePublicText(v SupportCasePublicText) NilSupportCasePublicText { + return NilSupportCasePublicText{ + Value: v, + } +} + +// NilSupportCasePublicText is nullable SupportCasePublicText. +type NilSupportCasePublicText struct { + Value SupportCasePublicText + Null bool +} + +// SetTo sets value to v. +func (o *NilSupportCasePublicText) SetTo(v SupportCasePublicText) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilSupportCasePublicText) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilSupportCasePublicText) SetToNull() { + o.Null = true + var v SupportCasePublicText + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilSupportCasePublicText) Get() (v SupportCasePublicText, 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 NilSupportCasePublicText) Or(d SupportCasePublicText) SupportCasePublicText { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilSupportCaseStatus returns new NilSupportCaseStatus with value set to v. +func NewNilSupportCaseStatus(v SupportCaseStatus) NilSupportCaseStatus { + return NilSupportCaseStatus{ + Value: v, + } +} + +// NilSupportCaseStatus is nullable SupportCaseStatus. +type NilSupportCaseStatus struct { + Value SupportCaseStatus + Null bool +} + +// SetTo sets value to v. +func (o *NilSupportCaseStatus) SetTo(v SupportCaseStatus) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilSupportCaseStatus) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilSupportCaseStatus) SetToNull() { + o.Null = true + var v SupportCaseStatus + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilSupportCaseStatus) Get() (v SupportCaseStatus, 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 NilSupportCaseStatus) Or(d SupportCaseStatus) SupportCaseStatus { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilTaskLanguage returns new NilTaskLanguage with value set to v. func NewNilTaskLanguage(v TaskLanguage) NilTaskLanguage { return NilTaskLanguage{ @@ -8334,6 +8693,144 @@ func (o OptString) Or(d string) string { return d } +// NewOptSupportCaseAssessmentTarget returns new OptSupportCaseAssessmentTarget with value set to v. +func NewOptSupportCaseAssessmentTarget(v SupportCaseAssessmentTarget) OptSupportCaseAssessmentTarget { + return OptSupportCaseAssessmentTarget{ + Value: v, + Set: true, + } +} + +// OptSupportCaseAssessmentTarget is optional SupportCaseAssessmentTarget. +type OptSupportCaseAssessmentTarget struct { + Value SupportCaseAssessmentTarget + Set bool +} + +// IsSet returns true if OptSupportCaseAssessmentTarget was set. +func (o OptSupportCaseAssessmentTarget) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptSupportCaseAssessmentTarget) Reset() { + var v SupportCaseAssessmentTarget + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptSupportCaseAssessmentTarget) SetTo(v SupportCaseAssessmentTarget) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptSupportCaseAssessmentTarget) Get() (v SupportCaseAssessmentTarget, 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 OptSupportCaseAssessmentTarget) Or(d SupportCaseAssessmentTarget) SupportCaseAssessmentTarget { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptSupportCaseAttemptReference returns new OptSupportCaseAttemptReference with value set to v. +func NewOptSupportCaseAttemptReference(v SupportCaseAttemptReference) OptSupportCaseAttemptReference { + return OptSupportCaseAttemptReference{ + Value: v, + Set: true, + } +} + +// OptSupportCaseAttemptReference is optional SupportCaseAttemptReference. +type OptSupportCaseAttemptReference struct { + Value SupportCaseAttemptReference + Set bool +} + +// IsSet returns true if OptSupportCaseAttemptReference was set. +func (o OptSupportCaseAttemptReference) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptSupportCaseAttemptReference) Reset() { + var v SupportCaseAttemptReference + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptSupportCaseAttemptReference) SetTo(v SupportCaseAttemptReference) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptSupportCaseAttemptReference) Get() (v SupportCaseAttemptReference, 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 OptSupportCaseAttemptReference) Or(d SupportCaseAttemptReference) SupportCaseAttemptReference { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewOptSupportCaseObjectReference returns new OptSupportCaseObjectReference with value set to v. +func NewOptSupportCaseObjectReference(v SupportCaseObjectReference) OptSupportCaseObjectReference { + return OptSupportCaseObjectReference{ + Value: v, + Set: true, + } +} + +// OptSupportCaseObjectReference is optional SupportCaseObjectReference. +type OptSupportCaseObjectReference struct { + Value SupportCaseObjectReference + Set bool +} + +// IsSet returns true if OptSupportCaseObjectReference was set. +func (o OptSupportCaseObjectReference) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptSupportCaseObjectReference) Reset() { + var v SupportCaseObjectReference + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptSupportCaseObjectReference) SetTo(v SupportCaseObjectReference) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptSupportCaseObjectReference) Get() (v SupportCaseObjectReference, 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 OptSupportCaseObjectReference) Or(d SupportCaseObjectReference) SupportCaseObjectReference { + if v, ok := o.Get(); ok { + return v + } + return d +} + // Every element of the item exactly once, in the chosen order. Two answers are equal only when the // sequences are identical. // Ref: #/components/schemas/OrderAnswer @@ -10164,6 +10661,1946 @@ type SubmitMyAssessmentAnswerUnprocessableEntity Problem func (*SubmitMyAssessmentAnswerUnprocessableEntity) submitMyAssessmentAnswerRes() {} +// Case of the current account. It contains what the author sent, the public processing state, and the +// public history. It never contains the identity of a moderator, an expert, or a support agent, +// internal notes, evidence, assessment answers or anti-cheat signals, risk signals, or contact data of +// another person. Fields that do not apply to the type are null. +// Ref: #/components/schemas/SupportCase +type SupportCase struct { + // Case identifier. + ID uuid.UUID `json:"id"` + Number SupportCaseNumber `json:"number"` + Type SupportCaseType `json:"type"` + Status SupportCaseStatus `json:"status"` + Description SupportCaseDescription `json:"description"` + // Object that the case is about, as sent on creation, or null when the case has none. + Object NilSupportCaseObjectReference `json:"object"` + // Category of a manual assessment, the optional category of a support case, or null. + AssessmentTarget NilSupportCaseAssessmentTarget `json:"assessment_target"` + // Ground of a complaint, or null for other types. + ComplaintReason NilSupportCaseComplaintReason `json:"complaint_reason"` + // For a manual assessment, the version of the published rubric of the category that the server fixed + // on creation; the expert assesses with it, the same rubric as the automated assessment. Null for + // other types, and null for a manual assessment whose category has no published rubric yet: the case + // then waits in `waiting_expert` and the client says so instead of promising a date. + RubricVersion NilInt32 `json:"rubric_version"` + ResponseTarget SupportResponseTarget `json:"response_target"` + // Decision once the case is `resolved`, otherwise null. + Decision NilSupportCaseDecision `json:"decision"` + // Every public event in the order it happened, starting with `created`; the list is never truncated. + // The server keeps a case within 200 events: it rejects a staff reply or status change that would + // leave no room for the terminal event, so a case always fits and can always be resolved or closed. + // Further correspondence goes into a new case that references this one as `support_case`. + History []SupportCaseEvent `json:"history"` + CreatedAt Timestamp `json:"created_at"` + UpdatedAt Timestamp `json:"updated_at"` +} + +// GetID returns the value of ID. +func (s *SupportCase) GetID() uuid.UUID { + return s.ID +} + +// GetNumber returns the value of Number. +func (s *SupportCase) GetNumber() SupportCaseNumber { + return s.Number +} + +// GetType returns the value of Type. +func (s *SupportCase) GetType() SupportCaseType { + return s.Type +} + +// GetStatus returns the value of Status. +func (s *SupportCase) GetStatus() SupportCaseStatus { + return s.Status +} + +// GetDescription returns the value of Description. +func (s *SupportCase) GetDescription() SupportCaseDescription { + return s.Description +} + +// GetObject returns the value of Object. +func (s *SupportCase) GetObject() NilSupportCaseObjectReference { + return s.Object +} + +// GetAssessmentTarget returns the value of AssessmentTarget. +func (s *SupportCase) GetAssessmentTarget() NilSupportCaseAssessmentTarget { + return s.AssessmentTarget +} + +// GetComplaintReason returns the value of ComplaintReason. +func (s *SupportCase) GetComplaintReason() NilSupportCaseComplaintReason { + return s.ComplaintReason +} + +// GetRubricVersion returns the value of RubricVersion. +func (s *SupportCase) GetRubricVersion() NilInt32 { + return s.RubricVersion +} + +// GetResponseTarget returns the value of ResponseTarget. +func (s *SupportCase) GetResponseTarget() SupportResponseTarget { + return s.ResponseTarget +} + +// GetDecision returns the value of Decision. +func (s *SupportCase) GetDecision() NilSupportCaseDecision { + return s.Decision +} + +// GetHistory returns the value of History. +func (s *SupportCase) GetHistory() []SupportCaseEvent { + return s.History +} + +// GetCreatedAt returns the value of CreatedAt. +func (s *SupportCase) GetCreatedAt() Timestamp { + return s.CreatedAt +} + +// GetUpdatedAt returns the value of UpdatedAt. +func (s *SupportCase) GetUpdatedAt() Timestamp { + return s.UpdatedAt +} + +// SetID sets the value of ID. +func (s *SupportCase) SetID(val uuid.UUID) { + s.ID = val +} + +// SetNumber sets the value of Number. +func (s *SupportCase) SetNumber(val SupportCaseNumber) { + s.Number = val +} + +// SetType sets the value of Type. +func (s *SupportCase) SetType(val SupportCaseType) { + s.Type = val +} + +// SetStatus sets the value of Status. +func (s *SupportCase) SetStatus(val SupportCaseStatus) { + s.Status = val +} + +// SetDescription sets the value of Description. +func (s *SupportCase) SetDescription(val SupportCaseDescription) { + s.Description = val +} + +// SetObject sets the value of Object. +func (s *SupportCase) SetObject(val NilSupportCaseObjectReference) { + s.Object = val +} + +// SetAssessmentTarget sets the value of AssessmentTarget. +func (s *SupportCase) SetAssessmentTarget(val NilSupportCaseAssessmentTarget) { + s.AssessmentTarget = val +} + +// SetComplaintReason sets the value of ComplaintReason. +func (s *SupportCase) SetComplaintReason(val NilSupportCaseComplaintReason) { + s.ComplaintReason = val +} + +// SetRubricVersion sets the value of RubricVersion. +func (s *SupportCase) SetRubricVersion(val NilInt32) { + s.RubricVersion = val +} + +// SetResponseTarget sets the value of ResponseTarget. +func (s *SupportCase) SetResponseTarget(val SupportResponseTarget) { + s.ResponseTarget = val +} + +// SetDecision sets the value of Decision. +func (s *SupportCase) SetDecision(val NilSupportCaseDecision) { + s.Decision = val +} + +// SetHistory sets the value of History. +func (s *SupportCase) SetHistory(val []SupportCaseEvent) { + s.History = val +} + +// SetCreatedAt sets the value of CreatedAt. +func (s *SupportCase) SetCreatedAt(val Timestamp) { + s.CreatedAt = val +} + +// SetUpdatedAt sets the value of UpdatedAt. +func (s *SupportCase) SetUpdatedAt(val Timestamp) { + s.UpdatedAt = val +} + +// Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a +// support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is +// a contract change. +// +// - user: the author of the case. +// - support: a person of the support, moderation, or expert staff. +// - system: the server, for example on creation or when it routes the case. +// +// Ref: #/components/schemas/SupportCaseActorKind +type SupportCaseActorKind string + +const ( + SupportCaseActorKindUser SupportCaseActorKind = "user" + SupportCaseActorKindSupport SupportCaseActorKind = "support" + SupportCaseActorKindSystem SupportCaseActorKind = "system" +) + +// AllValues returns all SupportCaseActorKind values. +func (SupportCaseActorKind) AllValues() []SupportCaseActorKind { + return []SupportCaseActorKind{ + SupportCaseActorKindUser, + SupportCaseActorKindSupport, + SupportCaseActorKindSystem, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseActorKind) MarshalText() ([]byte, error) { + switch s { + case SupportCaseActorKindUser: + return []byte(s), nil + case SupportCaseActorKindSupport: + return []byte(s), nil + case SupportCaseActorKindSystem: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseActorKind) UnmarshalText(data []byte) error { + switch SupportCaseActorKind(data) { + case SupportCaseActorKindUser: + *s = SupportCaseActorKindUser + return nil + case SupportCaseActorKindSupport: + *s = SupportCaseActorKindSupport + return nil + case SupportCaseActorKindSystem: + *s = SupportCaseActorKindSystem + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Category that the case is about: a specialization and a grade of the MVP scale. For a manual +// assessment it is the category to assess; for a support case it is optional context, for example the +// category whose test is not available. +// Ref: #/components/schemas/SupportCaseAssessmentTarget +type SupportCaseAssessmentTarget struct { + Specialization SpecializationCode `json:"specialization"` + Grade GradeCode `json:"grade"` +} + +// GetSpecialization returns the value of Specialization. +func (s *SupportCaseAssessmentTarget) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetGrade returns the value of Grade. +func (s *SupportCaseAssessmentTarget) GetGrade() GradeCode { + return s.Grade +} + +// SetSpecialization sets the value of Specialization. +func (s *SupportCaseAssessmentTarget) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetGrade sets the value of Grade. +func (s *SupportCaseAssessmentTarget) SetGrade(val GradeCode) { + s.Grade = val +} + +// Reference to an assessment attempt of the caller. Any other object type fails validation. +// Ref: #/components/schemas/SupportCaseAttemptReference +type SupportCaseAttemptReference struct { + Type SupportCaseAttemptReferenceType `json:"type"` + // Identifier of an assessment attempt of the caller. + ID uuid.UUID `json:"id"` +} + +// GetType returns the value of Type. +func (s *SupportCaseAttemptReference) GetType() SupportCaseAttemptReferenceType { + return s.Type +} + +// GetID returns the value of ID. +func (s *SupportCaseAttemptReference) GetID() uuid.UUID { + return s.ID +} + +// SetType sets the value of Type. +func (s *SupportCaseAttemptReference) SetType(val SupportCaseAttemptReferenceType) { + s.Type = val +} + +// SetID sets the value of ID. +func (s *SupportCaseAttemptReference) SetID(val uuid.UUID) { + s.ID = val +} + +type SupportCaseAttemptReferenceType string + +const ( + SupportCaseAttemptReferenceTypeAssessmentAttempt SupportCaseAttemptReferenceType = "assessment_attempt" +) + +// AllValues returns all SupportCaseAttemptReferenceType values. +func (SupportCaseAttemptReferenceType) AllValues() []SupportCaseAttemptReferenceType { + return []SupportCaseAttemptReferenceType{ + SupportCaseAttemptReferenceTypeAssessmentAttempt, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseAttemptReferenceType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseAttemptReferenceTypeAssessmentAttempt: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseAttemptReferenceType) UnmarshalText(data []byte) error { + switch SupportCaseAttemptReferenceType(data) { + case SupportCaseAttemptReferenceTypeAssessmentAttempt: + *s = SupportCaseAttemptReferenceTypeAssessmentAttempt + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Ground of a complaint (PRD FR18). +// +// - organization_conduct: conduct of the organization, for example fraudulent or abusive messages. +// - offer_content: misleading or discriminatory content of an offer. Requires an invitation +// reference. +// - salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation +// reference. +// - data_disclosure: a disclosure of the caller's personal data beyond what the caller granted. +// - other: another ground, explained in the description. +// +// Ref: #/components/schemas/SupportCaseComplaintReason +type SupportCaseComplaintReason string + +const ( + SupportCaseComplaintReasonOrganizationConduct SupportCaseComplaintReason = "organization_conduct" + SupportCaseComplaintReasonOfferContent SupportCaseComplaintReason = "offer_content" + SupportCaseComplaintReasonSalaryTermsViolation SupportCaseComplaintReason = "salary_terms_violation" + SupportCaseComplaintReasonDataDisclosure SupportCaseComplaintReason = "data_disclosure" + SupportCaseComplaintReasonOther SupportCaseComplaintReason = "other" +) + +// AllValues returns all SupportCaseComplaintReason values. +func (SupportCaseComplaintReason) AllValues() []SupportCaseComplaintReason { + return []SupportCaseComplaintReason{ + SupportCaseComplaintReasonOrganizationConduct, + SupportCaseComplaintReasonOfferContent, + SupportCaseComplaintReasonSalaryTermsViolation, + SupportCaseComplaintReasonDataDisclosure, + SupportCaseComplaintReasonOther, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseComplaintReason) MarshalText() ([]byte, error) { + switch s { + case SupportCaseComplaintReasonOrganizationConduct: + return []byte(s), nil + case SupportCaseComplaintReasonOfferContent: + return []byte(s), nil + case SupportCaseComplaintReasonSalaryTermsViolation: + return []byte(s), nil + case SupportCaseComplaintReasonDataDisclosure: + return []byte(s), nil + case SupportCaseComplaintReasonOther: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseComplaintReason) UnmarshalText(data []byte) error { + switch SupportCaseComplaintReason(data) { + case SupportCaseComplaintReasonOrganizationConduct: + *s = SupportCaseComplaintReasonOrganizationConduct + return nil + case SupportCaseComplaintReasonOfferContent: + *s = SupportCaseComplaintReasonOfferContent + return nil + case SupportCaseComplaintReasonSalaryTermsViolation: + *s = SupportCaseComplaintReasonSalaryTermsViolation + return nil + case SupportCaseComplaintReasonDataDisclosure: + *s = SupportCaseComplaintReasonDataDisclosure + return nil + case SupportCaseComplaintReasonOther: + *s = SupportCaseComplaintReasonOther + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Reference to the object of a complaint: an organization that the caller can see or an invitation +// addressed to the caller. Any other object type fails validation. +// Ref: #/components/schemas/SupportCaseComplaintReference +type SupportCaseComplaintReference struct { + Type SupportCaseComplaintReferenceType `json:"type"` + // Identifier of the organization or the invitation. + ID uuid.UUID `json:"id"` +} + +// GetType returns the value of Type. +func (s *SupportCaseComplaintReference) GetType() SupportCaseComplaintReferenceType { + return s.Type +} + +// GetID returns the value of ID. +func (s *SupportCaseComplaintReference) GetID() uuid.UUID { + return s.ID +} + +// SetType sets the value of Type. +func (s *SupportCaseComplaintReference) SetType(val SupportCaseComplaintReferenceType) { + s.Type = val +} + +// SetID sets the value of ID. +func (s *SupportCaseComplaintReference) SetID(val uuid.UUID) { + s.ID = val +} + +type SupportCaseComplaintReferenceType string + +const ( + SupportCaseComplaintReferenceTypeOrganization SupportCaseComplaintReferenceType = "organization" + SupportCaseComplaintReferenceTypeInvitation SupportCaseComplaintReferenceType = "invitation" +) + +// AllValues returns all SupportCaseComplaintReferenceType values. +func (SupportCaseComplaintReferenceType) AllValues() []SupportCaseComplaintReferenceType { + return []SupportCaseComplaintReferenceType{ + SupportCaseComplaintReferenceTypeOrganization, + SupportCaseComplaintReferenceTypeInvitation, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseComplaintReferenceType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseComplaintReferenceTypeOrganization: + return []byte(s), nil + case SupportCaseComplaintReferenceTypeInvitation: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseComplaintReferenceType) UnmarshalText(data []byte) error { + switch SupportCaseComplaintReferenceType(data) { + case SupportCaseComplaintReferenceTypeOrganization: + *s = SupportCaseComplaintReferenceTypeOrganization + return nil + case SupportCaseComplaintReferenceTypeInvitation: + *s = SupportCaseComplaintReferenceTypeInvitation + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// New case, selected by `type`. Each type fixes its required fields and the object types it accepts. +// The body carries only what the user states: the request has no status, decision, outcome, priority, +// response target, assignee, moderator, rubric, or contact field, and every variant rejects unknown +// fields, so a client cannot set any of them. The user and the account come only from the session. +// Ref: #/components/schemas/SupportCaseCreate +// SupportCaseCreate represents sum type. +type SupportCaseCreate struct { + // Type selects the active sum variant, switch on this field. + Type SupportCaseCreateType + SupportCaseCreateSupport SupportCaseCreateSupport + SupportCaseCreateComplaint SupportCaseCreateComplaint + SupportCaseCreateGradeAppeal SupportCaseCreateGradeAppeal + SupportCaseCreateAnticheatAppeal SupportCaseCreateAnticheatAppeal + SupportCaseCreateManualAssessment SupportCaseCreateManualAssessment +} + +// SupportCaseCreateType is oneOf type of SupportCaseCreate. +type SupportCaseCreateType string + +// Possible values for SupportCaseCreateType. +const ( + SupportCaseCreateSupportSupportCaseCreate SupportCaseCreateType = "SupportCaseCreateSupport" + SupportCaseCreateComplaintSupportCaseCreate SupportCaseCreateType = "SupportCaseCreateComplaint" + SupportCaseCreateGradeAppealSupportCaseCreate SupportCaseCreateType = "SupportCaseCreateGradeAppeal" + SupportCaseCreateAnticheatAppealSupportCaseCreate SupportCaseCreateType = "SupportCaseCreateAnticheatAppeal" + SupportCaseCreateManualAssessmentSupportCaseCreate SupportCaseCreateType = "SupportCaseCreateManualAssessment" +) + +// IsSupportCaseCreateSupport reports whether SupportCaseCreate is SupportCaseCreateSupport. +func (s SupportCaseCreate) IsSupportCaseCreateSupport() bool { + return s.Type == SupportCaseCreateSupportSupportCaseCreate +} + +// IsSupportCaseCreateComplaint reports whether SupportCaseCreate is SupportCaseCreateComplaint. +func (s SupportCaseCreate) IsSupportCaseCreateComplaint() bool { + return s.Type == SupportCaseCreateComplaintSupportCaseCreate +} + +// IsSupportCaseCreateGradeAppeal reports whether SupportCaseCreate is SupportCaseCreateGradeAppeal. +func (s SupportCaseCreate) IsSupportCaseCreateGradeAppeal() bool { + return s.Type == SupportCaseCreateGradeAppealSupportCaseCreate +} + +// IsSupportCaseCreateAnticheatAppeal reports whether SupportCaseCreate is SupportCaseCreateAnticheatAppeal. +func (s SupportCaseCreate) IsSupportCaseCreateAnticheatAppeal() bool { + return s.Type == SupportCaseCreateAnticheatAppealSupportCaseCreate +} + +// IsSupportCaseCreateManualAssessment reports whether SupportCaseCreate is SupportCaseCreateManualAssessment. +func (s SupportCaseCreate) IsSupportCaseCreateManualAssessment() bool { + return s.Type == SupportCaseCreateManualAssessmentSupportCaseCreate +} + +// SetSupportCaseCreateSupport sets SupportCaseCreate to SupportCaseCreateSupport. +func (s *SupportCaseCreate) SetSupportCaseCreateSupport(v SupportCaseCreateSupport) { + s.Type = SupportCaseCreateSupportSupportCaseCreate + s.SupportCaseCreateSupport = v +} + +// GetSupportCaseCreateSupport returns SupportCaseCreateSupport and true boolean if SupportCaseCreate is SupportCaseCreateSupport. +func (s SupportCaseCreate) GetSupportCaseCreateSupport() (v SupportCaseCreateSupport, ok bool) { + if !s.IsSupportCaseCreateSupport() { + return v, false + } + return s.SupportCaseCreateSupport, true +} + +// NewSupportCaseCreateSupportSupportCaseCreate returns new SupportCaseCreate from SupportCaseCreateSupport. +func NewSupportCaseCreateSupportSupportCaseCreate(v SupportCaseCreateSupport) SupportCaseCreate { + var s SupportCaseCreate + s.SetSupportCaseCreateSupport(v) + return s +} + +// SetSupportCaseCreateComplaint sets SupportCaseCreate to SupportCaseCreateComplaint. +func (s *SupportCaseCreate) SetSupportCaseCreateComplaint(v SupportCaseCreateComplaint) { + s.Type = SupportCaseCreateComplaintSupportCaseCreate + s.SupportCaseCreateComplaint = v +} + +// GetSupportCaseCreateComplaint returns SupportCaseCreateComplaint and true boolean if SupportCaseCreate is SupportCaseCreateComplaint. +func (s SupportCaseCreate) GetSupportCaseCreateComplaint() (v SupportCaseCreateComplaint, ok bool) { + if !s.IsSupportCaseCreateComplaint() { + return v, false + } + return s.SupportCaseCreateComplaint, true +} + +// NewSupportCaseCreateComplaintSupportCaseCreate returns new SupportCaseCreate from SupportCaseCreateComplaint. +func NewSupportCaseCreateComplaintSupportCaseCreate(v SupportCaseCreateComplaint) SupportCaseCreate { + var s SupportCaseCreate + s.SetSupportCaseCreateComplaint(v) + return s +} + +// SetSupportCaseCreateGradeAppeal sets SupportCaseCreate to SupportCaseCreateGradeAppeal. +func (s *SupportCaseCreate) SetSupportCaseCreateGradeAppeal(v SupportCaseCreateGradeAppeal) { + s.Type = SupportCaseCreateGradeAppealSupportCaseCreate + s.SupportCaseCreateGradeAppeal = v +} + +// GetSupportCaseCreateGradeAppeal returns SupportCaseCreateGradeAppeal and true boolean if SupportCaseCreate is SupportCaseCreateGradeAppeal. +func (s SupportCaseCreate) GetSupportCaseCreateGradeAppeal() (v SupportCaseCreateGradeAppeal, ok bool) { + if !s.IsSupportCaseCreateGradeAppeal() { + return v, false + } + return s.SupportCaseCreateGradeAppeal, true +} + +// NewSupportCaseCreateGradeAppealSupportCaseCreate returns new SupportCaseCreate from SupportCaseCreateGradeAppeal. +func NewSupportCaseCreateGradeAppealSupportCaseCreate(v SupportCaseCreateGradeAppeal) SupportCaseCreate { + var s SupportCaseCreate + s.SetSupportCaseCreateGradeAppeal(v) + return s +} + +// SetSupportCaseCreateAnticheatAppeal sets SupportCaseCreate to SupportCaseCreateAnticheatAppeal. +func (s *SupportCaseCreate) SetSupportCaseCreateAnticheatAppeal(v SupportCaseCreateAnticheatAppeal) { + s.Type = SupportCaseCreateAnticheatAppealSupportCaseCreate + s.SupportCaseCreateAnticheatAppeal = v +} + +// GetSupportCaseCreateAnticheatAppeal returns SupportCaseCreateAnticheatAppeal and true boolean if SupportCaseCreate is SupportCaseCreateAnticheatAppeal. +func (s SupportCaseCreate) GetSupportCaseCreateAnticheatAppeal() (v SupportCaseCreateAnticheatAppeal, ok bool) { + if !s.IsSupportCaseCreateAnticheatAppeal() { + return v, false + } + return s.SupportCaseCreateAnticheatAppeal, true +} + +// NewSupportCaseCreateAnticheatAppealSupportCaseCreate returns new SupportCaseCreate from SupportCaseCreateAnticheatAppeal. +func NewSupportCaseCreateAnticheatAppealSupportCaseCreate(v SupportCaseCreateAnticheatAppeal) SupportCaseCreate { + var s SupportCaseCreate + s.SetSupportCaseCreateAnticheatAppeal(v) + return s +} + +// SetSupportCaseCreateManualAssessment sets SupportCaseCreate to SupportCaseCreateManualAssessment. +func (s *SupportCaseCreate) SetSupportCaseCreateManualAssessment(v SupportCaseCreateManualAssessment) { + s.Type = SupportCaseCreateManualAssessmentSupportCaseCreate + s.SupportCaseCreateManualAssessment = v +} + +// GetSupportCaseCreateManualAssessment returns SupportCaseCreateManualAssessment and true boolean if SupportCaseCreate is SupportCaseCreateManualAssessment. +func (s SupportCaseCreate) GetSupportCaseCreateManualAssessment() (v SupportCaseCreateManualAssessment, ok bool) { + if !s.IsSupportCaseCreateManualAssessment() { + return v, false + } + return s.SupportCaseCreateManualAssessment, true +} + +// NewSupportCaseCreateManualAssessmentSupportCaseCreate returns new SupportCaseCreate from SupportCaseCreateManualAssessment. +func NewSupportCaseCreateManualAssessmentSupportCaseCreate(v SupportCaseCreateManualAssessment) SupportCaseCreate { + var s SupportCaseCreate + s.SetSupportCaseCreateManualAssessment(v) + return s +} + +// New appeal of an anti-cheat review decision on an own assessment attempt. +// Ref: #/components/schemas/SupportCaseCreateAnticheatAppeal +type SupportCaseCreateAnticheatAppeal struct { + Type SupportCaseCreateAnticheatAppealType `json:"type"` + Description SupportCaseDescription `json:"description"` + Object SupportCaseAttemptReference `json:"object"` +} + +// GetType returns the value of Type. +func (s *SupportCaseCreateAnticheatAppeal) GetType() SupportCaseCreateAnticheatAppealType { + return s.Type +} + +// GetDescription returns the value of Description. +func (s *SupportCaseCreateAnticheatAppeal) GetDescription() SupportCaseDescription { + return s.Description +} + +// GetObject returns the value of Object. +func (s *SupportCaseCreateAnticheatAppeal) GetObject() SupportCaseAttemptReference { + return s.Object +} + +// SetType sets the value of Type. +func (s *SupportCaseCreateAnticheatAppeal) SetType(val SupportCaseCreateAnticheatAppealType) { + s.Type = val +} + +// SetDescription sets the value of Description. +func (s *SupportCaseCreateAnticheatAppeal) SetDescription(val SupportCaseDescription) { + s.Description = val +} + +// SetObject sets the value of Object. +func (s *SupportCaseCreateAnticheatAppeal) SetObject(val SupportCaseAttemptReference) { + s.Object = val +} + +type SupportCaseCreateAnticheatAppealType string + +const ( + SupportCaseCreateAnticheatAppealTypeAnticheatAppeal SupportCaseCreateAnticheatAppealType = "anticheat_appeal" +) + +// AllValues returns all SupportCaseCreateAnticheatAppealType values. +func (SupportCaseCreateAnticheatAppealType) AllValues() []SupportCaseCreateAnticheatAppealType { + return []SupportCaseCreateAnticheatAppealType{ + SupportCaseCreateAnticheatAppealTypeAnticheatAppeal, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseCreateAnticheatAppealType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseCreateAnticheatAppealTypeAnticheatAppeal: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseCreateAnticheatAppealType) UnmarshalText(data []byte) error { + switch SupportCaseCreateAnticheatAppealType(data) { + case SupportCaseCreateAnticheatAppealTypeAnticheatAppeal: + *s = SupportCaseCreateAnticheatAppealTypeAnticheatAppeal + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// New complaint about an organization or an offer. +// Ref: #/components/schemas/SupportCaseCreateComplaint +type SupportCaseCreateComplaint struct { + Type SupportCaseCreateComplaintType `json:"type"` + Description SupportCaseDescription `json:"description"` + ComplaintReason SupportCaseComplaintReason `json:"complaint_reason"` + Object SupportCaseComplaintReference `json:"object"` +} + +// GetType returns the value of Type. +func (s *SupportCaseCreateComplaint) GetType() SupportCaseCreateComplaintType { + return s.Type +} + +// GetDescription returns the value of Description. +func (s *SupportCaseCreateComplaint) GetDescription() SupportCaseDescription { + return s.Description +} + +// GetComplaintReason returns the value of ComplaintReason. +func (s *SupportCaseCreateComplaint) GetComplaintReason() SupportCaseComplaintReason { + return s.ComplaintReason +} + +// GetObject returns the value of Object. +func (s *SupportCaseCreateComplaint) GetObject() SupportCaseComplaintReference { + return s.Object +} + +// SetType sets the value of Type. +func (s *SupportCaseCreateComplaint) SetType(val SupportCaseCreateComplaintType) { + s.Type = val +} + +// SetDescription sets the value of Description. +func (s *SupportCaseCreateComplaint) SetDescription(val SupportCaseDescription) { + s.Description = val +} + +// SetComplaintReason sets the value of ComplaintReason. +func (s *SupportCaseCreateComplaint) SetComplaintReason(val SupportCaseComplaintReason) { + s.ComplaintReason = val +} + +// SetObject sets the value of Object. +func (s *SupportCaseCreateComplaint) SetObject(val SupportCaseComplaintReference) { + s.Object = val +} + +type SupportCaseCreateComplaintType string + +const ( + SupportCaseCreateComplaintTypeComplaint SupportCaseCreateComplaintType = "complaint" +) + +// AllValues returns all SupportCaseCreateComplaintType values. +func (SupportCaseCreateComplaintType) AllValues() []SupportCaseCreateComplaintType { + return []SupportCaseCreateComplaintType{ + SupportCaseCreateComplaintTypeComplaint, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseCreateComplaintType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseCreateComplaintTypeComplaint: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseCreateComplaintType) UnmarshalText(data []byte) error { + switch SupportCaseCreateComplaintType(data) { + case SupportCaseCreateComplaintTypeComplaint: + *s = SupportCaseCreateComplaintTypeComplaint + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// New appeal of a category the caller received: the result of an own assessment attempt, or the +// outcome of an own resolved manual assessment. +// Ref: #/components/schemas/SupportCaseCreateGradeAppeal +type SupportCaseCreateGradeAppeal struct { + Type SupportCaseCreateGradeAppealType `json:"type"` + Description SupportCaseDescription `json:"description"` + Object SupportCaseGradeAppealReference `json:"object"` +} + +// GetType returns the value of Type. +func (s *SupportCaseCreateGradeAppeal) GetType() SupportCaseCreateGradeAppealType { + return s.Type +} + +// GetDescription returns the value of Description. +func (s *SupportCaseCreateGradeAppeal) GetDescription() SupportCaseDescription { + return s.Description +} + +// GetObject returns the value of Object. +func (s *SupportCaseCreateGradeAppeal) GetObject() SupportCaseGradeAppealReference { + return s.Object +} + +// SetType sets the value of Type. +func (s *SupportCaseCreateGradeAppeal) SetType(val SupportCaseCreateGradeAppealType) { + s.Type = val +} + +// SetDescription sets the value of Description. +func (s *SupportCaseCreateGradeAppeal) SetDescription(val SupportCaseDescription) { + s.Description = val +} + +// SetObject sets the value of Object. +func (s *SupportCaseCreateGradeAppeal) SetObject(val SupportCaseGradeAppealReference) { + s.Object = val +} + +type SupportCaseCreateGradeAppealType string + +const ( + SupportCaseCreateGradeAppealTypeGradeAppeal SupportCaseCreateGradeAppealType = "grade_appeal" +) + +// AllValues returns all SupportCaseCreateGradeAppealType values. +func (SupportCaseCreateGradeAppealType) AllValues() []SupportCaseCreateGradeAppealType { + return []SupportCaseCreateGradeAppealType{ + SupportCaseCreateGradeAppealTypeGradeAppeal, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseCreateGradeAppealType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseCreateGradeAppealTypeGradeAppeal: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseCreateGradeAppealType) UnmarshalText(data []byte) error { + switch SupportCaseCreateGradeAppealType(data) { + case SupportCaseCreateGradeAppealTypeGradeAppeal: + *s = SupportCaseCreateGradeAppealTypeGradeAppeal + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// New request for a manual assessment of a category by a subject expert. A prior attempt of the same +// category is optional context: a failed first test or no attempt at all never blocks the request. +// Ref: #/components/schemas/SupportCaseCreateManualAssessment +type SupportCaseCreateManualAssessment struct { + Type SupportCaseCreateManualAssessmentType `json:"type"` + Description SupportCaseDescription `json:"description"` + AssessmentTarget SupportCaseAssessmentTarget `json:"assessment_target"` + Object OptSupportCaseAttemptReference `json:"object"` +} + +// GetType returns the value of Type. +func (s *SupportCaseCreateManualAssessment) GetType() SupportCaseCreateManualAssessmentType { + return s.Type +} + +// GetDescription returns the value of Description. +func (s *SupportCaseCreateManualAssessment) GetDescription() SupportCaseDescription { + return s.Description +} + +// GetAssessmentTarget returns the value of AssessmentTarget. +func (s *SupportCaseCreateManualAssessment) GetAssessmentTarget() SupportCaseAssessmentTarget { + return s.AssessmentTarget +} + +// GetObject returns the value of Object. +func (s *SupportCaseCreateManualAssessment) GetObject() OptSupportCaseAttemptReference { + return s.Object +} + +// SetType sets the value of Type. +func (s *SupportCaseCreateManualAssessment) SetType(val SupportCaseCreateManualAssessmentType) { + s.Type = val +} + +// SetDescription sets the value of Description. +func (s *SupportCaseCreateManualAssessment) SetDescription(val SupportCaseDescription) { + s.Description = val +} + +// SetAssessmentTarget sets the value of AssessmentTarget. +func (s *SupportCaseCreateManualAssessment) SetAssessmentTarget(val SupportCaseAssessmentTarget) { + s.AssessmentTarget = val +} + +// SetObject sets the value of Object. +func (s *SupportCaseCreateManualAssessment) SetObject(val OptSupportCaseAttemptReference) { + s.Object = val +} + +type SupportCaseCreateManualAssessmentType string + +const ( + SupportCaseCreateManualAssessmentTypeManualAssessment SupportCaseCreateManualAssessmentType = "manual_assessment" +) + +// AllValues returns all SupportCaseCreateManualAssessmentType values. +func (SupportCaseCreateManualAssessmentType) AllValues() []SupportCaseCreateManualAssessmentType { + return []SupportCaseCreateManualAssessmentType{ + SupportCaseCreateManualAssessmentTypeManualAssessment, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseCreateManualAssessmentType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseCreateManualAssessmentTypeManualAssessment: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseCreateManualAssessmentType) UnmarshalText(data []byte) error { + switch SupportCaseCreateManualAssessmentType(data) { + case SupportCaseCreateManualAssessmentTypeManualAssessment: + *s = SupportCaseCreateManualAssessmentTypeManualAssessment + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// New support case. Both the object reference and the assessment target are optional context; omit +// what does not apply. +// Ref: #/components/schemas/SupportCaseCreateSupport +type SupportCaseCreateSupport struct { + Type SupportCaseCreateSupportType `json:"type"` + Description SupportCaseDescription `json:"description"` + Object OptSupportCaseObjectReference `json:"object"` + AssessmentTarget OptSupportCaseAssessmentTarget `json:"assessment_target"` +} + +// GetType returns the value of Type. +func (s *SupportCaseCreateSupport) GetType() SupportCaseCreateSupportType { + return s.Type +} + +// GetDescription returns the value of Description. +func (s *SupportCaseCreateSupport) GetDescription() SupportCaseDescription { + return s.Description +} + +// GetObject returns the value of Object. +func (s *SupportCaseCreateSupport) GetObject() OptSupportCaseObjectReference { + return s.Object +} + +// GetAssessmentTarget returns the value of AssessmentTarget. +func (s *SupportCaseCreateSupport) GetAssessmentTarget() OptSupportCaseAssessmentTarget { + return s.AssessmentTarget +} + +// SetType sets the value of Type. +func (s *SupportCaseCreateSupport) SetType(val SupportCaseCreateSupportType) { + s.Type = val +} + +// SetDescription sets the value of Description. +func (s *SupportCaseCreateSupport) SetDescription(val SupportCaseDescription) { + s.Description = val +} + +// SetObject sets the value of Object. +func (s *SupportCaseCreateSupport) SetObject(val OptSupportCaseObjectReference) { + s.Object = val +} + +// SetAssessmentTarget sets the value of AssessmentTarget. +func (s *SupportCaseCreateSupport) SetAssessmentTarget(val OptSupportCaseAssessmentTarget) { + s.AssessmentTarget = val +} + +type SupportCaseCreateSupportType string + +const ( + SupportCaseCreateSupportTypeSupport SupportCaseCreateSupportType = "support" +) + +// AllValues returns all SupportCaseCreateSupportType values. +func (SupportCaseCreateSupportType) AllValues() []SupportCaseCreateSupportType { + return []SupportCaseCreateSupportType{ + SupportCaseCreateSupportTypeSupport, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseCreateSupportType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseCreateSupportTypeSupport: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseCreateSupportType) UnmarshalText(data []byte) error { + switch SupportCaseCreateSupportType(data) { + case SupportCaseCreateSupportTypeSupport: + *s = SupportCaseCreateSupportTypeSupport + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Decision visible to the user. It exists only once the case is `resolved`. It holds the outcome and +// the public reason; it never names the moderator or the expert and never contains internal notes, +// evidence, sanctions against another party, or risk signals. An upheld grade appeal never rewrites +// the original result: the corrected result is a separate decision of the assessment, and both stay in +// the history of that attempt. +// Ref: #/components/schemas/SupportCaseDecision +type SupportCaseDecision struct { + Outcome SupportCaseDecisionOutcome `json:"outcome"` + Reason SupportCasePublicText `json:"reason"` + DecidedAt Timestamp `json:"decided_at"` +} + +// GetOutcome returns the value of Outcome. +func (s *SupportCaseDecision) GetOutcome() SupportCaseDecisionOutcome { + return s.Outcome +} + +// GetReason returns the value of Reason. +func (s *SupportCaseDecision) GetReason() SupportCasePublicText { + return s.Reason +} + +// GetDecidedAt returns the value of DecidedAt. +func (s *SupportCaseDecision) GetDecidedAt() Timestamp { + return s.DecidedAt +} + +// SetOutcome sets the value of Outcome. +func (s *SupportCaseDecision) SetOutcome(val SupportCaseDecisionOutcome) { + s.Outcome = val +} + +// SetReason sets the value of Reason. +func (s *SupportCaseDecision) SetReason(val SupportCasePublicText) { + s.Reason = val +} + +// SetDecidedAt sets the value of DecidedAt. +func (s *SupportCaseDecision) SetDecidedAt(val Timestamp) { + s.DecidedAt = val +} + +// Outcome of a decision as the user sees it. The allowed outcomes depend on the case type. +// +// - upheld: the appeal or the complaint is upheld in full. +// - partially_upheld: the appeal or the complaint is upheld in part. +// - not_upheld: the appeal or the complaint is not upheld. +// - answered: a support case was answered. +// - assessed: the expert finished a manual assessment. The resulting category is part of the +// assessment results, not of the case. +// +// Ref: #/components/schemas/SupportCaseDecisionOutcome +type SupportCaseDecisionOutcome string + +const ( + SupportCaseDecisionOutcomeUpheld SupportCaseDecisionOutcome = "upheld" + SupportCaseDecisionOutcomePartiallyUpheld SupportCaseDecisionOutcome = "partially_upheld" + SupportCaseDecisionOutcomeNotUpheld SupportCaseDecisionOutcome = "not_upheld" + SupportCaseDecisionOutcomeAnswered SupportCaseDecisionOutcome = "answered" + SupportCaseDecisionOutcomeAssessed SupportCaseDecisionOutcome = "assessed" +) + +// AllValues returns all SupportCaseDecisionOutcome values. +func (SupportCaseDecisionOutcome) AllValues() []SupportCaseDecisionOutcome { + return []SupportCaseDecisionOutcome{ + SupportCaseDecisionOutcomeUpheld, + SupportCaseDecisionOutcomePartiallyUpheld, + SupportCaseDecisionOutcomeNotUpheld, + SupportCaseDecisionOutcomeAnswered, + SupportCaseDecisionOutcomeAssessed, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseDecisionOutcome) MarshalText() ([]byte, error) { + switch s { + case SupportCaseDecisionOutcomeUpheld: + return []byte(s), nil + case SupportCaseDecisionOutcomePartiallyUpheld: + return []byte(s), nil + case SupportCaseDecisionOutcomeNotUpheld: + return []byte(s), nil + case SupportCaseDecisionOutcomeAnswered: + return []byte(s), nil + case SupportCaseDecisionOutcomeAssessed: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseDecisionOutcome) UnmarshalText(data []byte) error { + switch SupportCaseDecisionOutcome(data) { + case SupportCaseDecisionOutcomeUpheld: + *s = SupportCaseDecisionOutcomeUpheld + return nil + case SupportCaseDecisionOutcomePartiallyUpheld: + *s = SupportCaseDecisionOutcomePartiallyUpheld + return nil + case SupportCaseDecisionOutcomeNotUpheld: + *s = SupportCaseDecisionOutcomeNotUpheld + return nil + case SupportCaseDecisionOutcomeAnswered: + *s = SupportCaseDecisionOutcomeAnswered + return nil + case SupportCaseDecisionOutcomeAssessed: + *s = SupportCaseDecisionOutcomeAssessed + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type SupportCaseDescription string + +// One public event of the case history. Internal notes, assignments, evidence requests, and risk +// signals are never history events. +// Ref: #/components/schemas/SupportCaseEvent +type SupportCaseEvent struct { + // Position of the event in the history, starting at 1 and increasing by one. + Sequence int32 `json:"sequence"` + Kind SupportCaseEventKind `json:"kind"` + Actor SupportCaseActorKind `json:"actor"` + OccurredAt Timestamp `json:"occurred_at"` + // Status of the case after the event, or null for a reply. + Status NilSupportCaseStatus `json:"status"` + // Public text of the event, or null. + Message NilSupportCasePublicText `json:"message"` +} + +// GetSequence returns the value of Sequence. +func (s *SupportCaseEvent) GetSequence() int32 { + return s.Sequence +} + +// GetKind returns the value of Kind. +func (s *SupportCaseEvent) GetKind() SupportCaseEventKind { + return s.Kind +} + +// GetActor returns the value of Actor. +func (s *SupportCaseEvent) GetActor() SupportCaseActorKind { + return s.Actor +} + +// GetOccurredAt returns the value of OccurredAt. +func (s *SupportCaseEvent) GetOccurredAt() Timestamp { + return s.OccurredAt +} + +// GetStatus returns the value of Status. +func (s *SupportCaseEvent) GetStatus() NilSupportCaseStatus { + return s.Status +} + +// GetMessage returns the value of Message. +func (s *SupportCaseEvent) GetMessage() NilSupportCasePublicText { + return s.Message +} + +// SetSequence sets the value of Sequence. +func (s *SupportCaseEvent) SetSequence(val int32) { + s.Sequence = val +} + +// SetKind sets the value of Kind. +func (s *SupportCaseEvent) SetKind(val SupportCaseEventKind) { + s.Kind = val +} + +// SetActor sets the value of Actor. +func (s *SupportCaseEvent) SetActor(val SupportCaseActorKind) { + s.Actor = val +} + +// SetOccurredAt sets the value of OccurredAt. +func (s *SupportCaseEvent) SetOccurredAt(val Timestamp) { + s.OccurredAt = val +} + +// SetStatus sets the value of Status. +func (s *SupportCaseEvent) SetStatus(val NilSupportCaseStatus) { + s.Status = val +} + +// SetMessage sets the value of Message. +func (s *SupportCaseEvent) SetMessage(val NilSupportCasePublicText) { + s.Message = val +} + +// Kind of a public history event. Adding a value is a contract change. A reply of the author, planned +// with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision +// (TASK-317) is another `decision` event, so neither needs a new value. +// +// - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a +// `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. +// - status_changed: the status changed; `status` is the new status, and `message` may explain a +// closure. +// - reply: support replied; `message` holds the reply and `status` is null. +// - decision: a decision was made; `status` is `resolved` and `message` holds the public reason. +// +// Ref: #/components/schemas/SupportCaseEventKind +type SupportCaseEventKind string + +const ( + SupportCaseEventKindCreated SupportCaseEventKind = "created" + SupportCaseEventKindStatusChanged SupportCaseEventKind = "status_changed" + SupportCaseEventKindReply SupportCaseEventKind = "reply" + SupportCaseEventKindDecision SupportCaseEventKind = "decision" +) + +// AllValues returns all SupportCaseEventKind values. +func (SupportCaseEventKind) AllValues() []SupportCaseEventKind { + return []SupportCaseEventKind{ + SupportCaseEventKindCreated, + SupportCaseEventKindStatusChanged, + SupportCaseEventKindReply, + SupportCaseEventKindDecision, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseEventKind) MarshalText() ([]byte, error) { + switch s { + case SupportCaseEventKindCreated: + return []byte(s), nil + case SupportCaseEventKindStatusChanged: + return []byte(s), nil + case SupportCaseEventKindReply: + return []byte(s), nil + case SupportCaseEventKindDecision: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseEventKind) UnmarshalText(data []byte) error { + switch SupportCaseEventKind(data) { + case SupportCaseEventKindCreated: + *s = SupportCaseEventKindCreated + return nil + case SupportCaseEventKindStatusChanged: + *s = SupportCaseEventKindStatusChanged + return nil + case SupportCaseEventKindReply: + *s = SupportCaseEventKindReply + return nil + case SupportCaseEventKindDecision: + *s = SupportCaseEventKindDecision + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Reference to the category that a grade appeal disputes: an assessment attempt of the caller in a +// terminal state, or a `manual_assessment` case of the caller that is `resolved` with the outcome +// `assessed`, for a category that an expert assigned without an attempt. Any other object type fails +// validation. +// Ref: #/components/schemas/SupportCaseGradeAppealReference +type SupportCaseGradeAppealReference struct { + Type SupportCaseGradeAppealReferenceType `json:"type"` + // Identifier of the attempt or the case. + ID uuid.UUID `json:"id"` +} + +// GetType returns the value of Type. +func (s *SupportCaseGradeAppealReference) GetType() SupportCaseGradeAppealReferenceType { + return s.Type +} + +// GetID returns the value of ID. +func (s *SupportCaseGradeAppealReference) GetID() uuid.UUID { + return s.ID +} + +// SetType sets the value of Type. +func (s *SupportCaseGradeAppealReference) SetType(val SupportCaseGradeAppealReferenceType) { + s.Type = val +} + +// SetID sets the value of ID. +func (s *SupportCaseGradeAppealReference) SetID(val uuid.UUID) { + s.ID = val +} + +type SupportCaseGradeAppealReferenceType string + +const ( + SupportCaseGradeAppealReferenceTypeAssessmentAttempt SupportCaseGradeAppealReferenceType = "assessment_attempt" + SupportCaseGradeAppealReferenceTypeSupportCase SupportCaseGradeAppealReferenceType = "support_case" +) + +// AllValues returns all SupportCaseGradeAppealReferenceType values. +func (SupportCaseGradeAppealReferenceType) AllValues() []SupportCaseGradeAppealReferenceType { + return []SupportCaseGradeAppealReferenceType{ + SupportCaseGradeAppealReferenceTypeAssessmentAttempt, + SupportCaseGradeAppealReferenceTypeSupportCase, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseGradeAppealReferenceType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseGradeAppealReferenceTypeAssessmentAttempt: + return []byte(s), nil + case SupportCaseGradeAppealReferenceTypeSupportCase: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseGradeAppealReferenceType) UnmarshalText(data []byte) error { + switch SupportCaseGradeAppealReferenceType(data) { + case SupportCaseGradeAppealReferenceTypeAssessmentAttempt: + *s = SupportCaseGradeAppealReferenceTypeAssessmentAttempt + return nil + case SupportCaseGradeAppealReferenceTypeSupportCase: + *s = SupportCaseGradeAppealReferenceTypeSupportCase + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// SupportCaseHeaders wraps SupportCase with response headers. +type SupportCaseHeaders struct { + CacheControl CacheControlNoStore + Response SupportCase +} + +// GetCacheControl returns the value of CacheControl. +func (s *SupportCaseHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *SupportCaseHeaders) GetResponse() SupportCase { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *SupportCaseHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *SupportCaseHeaders) SetResponse(val SupportCase) { + s.Response = val +} + +func (*SupportCaseHeaders) createMySupportCaseRes() {} +func (*SupportCaseHeaders) getMySupportCaseRes() {} + +// One page of the cases of the current account, newest first by creation time. +// Ref: #/components/schemas/SupportCaseList +type SupportCaseList struct { + // Case summaries of the page. + Items []SupportCaseSummary `json:"items"` + Page PageInfo `json:"page"` +} + +// GetItems returns the value of Items. +func (s *SupportCaseList) GetItems() []SupportCaseSummary { + return s.Items +} + +// GetPage returns the value of Page. +func (s *SupportCaseList) GetPage() PageInfo { + return s.Page +} + +// SetItems sets the value of Items. +func (s *SupportCaseList) SetItems(val []SupportCaseSummary) { + s.Items = val +} + +// SetPage sets the value of Page. +func (s *SupportCaseList) SetPage(val PageInfo) { + s.Page = val +} + +// SupportCaseListHeaders wraps SupportCaseList with response headers. +type SupportCaseListHeaders struct { + CacheControl CacheControlNoStore + Response SupportCaseList +} + +// GetCacheControl returns the value of CacheControl. +func (s *SupportCaseListHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *SupportCaseListHeaders) GetResponse() SupportCaseList { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *SupportCaseListHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *SupportCaseListHeaders) SetResponse(val SupportCaseList) { + s.Response = val +} + +func (*SupportCaseListHeaders) listMySupportCasesRes() {} + +type SupportCaseNumber string + +// 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. +// Ref: #/components/schemas/SupportCaseObjectReference +type SupportCaseObjectReference struct { + Type SupportCaseObjectType `json:"type"` + // Identifier of the object. + ID uuid.UUID `json:"id"` +} + +// GetType returns the value of Type. +func (s *SupportCaseObjectReference) GetType() SupportCaseObjectType { + return s.Type +} + +// GetID returns the value of ID. +func (s *SupportCaseObjectReference) GetID() uuid.UUID { + return s.ID +} + +// SetType sets the value of Type. +func (s *SupportCaseObjectReference) SetType(val SupportCaseObjectType) { + s.Type = val +} + +// SetID sets the value of ID. +func (s *SupportCaseObjectReference) SetID(val uuid.UUID) { + s.ID = val +} + +// 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. +// +// - 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. +// - support_case: another case of the caller, for example the resolved manual assessment that a grade +// appeal disputes. +// +// Ref: #/components/schemas/SupportCaseObjectType +type SupportCaseObjectType string + +const ( + SupportCaseObjectTypeAssessmentAttempt SupportCaseObjectType = "assessment_attempt" + SupportCaseObjectTypeOrganization SupportCaseObjectType = "organization" + SupportCaseObjectTypeInvitation SupportCaseObjectType = "invitation" + SupportCaseObjectTypeSupportCase SupportCaseObjectType = "support_case" +) + +// AllValues returns all SupportCaseObjectType values. +func (SupportCaseObjectType) AllValues() []SupportCaseObjectType { + return []SupportCaseObjectType{ + SupportCaseObjectTypeAssessmentAttempt, + SupportCaseObjectTypeOrganization, + SupportCaseObjectTypeInvitation, + SupportCaseObjectTypeSupportCase, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseObjectType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseObjectTypeAssessmentAttempt: + return []byte(s), nil + case SupportCaseObjectTypeOrganization: + return []byte(s), nil + case SupportCaseObjectTypeInvitation: + return []byte(s), nil + case SupportCaseObjectTypeSupportCase: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseObjectType) UnmarshalText(data []byte) error { + switch SupportCaseObjectType(data) { + case SupportCaseObjectTypeAssessmentAttempt: + *s = SupportCaseObjectTypeAssessmentAttempt + return nil + case SupportCaseObjectTypeOrganization: + *s = SupportCaseObjectTypeOrganization + return nil + case SupportCaseObjectTypeInvitation: + *s = SupportCaseObjectTypeInvitation + return nil + case SupportCaseObjectTypeSupportCase: + *s = SupportCaseObjectTypeSupportCase + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type SupportCasePublicText string + +// 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. +// +// - submitted: the case was accepted and waits in its queue. +// - in_review: support or a moderator works on it. +// - 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. +// - 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. +// - resolved: terminal; a decision was made and `decision` holds its outcome and public reason. +// - 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. +// +// Ref: #/components/schemas/SupportCaseStatus +type SupportCaseStatus string + +const ( + SupportCaseStatusSubmitted SupportCaseStatus = "submitted" + SupportCaseStatusInReview SupportCaseStatus = "in_review" + SupportCaseStatusWaitingForUser SupportCaseStatus = "waiting_for_user" + SupportCaseStatusWaitingExpert SupportCaseStatus = "waiting_expert" + SupportCaseStatusResolved SupportCaseStatus = "resolved" + SupportCaseStatusClosed SupportCaseStatus = "closed" +) + +// AllValues returns all SupportCaseStatus values. +func (SupportCaseStatus) AllValues() []SupportCaseStatus { + return []SupportCaseStatus{ + SupportCaseStatusSubmitted, + SupportCaseStatusInReview, + SupportCaseStatusWaitingForUser, + SupportCaseStatusWaitingExpert, + SupportCaseStatusResolved, + SupportCaseStatusClosed, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseStatus) MarshalText() ([]byte, error) { + switch s { + case SupportCaseStatusSubmitted: + return []byte(s), nil + case SupportCaseStatusInReview: + return []byte(s), nil + case SupportCaseStatusWaitingForUser: + return []byte(s), nil + case SupportCaseStatusWaitingExpert: + return []byte(s), nil + case SupportCaseStatusResolved: + return []byte(s), nil + case SupportCaseStatusClosed: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseStatus) UnmarshalText(data []byte) error { + switch SupportCaseStatus(data) { + case SupportCaseStatusSubmitted: + *s = SupportCaseStatusSubmitted + return nil + case SupportCaseStatusInReview: + *s = SupportCaseStatusInReview + return nil + case SupportCaseStatusWaitingForUser: + *s = SupportCaseStatusWaitingForUser + return nil + case SupportCaseStatusWaitingExpert: + *s = SupportCaseStatusWaitingExpert + return nil + case SupportCaseStatusResolved: + *s = SupportCaseStatusResolved + return nil + case SupportCaseStatusClosed: + *s = SupportCaseStatusClosed + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Case in a list: the fields that a list of cases shows, without the description and the history. +// GetMySupportCase returns the full case. +// Ref: #/components/schemas/SupportCaseSummary +type SupportCaseSummary struct { + // Case identifier. + ID uuid.UUID `json:"id"` + Number SupportCaseNumber `json:"number"` + Type SupportCaseType `json:"type"` + Status SupportCaseStatus `json:"status"` + // Object that the case is about, or null. + Object NilSupportCaseObjectReference `json:"object"` + // Category of the case, or null. + AssessmentTarget NilSupportCaseAssessmentTarget `json:"assessment_target"` + ResponseTarget SupportResponseTarget `json:"response_target"` + // Outcome of the decision once the case is `resolved`, otherwise null. + DecisionOutcome NilSupportCaseDecisionOutcome `json:"decision_outcome"` + CreatedAt Timestamp `json:"created_at"` + UpdatedAt Timestamp `json:"updated_at"` +} + +// GetID returns the value of ID. +func (s *SupportCaseSummary) GetID() uuid.UUID { + return s.ID +} + +// GetNumber returns the value of Number. +func (s *SupportCaseSummary) GetNumber() SupportCaseNumber { + return s.Number +} + +// GetType returns the value of Type. +func (s *SupportCaseSummary) GetType() SupportCaseType { + return s.Type +} + +// GetStatus returns the value of Status. +func (s *SupportCaseSummary) GetStatus() SupportCaseStatus { + return s.Status +} + +// GetObject returns the value of Object. +func (s *SupportCaseSummary) GetObject() NilSupportCaseObjectReference { + return s.Object +} + +// GetAssessmentTarget returns the value of AssessmentTarget. +func (s *SupportCaseSummary) GetAssessmentTarget() NilSupportCaseAssessmentTarget { + return s.AssessmentTarget +} + +// GetResponseTarget returns the value of ResponseTarget. +func (s *SupportCaseSummary) GetResponseTarget() SupportResponseTarget { + return s.ResponseTarget +} + +// GetDecisionOutcome returns the value of DecisionOutcome. +func (s *SupportCaseSummary) GetDecisionOutcome() NilSupportCaseDecisionOutcome { + return s.DecisionOutcome +} + +// GetCreatedAt returns the value of CreatedAt. +func (s *SupportCaseSummary) GetCreatedAt() Timestamp { + return s.CreatedAt +} + +// GetUpdatedAt returns the value of UpdatedAt. +func (s *SupportCaseSummary) GetUpdatedAt() Timestamp { + return s.UpdatedAt +} + +// SetID sets the value of ID. +func (s *SupportCaseSummary) SetID(val uuid.UUID) { + s.ID = val +} + +// SetNumber sets the value of Number. +func (s *SupportCaseSummary) SetNumber(val SupportCaseNumber) { + s.Number = val +} + +// SetType sets the value of Type. +func (s *SupportCaseSummary) SetType(val SupportCaseType) { + s.Type = val +} + +// SetStatus sets the value of Status. +func (s *SupportCaseSummary) SetStatus(val SupportCaseStatus) { + s.Status = val +} + +// SetObject sets the value of Object. +func (s *SupportCaseSummary) SetObject(val NilSupportCaseObjectReference) { + s.Object = val +} + +// SetAssessmentTarget sets the value of AssessmentTarget. +func (s *SupportCaseSummary) SetAssessmentTarget(val NilSupportCaseAssessmentTarget) { + s.AssessmentTarget = val +} + +// SetResponseTarget sets the value of ResponseTarget. +func (s *SupportCaseSummary) SetResponseTarget(val SupportResponseTarget) { + s.ResponseTarget = val +} + +// SetDecisionOutcome sets the value of DecisionOutcome. +func (s *SupportCaseSummary) SetDecisionOutcome(val NilSupportCaseDecisionOutcome) { + s.DecisionOutcome = val +} + +// SetCreatedAt sets the value of CreatedAt. +func (s *SupportCaseSummary) SetCreatedAt(val Timestamp) { + s.CreatedAt = val +} + +// SetUpdatedAt sets the value of UpdatedAt. +func (s *SupportCaseSummary) SetUpdatedAt(val Timestamp) { + s.UpdatedAt = val +} + +// Kind of the case. It fixes the allowed object reference, the type-specific fields, the response +// target, and the queue that handles the case. +// +// - support: a question or a problem, for example an assessment that is not available or a failed +// sandbox run. Candidate and employer accounts. +// - 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. +// - 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. +// - anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. +// Candidate accounts. +// - 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. +// +// Ref: #/components/schemas/SupportCaseType +type SupportCaseType string + +const ( + SupportCaseTypeSupport SupportCaseType = "support" + SupportCaseTypeComplaint SupportCaseType = "complaint" + SupportCaseTypeGradeAppeal SupportCaseType = "grade_appeal" + SupportCaseTypeAnticheatAppeal SupportCaseType = "anticheat_appeal" + SupportCaseTypeManualAssessment SupportCaseType = "manual_assessment" +) + +// AllValues returns all SupportCaseType values. +func (SupportCaseType) AllValues() []SupportCaseType { + return []SupportCaseType{ + SupportCaseTypeSupport, + SupportCaseTypeComplaint, + SupportCaseTypeGradeAppeal, + SupportCaseTypeAnticheatAppeal, + SupportCaseTypeManualAssessment, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportCaseType) MarshalText() ([]byte, error) { + switch s { + case SupportCaseTypeSupport: + return []byte(s), nil + case SupportCaseTypeComplaint: + return []byte(s), nil + case SupportCaseTypeGradeAppeal: + return []byte(s), nil + case SupportCaseTypeAnticheatAppeal: + return []byte(s), nil + case SupportCaseTypeManualAssessment: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportCaseType) UnmarshalText(data []byte) error { + switch SupportCaseType(data) { + case SupportCaseTypeSupport: + *s = SupportCaseTypeSupport + return nil + case SupportCaseTypeComplaint: + *s = SupportCaseTypeComplaint + return nil + case SupportCaseTypeGradeAppeal: + *s = SupportCaseTypeGradeAppeal + return nil + case SupportCaseTypeAnticheatAppeal: + *s = SupportCaseTypeAnticheatAppeal + return nil + case SupportCaseTypeManualAssessment: + *s = SupportCaseTypeManualAssessment + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// Operational target for the answer to the case (PRD FR18: a case gets a number, a status, and a +// response deadline). The server fixes it on creation from the product policy version and the +// configured business calendar; it is a goal of the team, not a deadline set by law. The target is met +// by the first public reply, a decision, or a closure for `support` and `complaint`, and only by a +// decision or a closure for the appeals and `manual_assessment`. Missing the target never closes the +// case, never decides it, and never changes a grade. +// Ref: #/components/schemas/SupportResponseTarget +type SupportResponseTarget struct { + // Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as + // a legal deadline. + Kind SupportResponseTargetKind `json:"kind"` + // Length of the target in business days of the policy version, for example 5 for a manual assessment + // and 10 for an appeal. + BusinessDays int32 `json:"business_days"` + DueAt Timestamp `json:"due_at"` + // Time the target was met, or null while it is not. + AnsweredAt NilTimestamp `json:"answered_at"` + // Whether the target was missed: it was met after `due_at`, or it is not met and `due_at` has passed + // at the time of the response. + Late bool `json:"late"` + // Number of the `product` policy version that fixed the target. + PolicyVersion int32 `json:"policy_version"` +} + +// GetKind returns the value of Kind. +func (s *SupportResponseTarget) GetKind() SupportResponseTargetKind { + return s.Kind +} + +// GetBusinessDays returns the value of BusinessDays. +func (s *SupportResponseTarget) GetBusinessDays() int32 { + return s.BusinessDays +} + +// GetDueAt returns the value of DueAt. +func (s *SupportResponseTarget) GetDueAt() Timestamp { + return s.DueAt +} + +// GetAnsweredAt returns the value of AnsweredAt. +func (s *SupportResponseTarget) GetAnsweredAt() NilTimestamp { + return s.AnsweredAt +} + +// GetLate returns the value of Late. +func (s *SupportResponseTarget) GetLate() bool { + return s.Late +} + +// GetPolicyVersion returns the value of PolicyVersion. +func (s *SupportResponseTarget) GetPolicyVersion() int32 { + return s.PolicyVersion +} + +// SetKind sets the value of Kind. +func (s *SupportResponseTarget) SetKind(val SupportResponseTargetKind) { + s.Kind = val +} + +// SetBusinessDays sets the value of BusinessDays. +func (s *SupportResponseTarget) SetBusinessDays(val int32) { + s.BusinessDays = val +} + +// SetDueAt sets the value of DueAt. +func (s *SupportResponseTarget) SetDueAt(val Timestamp) { + s.DueAt = val +} + +// SetAnsweredAt sets the value of AnsweredAt. +func (s *SupportResponseTarget) SetAnsweredAt(val NilTimestamp) { + s.AnsweredAt = val +} + +// SetLate sets the value of Late. +func (s *SupportResponseTarget) SetLate(val bool) { + s.Late = val +} + +// SetPolicyVersion sets the value of PolicyVersion. +func (s *SupportResponseTarget) SetPolicyVersion(val int32) { + s.PolicyVersion = val +} + +// Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as +// a legal deadline. +type SupportResponseTargetKind string + +const ( + SupportResponseTargetKindOperationalGoal SupportResponseTargetKind = "operational_goal" +) + +// AllValues returns all SupportResponseTargetKind values. +func (SupportResponseTargetKind) AllValues() []SupportResponseTargetKind { + return []SupportResponseTargetKind{ + SupportResponseTargetKindOperationalGoal, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SupportResponseTargetKind) MarshalText() ([]byte, error) { + switch s { + case SupportResponseTargetKindOperationalGoal: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SupportResponseTargetKind) UnmarshalText(data []byte) error { + switch SupportResponseTargetKind(data) { + case SupportResponseTargetKindOperationalGoal: + *s = SupportResponseTargetKindOperationalGoal + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Programming language in which assessment tasks of a specialization are offered and solved. It is the // language of the task bank, not the candidate's platform stack, and it never forms a separate // category. Only banks that offer a choice of language define task languages; the first Backend bank @@ -10346,6 +12783,7 @@ func (s *TooManyRequestsHeaders) SetResponse(val Problem) { func (*TooManyRequestsHeaders) confirmEmailRes() {} func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {} +func (*TooManyRequestsHeaders) createMySupportCaseRes() {} func (*TooManyRequestsHeaders) createOrganizationNeedRes() {} func (*TooManyRequestsHeaders) loginRes() {} func (*TooManyRequestsHeaders) registerAccountRes() {} 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 ed1a146..dc1029d 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -57,6 +57,7 @@ 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{}, @@ -65,7 +66,9 @@ var operationRolesSessionCookie = map[string][]string{ GetMyAssessmentAvailabilityOperation: []string{}, GetMyAssessmentResultOperation: []string{}, GetMyQuestionnaireOperation: []string{}, + GetMySupportCaseOperation: []string{}, GetOrganizationNeedOperation: []string{}, + ListMySupportCasesOperation: []string{}, ListOrganizationNeedsOperation: []string{}, LogoutOperation: []string{}, SaveMyQuestionnaireOperation: []string{}, @@ -97,6 +100,7 @@ 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{}, 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 51f48fe..44009ab 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -74,6 +74,97 @@ type Handler interface { // // POST /api/v1/me/assessment-attempts CreateMyAssessmentAttempt(ctx context.Context, req *AssessmentAttemptCreate, params CreateMyAssessmentAttemptParams) (CreateMyAssessmentAttemptRes, error) + // CreateMySupportCase implements CreateMySupportCase operation. + // + // Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and + // an Idempotency-Key. The author is the account of the session; the body has no user, account, or + // organization field. A case is reachable from any screen, including a screen that denies access to an + // assessment: being refused an action never removes the path to a case about it. + // + // The client sends only what the user states: `type`, a non-blank `description`, and the fields of the + // type. It never sets the status, the decision, the outcome, the priority, the response target, the + // rubric, the assignee, or the moderator: every variant has `additionalProperties: false`, so such + // fields answer 400. Attachments are not part of the MVP; they are planned as an optional field and + // change no existing one. + // + // Types, accounts, and allowed references: + // + // Type | Accounts | Object reference | Other fields + // --------------------+---------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------ + // `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` that the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` + // `complaint` | candidate | required; an `organization` that the caller can see or an `invitation` addressed to the caller | required `complaint_reason`; `offer_content` and `salary_terms_violation` require an invitation + // `grade_appeal` | candidate | required; `assessment_attempt` of the caller in a terminal state, so it has a result, or a `support_case` of the caller of type `manual_assessment` that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt | none + // `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. + // + // 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. + // + // 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. + // + // Description check: the schema pattern `\S` uses the ECMAScript white space set in both generated + // validators (ogen converts it for Go), so a description of spaces such as U+00A0 or U+3000 already + // fails validation with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which + // Go `unicode.IsSpace` includes, so the server also applies a domain check: a description whose every + // character is `unicode.IsSpace` or U+FEFF answers 400 validation_failed with the pointer + // `/description`. This check comes with the implementation; generated Zod accepts a description of + // NEL, and the server stays authoritative. + // + // The new case gets a number and the status `submitted`. A grade appeal, an anti-cheat appeal, and a + // manual assessment are moved to `waiting_expert` by a `system` event in the same transaction, so the + // 201 already shows that status with both events; a support case and a complaint stay `submitted`. + // Each case gets a response target from the product policy version and the configured business + // calendar: 5 business days for a manual assessment and 10 for an appeal (PRD FR18 and C3), and a + // policy value for support and complaints. The target is an operational goal, not a deadline set by + // law. A manual assessment fixes the published rubric version of the category, or null when the + // category has none yet; the expert assesses with the same rubric as the automated assessment, and the + // request assigns no category by itself. Creating a case never grants, revokes, or changes a consent, + // a grade, or an attempt. + // + // Replies: the case itself is the channel. Support replies and decisions appear in the public + // `history` and `decision`. The server may also notify the verified email address of the account that + // the case changed, with the case number and a link, never with the description, the reply, or + // assessment details. No request field names another address or contact, so the operation cannot send + // mail to an address that the user typed. + // + // Idempotency: a retry with the same key and body within 24 hours replays the stored 201 with the same + // number and creates nothing, so a lost response never opens a second case. The replay is the snapshot + // stored at creation, following the repository convention; the client reads the current status and + // history with GetMySupportCase. 404 and 409 state_conflict are stored and replayed as well. A + // different body with the same key answers 422 idempotency_key_reused. 400, 403, 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 an employer account with a type other than `support`), the + // per-account case limit (429), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain + // rules (400 with the pointer `/description` for a text of only Unicode spaces or `/object/type` for a + // complaint reason that requires an invitation), the object reference (404 not_found), then the state + // of the object and the limits (409 state_conflict). The general rate limit can answer 429 with + // Retry-After before any check. + // + // POST /api/v1/me/support-cases + CreateMySupportCase(ctx context.Context, req SupportCaseCreate, params CreateMySupportCaseParams) (CreateMySupportCaseRes, error) // CreateOrganizationNeed implements CreateOrganizationNeed operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF @@ -287,6 +378,28 @@ type Handler interface { // // GET /api/v1/me/questionnaire GetMyQuestionnaire(ctx context.Context) (GetMyQuestionnaireRes, error) + // GetMySupportCase implements GetMySupportCase operation. + // + // Requires the session cookie of a candidate or an employer account. Returns the case with its number, + // type, object reference, status, response target, decision, and public history. The owner reads the + // case whatever happened to the object since then: a revoked access, a closed invitation, or a refused + // test never hides the case from its author. + // + // The case never contains the identity of a moderator, an expert, or a support agent, internal notes, + // evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. + // `decision` is null until the case is `resolved`. + // + // The history lists every public event and is never truncated: the server keeps a case within 200 + // events by rejecting a staff event that would leave no room for the terminal one. + // + // The case must belong to the account of the session: a case of another account, including another + // member of the same organization, answers 404 not_found, the same as an unknown identifier, so + // identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers + // 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A + // malformed `case_id` answers 400 validation_failed with the path pointer. + // + // GET /api/v1/me/support-cases/{case_id} + GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error) // GetOrganizationNeed implements GetOrganizationNeed operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. The @@ -338,6 +451,21 @@ type Handler interface { // // GET /api/v1/specializations GetSpecializationCatalog(ctx context.Context) (*SpecializationCatalog, error) + // ListMySupportCases implements ListMySupportCases operation. + // + // Requires the session cookie of a candidate or an employer account. Returns a page of the cases that + // this account created, newest first by creation time with the identifier as the tie-breaker, with + // cursor pagination. Each item is a summary with the number, type, status, object reference, category, + // response target, and decision outcome; it has no description and no history, which GetMySupportCase + // returns with the full case. Cases of other accounts are never listed, including cases of other + // members of the same organization. + // + // Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed + // `limit` or `cursor` answers 400 validation_failed. Filters by status and type are planned and add + // optional parameters. + // + // GET /api/v1/me/support-cases + ListMySupportCases(ctx context.Context, params ListMySupportCasesParams) (ListMySupportCasesRes, error) // ListOrganizationNeeds implements ListOrganizationNeeds operation. // // Requires the session cookie of an employer account with an active membership in `org_id`. The 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 2f7ba91..c47019a 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -85,6 +85,100 @@ func (UnimplementedHandler) CreateMyAssessmentAttempt(ctx context.Context, req * return r, ht.ErrNotImplemented } +// CreateMySupportCase implements CreateMySupportCase operation. +// +// Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and +// an Idempotency-Key. The author is the account of the session; the body has no user, account, or +// organization field. A case is reachable from any screen, including a screen that denies access to an +// assessment: being refused an action never removes the path to a case about it. +// +// The client sends only what the user states: `type`, a non-blank `description`, and the fields of the +// type. It never sets the status, the decision, the outcome, the priority, the response target, the +// rubric, the assignee, or the moderator: every variant has `additionalProperties: false`, so such +// fields answer 400. Attachments are not part of the MVP; they are planned as an optional field and +// change no existing one. +// +// Types, accounts, and allowed references: +// +// Type | Accounts | Object reference | Other fields +// --------------------+---------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------ +// `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` that the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` +// `complaint` | candidate | required; an `organization` that the caller can see or an `invitation` addressed to the caller | required `complaint_reason`; `offer_content` and `salary_terms_violation` require an invitation +// `grade_appeal` | candidate | required; `assessment_attempt` of the caller in a terminal state, so it has a result, or a `support_case` of the caller of type `manual_assessment` that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt | none +// `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. +// +// 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. +// +// 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. +// +// Description check: the schema pattern `\S` uses the ECMAScript white space set in both generated +// validators (ogen converts it for Go), so a description of spaces such as U+00A0 or U+3000 already +// fails validation with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which +// Go `unicode.IsSpace` includes, so the server also applies a domain check: a description whose every +// character is `unicode.IsSpace` or U+FEFF answers 400 validation_failed with the pointer +// `/description`. This check comes with the implementation; generated Zod accepts a description of +// NEL, and the server stays authoritative. +// +// The new case gets a number and the status `submitted`. A grade appeal, an anti-cheat appeal, and a +// manual assessment are moved to `waiting_expert` by a `system` event in the same transaction, so the +// 201 already shows that status with both events; a support case and a complaint stay `submitted`. +// Each case gets a response target from the product policy version and the configured business +// calendar: 5 business days for a manual assessment and 10 for an appeal (PRD FR18 and C3), and a +// policy value for support and complaints. The target is an operational goal, not a deadline set by +// law. A manual assessment fixes the published rubric version of the category, or null when the +// category has none yet; the expert assesses with the same rubric as the automated assessment, and the +// request assigns no category by itself. Creating a case never grants, revokes, or changes a consent, +// a grade, or an attempt. +// +// Replies: the case itself is the channel. Support replies and decisions appear in the public +// `history` and `decision`. The server may also notify the verified email address of the account that +// the case changed, with the case number and a link, never with the description, the reply, or +// assessment details. No request field names another address or contact, so the operation cannot send +// mail to an address that the user typed. +// +// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 with the same +// number and creates nothing, so a lost response never opens a second case. The replay is the snapshot +// stored at creation, following the repository convention; the client reads the current status and +// history with GetMySupportCase. 404 and 409 state_conflict are stored and replayed as well. A +// different body with the same key answers 422 idempotency_key_reused. 400, 403, 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 an employer account with a type other than `support`), the +// per-account case limit (429), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain +// rules (400 with the pointer `/description` for a text of only Unicode spaces or `/object/type` for a +// complaint reason that requires an invitation), the object reference (404 not_found), then the state +// of the object and the limits (409 state_conflict). The general rate limit can answer 429 with +// Retry-After before any check. +// +// POST /api/v1/me/support-cases +func (UnimplementedHandler) CreateMySupportCase(ctx context.Context, req SupportCaseCreate, params CreateMySupportCaseParams) (r CreateMySupportCaseRes, _ 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 @@ -328,6 +422,31 @@ func (UnimplementedHandler) GetMyQuestionnaire(ctx context.Context) (r GetMyQues return r, ht.ErrNotImplemented } +// GetMySupportCase implements GetMySupportCase operation. +// +// Requires the session cookie of a candidate or an employer account. Returns the case with its number, +// type, object reference, status, response target, decision, and public history. The owner reads the +// case whatever happened to the object since then: a revoked access, a closed invitation, or a refused +// test never hides the case from its author. +// +// The case never contains the identity of a moderator, an expert, or a support agent, internal notes, +// evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. +// `decision` is null until the case is `resolved`. +// +// The history lists every public event and is never truncated: the server keeps a case within 200 +// events by rejecting a staff event that would leave no room for the terminal one. +// +// The case must belong to the account of the session: a case of another account, including another +// member of the same organization, answers 404 not_found, the same as an unknown identifier, so +// identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers +// 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A +// malformed `case_id` answers 400 validation_failed with the path pointer. +// +// GET /api/v1/me/support-cases/{case_id} +func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (r GetMySupportCaseRes, _ 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 @@ -385,6 +504,24 @@ func (UnimplementedHandler) GetSpecializationCatalog(ctx context.Context) (r *Sp 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 +// this account created, newest first by creation time with the identifier as the tie-breaker, with +// cursor pagination. Each item is a summary with the number, type, status, object reference, category, +// response target, and decision outcome; it has no description and no history, which GetMySupportCase +// returns with the full case. Cases of other accounts are never listed, including cases of other +// members of the same organization. +// +// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed +// `limit` or `cursor` answers 400 validation_failed. Filters by status and type are planned and add +// optional parameters. +// +// GET /api/v1/me/support-cases +func (UnimplementedHandler) ListMySupportCases(ctx context.Context, params ListMySupportCasesParams) (r ListMySupportCasesRes, _ 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 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 9a52be5..c45842f 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -2998,6 +2998,54 @@ func (s *CreateMyAssessmentAttemptUnprocessableEntity) Validate() error { return nil } +func (s *CreateMySupportCaseBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMySupportCaseConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMySupportCaseForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMySupportCaseNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMySupportCaseUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *CreateMySupportCaseUnprocessableEntity) 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 { @@ -3590,6 +3638,30 @@ func (s *GetMyQuestionnaireUnauthorized) Validate() error { return nil } +func (s *GetMySupportCaseBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMySupportCaseNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMySupportCaseUnauthorized) 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 { @@ -3743,6 +3815,22 @@ func (s ItemContent) Validate() error { } } +func (s *ListMySupportCasesBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMySupportCasesUnauthorized) 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 { @@ -8563,6 +8651,1331 @@ func (s *SubmitMyAssessmentAnswerUnprocessableEntity) Validate() error { return nil } +func (s *SupportCase) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Number.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "number", + Error: err, + }) + } + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + 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 err := s.Description.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "description", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Object.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: "object", + Error: err, + }) + } + if err := func() error { + if value, ok := s.AssessmentTarget.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: "assessment_target", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ComplaintReason.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: "complaint_reason", + Error: err, + }) + } + if err := func() error { + if value, ok := s.RubricVersion.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + 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 { + failures = append(failures, validate.FieldError{ + Name: "rubric_version", + Error: err, + }) + } + if err := func() error { + if err := s.ResponseTarget.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "response_target", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Decision.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: "decision", + Error: err, + }) + } + if err := func() error { + if s.History == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + }).ValidateLength(len(s.History)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.History { + 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: "history", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseActorKind) Validate() error { + switch s { + case "user": + return nil + case "support": + return nil + case "system": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseAssessmentTarget) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + 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 len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *SupportCaseAttemptReference) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseAttemptReferenceType) Validate() error { + switch s { + case "assessment_attempt": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s SupportCaseComplaintReason) Validate() error { + switch s { + case "organization_conduct": + return nil + case "offer_content": + return nil + case "salary_terms_violation": + return nil + case "data_disclosure": + return nil + case "other": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseComplaintReference) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseComplaintReferenceType) Validate() error { + switch s { + case "organization": + return nil + case "invitation": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s SupportCaseCreate) Validate() error { + switch s.Type { + case SupportCaseCreateSupportSupportCaseCreate: + if err := s.SupportCaseCreateSupport.Validate(); err != nil { + return err + } + return nil + case SupportCaseCreateComplaintSupportCaseCreate: + if err := s.SupportCaseCreateComplaint.Validate(); err != nil { + return err + } + return nil + case SupportCaseCreateGradeAppealSupportCaseCreate: + if err := s.SupportCaseCreateGradeAppeal.Validate(); err != nil { + return err + } + return nil + case SupportCaseCreateAnticheatAppealSupportCaseCreate: + if err := s.SupportCaseCreateAnticheatAppeal.Validate(); err != nil { + return err + } + return nil + case SupportCaseCreateManualAssessmentSupportCaseCreate: + if err := s.SupportCaseCreateManualAssessment.Validate(); err != nil { + return err + } + return nil + default: + return errors.Errorf("invalid type %q", s.Type) + } +} + +func (s *SupportCaseCreateAnticheatAppeal) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + 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 err := func() error { + if err := s.Object.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "object", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseCreateAnticheatAppealType) Validate() error { + switch s { + case "anticheat_appeal": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseCreateComplaint) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + 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 err := func() error { + if err := s.ComplaintReason.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "complaint_reason", + Error: err, + }) + } + if err := func() error { + if err := s.Object.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "object", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseCreateComplaintType) Validate() error { + switch s { + case "complaint": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseCreateGradeAppeal) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + 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 err := func() error { + if err := s.Object.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "object", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseCreateGradeAppealType) Validate() error { + switch s { + case "grade_appeal": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseCreateManualAssessment) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + 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 err := func() error { + if err := s.AssessmentTarget.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "assessment_target", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Object.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: "object", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseCreateManualAssessmentType) Validate() error { + switch s { + case "manual_assessment": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseCreateSupport) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + 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 err := func() error { + if value, ok := s.Object.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: "object", + Error: err, + }) + } + if err := func() error { + if value, ok := s.AssessmentTarget.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: "assessment_target", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseCreateSupportType) Validate() error { + switch s { + case "support": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseDecision) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Outcome.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "outcome", + 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 len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseDecisionOutcome) Validate() error { + switch s { + case "upheld": + return nil + case "partially_upheld": + return nil + case "not_upheld": + return nil + case "answered": + return nil + case "assessed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s SupportCaseDescription) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4000, + 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 *SupportCaseEvent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.Sequence)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "sequence", + Error: err, + }) + } + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := s.Actor.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "actor", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Status.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: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Message.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: "message", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseEventKind) Validate() error { + switch s { + case "created": + return nil + case "status_changed": + return nil + case "reply": + return nil + case "decision": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseGradeAppealReference) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseGradeAppealReferenceType) Validate() error { + switch s { + case "assessment_attempt": + return nil + case "support_case": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseHeaders) 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 *SupportCaseList) 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 *SupportCaseListHeaders) 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 SupportCaseNumber) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 14, + MinLengthSet: true, + MaxLength: 18, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^SC-[0-9]{4}-[0-9]{6,10}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s *SupportCaseObjectReference) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseObjectType) Validate() error { + switch s { + case "assessment_attempt": + return nil + case "organization": + return nil + case "invitation": + return nil + case "support_case": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s SupportCasePublicText) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 4000, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + +func (s SupportCaseStatus) Validate() error { + switch s { + case "submitted": + return nil + case "in_review": + return nil + case "waiting_for_user": + return nil + case "waiting_expert": + return nil + case "resolved": + return nil + case "closed": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportCaseSummary) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Number.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "number", + Error: err, + }) + } + if err := func() error { + if err := s.Type.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "type", + 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.Object.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: "object", + Error: err, + }) + } + if err := func() error { + if value, ok := s.AssessmentTarget.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: "assessment_target", + Error: err, + }) + } + if err := func() error { + if err := s.ResponseTarget.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "response_target", + Error: err, + }) + } + if err := func() error { + if value, ok := s.DecisionOutcome.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: "decision_outcome", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportCaseType) Validate() error { + switch s { + case "support": + return nil + case "complaint": + return nil + case "grade_appeal": + return nil + case "anticheat_appeal": + return nil + case "manual_assessment": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *SupportResponseTarget) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Kind.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "kind", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 60, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.BusinessDays)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "business_days", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.PolicyVersion)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "policy_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SupportResponseTargetKind) Validate() error { + switch s { + case "operational_goal": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s TaskLanguage) Validate() error { switch s { case "python": diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index 28fe7a7..12c2d69 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -1080,6 +1080,296 @@ func TestNeedAccessBeforeImplementation(t *testing.T) { } } +// Support case request fixtures shared by the support case tests. +const ( + supportCasesPath = "/api/v1/me/support-cases" + supportCasePath = supportCasesPath + "/01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d" + supportAttemptRef = `{"type":"assessment_attempt","id":"01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b"}` + supportOrganizationRef = `{"type":"organization","id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"}` + supportInvitationRef = `{"type":"invitation","id":"01928f7a-7f8a-7b9c-8d0e-1f2a3b4c5d6e"}` + supportCaseRef = `{"type":"support_case","id":"01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d"}` + validManualAssessment = `{"type":"manual_assessment","description":"Прошу ручную оценку.","assessment_target":{"specialization":"backend","grade":"middle"}}` +) + +// supportCaseBody returns a CreateMySupportCase body of the given type with a +// valid description and the given extra fields, for example `"object":{...}`. +func supportCaseBody(caseType, fields string) string { + body := `{"type":"` + caseType + `","description":"Тест на Senior недоступен."` + if fields != "" { + body += `,` + fields + } + return body + `}` +} + +// The schema alone must accept the five case types with the object types each +// allows, and reject what the client may never send: an empty or blank +// description, an unknown type, an object type that the case type does not +// accept, a missing field of the type, and a status, decision, moderator, or +// contact set by the client. Security accepts the session here, so the +// request reaches validation; a valid request then answers 501 until support +// cases are implemented. Ownership of the object and the complaint reason +// that requires an invitation pass the schema; the server checks them. +func TestSupportCaseSchemaValidationPrecedesImplementation(t *testing.T) { + session := map[string]string{"Cookie": testSessionCookie} + command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey} + for _, test := range []struct { + name string + request identityRequest + location api.ProblemFieldLocation + pointer string + code string + }{ + { + name: "list", + request: identityRequest{method: http.MethodGet, path: supportCasesPath + "?limit=50&cursor=c2MtMDAwMTIz", headers: session}, + }, + { + name: "list with limit zero", + request: identityRequest{method: http.MethodGet, path: supportCasesPath + "?limit=0", headers: session}, + location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid", + }, + { + name: "read", + request: identityRequest{method: http.MethodGet, path: supportCasePath, headers: session}, + }, + { + name: "read with an identifier that is not a UUID", + request: identityRequest{method: http.MethodGet, path: supportCasesPath + "/SC-2026-000123", headers: session}, + location: api.ProblemFieldLocationPath, pointer: "/case_id", code: "invalid", + }, + { + name: "support without context", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", ""), headers: command}, + }, + { + name: "support about an unavailable test", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"assessment_target":{"specialization":"backend","grade":"senior"}`), headers: command}, + }, + { + name: "support about an organization", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"object":`+supportOrganizationRef), headers: command}, + }, + { + name: "complaint about an invitation", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("complaint", `"complaint_reason":"salary_terms_violation","object":`+supportInvitationRef), headers: command}, + }, + { + name: "grade appeal", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":`+supportAttemptRef), headers: command}, + }, + { + // A category that an expert assigned without an attempt is + // disputed through the resolved manual assessment case. + name: "grade appeal of a manual assessment case", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":`+supportCaseRef), headers: command}, + }, + { + name: "support follow-up of another case", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"object":`+supportCaseRef), headers: command}, + }, + { + name: "anti-cheat appeal", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("anticheat_appeal", `"object":`+supportAttemptRef), headers: command}, + }, + { + name: "manual assessment without an attempt", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: validManualAssessment, headers: command}, + }, + { + name: "manual assessment with a prior attempt", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: strings.Replace(validManualAssessment, `}}`, `},"object":`+supportAttemptRef+`}`, 1), headers: command}, + }, + { + name: "description with line breaks", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":"Строка 1\nСтрока 2"}`, headers: command}, + }, + { + // ogen converts `\S` to the ECMAScript white space set, so Go and + // generated Zod both reject Unicode spaces such as U+00A0. + name: "description of only Unicode spaces", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":"\u00a0\u3000\u2003"}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid", + }, + { + // U+0085 (NEL) is unicode.IsSpace but not ECMAScript white space, + // so it passes the schema. The implementation must reject it with + // a unicode.IsSpace domain check: 400 and the pointer /description. + name: "description of only NEL passes the schema", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":"\u0085"}`, headers: command}, + }, + { + name: "empty description", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":""}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid", + }, + { + name: "blank description", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":" \n\t "}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid", + }, + { + name: "description longer than 4000 characters", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":"` + strings.Repeat("a", 4001) + `"}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid", + }, + { + name: "missing description", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support"}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/description", code: "required", + }, + { + // The decoder selects the variant by `type` before it records a + // field path, so an unknown type points at the whole body. + name: "unknown type", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("feedback", ""), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "missing type", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"description":"Тест недоступен."}`, headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "status set by the client", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"status":"resolved"`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "decision set by the client", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":`+supportAttemptRef+`,"decision":{"outcome":"upheld","reason":"ok"}`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "moderator set by the client", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"moderator_id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "response target set by the client", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"response_target":{"due_at":"2026-10-07T09:00:00Z"}`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + // Replies go to the case and to the account address only. + name: "reply address set by the client", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"reply_to":"other@example.com"`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "grade appeal of an organization", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":`+supportOrganizationRef), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid", + }, + { + name: "complaint about an assessment attempt", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("complaint", `"complaint_reason":"other","object":`+supportAttemptRef), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid", + }, + { + name: "anti-cheat appeal of a support case", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("anticheat_appeal", `"object":`+supportCaseRef), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid", + }, + { + name: "complaint about a support case", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("complaint", `"complaint_reason":"other","object":`+supportCaseRef), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid", + }, + { + name: "manual assessment based on a support case", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: strings.Replace(validManualAssessment, `}}`, `},"object":`+supportCaseRef+`}`, 1), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid", + }, + { + name: "support about an unknown object type", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"object":{"type":"user","id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"}`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid", + }, + { + 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", + }, + { + name: "grade appeal without a reference", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", ""), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/object", code: "required", + }, + { + name: "complaint without a reason", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("complaint", `"object":`+supportInvitationRef), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/complaint_reason", code: "required", + }, + { + name: "support with a complaint reason", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"complaint_reason":"other"`), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "manual assessment without a category", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("manual_assessment", ""), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/assessment_target", code: "required", + }, + { + name: "manual assessment for a grade outside the MVP scale", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: strings.Replace(validManualAssessment, `"middle"`, `"lead"`, 1), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "/assessment_target/grade", code: "invalid", + }, + { + name: "manual assessment with a rubric chosen by the client", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: strings.Replace(validManualAssessment, `{"type"`, `{"rubric_version":1,"type"`, 1), headers: command}, + location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", + }, + { + name: "create without an Idempotency-Key", + request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: validManualAssessment, headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}}, + location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", 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 support case operation requires a session; DenyAllSecurity grants +// none, with or without a cookie and a CSRF token. +func TestSupportCaseAccessBeforeImplementation(t *testing.T) { + command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey} + for _, test := range []identityRequest{ + {method: http.MethodGet, path: supportCasesPath}, + {method: http.MethodGet, path: supportCasesPath, headers: map[string]string{"Cookie": testSessionCookie}}, + {method: http.MethodPost, path: supportCasesPath, body: validManualAssessment, headers: command}, + {method: http.MethodPost, path: supportCasesPath, body: validManualAssessment, headers: map[string]string{"Idempotency-Key": testIdempotencyKey}}, + {method: http.MethodGet, path: supportCasePath}, + {method: http.MethodGet, path: supportCasePath, headers: map[string]string{"Cookie": testSessionCookie}}, + } { + 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) + }) + } +} + func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) { var logs bytes.Buffer logger := slog.New(slog.NewJSONHandler(&logs, nil)) diff --git a/frontend/src/shared/api/endpoints/index.msw.ts b/frontend/src/shared/api/endpoints/index.msw.ts index 26efec2..9b0a3d9 100644 --- a/frontend/src/shared/api/endpoints/index.msw.ts +++ b/frontend/src/shared/api/endpoints/index.msw.ts @@ -4,3 +4,4 @@ export { getCatalogMock } from './catalog/catalog.msw' export { getHealthMock } from './health/health.msw' export { getIdentityMock } from './identity/identity.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 bc8d7e2..58f69af 100644 --- a/frontend/src/shared/api/endpoints/index.ts +++ b/frontend/src/shared/api/endpoints/index.ts @@ -4,3 +4,4 @@ export * from './catalog/catalog'; export * from './health/health'; export * from './identity/identity'; export * from './need/need'; +export * from './support/support'; diff --git a/frontend/src/shared/api/endpoints/support/support.msw.ts b/frontend/src/shared/api/endpoints/support/support.msw.ts new file mode 100644 index 0000000..0d8a474 --- /dev/null +++ b/frontend/src/shared/api/endpoints/support/support.msw.ts @@ -0,0 +1,101 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + faker +} from '@faker-js/faker'; + +import { + HttpResponse, + http +} from 'msw'; +import type { + RequestHandlerOptions +} from 'msw'; + +import { + GradeCode, + SpecializationCode, + SupportCaseActorKind, + SupportCaseComplaintReason, + SupportCaseDecisionOutcome, + SupportCaseEventKind, + SupportCaseObjectType, + SupportCaseStatus, + SupportCaseType +} from '../../schemas'; +import type { + SupportCase, + SupportCaseAssessmentTarget, + SupportCaseDecision, + SupportCaseList, + SupportCaseObjectReference +} from '../../schemas'; + + +export const getListMySupportCasesResponseSupportCaseObjectReferenceMock = (overrideResponse: Partial = {}): SupportCaseObjectReference => ({...{type: faker.helpers.arrayElement(Object.values(SupportCaseObjectType)), id: faker.string.uuid()}, ...overrideResponse}); + +export const getListMySupportCasesResponseSupportCaseAssessmentTargetMock = (overrideResponse: Partial = {}): SupportCaseAssessmentTarget => ({...{specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), grade: faker.helpers.arrayElement(Object.values(GradeCode))}, ...overrideResponse}); + +export const getListMySupportCasesResponseMock = (overrideResponse: Partial> = {}): SupportCaseList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), number: faker.helpers.fromRegExp("^SC-[0-9]{4}-[0-9]{6,10}$"), type: faker.helpers.arrayElement(Object.values(SupportCaseType)), status: faker.helpers.arrayElement(Object.values(SupportCaseStatus)), object: faker.helpers.arrayElement([{...getListMySupportCasesResponseSupportCaseObjectReferenceMock()},null,]), assessment_target: faker.helpers.arrayElement([{...getListMySupportCasesResponseSupportCaseAssessmentTargetMock()},null,]), response_target: {kind: faker.helpers.arrayElement(['operational_goal'] as const), business_days: faker.number.int({min: 1, max: 60}), due_at: faker.date.past().toISOString().slice(0, 19) + 'Z', answered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), late: faker.datatype.boolean(), policy_version: faker.number.int({min: 1})}, decision_outcome: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseDecisionOutcome)),null,]), 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([faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), null])}, ...overrideResponse}) + +export const getCreateMySupportCaseResponseSupportCaseObjectReferenceMock = (overrideResponse: Partial = {}): SupportCaseObjectReference => ({...{type: faker.helpers.arrayElement(Object.values(SupportCaseObjectType)), id: faker.string.uuid()}, ...overrideResponse}); + +export const getCreateMySupportCaseResponseSupportCaseAssessmentTargetMock = (overrideResponse: Partial = {}): SupportCaseAssessmentTarget => ({...{specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), grade: faker.helpers.arrayElement(Object.values(GradeCode))}, ...overrideResponse}); + +export const getCreateMySupportCaseResponseSupportCaseDecisionMock = (overrideResponse: Partial = {}): SupportCaseDecision => ({...{outcome: faker.helpers.arrayElement(Object.values(SupportCaseDecisionOutcome)), reason: faker.string.alpha({length: {min: 1, max: 4000}}), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse}); + +export const getCreateMySupportCaseResponseMock = (overrideResponse: Partial> = {}): SupportCase => ({id: faker.string.uuid(), number: faker.helpers.fromRegExp("^SC-[0-9]{4}-[0-9]{6,10}$"), type: faker.helpers.arrayElement(Object.values(SupportCaseType)), status: faker.helpers.arrayElement(Object.values(SupportCaseStatus)), description: faker.helpers.fromRegExp("\\S"), object: faker.helpers.arrayElement([{...getCreateMySupportCaseResponseSupportCaseObjectReferenceMock()},null,]), assessment_target: faker.helpers.arrayElement([{...getCreateMySupportCaseResponseSupportCaseAssessmentTargetMock()},null,]), complaint_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseComplaintReason)),null,]), rubric_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), response_target: {kind: faker.helpers.arrayElement(['operational_goal'] as const), business_days: faker.number.int({min: 1, max: 60}), due_at: faker.date.past().toISOString().slice(0, 19) + 'Z', answered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), late: faker.datatype.boolean(), policy_version: faker.number.int({min: 1})}, decision: faker.helpers.arrayElement([{...getCreateMySupportCaseResponseSupportCaseDecisionMock()},null,]), history: Array.from({ length: faker.number.int({min: 1, max: 200}) }, (_, i) => i + 1).map(() => ({sequence: faker.number.int({min: 1}), kind: faker.helpers.arrayElement(Object.values(SupportCaseEventKind)), actor: faker.helpers.arrayElement(Object.values(SupportCaseActorKind)), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', status: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseStatus)),null,]), message: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 4000}}),null,])})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + +export const getGetMySupportCaseResponseSupportCaseObjectReferenceMock = (overrideResponse: Partial = {}): SupportCaseObjectReference => ({...{type: faker.helpers.arrayElement(Object.values(SupportCaseObjectType)), id: faker.string.uuid()}, ...overrideResponse}); + +export const getGetMySupportCaseResponseSupportCaseAssessmentTargetMock = (overrideResponse: Partial = {}): SupportCaseAssessmentTarget => ({...{specialization: faker.helpers.arrayElement(Object.values(SpecializationCode)), grade: faker.helpers.arrayElement(Object.values(GradeCode))}, ...overrideResponse}); + +export const getGetMySupportCaseResponseSupportCaseDecisionMock = (overrideResponse: Partial = {}): SupportCaseDecision => ({...{outcome: faker.helpers.arrayElement(Object.values(SupportCaseDecisionOutcome)), reason: faker.string.alpha({length: {min: 1, max: 4000}}), decided_at: faker.date.past().toISOString().slice(0, 19) + 'Z'}, ...overrideResponse}); + +export const getGetMySupportCaseResponseMock = (overrideResponse: Partial> = {}): SupportCase => ({id: faker.string.uuid(), number: faker.helpers.fromRegExp("^SC-[0-9]{4}-[0-9]{6,10}$"), type: faker.helpers.arrayElement(Object.values(SupportCaseType)), status: faker.helpers.arrayElement(Object.values(SupportCaseStatus)), description: faker.helpers.fromRegExp("\\S"), object: faker.helpers.arrayElement([{...getGetMySupportCaseResponseSupportCaseObjectReferenceMock()},null,]), assessment_target: faker.helpers.arrayElement([{...getGetMySupportCaseResponseSupportCaseAssessmentTargetMock()},null,]), complaint_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseComplaintReason)),null,]), rubric_version: faker.helpers.arrayElement([faker.number.int({min: 1}), null]), response_target: {kind: faker.helpers.arrayElement(['operational_goal'] as const), business_days: faker.number.int({min: 1, max: 60}), due_at: faker.date.past().toISOString().slice(0, 19) + 'Z', answered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), late: faker.datatype.boolean(), policy_version: faker.number.int({min: 1})}, decision: faker.helpers.arrayElement([{...getGetMySupportCaseResponseSupportCaseDecisionMock()},null,]), history: Array.from({ length: faker.number.int({min: 1, max: 200}) }, (_, i) => i + 1).map(() => ({sequence: faker.number.int({min: 1}), kind: faker.helpers.arrayElement(Object.values(SupportCaseEventKind)), actor: faker.helpers.arrayElement(Object.values(SupportCaseActorKind)), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', status: faker.helpers.arrayElement([faker.helpers.arrayElement(Object.values(SupportCaseStatus)),null,]), message: faker.helpers.arrayElement([faker.string.alpha({length: {min: 1, max: 4000}}),null,])})), created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + + +export const getListMySupportCasesMockHandler = (overrideResponse?: SupportCaseList | ((info: Parameters[1]>[0]) => Promise | SupportCaseList), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/support-cases', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getListMySupportCasesResponseMock(), + { status: 200 + }) + }, options) +} + +export const getCreateMySupportCaseMockHandler = (overrideResponse?: SupportCase | ((info: Parameters[1]>[0]) => Promise | SupportCase), options?: RequestHandlerOptions) => { + return http.post('*/api/v1/me/support-cases', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getCreateMySupportCaseResponseMock(), + { status: 201 + }) + }, options) +} + +export const getGetMySupportCaseMockHandler = (overrideResponse?: SupportCase | ((info: Parameters[1]>[0]) => Promise | SupportCase), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/support-cases/:caseId', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMySupportCaseResponseMock(), + { status: 200 + }) + }, options) +} +export const getSupportMock = () => [ + getListMySupportCasesMockHandler(), + getCreateMySupportCaseMockHandler(), + getGetMySupportCaseMockHandler() +] diff --git a/frontend/src/shared/api/endpoints/support/support.ts b/frontend/src/shared/api/endpoints/support/support.ts new file mode 100644 index 0000000..d6dabea --- /dev/null +++ b/frontend/src/shared/api/endpoints/support/support.ts @@ -0,0 +1,391 @@ +/** + * 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 { + CreateMySupportCaseHeaders, + ListMySupportCasesParams, + Problem, + SupportCase, + SupportCaseCreate, + SupportCaseList +} 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 getListMySupportCasesUrl = (params?: ListMySupportCasesParams,) => { + 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/support-cases?${stringifiedParams}` : `/api/v1/me/support-cases` +} + +/** + * Requires the session cookie of a candidate or an employer account. Returns a page of the cases that this account created, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. Each item is a summary with the number, type, status, object reference, category, response target, and decision outcome; it has no description and no history, which GetMySupportCase returns with the full case. Cases of other accounts are never listed, including cases of other members of the same organization. + * + * Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit` or `cursor` answers 400 validation_failed. Filters by status and type are planned and add optional parameters. + * @summary List the support cases of the current account. + */ +export const listMySupportCases = async (params?: ListMySupportCasesParams, options?: Parameters[1]): Promise => { + + return apiRequest(getListMySupportCasesUrl(params), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getListMySupportCasesQueryKey = (params?: ListMySupportCasesParams,) => { + return [ + `/api/v1/me/support-cases`, ...(params ? [params] : []) + ] as const; + } + + +export const getListMySupportCasesQueryOptions = >, TError = ErrorType>(params?: ListMySupportCasesParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListMySupportCasesQueryKey(params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listMySupportCases(params, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListMySupportCasesQueryResult = NonNullable>> +export type ListMySupportCasesQueryError = ErrorType + + +export function useListMySupportCases>, TError = ErrorType>( + params: undefined | ListMySupportCasesParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListMySupportCases>, TError = ErrorType>( + params?: ListMySupportCasesParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListMySupportCases>, TError = ErrorType>( + params?: ListMySupportCasesParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary List the support cases of the current account. + */ + +export function useListMySupportCases>, TError = ErrorType>( + params?: ListMySupportCasesParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListMySupportCasesQueryOptions(params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getCreateMySupportCaseUrl = () => { + + + + + return `/api/v1/me/support-cases` +} + +/** + * Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The author is the account of the session; the body has no user, account, or organization field. A case is reachable from any screen, including a screen that denies access to an assessment: being refused an action never removes the path to a case about it. + * + * The client sends only what the user states: `type`, a non-blank `description`, and the fields of the type. It never sets the status, the decision, the outcome, the priority, the response target, the rubric, the assignee, or the moderator: every variant has `additionalProperties: false`, so such fields answer 400. Attachments are not part of the MVP; they are planned as an optional field and change no existing one. + * + * Types, accounts, and allowed references: + * + * | Type | Accounts | Object reference | Other fields | + * | --- | --- | --- | --- | + * | `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` that the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` | + * | `complaint` | candidate | required; an `organization` that the caller can see or an `invitation` addressed to the caller | required `complaint_reason`; `offer_content` and `salary_terms_violation` require an invitation | + * | `grade_appeal` | candidate | required; `assessment_attempt` of the caller in a terminal state, so it has a result, or a `support_case` of the caller of type `manual_assessment` that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt | none | + * | `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. + * + * 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. + * + * 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. + * + * Description check: the schema pattern `\S` uses the ECMAScript white space set in both generated validators (ogen converts it for Go), so a description of spaces such as U+00A0 or U+3000 already fails validation with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes, so the server also applies a domain check: a description whose every character is `unicode.IsSpace` or U+FEFF answers 400 validation_failed with the pointer `/description`. This check comes with the implementation; generated Zod accepts a description of NEL, and the server stays authoritative. + * + * The new case gets a number and the status `submitted`. A grade appeal, an anti-cheat appeal, and a manual assessment are moved to `waiting_expert` by a `system` event in the same transaction, so the 201 already shows that status with both events; a support case and a complaint stay `submitted`. Each case gets a response target from the product policy version and the configured business calendar: 5 business days for a manual assessment and 10 for an appeal (PRD FR18 and C3), and a policy value for support and complaints. The target is an operational goal, not a deadline set by law. A manual assessment fixes the published rubric version of the category, or null when the category has none yet; the expert assesses with the same rubric as the automated assessment, and the request assigns no category by itself. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt. + * + * Replies: the case itself is the channel. Support replies and decisions appear in the public `history` and `decision`. The server may also notify the verified email address of the account that the case changed, with the case number and a link, never with the description, the reply, or assessment details. No request field names another address or contact, so the operation cannot send mail to an address that the user typed. + * + * Idempotency: a retry with the same key and body within 24 hours replays the stored 201 with the same number and creates nothing, so a lost response never opens a second case. The replay is the snapshot stored at creation, following the repository convention; the client reads the current status and history with GetMySupportCase. 404 and 409 state_conflict are stored and replayed as well. A different body with the same key answers 422 idempotency_key_reused. 400, 403, 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 an employer account with a type other than `support`), the per-account case limit (429), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with the pointer `/description` for a text of only Unicode spaces or `/object/type` for a complaint reason that requires an invitation), the object reference (404 not_found), then the state of the object and the limits (409 state_conflict). The general rate limit can answer 429 with Retry-After before any check. + * @summary Open a support case, a complaint, an appeal, or a manual assessment request. + */ +export const createMySupportCase = async (supportCaseCreate: SupportCaseCreate, + headers: CreateMySupportCaseHeaders, 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(getCreateMySupportCaseUrl(), + { + ...options, + method: 'POST', + headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) }, + body: JSON.stringify(supportCaseCreate) + } +);} + + + + + +export const getCreateMySupportCaseMutationKey = () => ['createMySupportCase'] as const; + +export const getCreateMySupportCaseMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMySupportCaseMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,CreateMySupportCaseMutationVariables, TContext> => { + +const mutationKey = getCreateMySupportCaseMutationKey(); +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>, CreateMySupportCaseMutationVariables> = (props) => { + const {data,headers} = props ?? {}; + + return createMySupportCase(data,headers,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type CreateMySupportCaseMutationResult = NonNullable>> + export type CreateMySupportCaseMutationBody = SupportCaseCreate + export type CreateMySupportCaseMutationError = ErrorType + export type CreateMySupportCaseMutationVariables = {data: SupportCaseCreate;headers: CreateMySupportCaseHeaders} + + /** + * @summary Open a support case, a complaint, an appeal, or a manual assessment request. + */ +export const useCreateMySupportCase = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,CreateMySupportCaseMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + CreateMySupportCaseMutationVariables, + TContext + > => { + return useMutation(getCreateMySupportCaseMutationOptions(options), queryClient); + } + export const getGetMySupportCaseUrl = (caseId: string,) => { + + + + + return `/api/v1/me/support-cases/${caseId}` +} + +/** + * Requires the session cookie of a candidate or an employer account. Returns the case with its number, type, object reference, status, response target, decision, and public history. The owner reads the case whatever happened to the object since then: a revoked access, a closed invitation, or a refused test never hides the case from its author. + * + * The case never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. `decision` is null until the case is `resolved`. + * + * The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one. + * + * The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. TASK-314 says forbidden for a foreign case URL; the contract answers 404 instead, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. + * @summary Read a support case of the current account. + */ +export const getMySupportCase = async (caseId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getGetMySupportCaseUrl(caseId), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMySupportCaseQueryKey = (caseId: string,) => { + return [ + `/api/v1/me/support-cases/${caseId}` + ] as const; + } + + +export const getGetMySupportCaseQueryOptions = >, TError = ErrorType>(caseId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMySupportCaseQueryKey(caseId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMySupportCase(caseId, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, enabled: caseId !== null && caseId !== undefined, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMySupportCaseQueryResult = NonNullable>> +export type GetMySupportCaseQueryError = ErrorType + + +export function useGetMySupportCase>, TError = ErrorType>( + caseId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMySupportCase>, TError = ErrorType>( + caseId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMySupportCase>, TError = ErrorType>( + caseId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read a support case of the current account. + */ + +export function useGetMySupportCase>, TError = ErrorType>( + caseId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMySupportCaseQueryOptions(caseId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index aca2779..7fde953 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -6,6 +6,7 @@ */ export * from './gradeCode.zod'; +export * from './pageInfo.zod'; export * from './problem.zod'; export * from './problemCode.zod'; export * from './problemFieldError.zod'; @@ -20,3 +21,4 @@ export * from './catalog'; export * from './health'; export * from './identity'; export * from './need'; +export * from './support'; diff --git a/frontend/src/shared/api/schemas/need/index.ts b/frontend/src/shared/api/schemas/need/index.ts index 622cde7..9b233bd 100644 --- a/frontend/src/shared/api/schemas/need/index.ts +++ b/frontend/src/shared/api/schemas/need/index.ts @@ -55,7 +55,6 @@ export * from './needVersion.zod'; export * from './needVersionLabel.zod'; export * from './needWorkFormats.zod'; export * from './needWorkFormatsInput.zod'; -export * from './pageInfo.zod'; export * from './rubAmount.zod'; export * from './salaryPeriod.zod'; export * from './salaryRange.zod'; diff --git a/frontend/src/shared/api/schemas/need/pageInfo.zod.ts b/frontend/src/shared/api/schemas/pageInfo.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/need/pageInfo.zod.ts rename to frontend/src/shared/api/schemas/pageInfo.zod.ts diff --git a/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts b/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts new file mode 100644 index 0000000..1470e0e --- /dev/null +++ b/frontend/src/shared/api/schemas/support/createMySupportCaseBody.zod.ts @@ -0,0 +1,77 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const createMySupportCaseBodyOneDescriptionMax = 4000; + + +export const createMySupportCaseBodyOneDescriptionRegExp = new RegExp('\\S'); +export const createMySupportCaseBodyTwoDescriptionMax = 4000; + + +export const createMySupportCaseBodyTwoDescriptionRegExp = new RegExp('\\S'); +export const createMySupportCaseBodyThreeDescriptionMax = 4000; + + +export const createMySupportCaseBodyThreeDescriptionRegExp = new RegExp('\\S'); +export const createMySupportCaseBodyFourDescriptionMax = 4000; + + +export const createMySupportCaseBodyFourDescriptionRegExp = new RegExp('\\S'); +export const createMySupportCaseBodyFiveDescriptionMax = 4000; + + +export const createMySupportCaseBodyFiveDescriptionRegExp = new RegExp('\\S'); + +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.'), + "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({ + "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.') +}).exactOptional().describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.') +}).describe('New support case. Both the object reference and the assessment target are optional context; omit what does not apply.'),zod.object({ + "type": zod.enum(['complaint']), + "description": zod.string().min(1).max(createMySupportCaseBodyTwoDescriptionMax).regex(createMySupportCaseBodyTwoDescriptionRegExp).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.'), + "complaint_reason": zod.enum(['organization_conduct', 'offer_content', 'salary_terms_violation', 'data_disclosure', 'other']).describe('Ground of a complaint (PRD FR18).\n\n- organization_conduct: conduct of the organization, for example fraudulent or abusive messages.\n- offer_content: misleading or discriminatory content of an offer. Requires an invitation reference.\n- salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference.\n- data_disclosure: a disclosure of the caller\'s personal data beyond what the caller granted.\n- other: another ground, explained in the description.'), + "object": zod.object({ + "type": zod.enum(['organization', 'invitation']), + "id": zod.uuid().describe('Identifier of the organization or the invitation.') +}).describe('Reference to the object of a complaint: an organization that the caller can see or an invitation addressed to the caller. Any other object type fails validation.') +}).describe('New complaint about an organization or an offer.'),zod.object({ + "type": zod.enum(['grade_appeal']), + "description": zod.string().min(1).max(createMySupportCaseBodyThreeDescriptionMax).regex(createMySupportCaseBodyThreeDescriptionRegExp).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', 'support_case']), + "id": zod.uuid().describe('Identifier of the attempt or the case.') +}).describe('Reference to the category that a grade appeal disputes: an assessment attempt of the caller in a terminal state, or a `manual_assessment` case of the caller that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt. Any other object type fails validation.') +}).describe('New appeal of a category the caller received: the result of an own assessment attempt, or the outcome of an own resolved manual assessment.'),zod.object({ + "type": zod.enum(['anticheat_appeal']), + "description": zod.string().min(1).max(createMySupportCaseBodyFourDescriptionMax).regex(createMySupportCaseBodyFourDescriptionRegExp).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']), + "id": zod.uuid().describe('Identifier of an assessment attempt of the caller.') +}).describe('Reference to an assessment attempt of the caller. Any other object type fails validation.') +}).describe('New appeal of an anti-cheat review decision on an own assessment attempt.'),zod.object({ + "type": zod.enum(['manual_assessment']), + "description": zod.string().min(1).max(createMySupportCaseBodyFiveDescriptionMax).regex(createMySupportCaseBodyFiveDescriptionRegExp).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.'), + "assessment_target": zod.object({ + "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.') +}).describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.'), + "object": zod.object({ + "type": zod.enum(['assessment_attempt']), + "id": zod.uuid().describe('Identifier of an assessment attempt of the caller.') +}).exactOptional().describe('Reference to an assessment attempt of the caller. Any other object type fails validation.') +}).describe('New request for a manual assessment of a category by a subject expert. A prior attempt of the same category is optional context: a failed first test or no attempt at all never blocks the request.')]).describe('New case, selected by `type`. Each type fixes its required fields and the object types it accepts. The body carries only what the user states: the request has no status, decision, outcome, priority, response target, assignee, moderator, rubric, or contact field, and every variant rejects unknown fields, so a client cannot set any of them. The user and the account come only from the session.') + +export type CreateMySupportCaseBody = zod.input; +export type CreateMySupportCaseBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/createMySupportCaseHeaders.zod.ts b/frontend/src/shared/api/schemas/support/createMySupportCaseHeaders.zod.ts new file mode 100644 index 0000000..88c4f93 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/createMySupportCaseHeaders.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 createMySupportCaseHeadersIdempotencyKeyMax = 255; + + +export const createMySupportCaseHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$'); + +export const CreateMySupportCaseHeaders = zod.object({ + "Idempotency-Key": zod.string().min(1).max(createMySupportCaseHeadersIdempotencyKeyMax).regex(createMySupportCaseHeadersIdempotencyKeyRegExp) +}) + +export type CreateMySupportCaseHeaders = zod.input; +export type CreateMySupportCaseHeadersOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/index.ts b/frontend/src/shared/api/schemas/support/index.ts new file mode 100644 index 0000000..d1a658a --- /dev/null +++ b/frontend/src/shared/api/schemas/support/index.ts @@ -0,0 +1,37 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ + +export * from './createMySupportCaseBody.zod'; +export * from './createMySupportCaseHeaders.zod'; +export * from './listMySupportCasesParams.zod'; +export * from './supportCase.zod'; +export * from './supportCaseActorKind.zod'; +export * from './supportCaseAssessmentTarget.zod'; +export * from './supportCaseAttemptReference.zod'; +export * from './supportCaseComplaintReason.zod'; +export * from './supportCaseComplaintReference.zod'; +export * from './supportCaseCreate.zod'; +export * from './supportCaseCreateAnticheatAppeal.zod'; +export * from './supportCaseCreateComplaint.zod'; +export * from './supportCaseCreateGradeAppeal.zod'; +export * from './supportCaseCreateManualAssessment.zod'; +export * from './supportCaseCreateSupport.zod'; +export * from './supportCaseDecision.zod'; +export * from './supportCaseDecisionOutcome.zod'; +export * from './supportCaseDescription.zod'; +export * from './supportCaseEvent.zod'; +export * from './supportCaseEventKind.zod'; +export * from './supportCaseGradeAppealReference.zod'; +export * from './supportCaseList.zod'; +export * from './supportCaseNumber.zod'; +export * from './supportCaseObjectReference.zod'; +export * from './supportCaseObjectType.zod'; +export * from './supportCasePublicText.zod'; +export * from './supportCaseStatus.zod'; +export * from './supportCaseSummary.zod'; +export * from './supportCaseType.zod'; +export * from './supportResponseTarget.zod'; diff --git a/frontend/src/shared/api/schemas/support/listMySupportCasesParams.zod.ts b/frontend/src/shared/api/schemas/support/listMySupportCasesParams.zod.ts new file mode 100644 index 0000000..7c1e86a --- /dev/null +++ b/frontend/src/shared/api/schemas/support/listMySupportCasesParams.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 listMySupportCasesParamsLimitDefault = 20; +export const listMySupportCasesParamsLimitMax = 100; + +export const listMySupportCasesParamsCursorMax = 512; + + +export const listMySupportCasesParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const ListMySupportCasesParams = zod.object({ + "limit": zod.int().min(1).max(listMySupportCasesParamsLimitMax).default(listMySupportCasesParamsLimitDefault), + "cursor": zod.string().min(1).max(listMySupportCasesParamsCursorMax).regex(listMySupportCasesParamsCursorRegExp).exactOptional() +}) + +export type ListMySupportCasesParams = zod.input; +export type ListMySupportCasesParamsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCase.zod.ts b/frontend/src/shared/api/schemas/support/supportCase.zod.ts new file mode 100644 index 0000000..a34f15b --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCase.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 supportCaseNumberMin = 14; +export const supportCaseNumberMax = 18; + + +export const supportCaseNumberRegExp = new RegExp('^SC-[0-9]{4}-[0-9]{6,10}$'); +export const supportCaseDescriptionMax = 4000; + + +export const supportCaseDescriptionRegExp = new RegExp('\\S'); + +export const supportCaseResponseTargetBusinessDaysMax = 60; + + +export const supportCaseDecisionOneReasonMax = 4000; + + +export const supportCaseHistoryItemMessageOneMax = 4000; + +export const supportCaseHistoryMax = 200; + + +export const SupportCase = zod.object({ + "id": zod.uuid().describe('Case identifier.'), + "number": zod.string().min(supportCaseNumberMin).max(supportCaseNumberMax).regex(supportCaseNumberRegExp).describe('Human-readable case number that the server assigns on creation, for example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, and a sequence number of at least six digits with leading zeros. The sequence is global and never reused, so the number is unique across every case and year and never changes. The user quotes it in letters and calls; the API addresses a case only by its `id`. Clients show the number as text and never parse it.'), + "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.'), + "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.'), + "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({ + "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.') +}).describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.'),zod.null()]).describe('Category of a manual assessment, the optional category of a support case, or null.'), + "complaint_reason": zod.union([zod.enum(['organization_conduct', 'offer_content', 'salary_terms_violation', 'data_disclosure', 'other']).describe('Ground of a complaint (PRD FR18).\n\n- organization_conduct: conduct of the organization, for example fraudulent or abusive messages.\n- offer_content: misleading or discriminatory content of an offer. Requires an invitation reference.\n- salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference.\n- data_disclosure: a disclosure of the caller\'s personal data beyond what the caller granted.\n- other: another ground, explained in the description.'),zod.null()]).describe('Ground of a complaint, or null for other types.'), + "rubric_version": zod.int().min(1).nullable().describe('For a manual assessment, the version of the published rubric of the category that the server fixed on creation; the expert assesses with it, the same rubric as the automated assessment. Null for other types, and null for a manual assessment whose category has no published rubric yet: the case then waits in `waiting_expert` and the client says so instead of promising a date.'), + "response_target": zod.object({ + "kind": zod.enum(['operational_goal']).describe('Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as a legal deadline.'), + "business_days": zod.int().min(1).max(supportCaseResponseTargetBusinessDaysMax).describe('Length of the target in business days of the policy version, for example 5 for a manual assessment and 10 for an appeal.'), + "due_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.'), + "answered_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('Time the target was met, or null while it is not.'), + "late": zod.boolean().describe('Whether the target was missed: it was met after `due_at`, or it is not met and `due_at` has passed at the time of the response.'), + "policy_version": zod.int().min(1).describe('Number of the `product` policy version that fixed the target.') +}).describe('Operational target for the answer to the case (PRD FR18: a case gets a number, a status, and a response deadline). The server fixes it on creation from the product policy version and the configured business calendar; it is a goal of the team, not a deadline set by law. The target is met by the first public reply, a decision, or a closure for `support` and `complaint`, and only by a decision or a closure for the appeals and `manual_assessment`. Missing the target never closes the case, never decides it, and never changes a grade.'), + "decision": zod.union([zod.object({ + "outcome": zod.enum(['upheld', 'partially_upheld', 'not_upheld', 'answered', 'assessed']).describe('Outcome of a decision as the user sees it. The allowed outcomes depend on the case type.\n\n- upheld: the appeal or the complaint is upheld in full.\n- partially_upheld: the appeal or the complaint is upheld in part.\n- not_upheld: the appeal or the complaint is not upheld.\n- answered: a support case was answered.\n- assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case.'), + "reason": zod.string().min(1).max(supportCaseDecisionOneReasonMax).describe('Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.'), + "decided_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('Decision visible to the user. It exists only once the case is `resolved`. It holds the outcome and the public reason; it never names the moderator or the expert and never contains internal notes, evidence, sanctions against another party, or risk signals. An upheld grade appeal never rewrites the original result: the corrected result is a separate decision of the assessment, and both stay in the history of that attempt.'),zod.null()]).describe('Decision once the case is `resolved`, otherwise null.'), + "history": zod.array(zod.object({ + "sequence": zod.int().min(1).describe('Position of the event in the history, starting at 1 and increasing by one.'), + "kind": zod.enum(['created', 'status_changed', 'reply', 'decision']).describe('Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value.\n\n- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.\n- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.\n- reply: support replied; `message` holds the reply and `status` is null.\n- decision: a decision was made; `status` is `resolved` and `message` holds the public reason.'), + "actor": zod.enum(['user', 'support', 'system']).describe('Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change.\n\n- user: the author of the case.\n- support: a person of the support, moderation, or expert staff.\n- system: the server, for example on creation or when it routes the case.'), + "occurred_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.'), + "status": zod.union([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.'),zod.null()]).describe('Status of the case after the event, or null for a reply.'), + "message": zod.union([zod.string().min(1).max(supportCaseHistoryItemMessageOneMax).describe('Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.'),zod.null()]).describe('Public text of the event, or null.') +}).describe('One public event of the case history. Internal notes, assignments, evidence requests, and risk signals are never history events.')).min(1).max(supportCaseHistoryMax).describe('Every public event in the order it happened, starting with `created`; the list is never truncated. The server keeps a case within 200 events: it rejects a staff reply or status change that would leave no room for the terminal event, so a case always fits and can always be resolved or closed. Further correspondence goes into a new case that references this one as `support_case`.'), + "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('Case of the current account. It contains what the author sent, the public processing state, and the public history. It never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers or anti-cheat signals, risk signals, or contact data of another person. Fields that do not apply to the type are null.') + +export type SupportCase = zod.input; +export type SupportCaseOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseActorKind.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseActorKind.zod.ts new file mode 100644 index 0000000..0409118 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseActorKind.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 SupportCaseActorKind = zod.enum(['user', 'support', 'system']).describe('Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change.\n\n- user: the author of the case.\n- support: a person of the support, moderation, or expert staff.\n- system: the server, for example on creation or when it routes the case.') + +export type SupportCaseActorKind = zod.input; +export type SupportCaseActorKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseAssessmentTarget.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseAssessmentTarget.zod.ts new file mode 100644 index 0000000..082f77f --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseAssessmentTarget.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const SupportCaseAssessmentTarget = zod.object({ + "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.') +}).describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.') + +export type SupportCaseAssessmentTarget = zod.input; +export type SupportCaseAssessmentTargetOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseAttemptReference.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseAttemptReference.zod.ts new file mode 100644 index 0000000..cec7396 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseAttemptReference.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const SupportCaseAttemptReference = zod.object({ + "type": zod.enum(['assessment_attempt']), + "id": zod.uuid().describe('Identifier of an assessment attempt of the caller.') +}).describe('Reference to an assessment attempt of the caller. Any other object type fails validation.') + +export type SupportCaseAttemptReference = zod.input; +export type SupportCaseAttemptReferenceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseComplaintReason.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseComplaintReason.zod.ts new file mode 100644 index 0000000..2254427 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseComplaintReason.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 SupportCaseComplaintReason = zod.enum(['organization_conduct', 'offer_content', 'salary_terms_violation', 'data_disclosure', 'other']).describe('Ground of a complaint (PRD FR18).\n\n- organization_conduct: conduct of the organization, for example fraudulent or abusive messages.\n- offer_content: misleading or discriminatory content of an offer. Requires an invitation reference.\n- salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference.\n- data_disclosure: a disclosure of the caller\'s personal data beyond what the caller granted.\n- other: another ground, explained in the description.') + +export type SupportCaseComplaintReason = zod.input; +export type SupportCaseComplaintReasonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseComplaintReference.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseComplaintReference.zod.ts new file mode 100644 index 0000000..c48d789 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseComplaintReference.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const SupportCaseComplaintReference = zod.object({ + "type": zod.enum(['organization', 'invitation']), + "id": zod.uuid().describe('Identifier of the organization or the invitation.') +}).describe('Reference to the object of a complaint: an organization that the caller can see or an invitation addressed to the caller. Any other object type fails validation.') + +export type SupportCaseComplaintReference = zod.input; +export type SupportCaseComplaintReferenceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts new file mode 100644 index 0000000..3c6c4f8 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseCreate.zod.ts @@ -0,0 +1,77 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const supportCaseCreateOneDescriptionMax = 4000; + + +export const supportCaseCreateOneDescriptionRegExp = new RegExp('\\S'); +export const supportCaseCreateTwoDescriptionMax = 4000; + + +export const supportCaseCreateTwoDescriptionRegExp = new RegExp('\\S'); +export const supportCaseCreateThreeDescriptionMax = 4000; + + +export const supportCaseCreateThreeDescriptionRegExp = new RegExp('\\S'); +export const supportCaseCreateFourDescriptionMax = 4000; + + +export const supportCaseCreateFourDescriptionRegExp = new RegExp('\\S'); +export const supportCaseCreateFiveDescriptionMax = 4000; + + +export const supportCaseCreateFiveDescriptionRegExp = new RegExp('\\S'); + +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.'), + "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({ + "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.') +}).exactOptional().describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.') +}).describe('New support case. Both the object reference and the assessment target are optional context; omit what does not apply.'),zod.object({ + "type": zod.enum(['complaint']), + "description": zod.string().min(1).max(supportCaseCreateTwoDescriptionMax).regex(supportCaseCreateTwoDescriptionRegExp).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.'), + "complaint_reason": zod.enum(['organization_conduct', 'offer_content', 'salary_terms_violation', 'data_disclosure', 'other']).describe('Ground of a complaint (PRD FR18).\n\n- organization_conduct: conduct of the organization, for example fraudulent or abusive messages.\n- offer_content: misleading or discriminatory content of an offer. Requires an invitation reference.\n- salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference.\n- data_disclosure: a disclosure of the caller\'s personal data beyond what the caller granted.\n- other: another ground, explained in the description.'), + "object": zod.object({ + "type": zod.enum(['organization', 'invitation']), + "id": zod.uuid().describe('Identifier of the organization or the invitation.') +}).describe('Reference to the object of a complaint: an organization that the caller can see or an invitation addressed to the caller. Any other object type fails validation.') +}).describe('New complaint about an organization or an offer.'),zod.object({ + "type": zod.enum(['grade_appeal']), + "description": zod.string().min(1).max(supportCaseCreateThreeDescriptionMax).regex(supportCaseCreateThreeDescriptionRegExp).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', 'support_case']), + "id": zod.uuid().describe('Identifier of the attempt or the case.') +}).describe('Reference to the category that a grade appeal disputes: an assessment attempt of the caller in a terminal state, or a `manual_assessment` case of the caller that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt. Any other object type fails validation.') +}).describe('New appeal of a category the caller received: the result of an own assessment attempt, or the outcome of an own resolved manual assessment.'),zod.object({ + "type": zod.enum(['anticheat_appeal']), + "description": zod.string().min(1).max(supportCaseCreateFourDescriptionMax).regex(supportCaseCreateFourDescriptionRegExp).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']), + "id": zod.uuid().describe('Identifier of an assessment attempt of the caller.') +}).describe('Reference to an assessment attempt of the caller. Any other object type fails validation.') +}).describe('New appeal of an anti-cheat review decision on an own assessment attempt.'),zod.object({ + "type": zod.enum(['manual_assessment']), + "description": zod.string().min(1).max(supportCaseCreateFiveDescriptionMax).regex(supportCaseCreateFiveDescriptionRegExp).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.'), + "assessment_target": zod.object({ + "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.') +}).describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.'), + "object": zod.object({ + "type": zod.enum(['assessment_attempt']), + "id": zod.uuid().describe('Identifier of an assessment attempt of the caller.') +}).exactOptional().describe('Reference to an assessment attempt of the caller. Any other object type fails validation.') +}).describe('New request for a manual assessment of a category by a subject expert. A prior attempt of the same category is optional context: a failed first test or no attempt at all never blocks the request.')]).describe('New case, selected by `type`. Each type fixes its required fields and the object types it accepts. The body carries only what the user states: the request has no status, decision, outcome, priority, response target, assignee, moderator, rubric, or contact field, and every variant rejects unknown fields, so a client cannot set any of them. The user and the account come only from the session.') + +export type SupportCaseCreate = zod.input; +export type SupportCaseCreateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreateAnticheatAppeal.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreateAnticheatAppeal.zod.ts new file mode 100644 index 0000000..152ca46 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseCreateAnticheatAppeal.zod.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const supportCaseCreateAnticheatAppealDescriptionMax = 4000; + + +export const supportCaseCreateAnticheatAppealDescriptionRegExp = new RegExp('\\S'); + +export const SupportCaseCreateAnticheatAppeal = zod.object({ + "type": zod.enum(['anticheat_appeal']), + "description": zod.string().min(1).max(supportCaseCreateAnticheatAppealDescriptionMax).regex(supportCaseCreateAnticheatAppealDescriptionRegExp).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']), + "id": zod.uuid().describe('Identifier of an assessment attempt of the caller.') +}).describe('Reference to an assessment attempt of the caller. Any other object type fails validation.') +}).describe('New appeal of an anti-cheat review decision on an own assessment attempt.') + +export type SupportCaseCreateAnticheatAppeal = zod.input; +export type SupportCaseCreateAnticheatAppealOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreateComplaint.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreateComplaint.zod.ts new file mode 100644 index 0000000..fee5600 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseCreateComplaint.zod.ts @@ -0,0 +1,25 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const supportCaseCreateComplaintDescriptionMax = 4000; + + +export const supportCaseCreateComplaintDescriptionRegExp = new RegExp('\\S'); + +export const SupportCaseCreateComplaint = zod.object({ + "type": zod.enum(['complaint']), + "description": zod.string().min(1).max(supportCaseCreateComplaintDescriptionMax).regex(supportCaseCreateComplaintDescriptionRegExp).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.'), + "complaint_reason": zod.enum(['organization_conduct', 'offer_content', 'salary_terms_violation', 'data_disclosure', 'other']).describe('Ground of a complaint (PRD FR18).\n\n- organization_conduct: conduct of the organization, for example fraudulent or abusive messages.\n- offer_content: misleading or discriminatory content of an offer. Requires an invitation reference.\n- salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference.\n- data_disclosure: a disclosure of the caller\'s personal data beyond what the caller granted.\n- other: another ground, explained in the description.'), + "object": zod.object({ + "type": zod.enum(['organization', 'invitation']), + "id": zod.uuid().describe('Identifier of the organization or the invitation.') +}).describe('Reference to the object of a complaint: an organization that the caller can see or an invitation addressed to the caller. Any other object type fails validation.') +}).describe('New complaint about an organization or an offer.') + +export type SupportCaseCreateComplaint = zod.input; +export type SupportCaseCreateComplaintOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreateGradeAppeal.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreateGradeAppeal.zod.ts new file mode 100644 index 0000000..4240385 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseCreateGradeAppeal.zod.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const supportCaseCreateGradeAppealDescriptionMax = 4000; + + +export const supportCaseCreateGradeAppealDescriptionRegExp = new RegExp('\\S'); + +export const SupportCaseCreateGradeAppeal = zod.object({ + "type": zod.enum(['grade_appeal']), + "description": zod.string().min(1).max(supportCaseCreateGradeAppealDescriptionMax).regex(supportCaseCreateGradeAppealDescriptionRegExp).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', 'support_case']), + "id": zod.uuid().describe('Identifier of the attempt or the case.') +}).describe('Reference to the category that a grade appeal disputes: an assessment attempt of the caller in a terminal state, or a `manual_assessment` case of the caller that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt. Any other object type fails validation.') +}).describe('New appeal of a category the caller received: the result of an own assessment attempt, or the outcome of an own resolved manual assessment.') + +export type SupportCaseCreateGradeAppeal = zod.input; +export type SupportCaseCreateGradeAppealOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreateManualAssessment.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreateManualAssessment.zod.ts new file mode 100644 index 0000000..37177b9 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseCreateManualAssessment.zod.ts @@ -0,0 +1,28 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const supportCaseCreateManualAssessmentDescriptionMax = 4000; + + +export const supportCaseCreateManualAssessmentDescriptionRegExp = new RegExp('\\S'); + +export const SupportCaseCreateManualAssessment = zod.object({ + "type": zod.enum(['manual_assessment']), + "description": zod.string().min(1).max(supportCaseCreateManualAssessmentDescriptionMax).regex(supportCaseCreateManualAssessmentDescriptionRegExp).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.'), + "assessment_target": zod.object({ + "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.') +}).describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.'), + "object": zod.object({ + "type": zod.enum(['assessment_attempt']), + "id": zod.uuid().describe('Identifier of an assessment attempt of the caller.') +}).exactOptional().describe('Reference to an assessment attempt of the caller. Any other object type fails validation.') +}).describe('New request for a manual assessment of a category by a subject expert. A prior attempt of the same category is optional context: a failed first test or no attempt at all never blocks the request.') + +export type SupportCaseCreateManualAssessment = zod.input; +export type SupportCaseCreateManualAssessmentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts new file mode 100644 index 0000000..b9c3ee8 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseCreateSupport.zod.ts @@ -0,0 +1,28 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const supportCaseCreateSupportDescriptionMax = 4000; + + +export const supportCaseCreateSupportDescriptionRegExp = new RegExp('\\S'); + +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.'), + "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({ + "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.') +}).exactOptional().describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.') +}).describe('New support case. Both the object reference and the assessment target are optional context; omit what does not apply.') + +export type SupportCaseCreateSupport = zod.input; +export type SupportCaseCreateSupportOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseDecision.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseDecision.zod.ts new file mode 100644 index 0000000..2a1dcc9 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseDecision.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 supportCaseDecisionReasonMax = 4000; + + +export const SupportCaseDecision = zod.object({ + "outcome": zod.enum(['upheld', 'partially_upheld', 'not_upheld', 'answered', 'assessed']).describe('Outcome of a decision as the user sees it. The allowed outcomes depend on the case type.\n\n- upheld: the appeal or the complaint is upheld in full.\n- partially_upheld: the appeal or the complaint is upheld in part.\n- not_upheld: the appeal or the complaint is not upheld.\n- answered: a support case was answered.\n- assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case.'), + "reason": zod.string().min(1).max(supportCaseDecisionReasonMax).describe('Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.'), + "decided_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('Decision visible to the user. It exists only once the case is `resolved`. It holds the outcome and the public reason; it never names the moderator or the expert and never contains internal notes, evidence, sanctions against another party, or risk signals. An upheld grade appeal never rewrites the original result: the corrected result is a separate decision of the assessment, and both stay in the history of that attempt.') + +export type SupportCaseDecision = zod.input; +export type SupportCaseDecisionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseDecisionOutcome.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseDecisionOutcome.zod.ts new file mode 100644 index 0000000..d2bd1c7 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseDecisionOutcome.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 SupportCaseDecisionOutcome = zod.enum(['upheld', 'partially_upheld', 'not_upheld', 'answered', 'assessed']).describe('Outcome of a decision as the user sees it. The allowed outcomes depend on the case type.\n\n- upheld: the appeal or the complaint is upheld in full.\n- partially_upheld: the appeal or the complaint is upheld in part.\n- not_upheld: the appeal or the complaint is not upheld.\n- answered: a support case was answered.\n- assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case.') + +export type SupportCaseDecisionOutcome = zod.input; +export type SupportCaseDecisionOutcomeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseDescription.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseDescription.zod.ts new file mode 100644 index 0000000..c6df2f1 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseDescription.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 SupportCaseDescriptionMax = 4000; + + +export const SupportCaseDescriptionRegExp = new RegExp('\\S'); + +export const SupportCaseDescription = 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.') + +export type SupportCaseDescription = zod.input; +export type SupportCaseDescriptionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseEvent.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseEvent.zod.ts new file mode 100644 index 0000000..9750880 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseEvent.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 supportCaseEventMessageOneMax = 4000; + + +export const SupportCaseEvent = zod.object({ + "sequence": zod.int().min(1).describe('Position of the event in the history, starting at 1 and increasing by one.'), + "kind": zod.enum(['created', 'status_changed', 'reply', 'decision']).describe('Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value.\n\n- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.\n- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.\n- reply: support replied; `message` holds the reply and `status` is null.\n- decision: a decision was made; `status` is `resolved` and `message` holds the public reason.'), + "actor": zod.enum(['user', 'support', 'system']).describe('Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; experts and moderators of TASK-316 and TASK-323 are `support` too. Adding a value is a contract change.\n\n- user: the author of the case.\n- support: a person of the support, moderation, or expert staff.\n- system: the server, for example on creation or when it routes the case.'), + "occurred_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.'), + "status": zod.union([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.'),zod.null()]).describe('Status of the case after the event, or null for a reply.'), + "message": zod.union([zod.string().min(1).max(supportCaseEventMessageOneMax).describe('Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.'),zod.null()]).describe('Public text of the event, or null.') +}).describe('One public event of the case history. Internal notes, assignments, evidence requests, and risk signals are never history events.') + +export type SupportCaseEvent = zod.input; +export type SupportCaseEventOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseEventKind.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseEventKind.zod.ts new file mode 100644 index 0000000..b8dac05 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseEventKind.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 SupportCaseEventKind = zod.enum(['created', 'status_changed', 'reply', 'decision']).describe('Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision (TASK-317) is another `decision` event, so neither needs a new value.\n\n- created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction.\n- status_changed: the status changed; `status` is the new status, and `message` may explain a closure.\n- reply: support replied; `message` holds the reply and `status` is null.\n- decision: a decision was made; `status` is `resolved` and `message` holds the public reason.') + +export type SupportCaseEventKind = zod.input; +export type SupportCaseEventKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseGradeAppealReference.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseGradeAppealReference.zod.ts new file mode 100644 index 0000000..6183dc1 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseGradeAppealReference.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const SupportCaseGradeAppealReference = zod.object({ + "type": zod.enum(['assessment_attempt', 'support_case']), + "id": zod.uuid().describe('Identifier of the attempt or the case.') +}).describe('Reference to the category that a grade appeal disputes: an assessment attempt of the caller in a terminal state, or a `manual_assessment` case of the caller that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt. Any other object type fails validation.') + +export type SupportCaseGradeAppealReference = zod.input; +export type SupportCaseGradeAppealReferenceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts new file mode 100644 index 0000000..f0186d6 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseList.zod.ts @@ -0,0 +1,57 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const supportCaseListItemsItemNumberMin = 14; +export const supportCaseListItemsItemNumberMax = 18; + + +export const supportCaseListItemsItemNumberRegExp = new RegExp('^SC-[0-9]{4}-[0-9]{6,10}$'); +export const supportCaseListItemsItemResponseTargetBusinessDaysMax = 60; + + +export const supportCaseListItemsMax = 100; + +export const supportCaseListPageNextCursorMax = 512; + + +export const supportCaseListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const SupportCaseList = zod.object({ + "items": zod.array(zod.object({ + "id": zod.uuid().describe('Case identifier.'), + "number": zod.string().min(supportCaseListItemsItemNumberMin).max(supportCaseListItemsItemNumberMax).regex(supportCaseListItemsItemNumberRegExp).describe('Human-readable case number that the server assigns on creation, for example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, and a sequence number of at least six digits with leading zeros. The sequence is global and never reused, so the number is unique across every case and year and never changes. The user quotes it in letters and calls; the API addresses a case only by its `id`. Clients show the number as text and never parse it.'), + "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.'), + "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({ + "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.') +}).describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.'),zod.null()]).describe('Category of the case, or null.'), + "response_target": zod.object({ + "kind": zod.enum(['operational_goal']).describe('Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as a legal deadline.'), + "business_days": zod.int().min(1).max(supportCaseListItemsItemResponseTargetBusinessDaysMax).describe('Length of the target in business days of the policy version, for example 5 for a manual assessment and 10 for an appeal.'), + "due_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.'), + "answered_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('Time the target was met, or null while it is not.'), + "late": zod.boolean().describe('Whether the target was missed: it was met after `due_at`, or it is not met and `due_at` has passed at the time of the response.'), + "policy_version": zod.int().min(1).describe('Number of the `product` policy version that fixed the target.') +}).describe('Operational target for the answer to the case (PRD FR18: a case gets a number, a status, and a response deadline). The server fixes it on creation from the product policy version and the configured business calendar; it is a goal of the team, not a deadline set by law. The target is met by the first public reply, a decision, or a closure for `support` and `complaint`, and only by a decision or a closure for the appeals and `manual_assessment`. Missing the target never closes the case, never decides it, and never changes a grade.'), + "decision_outcome": zod.union([zod.enum(['upheld', 'partially_upheld', 'not_upheld', 'answered', 'assessed']).describe('Outcome of a decision as the user sees it. The allowed outcomes depend on the case type.\n\n- upheld: the appeal or the complaint is upheld in full.\n- partially_upheld: the appeal or the complaint is upheld in part.\n- not_upheld: the appeal or the complaint is not upheld.\n- answered: a support case was answered.\n- assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case.'),zod.null()]).describe('Outcome of the decision once the case is `resolved`, otherwise null.'), + "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('Case in a list: the fields that a list of cases shows, without the description and the history. GetMySupportCase returns the full case.')).max(supportCaseListItemsMax).describe('Case summaries of the page.'), + "page": zod.object({ + "has_more": zod.boolean().describe('Whether another page follows this one.'), + "next_cursor": zod.string().min(1).max(supportCaseListPageNextCursorMax).regex(supportCaseListPageNextCursorRegExp).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 cases of the current account, newest first by creation time.') + +export type SupportCaseList = zod.input; +export type SupportCaseListOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseNumber.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseNumber.zod.ts new file mode 100644 index 0000000..38a1cf6 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseNumber.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 SupportCaseNumberMin = 14; +export const SupportCaseNumberMax = 18; + + +export const SupportCaseNumberRegExp = new RegExp('^SC-[0-9]{4}-[0-9]{6,10}$'); + +export const SupportCaseNumber = zod.string().min(SupportCaseNumberMin).max(SupportCaseNumberMax).regex(SupportCaseNumberRegExp).describe('Human-readable case number that the server assigns on creation, for example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, and a sequence number of at least six digits with leading zeros. The sequence is global and never reused, so the number is unique across every case and year and never changes. The user quotes it in letters and calls; the API addresses a case only by its `id`. Clients show the number as text and never parse it.') + +export type SupportCaseNumber = zod.input; +export type SupportCaseNumberOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts new file mode 100644 index 0000000..f653be6 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseObjectReference.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +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.'), + "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.') + +export type SupportCaseObjectReference = zod.input; +export type SupportCaseObjectReferenceOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseObjectType.zod.ts new file mode 100644 index 0000000..db78826 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseObjectType.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 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 type SupportCaseObjectType = zod.input; +export type SupportCaseObjectTypeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCasePublicText.zod.ts b/frontend/src/shared/api/schemas/support/supportCasePublicText.zod.ts new file mode 100644 index 0000000..dedadb2 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCasePublicText.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const SupportCasePublicTextMax = 4000; + + +export const SupportCasePublicText = zod.string().min(1).max(SupportCasePublicTextMax).describe('Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.') + +export type SupportCasePublicText = zod.input; +export type SupportCasePublicTextOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseStatus.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseStatus.zod.ts new file mode 100644 index 0000000..219e131 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseStatus.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 SupportCaseStatus = 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.') + +export type SupportCaseStatus = zod.input; +export type SupportCaseStatusOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts new file mode 100644 index 0000000..d9fa66d --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseSummary.zod.ts @@ -0,0 +1,45 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const supportCaseSummaryNumberMin = 14; +export const supportCaseSummaryNumberMax = 18; + + +export const supportCaseSummaryNumberRegExp = new RegExp('^SC-[0-9]{4}-[0-9]{6,10}$'); +export const supportCaseSummaryResponseTargetBusinessDaysMax = 60; + + + +export const SupportCaseSummary = zod.object({ + "id": zod.uuid().describe('Case identifier.'), + "number": zod.string().min(supportCaseSummaryNumberMin).max(supportCaseSummaryNumberMax).regex(supportCaseSummaryNumberRegExp).describe('Human-readable case number that the server assigns on creation, for example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, and a sequence number of at least six digits with leading zeros. The sequence is global and never reused, so the number is unique across every case and year and never changes. The user quotes it in letters and calls; the API addresses a case only by its `id`. Clients show the number as text and never parse it.'), + "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.'), + "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({ + "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.') +}).describe('Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.'),zod.null()]).describe('Category of the case, or null.'), + "response_target": zod.object({ + "kind": zod.enum(['operational_goal']).describe('Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as a legal deadline.'), + "business_days": zod.int().min(1).max(supportCaseSummaryResponseTargetBusinessDaysMax).describe('Length of the target in business days of the policy version, for example 5 for a manual assessment and 10 for an appeal.'), + "due_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.'), + "answered_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('Time the target was met, or null while it is not.'), + "late": zod.boolean().describe('Whether the target was missed: it was met after `due_at`, or it is not met and `due_at` has passed at the time of the response.'), + "policy_version": zod.int().min(1).describe('Number of the `product` policy version that fixed the target.') +}).describe('Operational target for the answer to the case (PRD FR18: a case gets a number, a status, and a response deadline). The server fixes it on creation from the product policy version and the configured business calendar; it is a goal of the team, not a deadline set by law. The target is met by the first public reply, a decision, or a closure for `support` and `complaint`, and only by a decision or a closure for the appeals and `manual_assessment`. Missing the target never closes the case, never decides it, and never changes a grade.'), + "decision_outcome": zod.union([zod.enum(['upheld', 'partially_upheld', 'not_upheld', 'answered', 'assessed']).describe('Outcome of a decision as the user sees it. The allowed outcomes depend on the case type.\n\n- upheld: the appeal or the complaint is upheld in full.\n- partially_upheld: the appeal or the complaint is upheld in part.\n- not_upheld: the appeal or the complaint is not upheld.\n- answered: a support case was answered.\n- assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case.'),zod.null()]).describe('Outcome of the decision once the case is `resolved`, otherwise null.'), + "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('Case in a list: the fields that a list of cases shows, without the description and the history. GetMySupportCase returns the full case.') + +export type SupportCaseSummary = zod.input; +export type SupportCaseSummaryOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportCaseType.zod.ts b/frontend/src/shared/api/schemas/support/supportCaseType.zod.ts new file mode 100644 index 0000000..7e94bb5 --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportCaseType.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 SupportCaseType = 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.') + +export type SupportCaseType = zod.input; +export type SupportCaseTypeOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/support/supportResponseTarget.zod.ts b/frontend/src/shared/api/schemas/support/supportResponseTarget.zod.ts new file mode 100644 index 0000000..f80b97f --- /dev/null +++ b/frontend/src/shared/api/schemas/support/supportResponseTarget.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 supportResponseTargetBusinessDaysMax = 60; + + + +export const SupportResponseTarget = zod.object({ + "kind": zod.enum(['operational_goal']).describe('Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as a legal deadline.'), + "business_days": zod.int().min(1).max(supportResponseTargetBusinessDaysMax).describe('Length of the target in business days of the policy version, for example 5 for a manual assessment and 10 for an appeal.'), + "due_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.'), + "answered_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('Time the target was met, or null while it is not.'), + "late": zod.boolean().describe('Whether the target was missed: it was met after `due_at`, or it is not met and `due_at` has passed at the time of the response.'), + "policy_version": zod.int().min(1).describe('Number of the `product` policy version that fixed the target.') +}).describe('Operational target for the answer to the case (PRD FR18: a case gets a number, a status, and a response deadline). The server fixes it on creation from the product policy version and the configured business calendar; it is a goal of the team, not a deadline set by law. The target is met by the first public reply, a decision, or a closure for `support` and `complaint`, and only by a decision or a closure for the appeals and `manual_assessment`. Missing the target never closes the case, never decides it, and never changes a grade.') + +export type SupportResponseTarget = zod.input; +export type SupportResponseTargetOutput = zod.output; diff --git a/frontend/src/shared/api/support-contract.test.ts b/frontend/src/shared/api/support-contract.test.ts new file mode 100644 index 0000000..7e7f5e5 --- /dev/null +++ b/frontend/src/shared/api/support-contract.test.ts @@ -0,0 +1,311 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; +import { createMySupportCase } from "./endpoints/support/support"; +import { + CreateMySupportCaseBody, + SupportCase, + SupportCaseCreate, + SupportCaseDecision, + SupportCaseEvent, + SupportCaseList, + SupportCaseSummary, +} from "./schemas"; + +// These tests pin the generated support case contract that the FSD adapters +// consume. They fail when regeneration drops a case type, accepts a blank +// description or an object type that the case type does not allow, or adds a +// request field that would let the client set the status, the decision, the +// moderator, the response target, or a reply address. + +const attempt = { type: "assessment_attempt", id: "01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b" } as const; +const organization = { type: "organization", id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01" } as const; +const invitation = { type: "invitation", id: "01928f7a-7f8a-7b9c-8d0e-1f2a3b4c5d6e" } as const; +const manualCase = { type: "support_case", id: "01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d" } as const; +const description = "Практика не засчитана, хотя решение проходит публичные примеры."; + +const validCases = { + support: { type: "support", description }, + test_unavailable: { + type: "support", + description, + assessment_target: { specialization: "backend", grade: "senior" }, + }, + complaint: { + type: "complaint", + description, + complaint_reason: "salary_terms_violation", + object: invitation, + }, + grade_appeal: { type: "grade_appeal", description, object: attempt }, + category_appeal: { type: "grade_appeal", description, object: manualCase }, + follow_up: { type: "support", description, object: manualCase }, + anticheat_appeal: { type: "anticheat_appeal", description, object: attempt }, + manual_assessment: { + type: "manual_assessment", + description, + assessment_target: { specialization: "backend", grade: "middle" }, + }, +} as const; + +const bodySchemas = [ + ["SupportCaseCreate", SupportCaseCreate], + ["CreateMySupportCaseBody", CreateMySupportCaseBody], +] as const; + +describe.each(bodySchemas)("generated %s", (_name, schema) => { + it.each(Object.entries(validCases))("accepts a %s case", (_case, body) => { + expect(schema.parse(body)).toEqual(body); + }); + + it("accepts a manual assessment with a prior attempt and a multi-line text", () => { + const body = { + ...validCases.manual_assessment, + description: "Строка 1\nСтрока 2", + object: attempt, + }; + + expect(schema.parse(body)).toEqual(body); + }); + + it.each([["feedback"], ["SUPPORT"], [""], [null]])("rejects the case type %j", (type) => { + expect(schema.safeParse({ ...validCases.support, type }).success).toBe(false); + }); + + it.each([ + ["an empty", ""], + ["a blank", " \n\t "], + ["a too long", "a".repeat(4001)], + ["a Unicode-space", "\u00a0\u3000\u2003"], + ])("rejects %s description", (_case, text) => { + for (const body of Object.values(validCases)) { + expect(schema.safeParse({ ...body, description: text }).success).toBe(false); + } + }); + + it("leaves a description of NEL to the server", () => { + // U+0085 is not ECMAScript white space; the server rejects it with a + // unicode.IsSpace domain check and the pointer /description. + expect(schema.safeParse({ ...validCases.support, description: "\u0085" }).success).toBe(true); + }); + + it("rejects a missing description", () => { + expect(schema.safeParse({ type: "support" }).success).toBe(false); + }); + + it.each([ + ["a grade appeal of an organization", { ...validCases.grade_appeal, object: organization }], + [ + "an anti-cheat appeal of an invitation", + { ...validCases.anticheat_appeal, object: invitation }, + ], + ["a complaint about an attempt", { ...validCases.complaint, object: attempt }], + ["a complaint about a case", { ...validCases.complaint, object: manualCase }], + ["an anti-cheat appeal of a case", { ...validCases.anticheat_appeal, object: manualCase }], + [ + "a manual assessment based on a case", + { ...validCases.manual_assessment, object: manualCase }, + ], + [ + "a manual assessment of an organization", + { ...validCases.manual_assessment, object: organization }, + ], + [ + "a support case about an unknown object", + { ...validCases.support, object: { type: "user", id: attempt.id } }, + ], + [ + "a reference that is not a UUID", + { ...validCases.grade_appeal, object: { ...attempt, id: "42" } }, + ], + ])("rejects %s", (_case, body) => { + expect(schema.safeParse(body).success).toBe(false); + }); + + it.each([ + ["a grade appeal without an attempt", { type: "grade_appeal", description }], + ["a complaint without a reason", { type: "complaint", description, object: invitation }], + [ + "a complaint without an object", + { type: "complaint", description, complaint_reason: "other" }, + ], + ["a manual assessment without a category", { type: "manual_assessment", description }], + [ + "a manual assessment for a grade outside the MVP scale", + { + ...validCases.manual_assessment, + assessment_target: { specialization: "backend", grade: "lead" }, + }, + ], + ])("rejects %s", (_case, body) => { + expect(schema.safeParse(body).success).toBe(false); + }); + + it("never carries a status, a decision, a moderator, or a reply address in the parsed body", () => { + const parsed = schema.parse({ + ...validCases.grade_appeal, + status: "resolved", + decision: { outcome: "upheld", reason: "ok" }, + moderator_id: organization.id, + priority: "high", + response_target: { due_at: "2026-10-07T09:00:00Z" }, + reply_to: "other@example.com", + }); + + // Generated Zod strips unknown keys; the server rejects them with 400. + expect(parsed).toEqual(validCases.grade_appeal); + }); +}); + +const created = { + id: "01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d", + number: "SC-2026-000123", + type: "manual_assessment", + status: "waiting_expert", + description: validCases.manual_assessment.description, + object: null, + assessment_target: { specialization: "backend", grade: "middle" }, + complaint_reason: null, + rubric_version: 3, + response_target: { + kind: "operational_goal", + business_days: 5, + due_at: "2026-10-13T09:00:00Z", + answered_at: null, + late: false, + policy_version: 1, + }, + decision: null, + history: [ + { + sequence: 1, + kind: "created", + actor: "user", + occurred_at: "2026-10-06T09:00:00Z", + status: "submitted", + message: null, + }, + { + sequence: 2, + kind: "status_changed", + actor: "system", + occurred_at: "2026-10-06T09:00:00Z", + status: "waiting_expert", + message: null, + }, + ], + created_at: "2026-10-06T09:00:00Z", + updated_at: "2026-10-06T09:00:00Z", +} as const; + +it("parses an own case with its number, status, target, and history", () => { + const parsed = SupportCase.parse(created); + + expect(parsed.number).toBe("SC-2026-000123"); + expect(parsed.response_target.due_at).toBe("2026-10-13T09:00:00Z"); + expect(parsed.decision).toBeNull(); + expect(parsed.history).toHaveLength(2); +}); + +const summary = { + id: created.id, + number: created.number, + type: created.type, + status: "waiting_expert", + object: null, + assessment_target: created.assessment_target, + response_target: created.response_target, + decision_outcome: null, + created_at: created.created_at, + updated_at: created.updated_at, +} as const; + +it("parses a list of summaries without descriptions or histories", () => { + const parsed = SupportCaseList.parse({ + items: [summary, { ...summary, status: "resolved", decision_outcome: "assessed" }], + page: { has_more: false, next_cursor: null }, + }); + + expect(parsed.items[1]?.decision_outcome).toBe("assessed"); + expect(parsed.items[0]).not.toHaveProperty("history"); + expect(SupportCaseSummary.parse({ ...summary, history: [], description })).toEqual(summary); + expect(SupportCaseSummary.safeParse({ ...summary, status: "waiting_for_user" }).success).toBe( + true, + ); +}); + +it("rejects a case without a history, with a malformed number, or with an unknown actor", () => { + expect(SupportCase.safeParse({ ...created, history: [] }).success).toBe(false); + expect(SupportCase.safeParse({ ...created, number: "123" }).success).toBe(false); + expect( + SupportCase.safeParse({ + ...created, + history: [{ ...created.history[0], actor: "moderator:alice" }], + }).success, + ).toBe(false); +}); + +// Every key of every variant of a union. +type KeysOf = T extends unknown ? keyof T : never; + +type ForbiddenRequestKey = + | "status" + | "decision" + | "outcome" + | "moderator" + | "moderator_id" + | "assignee" + | "assignee_id" + | "priority" + | "response_target" + | "due_at" + | "rubric_version" + | "number" + | "history" + | "user_id" + | "account_id" + | "organization_id" + | "email" + | "reply_to" + | "contact"; + +type ForbiddenResponseKey = + | "moderator" + | "moderator_id" + | "moderator_name" + | "assignee" + | "assignee_id" + | "actor_id" + | "actor_name" + | "internal_note" + | "internal_notes" + | "internal_comment" + | "evidence" + | "risk_signals" + | "answers" + | "raw_answers" + | "contacts" + | "email" + | "phone"; + +it("exposes a request DTO without decision, status, moderator, or contact fields", () => { + expectTypeOf, ForbiddenRequestKey>>().toEqualTypeOf(); + // A reference carries only its type and identifier, never a copy of the + // object or an owner chosen by the client. + expectTypeOf< + KeysOf["object"]>> + >().toEqualTypeOf<"type" | "id">(); + expectTypeOf().toEqualTypeOf< + "support" | "complaint" | "grade_appeal" | "anticheat_appeal" | "manual_assessment" + >(); + expectTypeOf(createMySupportCase).parameter(0).toEqualTypeOf(); +}); + +it("exposes a case without moderator identity, internal notes, answers, or contacts", () => { + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + Extract + >().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf<"user" | "support" | "system">(); +});