fix(assessment): return confirmed categories with their basis and label demonstration categories

This commit is contained in:
shira committed 2026-10-09 21:24:24 +03:00
1 parent 623d41b969
commit d4903a3796
77 files changed
+1441 -288

No files matched your search

@@ -29,8 +29,12 @@ type AssessmentAvailability struct {
}
type SpecializationAvailability struct {
Specialization domain.SpecializationCode
Specialization domain.SpecializationCode
// ConfirmedGrade and ConfirmedBasis are set together from the current
// category of the specialization, or both are nil. The basis keeps a
// demonstration grade from reading as a real confirmation.
ConfirmedGrade *domain.GradeCode
ConfirmedBasis *domain.AssessmentCategorySource
ActiveAttemptID *domain.AssessmentAttemptID
Grades []GradeAvailability
}
@@ -108,6 +112,7 @@ type assessmentAvailabilityReads struct {
selections []outbound.AssessmentAvailabilitySelection
active map[domain.SpecializationCode]outbound.AssessmentActiveAttemptSummary
rootHistory map[domain.SpecializationCode][]outbound.AssessmentRootAvailabilitySummary
categories map[domain.SpecializationCode]domain.CandidateAssessmentCategory
quota outbound.AssessmentRootQuotaSnapshot
seen map[domain.AssessmentFamilyKey]struct{}
}
@@ -164,6 +169,14 @@ func readAssessmentAvailability(
if err != nil {
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read active attempts: %w", location, err)
}
categories, err := unit.AssessmentAttempts().ListCandidateCategories(ctx, userID)
if err != nil {
return assessmentAvailabilityReads{}, fmt.Errorf("%s - read confirmed categories: %w", location, err)
}
reads.categories = make(map[domain.SpecializationCode]domain.CandidateAssessmentCategory, len(categories))
for _, category := range categories {
reads.categories[category.Snapshot().Specialization] = category
}
window := policy.AttemptWindow.Duration()
reads.quota, err = unit.AssessmentAttempts().GetRootQuotaSnapshot(
ctx, userID, now.Add(-window), now, window, policy.MaxAttemptsPerWindow,
@@ -245,6 +258,12 @@ func buildSpecializationAvailability(
id := active.ID
result.ActiveAttemptID = &id
}
if category, confirmed := reads.categories[answer.Specialization]; confirmed {
snapshot := category.Snapshot()
grade, basis := snapshot.Grade, snapshot.Source
result.ConfirmedGrade = &grade
result.ConfirmedBasis = &basis
}
for _, grade := range availabilityGrades {
result.Grades = append(result.Grades, buildGradeAvailability(
answer, grade, reads, policy, now, seconds, itemCount, hasActive,
@@ -4,6 +4,8 @@ import (
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
@@ -98,3 +100,39 @@ func TestPlatformFailureDoesNotAddPromotionCooldown(t *testing.T) {
})
}
}
// The confirmed grade of a specialization and its basis come from the same
// stored category, so a demonstration grade is never returned without its basis.
func TestAvailabilityCarriesTheConfirmedGradeWithItsBasis(t *testing.T) {
now := time.Date(2026, time.October, 9, 12, 0, 0, 0, time.UTC)
policy := domain.AssessmentPolicy{Attempt: &domain.AssessmentAttemptPolicy{RealMode: domain.AssessmentRealModeDemoBasic}}
category, err := domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{
CandidateID: uuid.New(), Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior,
SourceAttemptID: domain.AssessmentAttemptID(uuid.New()), SourceReviewID: uuid.New(),
ProductPolicyVersionID: domain.PolicyVersionID(uuid.New()), ProductPolicyVersion: 1,
OpeningID: uuid.New(), OpeningManifestHash: [32]byte{1},
Source: domain.AssessmentCategorySourceSyntheticDemo, CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated,
AssignedAt: now,
})
if err != nil {
t.Fatalf("RestoreCandidateAssessmentCategory() error = %v", err)
}
reads := assessmentAvailabilityReads{categories: map[domain.SpecializationCode]domain.CandidateAssessmentCategory{
domain.SpecializationBackend: category,
}}
confirmed := buildSpecializationAvailability(
domain.QuestionnaireSpecialization{Specialization: domain.SpecializationBackend}, reads, policy, now, 60, 12)
if confirmed.ConfirmedGrade == nil || *confirmed.ConfirmedGrade != domain.GradeJunior {
t.Fatalf("ConfirmedGrade = %v, want junior", confirmed.ConfirmedGrade)
}
if confirmed.ConfirmedBasis == nil || *confirmed.ConfirmedBasis != domain.AssessmentCategorySourceSyntheticDemo {
t.Fatalf("ConfirmedBasis = %v, want synthetic_demo", confirmed.ConfirmedBasis)
}
unconfirmed := buildSpecializationAvailability(
domain.QuestionnaireSpecialization{Specialization: domain.SpecializationFrontend}, reads, policy, now, 60, 12)
if unconfirmed.ConfirmedGrade != nil || unconfirmed.ConfirmedBasis != nil {
t.Fatalf("unconfirmed specialization reports grade %v and basis %v, want none", unconfirmed.ConfirmedGrade, unconfirmed.ConfirmedBasis)
}
}
+2 -2
View File
@@ -639,10 +639,10 @@ func (seeder *Seeder) ensureProfile(ctx context.Context, spec accountSpec, userI
if err != nil {
return false, fmt.Errorf("read profile: %w", err)
}
if current.Version() > 0 {
if current.Profile.Version() > 0 {
return false, nil
}
if _, err := seeder.deps.Profiles.SaveMyProfile(ctx, userID, current.Version(), profileInput(spec)); err != nil {
if _, err := seeder.deps.Profiles.SaveMyProfile(ctx, userID, current.Profile.Version(), profileInput(spec)); err != nil {
return false, fmt.Errorf("save profile: %w", err)
}
return true, nil
+67 -16
View File
@@ -2,9 +2,11 @@
package profile
import (
"cmp"
"context"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
@@ -21,6 +23,16 @@ var (
ErrEmailNotVerified = errors.New("candidate profile requires a confirmed email")
)
// View is the profile as the candidate reads it: the saved document and the
// categories that assessment results confirmed. The categories are derived by
// the server, are read-only, and are never part of the saved document.
type View struct {
Profile domain.CandidateProfile
// ConfirmedCategories holds at most one category per specialization, in
// catalog order.
ConfirmedCategories []domain.CandidateAssessmentCategory
}
// Service is stateless between calls. Profile data, its history, and onboarding
// movement are written through one transaction.
type Service struct {
@@ -40,27 +52,28 @@ func NewService(transactor outbound.Transactor, clock func() time.Time) *Service
return &Service{transactor: transactor, clock: clock}
}
// GetMyProfile reads only the profile owned by userID. Version zero means the
// GetMyProfile reads only the profile owned by userID, with the categories
// that the candidate's assessment results confirmed. Version zero means the
// candidate has not saved a profile yet.
func (service *Service) GetMyProfile(ctx context.Context, userID uuid.UUID) (domain.CandidateProfile, error) {
func (service *Service) GetMyProfile(ctx context.Context, userID uuid.UUID) (View, error) {
const location = "Service.GetMyProfile"
if userID == uuid.Nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
return View{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
var result domain.CandidateProfile
var result View
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, userID, location); err != nil {
return err
}
var err error
result, err = unit.CandidateProfiles().Get(ctx, userID)
profile, err := unit.CandidateProfiles().Get(ctx, userID)
if err != nil {
return fmt.Errorf("%s - read profile: %w", location, err)
}
return nil
result, err = readView(ctx, unit, userID, profile, location)
return err
})
if err != nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err)
return View{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
@@ -73,16 +86,16 @@ func (service *Service) SaveMyProfile(
userID uuid.UUID,
expectedVersion int64,
input domain.CandidateProfileInput,
) (domain.CandidateProfile, error) {
) (View, error) {
const location = "Service.SaveMyProfile"
if userID == uuid.Nil {
return domain.CandidateProfile{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
return View{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
}
at := service.clock().UTC()
if at.IsZero() {
return domain.CandidateProfile{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateProfile)
return View{}, fmt.Errorf("%s - application clock returned zero: %w", location, domain.ErrInvalidCandidateProfile)
}
var result domain.CandidateProfile
var result View
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireCandidate(ctx, unit, userID, location); err != nil {
return err
@@ -105,18 +118,56 @@ func (service *Service) SaveMyProfile(
if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil {
return fmt.Errorf("%s - advance onboarding: %w", location, err)
}
result = updated
return nil
result, err = readView(ctx, unit, userID, updated, location)
return err
})
if err != nil {
if errors.Is(err, outbound.ErrCandidateProfileVersionConflict) || errors.Is(err, domain.ErrCandidateProfileVersionConflict) {
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateProfileVersionConflict)
return View{}, fmt.Errorf("%s - transaction: %w", location, domain.ErrCandidateProfileVersionConflict)
}
return domain.CandidateProfile{}, fmt.Errorf("%s - transaction: %w", location, err)
return View{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return result, nil
}
// readView attaches the confirmed categories of the candidate to a profile
// that was read or written in the same transaction.
func readView(
ctx context.Context,
unit outbound.UnitOfWork,
userID uuid.UUID,
profile domain.CandidateProfile,
location string,
) (View, error) {
categories, err := unit.AssessmentAttempts().ListCandidateCategories(ctx, userID)
if err != nil {
return View{}, fmt.Errorf("%s - read confirmed categories: %w", location, err)
}
return View{Profile: profile, ConfirmedCategories: inCatalogOrder(categories)}, nil
}
// inCatalogOrder sorts the categories by their place in the catalog. A
// category outside the catalog cannot exist (the storage constraint and the
// domain both reject it), so it sorts last instead of being dropped silently.
func inCatalogOrder(categories []domain.CandidateAssessmentCategory) []domain.CandidateAssessmentCategory {
position := make(map[domain.SpecializationCode]int, len(domain.SpecializationCatalog()))
for index, code := range domain.SpecializationCatalog() {
position[code] = index
}
sorted := slices.Clone(categories)
slices.SortStableFunc(sorted, func(left, right domain.CandidateAssessmentCategory) int {
return cmp.Compare(catalogPosition(position, left), catalogPosition(position, right))
})
return sorted
}
func catalogPosition(position map[domain.SpecializationCode]int, category domain.CandidateAssessmentCategory) int {
if index, known := position[category.Snapshot().Specialization]; known {
return index
}
return len(position)
}
func requireCandidate(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, location string) error {
user, err := unit.Users().GetByID(ctx, userID)
if err != nil {
@@ -3,6 +3,7 @@ package profile
import (
"context"
"errors"
"fmt"
"testing"
"time"
@@ -28,6 +29,8 @@ type profileTestUnit struct {
users outbound.UserRepository
profiles outbound.CandidateProfileRepository
// attempts is the zero value by default: a candidate without categories.
attempts profileTestAttempts
}
func (unit profileTestUnit) Users() outbound.UserRepository { return unit.users }
@@ -36,6 +39,48 @@ func (unit profileTestUnit) CandidateProfiles() outbound.CandidateProfileReposit
return unit.profiles
}
func (unit profileTestUnit) AssessmentAttempts() outbound.AssessmentAttemptRepository {
return unit.attempts
}
type profileTestAttempts struct {
outbound.AssessmentAttemptRepository
categories []domain.CandidateAssessmentCategory
err error
}
func (attempts profileTestAttempts) ListCandidateCategories(
_ context.Context,
_ uuid.UUID,
) ([]domain.CandidateAssessmentCategory, error) {
return attempts.categories, attempts.err
}
// profileTestCategory is a stored synthetic demonstration category of the
// candidate, as the assessment result that assigned it left it.
func profileTestCategory(
t *testing.T,
candidateID uuid.UUID,
specialization domain.SpecializationCode,
grade domain.GradeCode,
assignedAt time.Time,
) domain.CandidateAssessmentCategory {
t.Helper()
category, err := domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{
CandidateID: candidateID, Specialization: specialization, Grade: grade,
SourceAttemptID: domain.AssessmentAttemptID(uuid.Must(uuid.NewV7())), SourceReviewID: uuid.Must(uuid.NewV7()),
ProductPolicyVersionID: domain.PolicyVersionID(uuid.Must(uuid.NewV7())), ProductPolicyVersion: 1,
OpeningID: uuid.Must(uuid.NewV7()), OpeningManifestHash: [32]byte{1},
Source: domain.AssessmentCategorySourceSyntheticDemo, CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated,
AssignedAt: assignedAt,
})
if err != nil {
t.Fatalf("RestoreCandidateAssessmentCategory() error = %v", err)
}
return category
}
type profileTestUsers struct {
outbound.UserRepository
@@ -182,3 +227,93 @@ func TestSaveMyProfileDoesNotAdvanceAfterProfileWriteFailure(t *testing.T) {
t.Fatalf("onboarding advances %d times after a failed write, want 0", profiles.advanceCalls)
}
}
func TestGetMyProfileReturnsConfirmedCategoriesInCatalogOrder(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
user := domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
users := &profileTestUsers{user: user}
profiles := &profileTestRepository{}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
// The storage returns codes in alphabetical order; the catalog starts with backend.
categories := []domain.CandidateAssessmentCategory{
profileTestCategory(t, id, domain.SpecializationQA, domain.GradeIntern, now),
profileTestCategory(t, id, domain.SpecializationBackend, domain.GradeJunior, now),
profileTestCategory(t, id, domain.SpecializationFrontend, domain.GradeMiddle, now),
}
attempts := profileTestAttempts{categories: categories}
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles, attempts: attempts}}, func() time.Time { return now })
view, err := service.GetMyProfile(context.Background(), id)
if err != nil {
t.Fatalf("GetMyProfile() error = %v", err)
}
got := make([]domain.SpecializationCode, 0, len(view.ConfirmedCategories))
for _, category := range view.ConfirmedCategories {
got = append(got, category.Snapshot().Specialization)
}
want := []domain.SpecializationCode{domain.SpecializationBackend, domain.SpecializationFrontend, domain.SpecializationQA}
if fmt.Sprint(got) != fmt.Sprint(want) {
t.Fatalf("confirmed categories = %v, want catalog order %v", got, want)
}
if snapshot := view.ConfirmedCategories[0].Snapshot(); snapshot.Source != domain.AssessmentCategorySourceSyntheticDemo || snapshot.Grade != domain.GradeJunior {
t.Fatalf("first category = %+v, want the synthetic junior category", snapshot)
}
if view.Profile.UserID() != id {
t.Fatalf("profile owner = %s, want %s", view.Profile.UserID(), id)
}
}
func TestGetMyProfileWithoutCategoriesReturnsAnEmptyList(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
users := &profileTestUsers{user: domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}}
profiles := &profileTestRepository{}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles}}, func() time.Time { return now })
view, err := service.GetMyProfile(context.Background(), id)
if err != nil {
t.Fatalf("GetMyProfile() error = %v", err)
}
if len(view.ConfirmedCategories) != 0 {
t.Fatalf("confirmed categories = %d, want none", len(view.ConfirmedCategories))
}
}
func TestGetMyProfileFailsWhenCategoriesCannotBeRead(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
users := &profileTestUsers{user: domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}}
profiles := &profileTestRepository{}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
readErr := errors.New("categories unavailable")
attempts := profileTestAttempts{err: readErr}
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles, attempts: attempts}}, func() time.Time { return now })
if _, err := service.GetMyProfile(context.Background(), id); !errors.Is(err, readErr) {
t.Fatalf("GetMyProfile() error = %v, want the category read failure", err)
}
}
func TestSaveMyProfileReturnsTheConfirmedCategoriesAsWell(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
id := uuid.Must(uuid.NewV7())
users := &profileTestUsers{user: domain.User{ID: id, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}}
profiles := &profileTestRepository{}
profiles.profile, _ = domain.EmptyCandidateProfile(id)
attempts := profileTestAttempts{categories: []domain.CandidateAssessmentCategory{
profileTestCategory(t, id, domain.SpecializationDSML, domain.GradeMiddle, now),
}}
service := NewService(profileTestTransactor{unit: profileTestUnit{users: users, profiles: profiles, attempts: attempts}}, func() time.Time { return now })
input := domain.CandidateProfileInput{FullName: &domain.ProfileClaimInput[string]{Value: "Anna Sokolova", Status: domain.ProfileClaimConfirmed}}
view, err := service.SaveMyProfile(context.Background(), id, 0, input)
if err != nil {
t.Fatalf("SaveMyProfile() error = %v", err)
}
if view.Profile.Version() != 1 || len(view.ConfirmedCategories) != 1 ||
view.ConfirmedCategories[0].Snapshot().Specialization != domain.SpecializationDSML {
t.Fatalf("saved view = version %d with categories %v, want version 1 with the ds_ml category", view.Profile.Version(), view.ConfirmedCategories)
}
}