From 68286af8b754f0a2274795104418a058c2aa4766 Mon Sep 17 00:00:00 2001 From: shira Date: Thu, 8 Oct 2026 21:26:00 +0300 Subject: [PATCH] feat(support): verify the manual assessment request after a C3 refusal --- api/README.en.md | 6 +- api/README.md | 6 +- backend/README.en.md | 4 + backend/README.md | 4 + .../manual_assessment_request_test.go | 302 ++++++++++++++++++ .../integration_test/support_cases_test.go | 40 ++- .../usecase/supportcase/manual_assessment.go | 69 ++++ .../internal/usecase/supportcase/service.go | 32 +- frontend/README.en.md | 2 +- frontend/README.md | 2 +- frontend/src/entities/support-case/index.ts | 1 + .../support-case/model/presentation.test.ts | 46 ++- .../support-case/model/presentation.ts | 27 ++ .../model/availability-message.ts | 25 +- .../model/failure-message.ts | 15 + .../ui/manual-request-failure.test.tsx | 37 +++ .../ui/manual-request-failure.tsx | 31 ++ .../ui/request-manual-assessment.test.ts | 58 ++++ .../ui/request-manual-assessment.tsx | 42 +-- .../support-cases/ui/support-cases-pages.tsx | 5 +- 20 files changed, 680 insertions(+), 74 deletions(-) create mode 100644 backend/integration_test/manual_assessment_request_test.go create mode 100644 backend/internal/usecase/supportcase/manual_assessment.go create mode 100644 frontend/src/features/request-manual-assessment/model/failure-message.ts create mode 100644 frontend/src/features/request-manual-assessment/ui/manual-request-failure.test.tsx create mode 100644 frontend/src/features/request-manual-assessment/ui/manual-request-failure.tsx diff --git a/api/README.en.md b/api/README.en.md index ed2a3d0..88d67d3 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -384,7 +384,7 @@ Planned, additive: reading and comparing versions, exclusions, the market range ### 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, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. +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 implemented: a guest answers 401 `unauthenticated`, and a verified session passes request validation and the domain rules. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -415,7 +415,7 @@ Types and object references: - An organization is visible to a candidate that it invited or whose profile the organization contract shows to the candidate, and to an employer account with an active membership. The server checks every reference against the session account: an unknown object and someone else's object both answer 404 `not_found`, so a reference never reveals whether a foreign object exists. The case stores only `{type, id}`. - Invitations are in the contract (see Invitations and contact grants below) but not implemented, and anti-cheat review decisions are not in the contract yet. Until they are implemented, every `invitation` reference answers 404 and every anti-cheat appeal answers 409 `state_conflict`; the request shapes stay the same. - `offer_content` and `salary_terms_violation` complaints require an invitation; another object answers 400 with the pointer `/object/type` (a domain rule after the schema). -- A failed first test or no attempt at all never blocks a manual assessment. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt; how a manual assessment relates to the C3 consent is defined by consent revocation and manual assessment. +- 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; a manual assessment does not depend on C3. A candidate who revoked C3 (`DELETE /api/v1/me/consents/c3`) or never gave it creates the same request, and the request neither reads nor changes the consent ledger. A retry with the same `Idempotency-Key` returns the original case; a new key (for example after a page reload) while a manual assessment of the same specialization is open answers 409 `state_conflict`, and the open case stays the only one. `rubric_version` is `null` when the target has no single current reviewed category; the server does not guess a rubric, and the case still waits for an expert with no automatic result. Content and fields the client never sets: @@ -444,6 +444,8 @@ Commands and limits: Open product question for manual assessment: whether repeated manual assessments of the same category follow the retest rules of FR04 (the same grade after 30 days, at most three attempts in 180 days) or their own rule. The contract only allows one open manual assessment per specialization and invents no interval. +Open questions for manual assessment after a C3 refusal: whether the request needs a structured reason (for example a "C3 refused" marker) instead of the free-text `description`; whether a target with two current categories for the same specialization and grade (different task languages) should get a rubric chosen by language instead of `null`; whether a repeat with a new key should return the existing open case instead of 409. The contract invents none of these. + Planned, additive (a new operation or an optional field): replies of the author, attachments, withdrawal of a case, list filters by status and type, the resulting category of a manual assessment in the decision, a next step for the author, staff queues and decisions, and the pause rules of the response target. Planned contract changes (new enum values; like the catalog codes, generated clients reject an unknown value, so each one is released with regenerated clients): object types `vacancy` and `application` for the vacancies and protected applications of FR16, and an object type for the profile analysis findings. `waiting_for_user` and `support_case` are already in the enums, so the reply operation and follow-up cases need no such change. No new event kind or actor kind is planned: an author reply is a `reply` with the actor `user`, a decision revision is another `decision` event, and experts and moderators are `support`. diff --git a/api/README.md b/api/README.md index 80a342b..62a19fb 100644 --- a/api/README.md +++ b/api/README.md @@ -384,7 +384,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Обращения -Тег `support` описывает обращения текущего аккаунта (FR18 в PRD, с ручной оценкой из FR04 и C3): вопросы в поддержку, жалобы, апелляции грейда и античит-решения, запросы ручной оценки. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. +Тег `support` описывает обращения текущего аккаунта (FR18 в PRD, с ручной оценкой из FR04 и C3): вопросы в поддержку, жалобы, апелляции грейда и античит-решения, запросы ручной оценки. Операции реализованы: гость получает 401 `unauthenticated`, а подтвержденная сессия проходит проверку запроса и доменные правила. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -415,7 +415,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Организацию видит кандидат, которого она пригласила или которому контракт организации показывает ее профиль, и аккаунт работодателя с действующим членством в ней. Сервер сверяет каждую ссылку с аккаунтом сессии: неизвестный и чужой объект одинаково дают 404 `not_found`, поэтому ссылка не раскрывает, существует ли чужой объект. Обращение хранит только `{type, id}`. - Приглашения есть в контракте (см. раздел Приглашения и контактные разрешения ниже), но не реализованы, а решений античит-проверки в контракте пока нет. До их реализации любая ссылка `invitation` дает 404, а любая античит-апелляция - 409 `state_conflict`; форма запроса не меняется. - Жалобы `offer_content` и `salary_terms_violation` требуют приглашения; другой объект дает 400 с pointer `/object/type` (доменное правило после схемы). -- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; связь ручной оценки с согласием C3 определяют отзыв согласия и ручная оценка. +- Неудачный первый тест или отсутствие попыток не блокируют ручную оценку. Создание обращения не дает, не отзывает и не меняет согласие, грейд или попытку; ручная оценка не зависит от C3. Кандидат, отозвавший C3 (`DELETE /api/v1/me/consents/c3`) или не дававший его, создает такой же запрос, а запрос не читает и не меняет журнал согласий. Повтор с тем же `Idempotency-Key` возвращает исходное обращение; новый ключ (например, после перезагрузки страницы) при открытой ручной оценке той же специализации дает 409 `state_conflict`, и открытое обращение остается единственным. `rubric_version` равна `null`, если для цели нет единственной актуальной проверенной категории; сервер не выбирает рубрику наугад, а обращение все равно ожидает эксперта без автоматического результата. Содержание и поля, которые клиент не задает: @@ -444,6 +444,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro Открытый продуктовый вопрос для ручной оценки: подчиняются ли повторные ручные оценки той же категории правилам пересдачи из FR04 (тот же грейд через 30 дней, не больше трех попыток за 180 дней) или собственному правилу. Контракт разрешает только одну открытую ручную оценку на специализацию и интервал не придумывает. +Открытые вопросы ручной оценки после отказа от C3: нужна ли структурная причина запроса (например, пометка "отказ от C3") вместо свободного текста `description`; должен ли запрос со второй задачей языка (две актуальные категории для одной специализации и грейда) получать рубрику с выбором языка, а не `null`; нужно ли возвращать существующее открытое обращение вместо 409 при повторе с новым ключом. Контракт ничего из этого не выдумывает. + Запланировано, добавляется без ломающих изменений (новая операция или необязательное поле): ответы автора, вложения, отзыв обращения, фильтры списка по статусу и типу, итоговая категория ручной оценки в решении, следующий шаг для автора, служебные очереди и решения и правила паузы срока ответа. Запланированные изменения контракта (новые значения перечислений; как и коды каталога, сгенерированные клиенты отклоняют неизвестное значение, поэтому каждое выходит вместе с перегенерированными клиентами): типы объектов `vacancy` и `application` для вакансий и защищенных откликов из FR16 и тип объекта для замечаний из анализа профиля. `waiting_for_user` и `support_case` уже есть в перечислениях, поэтому операции ответа и последующим обращениям такое изменение не нужно. Новых видов событий и участников не планируется: ответ автора - это `reply` с участником `user`, пересмотр решения - еще одно событие `decision`, а эксперты и модераторы - это `support`. diff --git a/backend/README.en.md b/backend/README.en.md index 99fb54e..7baa96f 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -64,6 +64,10 @@ Creation requires an explicit support section in the effective product policy. ` The account-wide rolling request limit is checked under a database lock before idempotent replay. Valid retries consume that request budget and return the original creation response during the 24-hour window. A 429 response includes `Retry-After`. GET and list show the current status, public history, and current overdue flag. Migration `00025_create_support_cases.sql` stores immutable events and replay results; rollback removes these records and is destructive. +The manual assessment rules live in `internal/usecase/supportcase/manual_assessment.go`: the request neither reads nor changes consent, creates no attempt, and writes no grade or category, and a prior attempt is optional and may have failed. + +`TestManualAssessmentRequestAfterC3Refusal` goes through the real router: granting and revoking C3, a request before the first test with a pinned rubric, a request without a published rubric (`rubric_version` is `null`), and requests after a failed and after a confirmed attempt. The test compares the consent ledger and events, attempts, and immutable results before and after the request, and checks that a repeat with a new key leaves one open case. + `TestSupportCasesOverHTTP` covers real sessions, owner isolation, typed-reference checks, replay, manual assessment without C3, and request limits. `TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock` checks concurrent requests and clock ordering. Expert processing and references to not-yet-implemented invitations or anti-cheat reviews remain unavailable. ## Candidate questionnaire diff --git a/backend/README.md b/backend/README.md index 5f5ba78..3294915 100644 --- a/backend/README.md +++ b/backend/README.md @@ -64,6 +64,10 @@ Скользящий лимит запросов аккаунта проверяется под блокировкой БД до идемпотентного повтора. Корректные повторы расходуют этот бюджет и возвращают исходный ответ создания в течение 24 часов. Ответ 429 содержит `Retry-After`. GET и список показывают актуальный статус, публичную историю и текущий признак просрочки. Миграция `00025_create_support_cases.sql` хранит неизменяемые события и результаты повторов; откат удаляет эти записи и является разрушительным. +Правила ручной оценки лежат в `internal/usecase/supportcase/manual_assessment.go`: запрос не читает и не меняет согласия, не создает попытку и не пишет грейд или категорию, а предыдущая попытка нужна не всегда и может быть неудачной. + +`TestManualAssessmentRequestAfterC3Refusal` проходит через настоящий роутер: выдача и отзыв C3, запрос до первого теста с зафиксированной рубрикой, запрос без опубликованной рубрики (`rubric_version` равна `null`), запрос после неудачной и после подтвержденной попытки. Тест сравнивает журнал согласий и события, попытки и неизменяемые результаты до и после запроса и проверяет, что повтор с новым ключом оставляет одно открытое обращение. + `TestSupportCasesOverHTTP` проверяет настоящие сессии, изоляцию владельцев, типизированные ссылки, повторы, ручную оценку без C3 и лимиты запросов. `TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock` проверяет конкурентные запросы и порядок времени. Обработка экспертом и ссылки на еще не реализованные приглашения или античит-проверки остаются недоступны. ## Анкета кандидата diff --git a/backend/integration_test/manual_assessment_request_test.go b/backend/integration_test/manual_assessment_request_test.go new file mode 100644 index 0000000..4495e95 --- /dev/null +++ b/backend/integration_test/manual_assessment_request_test.go @@ -0,0 +1,302 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/consent" +) + +const manualAssessmentHTTPTimeout = 8 * time.Minute + +const manualAssessmentBody = `{"type":"manual_assessment","description":"I do not consent to automated categorization.","assessment_target":{"specialization":"backend","grade":"junior"}}` + +// TestManualAssessmentRequestAfterC3Refusal drives the real router through a +// C3 refusal and the manual assessment request that replaces the automated +// path. The request must neither depend on C3 nor change it, and it must leave +// existing attempts and results untouched. +func TestManualAssessmentRequestAfterC3Refusal(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), manualAssessmentHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv) + productPolicy, _, _, _ := seedSupportManualRubric(ctx, t, harness) + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + reader := consent.NewQueryService(postgresadapter.NewConsentStore(harness.pool), time.Now) + + t.Run("refusal before the first test", func(t *testing.T) { + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-before-test@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.10:1234") + grantManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.11:1234") + revokeManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.12:1234") + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + consentBefore := consentLedgerSnapshot(ctx, t, harness, candidate.ID) + + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody, + cookie.Value, csrf, "manual-before-test-1", "198.51.100.13:1234") + var request supportCaseHTTPResponse + if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &request) != nil { + t.Fatalf("manual request after C3 revocation = %d %s, want 201", created.Code, created.Body.String()) + } + if request.Type != "manual_assessment" || request.Status != "waiting_expert" || request.Decision != nil || + request.RubricVersion == nil || *request.RubricVersion != productPolicy.Version() { + t.Fatalf("created request = %+v, want waiting_expert without a decision, pinned to rubric version %d", request, productPolicy.Version()) + } + if len(request.History) != 2 || request.History[1].Actor != "system" || request.History[1].Status != "waiting_expert" { + t.Fatalf("request history = %+v, want creation and a system move to the expert queue", request.History) + } + if request.AssessmentTarget == nil || request.AssessmentTarget.Specialization != "backend" || request.AssessmentTarget.Grade != "junior" || + request.Description != "I do not consent to automated categorization." { + t.Fatalf("request target/reason = %+v / %q, want backend junior and the stated reason", request.AssessmentTarget, request.Description) + } + + read := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+request.ID, "", cookie.Value, "", "", "198.51.100.14:1234") + if read.Code != http.StatusOK || read.Body.String() != created.Body.String() { + t.Fatalf("manual request GET = %d %s, want the created case %s", read.Code, read.Body.String(), created.Body.String()) + } + + // The request is not a consent action and not an assessment action. + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + if after := consentLedgerSnapshot(ctx, t, harness, candidate.ID); after != consentBefore { + t.Fatalf("manual request changed the consent ledger or its events:\nbefore %s\nafter %s", consentBefore, after) + } + if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != "[]|[]" { + t.Fatalf("manual request created assessment rows %s, want no attempt and no result", got) + } + + // A page reload loses the form's idempotency key: a new key must not + // create a second case, and the same key still replays the first. + reload := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody, + cookie.Value, csrf, "manual-before-test-2", "198.51.100.15:1234") + requireSessionProblem(t, reload, http.StatusConflict, "state_conflict") + replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody, + cookie.Value, csrf, "manual-before-test-1", "198.51.100.16:1234") + if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() { + t.Fatalf("same-key replay = %d %s, want the original case", replay.Code, replay.Body.String()) + } + assertSupportCaseCount(t, ctx, harness, candidate.ID, 1) + if after := consentLedgerSnapshot(ctx, t, harness, candidate.ID); after != consentBefore { + t.Fatalf("repeated manual requests changed the consent ledger or its events") + } + }) + + t.Run("unavailable rubric is stored as unavailable", func(t *testing.T) { + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-no-rubric@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.20:1234") + body := `{"type":"manual_assessment","description":"No automated bank exists for this target.","assessment_target":{"specialization":"backend","grade":"senior"}}` + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + cookie.Value, csrf, "manual-no-rubric-1", "198.51.100.21:1234") + var request supportCaseHTTPResponse + if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &request) != nil || + request.Status != "waiting_expert" || request.RubricVersion != nil || request.Decision != nil { + t.Fatalf("manual request without a published rubric = %d %s, want waiting_expert with a null rubric version", created.Code, created.Body.String()) + } + var storedVersion *int32 + var storedOpening *uuid.UUID + if err := harness.pool.QueryRow(ctx, `SELECT rubric_version, rubric_opening_id FROM support_cases WHERE id = $1::uuid`, request.ID). + Scan(&storedVersion, &storedOpening); err != nil || storedVersion != nil || storedOpening != nil { + t.Fatalf("stored rubric pin = %v/%v, %v; want none", storedVersion, storedOpening, err) + } + }) + + t.Run("failed first test and missing attempt reference", func(t *testing.T) { + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-after-failure@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.30:1234") + attemptID := completeManualAssessmentFixtureAttempt(ctx, t, harness, candidate.ID, cookie, csrf, "198.51.100.3", false) + revokeManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.39:1234") + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + // The snapshot is taken after the revocation on purpose: the fixture attempt + // needs a granted C3, so the ledger legitimately changes until then. Only + // changes made by the manual request itself are being checked. + consentBefore := consentLedgerSnapshot(ctx, t, harness, candidate.ID) + assessmentBefore := userAssessmentSnapshot(ctx, t, harness, candidate.ID) + if assessmentBefore == "[]|[]" { + t.Fatal("fixture did not store a failed attempt and its result") + } + + // The refusal and the failed first test do not block the request. The + // failed attempt is accepted as the optional reference; it is not changed. + withReferenceBody := fmt.Sprintf(`{"type":"manual_assessment","description":"Please assess this specialization.","assessment_target":{"specialization":"backend","grade":"junior"},"object":{"type":"assessment_attempt","id":%q}}`, attemptID) + withReference := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", withReferenceBody, + cookie.Value, csrf, "manual-failure-1", "198.51.100.40:1234") + var referenced supportCaseHTTPResponse + if withReference.Code != http.StatusCreated || json.Unmarshal(withReference.Body.Bytes(), &referenced) != nil || + referenced.Status != "waiting_expert" || referenced.Decision != nil { + t.Fatalf("manual request referencing the failed attempt = %d %s, want waiting_expert without a decision", withReference.Code, withReference.Body.String()) + } + if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != assessmentBefore { + t.Fatalf("manual request changed attempts or results:\nbefore %s\nafter %s", assessmentBefore, got) + } + if after := consentLedgerSnapshot(ctx, t, harness, candidate.ID); after != consentBefore { + t.Fatal("manual request changed the consent ledger or its events") + } + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + + // A reload creates a new key: still one open case, attempts unchanged. + reload := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", withReferenceBody, + cookie.Value, csrf, "manual-failure-2", "198.51.100.41:1234") + requireSessionProblem(t, reload, http.StatusConflict, "state_conflict") + assertSupportCaseCount(t, ctx, harness, candidate.ID, 1) + if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != assessmentBefore { + t.Fatalf("repeated manual request changed attempts or results:\nbefore %s\nafter %s", assessmentBefore, got) + } + }) + + t.Run("confirmed result is kept", func(t *testing.T) { + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-after-confirmation@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.50:1234") + completeManualAssessmentFixtureAttempt(ctx, t, harness, candidate.ID, cookie, csrf, "198.51.100.5", true) + revokeManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.59:1234") + assessmentBefore := userAssessmentSnapshot(ctx, t, harness, candidate.ID) + + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody, + cookie.Value, csrf, "manual-confirmed-1", "198.51.100.60:1234") + if created.Code != http.StatusCreated { + t.Fatalf("manual request after a confirmed result = %d %s, want 201", created.Code, created.Body.String()) + } + if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != assessmentBefore { + t.Fatalf("manual request changed the confirmed result or attempts:\nbefore %s\nafter %s", assessmentBefore, got) + } + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + }) +} + +func grantManualAssessmentC3(t *testing.T, harness *supportCaseHTTPHarness, cookie *http.Cookie, csrf, remoteAddr string) { + t.Helper() + text := harness.request(t, http.MethodGet, "/api/v1/me/consent-texts/c3", "", "", cookie.Value, "", remoteAddr) + var current struct { + TextVersion string `json:"text_version"` + } + if text.Code != http.StatusOK || json.Unmarshal(text.Body.Bytes(), ¤t) != nil || current.TextVersion == "" { + t.Fatalf("read current C3 text = %d %s", text.Code, text.Body.String()) + } + if grant := consentGrantHTTP(t, harness.sessionHTTPHarness, cookie, csrf, "c3", current.TextVersion, sessionHTTPTestOrigin); grant.Code != http.StatusOK { + t.Fatalf("grant C3 = %d %s", grant.Code, grant.Body.String()) + } +} + +func revokeManualAssessmentC3(t *testing.T, harness *supportCaseHTTPHarness, cookie *http.Cookie, csrf, remoteAddr string) { + t.Helper() + revoked := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c3", "", sessionHTTPTestOrigin, cookie.Value, csrf, remoteAddr) + if revoked.Code != http.StatusNoContent { + t.Fatalf("revoke C3 = %d %s, want 204", revoked.Code, revoked.Body.String()) + } +} + +func requireManualAssessmentC3Inactive(ctx context.Context, t *testing.T, reader *consent.QueryService, subject uuid.UUID) { + t.Helper() + active, err := reader.HasCurrentConsent(ctx, subject, domain.ConsentPurposeAutoCategorization) + if err != nil || active { + t.Fatalf("current C3 = %v, %v; want no active C3", active, err) + } +} + +// consentLedgerSnapshot returns every consent row and the count of consent +// events of the subject, so a test can prove a command left both unchanged. +func consentLedgerSnapshot(ctx context.Context, t *testing.T, harness *supportCaseHTTPHarness, subject uuid.UUID) string { + t.Helper() + var records string + var events int64 + if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(jsonb_agg(to_jsonb(record) ORDER BY record.id)::text, '[]') + FROM consent_records AS record WHERE record.subject_id = $1`, subject).Scan(&records); err != nil { + t.Fatalf("read consent ledger: %v", err) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events + WHERE event_type LIKE 'consent.%' AND payload->>'subject_id' = $1`, subject.String()).Scan(&events); err != nil { + t.Fatalf("count consent events: %v", err) + } + return fmt.Sprintf("%s|events=%d", records, events) +} + +// userAssessmentSnapshot returns the attempts and the immutable results of one +// account as stable JSON, joined by "|". +func userAssessmentSnapshot(ctx context.Context, t *testing.T, harness *supportCaseHTTPHarness, userID uuid.UUID) string { + t.Helper() + var attempts, results string + if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(jsonb_agg(to_jsonb(attempt) ORDER BY attempt.id)::text, '[]') + FROM assessment_attempts AS attempt WHERE attempt.user_id = $1`, userID).Scan(&attempts); err != nil { + t.Fatalf("read assessment attempts: %v", err) + } + if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(jsonb_agg(to_jsonb(result) ORDER BY result.attempt_id)::text, '[]') + FROM assessment_attempt_results AS result WHERE result.user_id = $1`, userID).Scan(&results); err != nil { + t.Fatalf("read assessment results: %v", err) + } + return attempts + "|" + results +} + +// completeManualAssessmentFixtureAttempt grants C3 (an automated attempt needs +// it), runs one real Backend/Junior attempt to completion, and answers every +// item correctly or incorrectly. +func completeManualAssessmentFixtureAttempt( + ctx context.Context, + t *testing.T, + harness *supportCaseHTTPHarness, + userID uuid.UUID, + cookie *http.Cookie, + csrf, remotePrefix string, + correct bool, +) uuid.UUID { + t.Helper() + attemptHarness := &assessmentAttemptHTTPHarness{sessionHTTPHarness: harness.sessionHTTPHarness, keyring: harness.keyring} + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", userID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + questionnaire := `{"expected_version":0,"specializations":[{"specialization":"backend","self_assessed_grade":"junior","task_languages":["go"],"stack":[],"experience":null}],"work_context":{"work_formats":["remote"]}}` + if response := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPut, "/api/v1/me/questionnaire", questionnaire, + sessionHTTPTestOrigin, cookie.Value, csrf, "", remotePrefix+"1:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantManualAssessmentC3(t, harness, cookie, csrf, remotePrefix+"2:1234") + create := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "manual-fixture-create-"+userID.String(), remotePrefix+"3:1234") + var attempt assessmentAnswerHTTPAttempt + if create.Code != http.StatusCreated || json.Unmarshal(create.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil { + t.Fatalf("create fixture attempt = %d %s", create.Code, create.Body.String()) + } + version := attempt.Version + for _, item := range readAssessmentAnswerHTTPItems(t, ctx, attemptHarness, attempt.ID) { + body := assessmentAnswerHTTPBodyWithCorrectness(t, version, item, correct) + response := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(body), + sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("manual-fixture-answer-%s-%d", userID, item.Ordinal), remotePrefix+"4:1234") + var next assessmentAnswerHTTPAttempt + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil { + t.Fatalf("answer fixture item %d = %d %s", item.Ordinal, response.Code, response.Body.String()) + } + version = next.Version + } + finalizeBody := fmt.Sprintf(`{"expected_version":%d}`, version) + finalized := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", finalizeBody, + sessionHTTPTestOrigin, cookie.Value, csrf, "manual-fixture-finalize-"+userID.String(), remotePrefix+"5:1234") + var completed assessmentAnswerHTTPAttempt + if finalized.Code != http.StatusOK || json.Unmarshal(finalized.Body.Bytes(), &completed) != nil || completed.State != "completed" { + t.Fatalf("finalize fixture attempt = %d %s, want completed", finalized.Code, finalized.Body.String()) + } + wantOutcome := "not_confirmed" + if correct { + wantOutcome = "confirmed" + } + var outcome string + if err := harness.pool.QueryRow(ctx, `SELECT outcome FROM assessment_attempt_results WHERE attempt_id = $1`, attempt.ID).Scan(&outcome); err != nil || outcome != wantOutcome { + t.Fatalf("stored fixture outcome = %q, %v; want %q", outcome, err, wantOutcome) + } + return attempt.ID +} diff --git a/backend/integration_test/support_cases_test.go b/backend/integration_test/support_cases_test.go index a04a90b..b0cf784 100644 --- a/backend/integration_test/support_cases_test.go +++ b/backend/integration_test/support_cases_test.go @@ -27,9 +27,11 @@ import ( "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/domain" "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/consent" "lincodex/backend/internal/usecase/health" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/policy" + questionnaireusecase "lincodex/backend/internal/usecase/questionnaire" "lincodex/backend/internal/usecase/supportcase" ) @@ -38,6 +40,7 @@ const supportCaseHTTPTimeout = 5 * time.Minute type supportCaseHTTPHarness struct { *sessionHTTPHarness supportClock *testClock + keyring *identity.Keyring } func TestSupportCasesOverHTTP(t *testing.T) { @@ -628,14 +631,21 @@ func createSupportCaseHTTPEmployer( } type supportCaseHTTPResponse struct { - ID string `json:"id"` - Number string `json:"number"` - Type string `json:"type"` - Status string `json:"status"` - Description string `json:"description"` - RubricVersion *int32 `json:"rubric_version"` - History []struct { - Kind string `json:"kind"` + ID string `json:"id"` + Number string `json:"number"` + Type string `json:"type"` + Status string `json:"status"` + Description string `json:"description"` + RubricVersion *int32 `json:"rubric_version"` + Decision *json.RawMessage `json:"decision"` + AssessmentTarget *struct { + Specialization string `json:"specialization"` + Grade string `json:"grade"` + } `json:"assessment_target"` + History []struct { + Kind string `json:"kind"` + Actor string `json:"actor"` + Status string `json:"status"` } `json:"history"` ResponseTarget struct { Kind string `json:"kind"` @@ -690,8 +700,21 @@ func newSupportCaseHTTPHarness(ctx context.Context, t *testing.T, env *testEnvir v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL), ) supportHandler := v1.NewSupportHandler(service) + // Consent, questionnaire, and assessment routes share the support clock and + // policy so one test can drive a C3 revocation, a failed attempt, and a + // manual assessment request through the real router. + consentHandler := v1.NewConsentHandler( + consent.NewQueryService(postgresadapter.NewConsentStore(pool), time.Now), consent.NewService(transactor, time.Now), + ) + questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, supportClock.Now)) + attemptService, err := assessment.NewAttemptService(transactor, transactor, keyring, supportClock.Now) + if err != nil { + t.Fatalf("NewAttemptService() error = %v", err) + } handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler), v1.WithSupport(supportHandler), + v1.WithConsent(consentHandler), v1.WithQuestionnaire(questionnaireHandler), + v1.WithAssessment(v1.NewAssessmentHandler(attemptService)), ) router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil) @@ -701,6 +724,7 @@ func newSupportCaseHTTPHarness(ctx context.Context, t *testing.T, env *testEnvir return &supportCaseHTTPHarness{ sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}, supportClock: supportClock, + keyring: keyring, } } diff --git a/backend/internal/usecase/supportcase/manual_assessment.go b/backend/internal/usecase/supportcase/manual_assessment.go new file mode 100644 index 0000000..13fcee6 --- /dev/null +++ b/backend/internal/usecase/supportcase/manual_assessment.go @@ -0,0 +1,69 @@ +package supportcase + +import ( + "context" + "fmt" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// A manual assessment request is an ordinary support case. This file holds the +// rules that are specific to it: +// +// - It never reads, grants, or revokes any consent. A candidate who refused +// C3, or who never answered the C3 question, reaches the same code path +// as every other candidate, so the manual path cannot become a hidden +// way to enable automated categorization. +// - It never creates an attempt and never writes a grade or category. The +// case only enters the expert queue (waiting_expert) in the creation +// transaction. +// - A prior attempt is optional. When the author references one it has to +// belong to the same specialization; its outcome (including a failed +// first test) does not matter and is never changed. +// - The grading rubric is pinned when exactly one current reviewed category +// answers the requested specialization and grade. Otherwise no rubric is +// pinned and the case reports that honestly with a null rubric version. + +// resolveManualAssessmentRubric pins the current reviewed rubric for the +// requested target. It leaves the pin empty, without an error, when the bank +// has no single current category for the target: the request is still +// accepted and waits for an expert. +func resolveManualAssessmentRubric( + ctx context.Context, + repositories outbound.SupportCaseRepositories, + fields *domain.NewSupportCaseInput, +) error { + if fields.Type != domain.SupportCaseTypeManualAssessment || fields.AssessmentTarget == nil { + return nil + } + rubric, err := repositories.SupportCaseRubrics().ResolveCurrent( + ctx, fields.AssessmentTarget.Specialization, fields.AssessmentTarget.Grade, + ) + if err != nil { + return fmt.Errorf("%s - resolve current manual assessment rubric: %w", createLocation, err) + } + if rubric == nil { + return nil + } + if rubric.Version < 1 || rubric.OpeningID == uuid.Nil || rubric.PolicyVersionID.IsZero() { + return fmt.Errorf("%s - rubric resolver returned an incomplete pin: %w", createLocation, domain.ErrInvalidSupportCase) + } + fields.RubricVersion = &rubric.Version + fields.RubricOpeningID = &rubric.OpeningID + fields.RubricPolicyID = &rubric.PolicyVersionID + return nil +} + +// validateManualAssessmentAttempt accepts an owned attempt of the requested +// specialization in any state. A failed or unfinished attempt is exactly the +// case a manual assessment exists for, so only the specialization is compared. +func validateManualAssessmentAttempt(target *domain.SupportCaseAssessmentTarget, attempt domain.AssessmentAttempt) error { + snapshot := attempt.Snapshot() + if target == nil || snapshot.Specialization == nil || *snapshot.Specialization != target.Specialization { + return ErrStateConflict + } + return nil +} diff --git a/backend/internal/usecase/supportcase/service.go b/backend/internal/usecase/supportcase/service.go index 870ffd5..5194e73 100644 --- a/backend/internal/usecase/supportcase/service.go +++ b/backend/internal/usecase/supportcase/service.go @@ -294,32 +294,6 @@ func createSupportCaseInTransaction( return storeCreatedCase(ctx, unit, repositories, request, supportCase) } -func resolveManualAssessmentRubric( - ctx context.Context, - repositories outbound.SupportCaseRepositories, - fields *domain.NewSupportCaseInput, -) error { - if fields.Type != domain.SupportCaseTypeManualAssessment || fields.AssessmentTarget == nil { - return nil - } - rubric, err := repositories.SupportCaseRubrics().ResolveCurrent( - ctx, fields.AssessmentTarget.Specialization, fields.AssessmentTarget.Grade, - ) - if err != nil { - return fmt.Errorf("%s - resolve current manual assessment rubric: %w", createLocation, err) - } - if rubric == nil { - return nil - } - if rubric.Version < 1 || rubric.OpeningID == uuid.Nil || rubric.PolicyVersionID.IsZero() { - return fmt.Errorf("%s - rubric resolver returned an incomplete pin: %w", createLocation, domain.ErrInvalidSupportCase) - } - fields.RubricVersion = &rubric.Version - fields.RubricOpeningID = &rubric.OpeningID - fields.RubricPolicyID = &rubric.PolicyVersionID - return nil -} - func storeReferenceFailure( ctx context.Context, unit outbound.UnitOfWork, @@ -505,11 +479,7 @@ func validateAttemptReference(input domain.NewSupportCaseInput, attempt domain.A case domain.SupportCaseTypeSupport, domain.SupportCaseTypeComplaint: return nil case domain.SupportCaseTypeManualAssessment: - target := input.AssessmentTarget - attemptSnapshot := attempt.Snapshot() - if target == nil || attemptSnapshot.Specialization == nil || *attemptSnapshot.Specialization != target.Specialization { - return ErrStateConflict - } + return validateManualAssessmentAttempt(input.AssessmentTarget, attempt) case domain.SupportCaseTypeGradeAppeal: if attempt.State() != domain.AssessmentAttemptStateCompleted { return ErrStateConflict diff --git a/frontend/README.en.md b/frontend/README.en.md index 2ddded6..8f73777 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -87,7 +87,7 @@ The tests take their fixtures from the named contract examples in `api/core/open `/candidate/support/cases` and `/employer/support/cases` show each account's paginated support history. Their `.../new` routes create a case and `.../:caseId` routes show its status and history. The public `/support` route directs a signed-in user to their cabinet. The form draft stays in memory, and a retry of an unchanged request reuses its idempotency key. Support history is scoped to the current account and cleared when the session changes or the server denies access. -Candidates can use `/candidate/support/cases/manual-assessment` to submit a support request with a specialization, desired grade, and description. This does not run automatic assessment, create an attempt, change C3, or grant a confirmed grade. The case page displays the status and rubric version returned by the server; the client does not create an outcome. +Candidates can use `/candidate/support/cases/manual-assessment` to submit a support request with a specialization, desired grade, and description. This does not run automatic assessment, create an attempt, change C3, or grant a confirmed grade. The hint under the specialization and grade selectors uses the published grades from the catalog but does not promise a rubric: the server pins the version on submission. The case page displays the status and rubric version returned by the server and, for `null`, says plainly that no published rubric existed when the request was made; the client does not create an outcome. After a page reload the form loses its idempotency key, and a repeated submission while a manual assessment of the same specialization is open receives 409; the page explains this and links to "My cases" without creating a second request. ## API client generation diff --git a/frontend/README.md b/frontend/README.md index d326b9c..241c839 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -87,7 +87,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS `/candidate/support/cases` и `/employer/support/cases` показывают постраничную историю обращений аккаунта; маршруты `.../new` создают обращение, а `.../:caseId` открывает его состояние и историю. Публичный `/support` направляет вошедшего пользователя в его кабинет. Черновик формы остается в памяти, а повтор неизмененного запроса использует тот же ключ идемпотентности. История кешируется с областью текущего аккаунта и очищается при смене сессии или отказе сервера в доступе. -Кандидату доступен `/candidate/support/cases/manual-assessment`: форма отправляет специальность, желаемый грейд и описание как запрос поддержки. Это не запускает автоматическую оценку, не создает попытку, не меняет C3 и не присваивает подтвержденный грейд. Страница обращения показывает статус и сведения о версии рубрики, возвращенные сервером; результат не создается на клиенте. +Кандидату доступен `/candidate/support/cases/manual-assessment`: форма отправляет специальность, желаемый грейд и описание как запрос поддержки. Это не запускает автоматическую оценку, не создает попытку, не меняет C3 и не присваивает подтвержденный грейд. Подсказка под выбором специальности и грейда учитывает опубликованные грейды каталога, но не обещает рубрику: версию фиксирует сервер при отправке. Страница обращения показывает статус и версию рубрики, возвращенные сервером, а при `null` прямо сообщает, что опубликованной рубрики на момент запроса не было; результат не создается на клиенте. После перезагрузки страницы форма теряет ключ идемпотентности, и повторная отправка при открытой ручной оценке той же специальности получает 409; страница объясняет это и ведет в "Мои обращения", не создавая второй запрос. ## Генерация API-клиента diff --git a/frontend/src/entities/support-case/index.ts b/frontend/src/entities/support-case/index.ts index 73e1c22..cab24dd 100644 --- a/frontend/src/entities/support-case/index.ts +++ b/frontend/src/entities/support-case/index.ts @@ -10,6 +10,7 @@ export { } from "./model/submission"; export { formatSupportDate, + manualAssessmentRubricDescription, supportCaseActorLabels, supportCaseEventKindLabels, supportCaseStatusLabels, diff --git a/frontend/src/entities/support-case/model/presentation.test.ts b/frontend/src/entities/support-case/model/presentation.test.ts index 7599441..5663485 100644 --- a/frontend/src/entities/support-case/model/presentation.test.ts +++ b/frontend/src/entities/support-case/model/presentation.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from "vitest"; -import { supportCaseStatusLabels, supportTargetDescription } from "./presentation"; +import { + manualAssessmentRubricDescription, + supportCaseStatusLabels, + supportTargetDescription, +} from "./presentation"; describe("support case presentation", () => { it("describes operational goals without presenting them as legal deadlines", () => { @@ -18,4 +22,44 @@ describe("support case presentation", () => { it("labels manual assessment as waiting for an expert", () => { expect(supportCaseStatusLabels.waiting_expert).toBe("Ожидает эксперта"); }); + + it("states honestly when a manual request has no pinned rubric", () => { + const copy = manualAssessmentRubricDescription(null, "waiting_expert"); + + expect(copy).toContain("рубрики для этой цели на момент запроса не было"); + expect(copy).toContain("категория не присвоена"); + expect(copy).toContain("ожидает эксперта"); + }); + + it("shows the pinned policy version", () => { + expect(manualAssessmentRubricDescription(3, "waiting_expert")).toContain( + "версия политики оценивания 3", + ); + }); + + it.each(["submitted", "in_review", "waiting_for_user"] as const)( + "keeps the unassigned-category note for the open status %s without the queue note", + (status) => { + const copy = manualAssessmentRubricDescription(3, status); + + expect(copy).toContain("категория не присвоена"); + expect(copy).not.toContain("ожидает эксперта"); + }, + ); + + it("refers a resolved case to its decision instead of claiming no category", () => { + const copy = manualAssessmentRubricDescription(null, "resolved"); + + expect(copy).toContain("Автоматическая оценка не выполнялась"); + expect(copy).toContain("решении"); + expect(copy).not.toContain("категория не присвоена"); + expect(copy).not.toContain("ожидает эксперта"); + }); + + it("does not claim an unassigned category for a closed case", () => { + const copy = manualAssessmentRubricDescription(3, "closed"); + + expect(copy).toContain("Автоматическая оценка не выполнялась"); + expect(copy).not.toContain("категория не присвоена"); + }); }); diff --git a/frontend/src/entities/support-case/model/presentation.ts b/frontend/src/entities/support-case/model/presentation.ts index 5f7a74e..ce338f8 100644 --- a/frontend/src/entities/support-case/model/presentation.ts +++ b/frontend/src/entities/support-case/model/presentation.ts @@ -36,6 +36,33 @@ export const supportCaseActorLabels: Readonly + + , + ); +} + +describe("manual assessment failure notice", () => { + it("explains a state_conflict as an open request and links to the case list", () => { + const html = render( + new ApiRequestError({ status: 409, code: "state_conflict", title: "Conflict" }), + ); + + expect(html).toContain('role="alert"'); + expect(html).toContain("уже есть открытый запрос ручной оценки"); + expect(html).toContain(`href="${paths.candidate.supportCases}"`); + expect(html).toContain("Мои обращения"); + expect(html).not.toContain("Обновите страницу"); + }); + + it("does not add the case-list link to other failures", () => { + const html = render( + new ApiRequestError({ status: 429, code: "rate_limited", title: "Slow down" }), + ); + + expect(html).toContain("Слишком много запросов"); + expect(html).not.toContain("Мои обращения"); + }); +}); diff --git a/frontend/src/features/request-manual-assessment/ui/manual-request-failure.tsx b/frontend/src/features/request-manual-assessment/ui/manual-request-failure.tsx new file mode 100644 index 0000000..7225243 --- /dev/null +++ b/frontend/src/features/request-manual-assessment/ui/manual-request-failure.tsx @@ -0,0 +1,31 @@ +import type { Ref } from "react"; +import { ApiRequestError } from "../../../shared/api"; +import { paths } from "../../../shared/config"; +import { TextLink } from "../../../shared/ui"; +import { manualRequestFailureMessage } from "../model/failure-message"; +import styles from "./request-manual-assessment.module.css"; + +type ManualRequestFailureProps = { + id: string; + error: unknown; + innerRef?: Ref; +}; + +/** + * Failed submission notice. For a conflict with an open request it links to + * the case list, where the existing request and its status can be opened. + */ +export function ManualRequestFailure({ id, error, innerRef }: ManualRequestFailureProps) { + const isOpenRequestConflict = error instanceof ApiRequestError && error.code === "state_conflict"; + return ( + + ); +} diff --git a/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.test.ts b/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.test.ts index c02c740..76cdac8 100644 --- a/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.test.ts +++ b/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from "vitest"; import type { CatalogSpecializationOption } from "../../../entities/specialization"; +import { ApiRequestError } from "../../../shared/api"; import { manualAvailabilityMessage } from "../model/availability-message"; +import { manualRequestFailureMessage } from "../model/failure-message"; const unavailableOption: CatalogSpecializationOption = { code: "ds_ml", @@ -36,4 +38,60 @@ describe("manual assessment availability copy", () => { expect(copy).toContain("не запускает тест"); }); + + it("does not promise a rubric for a grade without a published bank", () => { + const copy = manualAvailabilityMessage( + { + ...unavailableOption, + test_availability: { + status: "available", + grades: ["junior"], + task_languages: ["go"], + note: null, + }, + }, + "senior", + ); + + expect(copy).toContain("рубрика может не быть зафиксирована"); + expect(copy).toContain("остается доступен"); + }); + + it("describes a published bank for the chosen grade without starting a test", () => { + const copy = manualAvailabilityMessage( + { + ...unavailableOption, + test_availability: { + status: "available", + grades: ["junior"], + task_languages: ["go"], + note: null, + }, + }, + "junior", + ); + + expect(copy).toContain("не запускает тест"); + expect(copy).toContain("только если"); + expect(copy).not.toContain("зафиксирует версию рубрики при отправке"); + }); +}); + +describe("manual assessment failure copy", () => { + it("sends a duplicate request to the existing case instead of a stale-data hint", () => { + const error = new ApiRequestError({ + status: 409, + code: "state_conflict", + title: "Conflict", + }); + + expect(manualRequestFailureMessage(error)).toContain("уже есть открытый запрос"); + expect(manualRequestFailureMessage(error)).toContain("Мои обращения"); + }); + + it("keeps the generic copy for other failures", () => { + const error = new ApiRequestError({ status: 429, code: "rate_limited", title: "Slow down" }); + + expect(manualRequestFailureMessage(error)).toContain("Слишком много запросов"); + }); }); diff --git a/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.tsx b/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.tsx index 3447c12..dbd44ee 100644 --- a/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.tsx +++ b/frontend/src/features/request-manual-assessment/ui/request-manual-assessment.tsx @@ -6,7 +6,6 @@ import { getSupportCaseIdempotencyKey, isSupportSessionAccessError, queryClientHasSupportActor, - supportCaseCreateFailureMessage, supportCaseDetailQueryKey, supportCaseListQueryKey, supportCasePathFor, @@ -39,6 +38,7 @@ import { Section, TextLink, } from "../../../shared/ui"; +import { ManualRequestFailure } from "./manual-request-failure"; import styles from "./request-manual-assessment.module.css"; export function RequestManualAssessment() { @@ -55,7 +55,7 @@ export function RequestManualAssessment() { const [specializationCode, setSpecializationCode] = useState(""); const [gradeCode, setGradeCode] = useState(""); const [description, setDescription] = useState(""); - const [actionError, setActionError] = useState(null); + const [failure, setFailure] = useState<{ error: unknown } | null>(null); const options = useMemo( () => (catalog.data ? listSpecializationOptions(catalog.data) : []), [catalog.data], @@ -81,8 +81,8 @@ export function RequestManualAssessment() { }); useEffect(() => { - if (actionError) errorRef.current?.focus(); - }, [actionError]); + if (failure) errorRef.current?.focus(); + }, [failure]); useEffect(() => { const accountId = actor?.account.id ?? knownActor?.account.id; @@ -165,7 +165,7 @@ export function RequestManualAssessment() { ) { return; } - setActionError(null); + setFailure(null); const data: SupportCaseCreate = { type: "manual_assessment", description, @@ -189,7 +189,7 @@ export function RequestManualAssessment() { if (error instanceof ApiRequestError && error.code === "idempotency_key_reused") { idempotencyBinding.current = null; } - setActionError(supportCaseCreateFailureMessage(error)); + setFailure({ error }); return; } @@ -204,7 +204,8 @@ export function RequestManualAssessment() {

