feat(support): verify the manual assessment request after a C3 refusal

This commit is contained in:
shira committed 2026-10-08 21:26:00 +03:00
1 parent 6bfd7098c3
commit 68286af8b7
20 files changed
+680 -74

No files matched your search

+4
View File
@@ -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
+4
View File
@@ -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` проверяет конкурентные запросы и порядок времени. Обработка экспертом и ссылки на еще не реализованные приглашения или античит-проверки остаются недоступны.
## Анкета кандидата
@@ -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(), &current) != 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
}
+32 -8
View File
@@ -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,
}
}
@@ -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
}
@@ -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