feat(assessment): assign the demonstration category and keep result history
This commit is contained in:
1 parent
b3c6dc870b
commit
8277133712
61 files changed
+4338
-268
No files matched your search
@@ -0,0 +1,151 @@
|
||||
// Package categoryattest implements the local operator command that attests the
|
||||
// current opening of an assessment category as a source of synthetic
|
||||
// demonstration categories. It is meant for isolated synthetic stands: a
|
||||
// category is assigned only when the runtime gate
|
||||
// ASSESSMENT_DEMO_CATEGORIES_ENABLED is also on.
|
||||
package categoryattest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// syntheticOnlyWarning is printed before any work, also when the command fails.
|
||||
const syntheticOnlyWarning = "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand\n"
|
||||
|
||||
const usage = "usage: assessment-category-attest attest --specialization <code> --grade <code> [--task-language <code>] --actor operator:<handle>"
|
||||
|
||||
// Command is a parsed, validated attestation request.
|
||||
type Command struct {
|
||||
Specialization domain.SpecializationCode
|
||||
Grade domain.GradeCode
|
||||
TaskLanguage *domain.TaskLanguageCode
|
||||
Actor string
|
||||
}
|
||||
|
||||
// Attestor stores an attestation.
|
||||
type Attestor interface {
|
||||
Attest(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (assessment.CategoryAttestation, error)
|
||||
}
|
||||
|
||||
// Parse validates every argument before Run reads configuration or connects
|
||||
// to PostgreSQL.
|
||||
func Parse(args []string) (Command, error) {
|
||||
if len(args) == 0 || args[0] != "attest" {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
flags := flag.NewFlagSet("assessment-category-attest attest", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
specialization := flags.String("specialization", "", "specialization code")
|
||||
grade := flags.String("grade", "", "grade code")
|
||||
language := flags.String("task-language", "", "task language code")
|
||||
actor := flags.String("actor", "", "operator handle")
|
||||
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
command := Command{
|
||||
Specialization: domain.SpecializationCode(strings.TrimSpace(*specialization)),
|
||||
Grade: domain.GradeCode(strings.TrimSpace(*grade)),
|
||||
Actor: strings.TrimSpace(*actor),
|
||||
}
|
||||
if !command.Specialization.IsKnown() {
|
||||
return Command{}, errors.New("specialization must be a known specialization code")
|
||||
}
|
||||
if !command.Grade.IsKnown() {
|
||||
return Command{}, errors.New("grade must be intern, junior, middle, or senior")
|
||||
}
|
||||
if trimmed := strings.TrimSpace(*language); trimmed != "" {
|
||||
taskLanguage := domain.TaskLanguageCode(trimmed)
|
||||
if !taskLanguage.IsKnown() {
|
||||
return Command{}, errors.New("task language must be a known task language code")
|
||||
}
|
||||
command.TaskLanguage = &taskLanguage
|
||||
}
|
||||
if _, err := domain.ParseAssessmentOperator(command.Actor); err != nil {
|
||||
return Command{}, errors.New("actor must be operator:<handle>")
|
||||
}
|
||||
return command, nil
|
||||
}
|
||||
|
||||
// Run parses the command, loads only DATABASE_URL from the supplied
|
||||
// environment, and executes the attestation. It does not load dotenv files.
|
||||
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
|
||||
command, err := Parse(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lookup == nil || output == nil {
|
||||
return errors.New("category attestation command dependencies are required")
|
||||
}
|
||||
databaseURL := config.DatabaseURLFromEnv(lookup)
|
||||
if databaseURL == "" {
|
||||
return errors.New("DATABASE_URL is not set")
|
||||
}
|
||||
pool, err := postgres.NewPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return errors.New("database configuration is invalid")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("database is unavailable")
|
||||
}
|
||||
attestor, err := assessment.NewCategoryAttestor(postgres.NewTransactor(pool))
|
||||
if err != nil {
|
||||
return errors.New("category attestation is unavailable")
|
||||
}
|
||||
return Execute(ctx, command, attestor, output)
|
||||
}
|
||||
|
||||
// Execute stores the attestation and prints identifiers and versions only; it
|
||||
// prints no candidate, answer, or contact data.
|
||||
func Execute(ctx context.Context, command Command, attestor Attestor, output io.Writer) error {
|
||||
if attestor == nil || output == nil {
|
||||
return errors.New("category attestation command dependencies are required")
|
||||
}
|
||||
if _, err := io.WriteString(output, syntheticOnlyWarning); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
attestation, err := attestor.Attest(ctx, command.Specialization, command.Grade, command.TaskLanguage, command.Actor)
|
||||
if err != nil {
|
||||
return safeOperationError(err)
|
||||
}
|
||||
status := "already attested"
|
||||
if attestation.Created {
|
||||
status = "attested"
|
||||
}
|
||||
if _, err := fmt.Fprintf(output,
|
||||
"%s: category %s, opening %s, review %s, policy_version %d, by %s\n"+
|
||||
"note: synthetic demonstration only; categories are assigned only while ASSESSMENT_DEMO_CATEGORIES_ENABLED is true on this stand\n",
|
||||
status, attestation.Category, attestation.OpeningID, attestation.ReviewID, attestation.ProductPolicyVersion, attestation.ReviewedBy,
|
||||
); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeOperationError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, outbound.ErrAssessmentSelectionUnavailable), errors.Is(err, outbound.ErrAssessmentSelectionAmbiguous):
|
||||
return errors.New("no single current reviewed category matches the request")
|
||||
case errors.Is(err, domain.ErrInvalidAssessmentCategory):
|
||||
return errors.New("the request is invalid or the current policy is not the explicit demo_basic demonstration policy")
|
||||
default:
|
||||
return errors.New("category attestation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package categoryattest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type attestorFake struct {
|
||||
attestation assessment.CategoryAttestation
|
||||
err error
|
||||
calls int
|
||||
command Command
|
||||
}
|
||||
|
||||
func (attestor *attestorFake) Attest(
|
||||
_ context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (assessment.CategoryAttestation, error) {
|
||||
attestor.calls++
|
||||
attestor.command = Command{Specialization: specialization, Grade: grade, TaskLanguage: language, Actor: actor}
|
||||
return attestor.attestation, attestor.err
|
||||
}
|
||||
|
||||
func TestParseRequiresATrackAndAnOperatorHandle(t *testing.T) {
|
||||
command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", "--actor", "operator:night"})
|
||||
if err != nil || command.Specialization != domain.SpecializationBackend || command.Grade != domain.GradeIntern ||
|
||||
command.TaskLanguage == nil || *command.TaskLanguage != domain.TaskLanguageGo || command.Actor != "operator:night" {
|
||||
t.Fatalf("Parse(valid) = %+v, %v", command, err)
|
||||
}
|
||||
if command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night"}); err != nil || command.TaskLanguage != nil {
|
||||
t.Fatalf("Parse(without language) = %+v, %v", command, err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil,
|
||||
{"list"},
|
||||
{"attest"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "alice"},
|
||||
{"attest", "--specialization", "chef", "--grade", "junior", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "lead", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--task-language", "cobol", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night", "extra"},
|
||||
} {
|
||||
if _, err := Parse(args); err == nil {
|
||||
t.Errorf("Parse(%v) accepted invalid arguments", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunValidatesArgumentsBeforeReadingTheEnvironment(t *testing.T) {
|
||||
lookup := func(string) (string, bool) {
|
||||
t.Fatal("environment read before arguments were validated")
|
||||
return "", false
|
||||
}
|
||||
if err := Run(context.Background(), []string{"attest"}, lookup, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("Run(invalid arguments) succeeded")
|
||||
}
|
||||
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
|
||||
err := Run(context.Background(), []string{"attest", "--specialization", "backend", "--grade", "intern", "--actor", "operator:night"}, noDatabase, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
|
||||
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutePrintsIdentifiersAndTheSyntheticOnlyNote(t *testing.T) {
|
||||
attestor := &attestorFake{attestation: assessment.CategoryAttestation{
|
||||
ReviewID: uuid.New(), OpeningID: uuid.New(), Category: "backend-intern", ProductPolicyVersion: 2,
|
||||
ReviewedBy: "operator:night", Created: true,
|
||||
}}
|
||||
var output bytes.Buffer
|
||||
command := Command{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Actor: "operator:night"}
|
||||
if err := Execute(context.Background(), command, attestor, &output); err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(output.String(), "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand") {
|
||||
t.Errorf("output does not start with the synthetic-only warning:\n%s", output.String())
|
||||
}
|
||||
for _, want := range []string{"attested: category backend-intern", attestor.attestation.ReviewID.String(), "policy_version 2", "by operator:night", "synthetic demonstration only", "ASSESSMENT_DEMO_CATEGORIES_ENABLED"} {
|
||||
if !strings.Contains(output.String(), want) {
|
||||
t.Errorf("output lacks %q:\n%s", want, output.String())
|
||||
}
|
||||
}
|
||||
attestor.attestation.Created = false
|
||||
output.Reset()
|
||||
if err := Execute(context.Background(), command, attestor, &output); err != nil || !strings.Contains(output.String(), "\nalready attested") {
|
||||
t.Fatalf("Execute(repeat) = %v, %q, want an already attested line", err, output.String())
|
||||
}
|
||||
if attestor.calls != 2 || attestor.command.Actor != "operator:night" || attestor.command.Grade != domain.GradeIntern {
|
||||
t.Fatalf("attestor calls/command = %d/%+v, want the parsed request", attestor.calls, attestor.command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{outbound.ErrAssessmentSelectionUnavailable, "no single current reviewed category"},
|
||||
{domain.ErrInvalidAssessmentCategory, "demo_basic"},
|
||||
{errors.New("pq: password authentication failed for user lincodex at 10.0.0.5"), "attestation failed"},
|
||||
} {
|
||||
err := Execute(context.Background(), Command{}, &attestorFake{err: test.err}, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "10.0.0.5") {
|
||||
t.Errorf("Execute(%v) error = %v, want a safe %q message", test.err, err, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -302,6 +302,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
continue
|
||||
}
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, schema)) {
|
||||
if searchResultMayReachCardBand(name, reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) && reached != "AnonymousCardContent" && reached != "CardCategory" && reached != "CardField" && reached != "CardFieldSet" {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", name, reached)
|
||||
}
|
||||
@@ -320,6 +323,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}, reached) {
|
||||
continue
|
||||
}
|
||||
if path == "/api/v1/organizations/{org_id}/matches" && searchResultMayReachCardBand("Match", reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", path, reached)
|
||||
}
|
||||
@@ -332,6 +338,18 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// searchResultMayReachCardBand reports whether a match search schema reaches
|
||||
// one of the two coarse leaves that the anonymous card itself carries: the
|
||||
// salary compatibility (a compatible or not_compatible verdict, never an
|
||||
// amount) and the experience band (a coarse bucket, never a date). The search
|
||||
// contract reuses the card content, so its filters and results legitimately
|
||||
// name these leaves. Only match schemas get this allowance; no other
|
||||
// organization-visible schema may reach a privacy schema.
|
||||
func searchResultMayReachCardBand(schema, reached string) bool {
|
||||
return strings.HasPrefix(schema, "Match") &&
|
||||
(reached == "CandidateSalaryCompatibility" || reached == "CandidateExperienceBand")
|
||||
}
|
||||
|
||||
// The generated request DTOs carry only what the candidate may choose: no
|
||||
// consent identifier, time, interval, or policy version.
|
||||
func TestGeneratedPrivacyDTOsCarryNoServerOwnedFields(t *testing.T) {
|
||||
|
||||
@@ -36,6 +36,10 @@ var ownerCompanyOperations = map[apiadapter.OperationName]struct{}{
|
||||
apiadapter.GetOrganizationInvitationContactsOperation: {},
|
||||
apiadapter.WithdrawOrganizationInvitationOperation: {},
|
||||
apiadapter.RaiseOrganizationInvitationSalaryOperation: {},
|
||||
// The match search contract requires an active owner membership. The
|
||||
// operation has no handler yet; classifying it here keeps it closed to
|
||||
// every other role when the handler arrives.
|
||||
apiadapter.SearchOrganizationMatchesOperation: {},
|
||||
}
|
||||
|
||||
// NewCompanyContextMiddleware verifies every owner-scoped company operation
|
||||
|
||||
@@ -124,8 +124,8 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
if err := yaml.Unmarshal(data, &document); err != nil {
|
||||
t.Fatalf("decode OpenAPI bundle: %v", err)
|
||||
}
|
||||
if len(ownerCompanyOperations) != 14 {
|
||||
t.Fatalf("owner operation inventory has %d entries, want 14", len(ownerCompanyOperations))
|
||||
if len(ownerCompanyOperations) != 15 {
|
||||
t.Fatalf("owner operation inventory has %d entries, want 15", len(ownerCompanyOperations))
|
||||
}
|
||||
candidateExceptions := map[string]string{
|
||||
"HideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}",
|
||||
|
||||
@@ -507,25 +507,40 @@ func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult)
|
||||
NextSteps: []api.AssessmentNextStep{}, Summary: result.Summary, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
realResult, err := assessmentRealResultResponse(result)
|
||||
if err != nil {
|
||||
return api.AssessmentResult{}, err
|
||||
}
|
||||
if realResult.Type == api.AssessmentQualifiedResultAssessmentRealResult {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(realResult.AssessmentQualifiedResult), nil
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(realResult.AssessmentCorrectiveResult), nil
|
||||
}
|
||||
|
||||
// assessmentRealResultResponse maps a completed root or corrective result. It
|
||||
// serves both the single result read and the owner's history, so the two never
|
||||
// describe the same stored result differently.
|
||||
func assessmentRealResultResponse(result assessmentusecase.AssessmentAttemptResult) (api.AssessmentRealResult, error) {
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentRealResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentRealResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
if err != nil {
|
||||
return api.AssessmentRealResult{}, err
|
||||
}
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindRoot {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(api.AssessmentQualifiedResult{
|
||||
return api.NewAssessmentQualifiedResultAssessmentRealResult(api.AssessmentQualifiedResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentQualifiedResultKindRoot, Mode: api.AssessmentQualifiedResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
PreviousConfirmedGrade: fields.previousGrade, CategoryDecision: fields.categoryDecision,
|
||||
Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
@@ -533,16 +548,17 @@ func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult)
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
|
||||
return api.AssessmentResult{}, errors.New("corrective result chain is incomplete")
|
||||
return api.AssessmentRealResult{}, errors.New("corrective result chain is incomplete")
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(api.AssessmentCorrectiveResult{
|
||||
return api.NewAssessmentCorrectiveResultAssessmentRealResult(api.AssessmentCorrectiveResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentCorrectiveResultKindCorrective, Mode: api.AssessmentCorrectiveResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
PreviousConfirmedGrade: fields.previousGrade, CategoryDecision: fields.categoryDecision,
|
||||
Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
@@ -558,10 +574,13 @@ type assessmentRealResultResponseFields struct {
|
||||
reason api.NilAssessmentNotDeterminedReason
|
||||
confirmedGrade api.NilGradeCode
|
||||
previousGrade api.NilGradeCode
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
// categoryDecision is absent for a legacy result stored before category
|
||||
// decisions existed; its grade is never inferred from the current state.
|
||||
categoryDecision api.OptAssessmentCategoryDecisionView
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
}
|
||||
|
||||
func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult) (assessmentRealResultResponseFields, error) {
|
||||
@@ -588,8 +607,7 @@ func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult
|
||||
} else {
|
||||
fields.reason.SetTo(api.AssessmentNotDeterminedReason(result.NotDeterminedReason))
|
||||
}
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
setAssessmentCategoryFields(&fields, result.CategoryDecision)
|
||||
fields.strength.SetToNull()
|
||||
fields.uncertainty.SetToNull()
|
||||
if result.BasicScore == nil {
|
||||
@@ -605,6 +623,45 @@ func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// setAssessmentCategoryFields copies the stored category decision. A result
|
||||
// confirms its target grade only when a reviewed synthetic source accepted the
|
||||
// outcome (assigned, or unchanged because the grade was not higher); a passing
|
||||
// score without such a source claims no category.
|
||||
func setAssessmentCategoryFields(fields *assessmentRealResultResponseFields, decision *domain.AssessmentCategoryDecisionSnapshot) {
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
view := api.AssessmentCategoryDecisionView{Status: api.AssessmentCategoryDecisionViewStatus(decision.Status)}
|
||||
view.PreviousConfirmedGrade.SetToNull()
|
||||
view.CurrentConfirmedGrade.SetToNull()
|
||||
view.Method.SetToNull()
|
||||
view.Source.SetToNull()
|
||||
view.CalibrationStatus.SetToNull()
|
||||
if decision.PreviousGrade != nil {
|
||||
fields.previousGrade.SetTo(api.GradeCode(*decision.PreviousGrade))
|
||||
view.PreviousConfirmedGrade.SetTo(api.GradeCode(*decision.PreviousGrade))
|
||||
}
|
||||
if decision.CurrentGrade != nil {
|
||||
view.CurrentConfirmedGrade.SetTo(api.GradeCode(*decision.CurrentGrade))
|
||||
}
|
||||
if decision.Method != "" {
|
||||
view.Method.SetTo(api.AssessmentCategoryDecisionViewMethod(decision.Method))
|
||||
}
|
||||
if decision.Source != "" {
|
||||
view.Source.SetTo(api.AssessmentCategoryDecisionViewSource(decision.Source))
|
||||
}
|
||||
if decision.CalibrationStatus != "" {
|
||||
view.CalibrationStatus.SetTo(api.CalibrationStatus(decision.CalibrationStatus))
|
||||
}
|
||||
if (decision.Status == domain.AssessmentCategoryDecisionAssigned || decision.Status == domain.AssessmentCategoryDecisionUnchanged) &&
|
||||
decision.AttemptedGrade != nil {
|
||||
fields.confirmedGrade.SetTo(api.GradeCode(*decision.AttemptedGrade))
|
||||
}
|
||||
fields.categoryDecision.SetTo(view)
|
||||
}
|
||||
|
||||
func assessmentResultVersions(snapshot domain.AssessmentAttemptPublicSnapshot) api.AssessmentVersions {
|
||||
return api.AssessmentVersions{
|
||||
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// AssessmentResultOperations reads the candidate's immutable result history.
|
||||
// An employer has no operation here; the current category reaches an employer
|
||||
// only through the anonymous card.
|
||||
type AssessmentResultOperations interface {
|
||||
ListMyResults(ctx context.Context, userID uuid.UUID, cursor string, limit int32) (assessmentusecase.AssessmentResultHistoryPage, error)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyAssessmentResults(
|
||||
ctx context.Context,
|
||||
params api.ListMyAssessmentResultsParams,
|
||||
) (api.ListMyAssessmentResultsRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.ListMyAssessmentResults(ctx, params)
|
||||
}
|
||||
return handler.assessment.ListMyAssessmentResults(ctx, params)
|
||||
}
|
||||
|
||||
// ListMyAssessmentResults serves the owner-only history. The operations of
|
||||
// AssessmentHandler provide it as an optional capability, like GetMyResult.
|
||||
func (handler *AssessmentHandler) ListMyAssessmentResults(
|
||||
ctx context.Context,
|
||||
params api.ListMyAssessmentResultsParams,
|
||||
) (api.ListMyAssessmentResultsRes, error) {
|
||||
const location = "AssessmentHandler.ListMyAssessmentResults"
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyAssessmentResultsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(AssessmentResultOperations)
|
||||
if !ok {
|
||||
return nil, errors.New(location + " - result history operation is unavailable")
|
||||
}
|
||||
// The generated validator has already bounded limit to the contract range.
|
||||
page, err := operations.ListMyResults(ctx, principal.UserID, params.Cursor.Or(""), params.Limit.Or(0))
|
||||
if err != nil {
|
||||
return assessmentResultsFailure(ctx, err)
|
||||
}
|
||||
items := make([]api.AssessmentRealResult, 0, len(page.Entries))
|
||||
for _, entry := range page.Entries {
|
||||
item, err := assessmentRealResultResponse(assessmentusecase.AssessmentAttemptResultFromHistoryEntry(entry))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - map stored result: %w", location, err)
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
next := api.NilString{}
|
||||
if page.NextCursor == "" {
|
||||
next.SetToNull()
|
||||
} else {
|
||||
next.SetTo(page.NextCursor)
|
||||
}
|
||||
return &api.AssessmentResultHistoryPageHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.AssessmentResultHistoryPage{Items: items, Page: api.PageInfo{HasMore: page.NextCursor != "", NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentResultsFailure(ctx context.Context, err error) (api.ListMyAssessmentResultsRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAssessmentResultHistoryRequest):
|
||||
return (*api.ListMyAssessmentResultsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/cursor").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.ListMyAssessmentResultsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func gradePtr(grade domain.GradeCode) *domain.GradeCode { return &grade }
|
||||
|
||||
func TestAssessmentCategoryFieldsClaimAGradeOnlyForAReviewedConfirmation(t *testing.T) {
|
||||
specialization := domain.SpecializationBackend
|
||||
reviewed := func(status domain.AssessmentCategoryDecisionStatus, attempted domain.GradeCode, previous, current *domain.GradeCode) *domain.AssessmentCategoryDecisionSnapshot {
|
||||
return &domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(uuid.New()), Specialization: &specialization, AttemptedGrade: gradePtr(attempted),
|
||||
PreviousGrade: previous, CurrentGrade: current, Status: status,
|
||||
Method: domain.AssessmentCategoryDecisionDemoBasicPassMark, Source: domain.AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, DecidedAt: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
}
|
||||
notEligible := &domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(uuid.New()), Specialization: &specialization, AttemptedGrade: gradePtr(domain.GradeJunior),
|
||||
PreviousGrade: gradePtr(domain.GradeIntern), CurrentGrade: gradePtr(domain.GradeIntern),
|
||||
Status: domain.AssessmentCategoryDecisionNotEligible,
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
decision *domain.AssessmentCategoryDecisionSnapshot
|
||||
wantConfirmed string
|
||||
wantPrevious string
|
||||
wantView bool
|
||||
}{
|
||||
{name: "legacy result without a decision", decision: nil},
|
||||
{name: "assigned", decision: reviewed(domain.AssessmentCategoryDecisionAssigned, domain.GradeJunior, gradePtr(domain.GradeIntern), gradePtr(domain.GradeJunior)),
|
||||
wantConfirmed: "junior", wantPrevious: "intern", wantView: true},
|
||||
{name: "unchanged", decision: reviewed(domain.AssessmentCategoryDecisionUnchanged, domain.GradeIntern, gradePtr(domain.GradeMiddle), gradePtr(domain.GradeMiddle)),
|
||||
wantConfirmed: "intern", wantPrevious: "middle", wantView: true},
|
||||
{name: "not confirmed keeps the previous grade", decision: reviewed(domain.AssessmentCategoryDecisionNotConfirmed, domain.GradeJunior, gradePtr(domain.GradeIntern), gradePtr(domain.GradeIntern)),
|
||||
wantPrevious: "intern", wantView: true},
|
||||
{name: "not eligible claims no grade", decision: notEligible, wantPrevious: "intern", wantView: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var fields assessmentRealResultResponseFields
|
||||
setAssessmentCategoryFields(&fields, test.decision)
|
||||
confirmed, confirmedSet := fields.confirmedGrade.Get()
|
||||
previous, previousSet := fields.previousGrade.Get()
|
||||
if (test.wantConfirmed == "") == confirmedSet || confirmedSet && string(confirmed) != test.wantConfirmed {
|
||||
t.Fatalf("confirmed_grade = %q (set %v), want %q", confirmed, confirmedSet, test.wantConfirmed)
|
||||
}
|
||||
if (test.wantPrevious == "") == previousSet || previousSet && string(previous) != test.wantPrevious {
|
||||
t.Fatalf("previous_confirmed_grade = %q (set %v), want %q", previous, previousSet, test.wantPrevious)
|
||||
}
|
||||
if fields.categoryDecision.IsSet() != test.wantView {
|
||||
t.Fatalf("category_decision present = %v, want %v", fields.categoryDecision.IsSet(), test.wantView)
|
||||
}
|
||||
if view, ok := fields.categoryDecision.Get(); ok && test.decision.Status == domain.AssessmentCategoryDecisionNotEligible {
|
||||
_, hasMethod := view.Method.Get()
|
||||
_, hasSource := view.Source.Get()
|
||||
if hasMethod || hasSource {
|
||||
t.Fatalf("not eligible view names a method or source: %+v", view)
|
||||
}
|
||||
}
|
||||
if view, ok := fields.categoryDecision.Get(); ok && string(view.Status) != string(test.decision.Status) {
|
||||
t.Fatalf("view status = %s, want %s", view.Status, test.decision.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user