Вы выбираете специальность и желаемый грейд. Эксперт рассмотрит запрос по рубрике этой - категории, если она опубликована. Запрос доступен до первой попытки и не требует C3. + категории, если она опубликована. Запрос доступен до первого теста, после неудачной + попытки и без согласия C3.

Отправка не включает и не меняет C3, не создает попытку и не меняет подтвержденный грейд.{" "} @@ -230,8 +231,8 @@ export function RequestManualAssessment() { ))} -

- {manualAvailabilityMessage(specialization)} +

+ {manualAvailabilityMessage(specialization, gradeCode)}

@@ -243,6 +244,7 @@ export function RequestManualAssessment() { setGradeCode(event.currentTarget.value as CatalogGrade["code"] | "") } disabled={isSubmitting} + aria-describedby={`${formId}-availability ${formId}-grade-hint`} required > @@ -252,7 +254,9 @@ export function RequestManualAssessment() { ))} -

Это желаемая цель оценки, а не подтвержденный результат.

+

+ Это желаемая цель оценки, а не подтвержденный результат. +

@@ -264,22 +268,18 @@ export function RequestManualAssessment() { maxLength={4000} required disabled={isSubmitting} - aria-describedby={`${formId}-description-hint${actionError ? ` ${formId}-error` : ""}`} + aria-describedby={`${formId}-description-hint${failure ? ` ${formId}-error` : ""}`} />

- Можно отправить запрос без предыдущей попытки. До 4000 символов. + Предыдущая попытка не нужна. До 4000 символов.

- {actionError ? ( - + error={failure.error} + innerRef={errorRef} + /> ) : null}