chore: checkpoint assessment and inbox integration
This commit is contained in:
1 parent
88a31ba0d5
commit
5c52fd8b91
31 files changed
+4608
-181
No files matched your search
@@ -0,0 +1,675 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrInvalidAssessmentCategory = errors.New("invalid assessment category")
|
||||
|
||||
type AssessmentCategoryDecisionStatus string
|
||||
|
||||
const (
|
||||
AssessmentCategoryDecisionNotEligible AssessmentCategoryDecisionStatus = "not_eligible"
|
||||
AssessmentCategoryDecisionNotConfirmed AssessmentCategoryDecisionStatus = "not_confirmed"
|
||||
AssessmentCategoryDecisionAssigned AssessmentCategoryDecisionStatus = "assigned"
|
||||
AssessmentCategoryDecisionUnchanged AssessmentCategoryDecisionStatus = "unchanged"
|
||||
AssessmentCategoryDecisionTrainingOnly AssessmentCategoryDecisionStatus = "training_only"
|
||||
)
|
||||
|
||||
const (
|
||||
AssessmentAttemptResultHistorySchemaV1 int32 = 1
|
||||
AssessmentAttemptResultHistorySchemaV2 int32 = 2
|
||||
)
|
||||
|
||||
type AssessmentCategoryDecisionMethod string
|
||||
|
||||
const AssessmentCategoryDecisionDemoBasicPassMark AssessmentCategoryDecisionMethod = "demo_basic_pass_mark"
|
||||
|
||||
type AssessmentCategoryCalibrationStatus string
|
||||
|
||||
const AssessmentCategoryCalibrationUncalibrated AssessmentCategoryCalibrationStatus = "uncalibrated"
|
||||
|
||||
type AssessmentCategorySource string
|
||||
|
||||
const AssessmentCategorySourceSyntheticDemo AssessmentCategorySource = "synthetic_demo"
|
||||
|
||||
// AssessmentSyntheticCategoryReviewSnapshot pins the reviewed synthetic bank
|
||||
// opening to the exact product policy under which demo categories may be assigned.
|
||||
type AssessmentSyntheticCategoryReviewSnapshot struct {
|
||||
ID uuid.UUID
|
||||
OpeningID uuid.UUID
|
||||
Category AssessmentCategory
|
||||
Source AssessmentCategorySource
|
||||
OpeningManifestHash [32]byte
|
||||
ProductPolicyVersionID PolicyVersionID
|
||||
ProductPolicyVersion int32
|
||||
ReviewedBy AssessmentOperator
|
||||
ReviewedAt time.Time
|
||||
}
|
||||
|
||||
// AssessmentSyntheticCategoryReview is an immutable review attestation used
|
||||
// only when the separate synthetic-category config gate is enabled.
|
||||
type AssessmentSyntheticCategoryReview struct {
|
||||
snapshot AssessmentSyntheticCategoryReviewSnapshot
|
||||
}
|
||||
|
||||
func NewAssessmentSyntheticCategoryReview(
|
||||
snapshot AssessmentSyntheticCategoryReviewSnapshot,
|
||||
) (AssessmentSyntheticCategoryReview, error) {
|
||||
const location = "domain.NewAssessmentSyntheticCategoryReview"
|
||||
review, err := RestoreAssessmentSyntheticCategoryReview(snapshot)
|
||||
if err != nil {
|
||||
return AssessmentSyntheticCategoryReview{}, fmt.Errorf("%s - validate review: %w", location, err)
|
||||
}
|
||||
return review, nil
|
||||
}
|
||||
|
||||
func RestoreAssessmentSyntheticCategoryReview(
|
||||
snapshot AssessmentSyntheticCategoryReviewSnapshot,
|
||||
) (AssessmentSyntheticCategoryReview, error) {
|
||||
const location = "domain.RestoreAssessmentSyntheticCategoryReview"
|
||||
operator, operatorErr := ParseAssessmentOperator(string(snapshot.ReviewedBy))
|
||||
category, categoryErr := ParseAssessmentCategory(string(snapshot.Category))
|
||||
if snapshot.ID == uuid.Nil || snapshot.OpeningID == uuid.Nil || snapshot.OpeningManifestHash == [32]byte{} ||
|
||||
snapshot.ProductPolicyVersionID.IsZero() || snapshot.ProductPolicyVersion <= 0 || snapshot.ReviewedAt.IsZero() ||
|
||||
snapshot.Source != AssessmentCategorySourceSyntheticDemo ||
|
||||
operatorErr != nil || operator != snapshot.ReviewedBy || categoryErr != nil || category != snapshot.Category {
|
||||
return AssessmentSyntheticCategoryReview{}, fmt.Errorf("%s - review identity or pins are invalid: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
snapshot.ReviewedAt = canonicalAssessmentTime(snapshot.ReviewedAt)
|
||||
return AssessmentSyntheticCategoryReview{snapshot: snapshot}, nil
|
||||
}
|
||||
|
||||
func (review AssessmentSyntheticCategoryReview) IsZero() bool { return review.snapshot.ID == uuid.Nil }
|
||||
|
||||
func (review AssessmentSyntheticCategoryReview) Snapshot() AssessmentSyntheticCategoryReviewSnapshot {
|
||||
return review.snapshot
|
||||
}
|
||||
|
||||
// CandidateAssessmentCategorySnapshot is the private current-state and audit
|
||||
// record. It contains candidate and source identifiers and must not be returned
|
||||
// directly to an employer-facing API.
|
||||
type CandidateAssessmentCategorySnapshot struct {
|
||||
CandidateID uuid.UUID
|
||||
Specialization SpecializationCode
|
||||
Grade GradeCode
|
||||
SourceAttemptID AssessmentAttemptID
|
||||
SourceReviewID uuid.UUID
|
||||
ProductPolicyVersionID PolicyVersionID
|
||||
ProductPolicyVersion int32
|
||||
OpeningID uuid.UUID
|
||||
OpeningManifestHash [32]byte
|
||||
Source AssessmentCategorySource
|
||||
CalibrationStatus AssessmentCategoryCalibrationStatus
|
||||
AssignedAt time.Time
|
||||
}
|
||||
|
||||
// CandidateAssessmentCategory is the current confirmed category for one
|
||||
// candidate specialization.
|
||||
type CandidateAssessmentCategory struct {
|
||||
snapshot CandidateAssessmentCategorySnapshot
|
||||
}
|
||||
|
||||
func RestoreCandidateAssessmentCategory(
|
||||
snapshot CandidateAssessmentCategorySnapshot,
|
||||
) (CandidateAssessmentCategory, error) {
|
||||
const location = "domain.RestoreCandidateAssessmentCategory"
|
||||
if snapshot.CandidateID == uuid.Nil || !snapshot.Specialization.IsKnown() || !snapshot.Grade.IsKnown() ||
|
||||
snapshot.SourceAttemptID.IsZero() || snapshot.SourceReviewID == uuid.Nil ||
|
||||
snapshot.ProductPolicyVersionID.IsZero() || snapshot.ProductPolicyVersion <= 0 ||
|
||||
snapshot.OpeningID == uuid.Nil || snapshot.OpeningManifestHash == [32]byte{} ||
|
||||
snapshot.Source != AssessmentCategorySourceSyntheticDemo ||
|
||||
snapshot.CalibrationStatus != AssessmentCategoryCalibrationUncalibrated || snapshot.AssignedAt.IsZero() {
|
||||
return CandidateAssessmentCategory{}, fmt.Errorf("%s - current category or source is invalid: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
snapshot.AssignedAt = canonicalAssessmentTime(snapshot.AssignedAt)
|
||||
return CandidateAssessmentCategory{snapshot: snapshot}, nil
|
||||
}
|
||||
|
||||
func (category CandidateAssessmentCategory) IsZero() bool {
|
||||
return category.snapshot.CandidateID == uuid.Nil
|
||||
}
|
||||
|
||||
func (category CandidateAssessmentCategory) Snapshot() CandidateAssessmentCategorySnapshot {
|
||||
return category.snapshot
|
||||
}
|
||||
|
||||
// AssessmentCategoryDecisionSnapshot is the allowlisted category extension
|
||||
// for one immutable result. It contains no private answer or item data.
|
||||
type AssessmentCategoryDecisionSnapshot struct {
|
||||
AttemptID AssessmentAttemptID
|
||||
BankCategory AssessmentCategory
|
||||
Specialization *SpecializationCode
|
||||
AttemptedGrade *GradeCode
|
||||
PreviousGrade *GradeCode
|
||||
CurrentGrade *GradeCode
|
||||
Status AssessmentCategoryDecisionStatus
|
||||
Method AssessmentCategoryDecisionMethod
|
||||
ProductPolicyVersionID PolicyVersionID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID PolicyVersionID
|
||||
OpeningID uuid.UUID
|
||||
OpeningManifestHash [32]byte
|
||||
ReviewID uuid.UUID
|
||||
Source AssessmentCategorySource
|
||||
CalibrationStatus AssessmentCategoryCalibrationStatus
|
||||
DecidedAt time.Time
|
||||
}
|
||||
|
||||
// AssessmentCategoryDecision is the immutable category outcome associated
|
||||
// with a completed result. Current category changes only for a higher passing
|
||||
// grade from a reviewed synthetic source.
|
||||
type AssessmentCategoryDecision struct {
|
||||
snapshot AssessmentCategoryDecisionSnapshot
|
||||
current *CandidateAssessmentCategory
|
||||
}
|
||||
|
||||
type AssessmentCategoryDecisionInput struct {
|
||||
Attempt AssessmentAttempt
|
||||
Result AssessmentAttemptResultSnapshot
|
||||
Policy PolicyVersion
|
||||
Review *AssessmentSyntheticCategoryReview
|
||||
Current *CandidateAssessmentCategory
|
||||
SyntheticDemoCategoryAssignmentEnabled bool
|
||||
}
|
||||
|
||||
func DecideAssessmentCategory(
|
||||
input AssessmentCategoryDecisionInput,
|
||||
) (AssessmentCategoryDecision, error) {
|
||||
const location = "domain.DecideAssessmentCategory"
|
||||
result, err := RestoreAssessmentAttemptResultSnapshot(input.Result)
|
||||
if err != nil || !assessmentResultMatchesAttempt(input.Attempt, result) {
|
||||
return AssessmentCategoryDecision{}, fmt.Errorf("%s - result and attempt do not match: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
attempt := input.Attempt.Snapshot()
|
||||
if input.Current != nil && input.Current.snapshot.CandidateID != attempt.UserID {
|
||||
return AssessmentCategoryDecision{}, fmt.Errorf("%s - current category belongs to another candidate: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
if attempt.Kind == AssessmentAttemptKindDemoExpress {
|
||||
return restoreDecision(newTrainingOnlyCategoryDecision(attempt, result), input.Current)
|
||||
}
|
||||
if attempt.Kind != AssessmentAttemptKindRoot && attempt.Kind != AssessmentAttemptKindCorrective {
|
||||
return AssessmentCategoryDecision{}, fmt.Errorf("%s - attempt kind cannot produce a category: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
if attempt.Specialization == nil || attempt.TargetGrade == nil || !input.PolicyMatchesResult(result) {
|
||||
return AssessmentCategoryDecision{}, fmt.Errorf("%s - track or pinned policy is invalid: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
if input.Current != nil && !currentCategoryMatchesAttempt(input.Current, attempt) {
|
||||
return AssessmentCategoryDecision{}, fmt.Errorf("%s - current category is outside the attempt scope: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
return decideReviewedSyntheticCategory(input, attempt, result)
|
||||
}
|
||||
|
||||
func decideReviewedSyntheticCategory(
|
||||
input AssessmentCategoryDecisionInput,
|
||||
attempt AssessmentAttemptSnapshot,
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
) (AssessmentCategoryDecision, error) {
|
||||
decision := newRealCategoryDecision(attempt, result, input.Current)
|
||||
if !input.SyntheticDemoCategoryAssignmentEnabled || !eligibleSyntheticCategoryPolicy(input.Policy, result) ||
|
||||
!reviewMatchesCategoryAttempt(input.Review, attempt, result) {
|
||||
return restoreDecision(decision, input.Current)
|
||||
}
|
||||
decision.Status = AssessmentCategoryDecisionNotConfirmed
|
||||
decision.Method = AssessmentCategoryDecisionDemoBasicPassMark
|
||||
decision.ReviewID = input.Review.snapshot.ID
|
||||
decision.Source = AssessmentCategorySourceSyntheticDemo
|
||||
decision.CalibrationStatus = AssessmentCategoryCalibrationUncalibrated
|
||||
if result.Outcome != AssessmentAttemptOutcomeConfirmed {
|
||||
return restoreDecision(decision, input.Current)
|
||||
}
|
||||
if input.Current != nil && gradeRank(*attempt.TargetGrade) <= gradeRank(input.Current.snapshot.Grade) {
|
||||
decision.Status = AssessmentCategoryDecisionUnchanged
|
||||
return restoreDecision(decision, input.Current)
|
||||
}
|
||||
return assignSyntheticCategory(decision, attempt, result, input)
|
||||
}
|
||||
|
||||
func assignSyntheticCategory(
|
||||
decision AssessmentCategoryDecisionSnapshot,
|
||||
attempt AssessmentAttemptSnapshot,
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
input AssessmentCategoryDecisionInput,
|
||||
) (AssessmentCategoryDecision, error) {
|
||||
decision.Status = AssessmentCategoryDecisionAssigned
|
||||
decision.CurrentGrade = clonePointer(attempt.TargetGrade)
|
||||
current, err := RestoreCandidateAssessmentCategory(CandidateAssessmentCategorySnapshot{
|
||||
CandidateID: attempt.UserID, Specialization: *attempt.Specialization, Grade: *attempt.TargetGrade,
|
||||
SourceAttemptID: attempt.ID, SourceReviewID: input.Review.snapshot.ID,
|
||||
ProductPolicyVersionID: result.Pins.ProductPolicyVersionID, ProductPolicyVersion: result.Pins.ProductPolicyVersion,
|
||||
OpeningID: result.Pins.OpeningID, OpeningManifestHash: result.Pins.OpeningManifestHash,
|
||||
Source: AssessmentCategorySourceSyntheticDemo, CalibrationStatus: AssessmentCategoryCalibrationUncalibrated,
|
||||
AssignedAt: result.DecidedAt,
|
||||
})
|
||||
if err != nil {
|
||||
return AssessmentCategoryDecision{}, fmt.Errorf("domain.assignSyntheticCategory - build current category: %w", err)
|
||||
}
|
||||
return restoreDecision(decision, ¤t)
|
||||
}
|
||||
|
||||
func (input AssessmentCategoryDecisionInput) PolicyMatchesResult(result AssessmentAttemptResultSnapshot) bool {
|
||||
return !input.Policy.IsZero() && input.Policy.Key() == ProductPolicyKey &&
|
||||
input.Policy.ID() == result.Pins.ProductPolicyVersionID &&
|
||||
input.Policy.Version() == result.Pins.ProductPolicyVersion
|
||||
}
|
||||
|
||||
func newTrainingOnlyCategoryDecision(
|
||||
attempt AssessmentAttemptSnapshot,
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
) AssessmentCategoryDecisionSnapshot {
|
||||
return AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: attempt.ID, Status: AssessmentCategoryDecisionTrainingOnly,
|
||||
ProductPolicyVersionID: result.Pins.ProductPolicyVersionID,
|
||||
ProductPolicyVersion: result.Pins.ProductPolicyVersion, DecidedAt: result.DecidedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func newRealCategoryDecision(
|
||||
attempt AssessmentAttemptSnapshot,
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
current *CandidateAssessmentCategory,
|
||||
) AssessmentCategoryDecisionSnapshot {
|
||||
decision := AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: attempt.ID, BankCategory: attempt.BankCategory,
|
||||
Specialization: clonePointer(attempt.Specialization), AttemptedGrade: clonePointer(attempt.TargetGrade),
|
||||
Status: AssessmentCategoryDecisionNotEligible,
|
||||
ProductPolicyVersionID: result.Pins.ProductPolicyVersionID,
|
||||
ProductPolicyVersion: result.Pins.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: result.Pins.GradingPolicyVersionID,
|
||||
OpeningID: result.Pins.OpeningID, OpeningManifestHash: result.Pins.OpeningManifestHash,
|
||||
DecidedAt: result.DecidedAt,
|
||||
}
|
||||
if current != nil {
|
||||
previous := current.snapshot.Grade
|
||||
decision.PreviousGrade = &previous
|
||||
decision.CurrentGrade = &previous
|
||||
}
|
||||
return decision
|
||||
}
|
||||
|
||||
func eligibleSyntheticCategoryPolicy(policy PolicyVersion, result AssessmentAttemptResultSnapshot) bool {
|
||||
product := policy.Policy()
|
||||
return policy.Kind() == PolicyKindDemo && policy.Key() == ProductPolicyKey &&
|
||||
sameAssessmentPolicy(product.Assessment, DemoProductPolicyV2().Assessment) &&
|
||||
result.Attempt.Mode == AssessmentAttemptModeDemoBasic && result.Rationale.Rule == assessmentResultRuleBasicPassMark &&
|
||||
int32(product.Assessment.Attempt.BasicPassMark) == result.Rationale.PassMarkBasisPoints &&
|
||||
(result.Outcome == AssessmentAttemptOutcomeConfirmed || result.Outcome == AssessmentAttemptOutcomeNotConfirmed)
|
||||
}
|
||||
|
||||
func sameAssessmentPolicy(left, right AssessmentPolicy) bool {
|
||||
return sameAssessmentPolicyRules(left, right) &&
|
||||
sameOptionalAssessmentAttemptPolicy(left.Attempt, right.Attempt) &&
|
||||
sameOptionalAssessmentTrainingPolicy(left.Training, right.Training)
|
||||
}
|
||||
|
||||
func sameAssessmentPolicyRules(left, right AssessmentPolicy) bool {
|
||||
return left.Calibration == right.Calibration && left.SameGradeRetryAfter == right.SameGradeRetryAfter &&
|
||||
left.MaxAttemptsPerWindow == right.MaxAttemptsPerWindow && left.AttemptWindow == right.AttemptWindow &&
|
||||
left.PromotionMinInterval == right.PromotionMinInterval && left.ConfirmationThreshold == right.ConfirmationThreshold &&
|
||||
left.HighStrengthThreshold == right.HighStrengthThreshold && left.PracticeRequired == right.PracticeRequired &&
|
||||
left.StopRule == right.StopRule
|
||||
}
|
||||
|
||||
func sameOptionalAssessmentAttemptPolicy(left, right *AssessmentAttemptPolicy) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
|
||||
func sameOptionalAssessmentTrainingPolicy(left, right *AssessmentTrainingPolicy) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
|
||||
func reviewMatchesCategoryAttempt(
|
||||
review *AssessmentSyntheticCategoryReview,
|
||||
attempt AssessmentAttemptSnapshot,
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
) bool {
|
||||
if review == nil || review.IsZero() {
|
||||
return false
|
||||
}
|
||||
snapshot := review.snapshot
|
||||
return !snapshot.ReviewedAt.After(result.DecidedAt) &&
|
||||
snapshot.OpeningID == result.Pins.OpeningID && snapshot.Category == attempt.BankCategory &&
|
||||
snapshot.OpeningManifestHash == result.Pins.OpeningManifestHash &&
|
||||
snapshot.ProductPolicyVersionID == result.Pins.ProductPolicyVersionID &&
|
||||
snapshot.ProductPolicyVersion == result.Pins.ProductPolicyVersion
|
||||
}
|
||||
|
||||
func assessmentResultMatchesAttempt(attempt AssessmentAttempt, result AssessmentAttemptResultSnapshot) bool {
|
||||
if !assessmentAttemptCompletedMatchesResult(attempt, result) || !assessmentAttemptPublicMatchesResult(attempt, result) {
|
||||
return false
|
||||
}
|
||||
return assessmentAttemptVersionsMatchResult(attempt.Snapshot().Versions, result.Pins)
|
||||
}
|
||||
|
||||
func assessmentAttemptCompletedMatchesResult(attempt AssessmentAttempt, result AssessmentAttemptResultSnapshot) bool {
|
||||
return !attempt.IsZero() && attempt.State() == AssessmentAttemptStateCompleted &&
|
||||
result.Attempt.ID == attempt.ID() && result.Attempt.Kind == attempt.Kind() &&
|
||||
result.Attempt.Mode == attempt.Mode() && result.Outcome == attempt.snapshot.Outcome &&
|
||||
result.DecidedAt.Equal(attempt.snapshot.EndedAt)
|
||||
}
|
||||
|
||||
func assessmentAttemptPublicMatchesResult(attempt AssessmentAttempt, result AssessmentAttemptResultSnapshot) bool {
|
||||
public := attempt.PublicSnapshot()
|
||||
return public.PolicyVersion == result.Attempt.PolicyVersion && public.BankVersion == result.Attempt.BankVersion &&
|
||||
public.AlgorithmVersion == result.Attempt.AlgorithmVersion &&
|
||||
sameSpecialization(public.Specialization, result.Attempt.Specialization) &&
|
||||
sameGrade(public.TargetGrade, result.Attempt.TargetGrade)
|
||||
}
|
||||
|
||||
func assessmentAttemptVersionsMatchResult(versions AssessmentAttemptVersions, pins AssessmentAttemptResultPins) bool {
|
||||
return versions.ProductPolicyVersionID == pins.ProductPolicyVersionID && versions.ProductPolicyVersion == pins.ProductPolicyVersion &&
|
||||
versions.GradingPolicyVersionID == pins.GradingPolicyVersionID && versions.OpeningID == pins.OpeningID &&
|
||||
versions.OpeningManifestHash == pins.OpeningManifestHash && versions.TrainingBindingID == pins.TrainingBindingID &&
|
||||
versions.TrainingManifestHash == pins.TrainingManifestHash && versions.BankVersion == pins.BankVersion &&
|
||||
versions.AlgorithmVersion == pins.AlgorithmVersion
|
||||
}
|
||||
|
||||
func currentCategoryMatchesAttempt(current *CandidateAssessmentCategory, attempt AssessmentAttemptSnapshot) bool {
|
||||
return current != nil && !current.IsZero() && attempt.Specialization != nil &&
|
||||
current.snapshot.CandidateID == attempt.UserID && current.snapshot.Specialization == *attempt.Specialization
|
||||
}
|
||||
|
||||
func restoreDecision(
|
||||
snapshot AssessmentCategoryDecisionSnapshot,
|
||||
current *CandidateAssessmentCategory,
|
||||
) (AssessmentCategoryDecision, error) {
|
||||
const location = "domain.restoreDecision"
|
||||
if err := validateAssessmentCategoryDecision(snapshot); err != nil {
|
||||
return AssessmentCategoryDecision{}, fmt.Errorf("%s - decision is invalid: %w", location, err)
|
||||
}
|
||||
cloned := snapshot
|
||||
cloned.Specialization = clonePointer(snapshot.Specialization)
|
||||
cloned.AttemptedGrade = clonePointer(snapshot.AttemptedGrade)
|
||||
cloned.PreviousGrade = clonePointer(snapshot.PreviousGrade)
|
||||
cloned.CurrentGrade = clonePointer(snapshot.CurrentGrade)
|
||||
return AssessmentCategoryDecision{snapshot: cloned, current: current}, nil
|
||||
}
|
||||
|
||||
// RestoreAssessmentCategoryDecision validates a stored immutable decision.
|
||||
func RestoreAssessmentCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) (AssessmentCategoryDecision, error) {
|
||||
return restoreDecision(snapshot, nil)
|
||||
}
|
||||
|
||||
func validateAssessmentCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error {
|
||||
if snapshot.AttemptID.IsZero() || snapshot.DecidedAt.IsZero() {
|
||||
return ErrInvalidAssessmentCategory
|
||||
}
|
||||
if snapshot.Status == AssessmentCategoryDecisionTrainingOnly {
|
||||
return validateTrainingOnlyCategoryDecision(snapshot)
|
||||
}
|
||||
category, categoryErr := ParseAssessmentCategory(string(snapshot.BankCategory))
|
||||
if categoryErr != nil || category != snapshot.BankCategory {
|
||||
return ErrInvalidAssessmentCategory
|
||||
}
|
||||
if !validRealCategoryDecisionTrack(snapshot) || !validRealCategoryDecisionPins(snapshot) || !validRealCategoryDecisionGrades(snapshot) {
|
||||
return ErrInvalidAssessmentCategory
|
||||
}
|
||||
return validateCategoryDecisionStatus(snapshot)
|
||||
}
|
||||
|
||||
func validateTrainingOnlyCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error {
|
||||
if snapshot.Specialization != nil || snapshot.AttemptedGrade != nil || snapshot.PreviousGrade != nil || snapshot.CurrentGrade != nil ||
|
||||
snapshot.Method != "" || snapshot.ReviewID != uuid.Nil || snapshot.Source != "" || snapshot.CalibrationStatus != "" {
|
||||
return ErrInvalidAssessmentCategory
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validRealCategoryDecisionPins(snapshot AssessmentCategoryDecisionSnapshot) bool {
|
||||
return !snapshot.ProductPolicyVersionID.IsZero() && snapshot.ProductPolicyVersion > 0 &&
|
||||
!snapshot.GradingPolicyVersionID.IsZero() && snapshot.OpeningID != uuid.Nil && snapshot.OpeningManifestHash != [32]byte{}
|
||||
}
|
||||
|
||||
func validRealCategoryDecisionGrades(snapshot AssessmentCategoryDecisionSnapshot) bool {
|
||||
return (snapshot.PreviousGrade == nil || snapshot.PreviousGrade.IsKnown()) &&
|
||||
(snapshot.CurrentGrade == nil || snapshot.CurrentGrade.IsKnown())
|
||||
}
|
||||
|
||||
func validateCategoryDecisionStatus(snapshot AssessmentCategoryDecisionSnapshot) error {
|
||||
switch snapshot.Status {
|
||||
case AssessmentCategoryDecisionNotEligible:
|
||||
return validateNotEligibleCategoryDecision(snapshot)
|
||||
case AssessmentCategoryDecisionNotConfirmed:
|
||||
return validateNotConfirmedCategoryDecision(snapshot)
|
||||
case AssessmentCategoryDecisionAssigned:
|
||||
return validateAssignedCategoryDecision(snapshot)
|
||||
case AssessmentCategoryDecisionUnchanged:
|
||||
return validateUnchangedCategoryDecision(snapshot)
|
||||
case AssessmentCategoryDecisionTrainingOnly:
|
||||
return ErrInvalidAssessmentCategory
|
||||
default:
|
||||
return ErrInvalidAssessmentCategory
|
||||
}
|
||||
}
|
||||
|
||||
func validateNotEligibleCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error {
|
||||
if snapshot.ReviewID != uuid.Nil || snapshot.Method != "" || snapshot.Source != "" ||
|
||||
snapshot.CalibrationStatus != "" || !sameGrade(snapshot.CurrentGrade, snapshot.PreviousGrade) {
|
||||
return ErrInvalidAssessmentCategory
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateNotConfirmedCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error {
|
||||
if !hasSyntheticReviewDecisionPins(snapshot) || !sameGrade(snapshot.CurrentGrade, snapshot.PreviousGrade) {
|
||||
return ErrInvalidAssessmentCategory
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAssignedCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error {
|
||||
if !hasSyntheticReviewDecisionPins(snapshot) || snapshot.CurrentGrade == nil ||
|
||||
*snapshot.CurrentGrade != *snapshot.AttemptedGrade || snapshot.PreviousGrade != nil &&
|
||||
gradeRank(*snapshot.CurrentGrade) <= gradeRank(*snapshot.PreviousGrade) {
|
||||
return ErrInvalidAssessmentCategory
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateUnchangedCategoryDecision(snapshot AssessmentCategoryDecisionSnapshot) error {
|
||||
if !hasSyntheticReviewDecisionPins(snapshot) || snapshot.PreviousGrade == nil || snapshot.CurrentGrade == nil ||
|
||||
*snapshot.CurrentGrade != *snapshot.PreviousGrade ||
|
||||
gradeRank(*snapshot.AttemptedGrade) > gradeRank(*snapshot.PreviousGrade) {
|
||||
return ErrInvalidAssessmentCategory
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hasSyntheticReviewDecisionPins(snapshot AssessmentCategoryDecisionSnapshot) bool {
|
||||
return snapshot.ReviewID != uuid.Nil && snapshot.Method == AssessmentCategoryDecisionDemoBasicPassMark &&
|
||||
snapshot.Source == AssessmentCategorySourceSyntheticDemo &&
|
||||
snapshot.CalibrationStatus == AssessmentCategoryCalibrationUncalibrated
|
||||
}
|
||||
|
||||
func validRealCategoryDecisionTrack(snapshot AssessmentCategoryDecisionSnapshot) bool {
|
||||
return snapshot.Specialization != nil && snapshot.Specialization.IsKnown() &&
|
||||
snapshot.AttemptedGrade != nil && snapshot.AttemptedGrade.IsKnown()
|
||||
}
|
||||
|
||||
func sameGrade(left, right *GradeCode) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == nil && right == nil
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
|
||||
func sameSpecialization(left, right *SpecializationCode) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == nil && right == nil
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
|
||||
func gradeRank(grade GradeCode) int {
|
||||
switch grade {
|
||||
case GradeIntern:
|
||||
return 0
|
||||
case GradeJunior:
|
||||
return 1
|
||||
case GradeMiddle:
|
||||
return 2
|
||||
case GradeSenior:
|
||||
return 3
|
||||
default:
|
||||
return -1
|
||||
}
|
||||
}
|
||||
|
||||
func (decision AssessmentCategoryDecision) Snapshot() AssessmentCategoryDecisionSnapshot {
|
||||
snapshot := decision.snapshot
|
||||
snapshot.Specialization = clonePointer(decision.snapshot.Specialization)
|
||||
snapshot.AttemptedGrade = clonePointer(decision.snapshot.AttemptedGrade)
|
||||
snapshot.PreviousGrade = clonePointer(decision.snapshot.PreviousGrade)
|
||||
snapshot.CurrentGrade = clonePointer(decision.snapshot.CurrentGrade)
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func (decision AssessmentCategoryDecision) ShouldUpdateCurrent() bool {
|
||||
return decision.snapshot.Status == AssessmentCategoryDecisionAssigned && decision.current != nil
|
||||
}
|
||||
|
||||
func (decision AssessmentCategoryDecision) CurrentCategory() (CandidateAssessmentCategory, bool) {
|
||||
if decision.current != nil {
|
||||
return *decision.current, true
|
||||
}
|
||||
return CandidateAssessmentCategory{}, false
|
||||
}
|
||||
|
||||
// AssessmentAttemptResultHistoryEntry is a read-side projection of the
|
||||
// immutable result store. V1 entries have no category decision and therefore
|
||||
// carry no inferred current grade. V2 entries capture the category decision
|
||||
// and current grade as they existed when that result was finalized.
|
||||
type AssessmentAttemptResultHistoryEntry struct {
|
||||
SchemaVersion int32
|
||||
Result AssessmentAttemptResultSnapshot
|
||||
CategoryDecision *AssessmentCategoryDecisionSnapshot
|
||||
CurrentConfirmedGrade *GradeCode
|
||||
}
|
||||
|
||||
func NewLegacyAssessmentAttemptResultHistoryEntry(
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
) (AssessmentAttemptResultHistoryEntry, error) {
|
||||
const location = "domain.NewLegacyAssessmentAttemptResultHistoryEntry"
|
||||
validated, err := RestoreAssessmentAttemptResultSnapshot(result)
|
||||
if err != nil {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - validate legacy result: %w", location, err)
|
||||
}
|
||||
return AssessmentAttemptResultHistoryEntry{
|
||||
SchemaVersion: AssessmentAttemptResultHistorySchemaV1,
|
||||
Result: validated,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func NewCategoryAssessmentAttemptResultHistoryEntry(
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
decision AssessmentCategoryDecisionSnapshot,
|
||||
) (AssessmentAttemptResultHistoryEntry, error) {
|
||||
const location = "domain.NewCategoryAssessmentAttemptResultHistoryEntry"
|
||||
validated, err := RestoreAssessmentAttemptResultSnapshot(result)
|
||||
if err != nil {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - validate result: %w", location, err)
|
||||
}
|
||||
if validated.Attempt.Kind == AssessmentAttemptKindDemoExpress {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - training result cannot carry category data: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
categoryDecision, err := RestoreAssessmentCategoryDecision(decision)
|
||||
if err != nil {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - validate category decision: %w", location, err)
|
||||
}
|
||||
if !categoryDecisionMatchesResult(categoryDecision.snapshot, validated) {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - decision does not match result: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
entry := AssessmentAttemptResultHistoryEntry{
|
||||
SchemaVersion: AssessmentAttemptResultHistorySchemaV2,
|
||||
Result: validated,
|
||||
CategoryDecision: pointer(categoryDecision.Snapshot()),
|
||||
CurrentConfirmedGrade: clonePointer(categoryDecision.snapshot.CurrentGrade),
|
||||
}
|
||||
return RestoreAssessmentAttemptResultHistoryEntry(entry)
|
||||
}
|
||||
|
||||
func RestoreAssessmentAttemptResultHistoryEntry(
|
||||
entry AssessmentAttemptResultHistoryEntry,
|
||||
) (AssessmentAttemptResultHistoryEntry, error) {
|
||||
const location = "domain.RestoreAssessmentAttemptResultHistoryEntry"
|
||||
result, err := RestoreAssessmentAttemptResultSnapshot(entry.Result)
|
||||
if err != nil {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - restore result: %w", location, err)
|
||||
}
|
||||
entry.Result = result
|
||||
switch entry.SchemaVersion {
|
||||
case AssessmentAttemptResultHistorySchemaV1:
|
||||
if entry.CategoryDecision != nil || entry.CurrentConfirmedGrade != nil {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - legacy result must not contain category data: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
return entry, nil
|
||||
case AssessmentAttemptResultHistorySchemaV2:
|
||||
if entry.CategoryDecision == nil || entry.CurrentConfirmedGrade != nil && !entry.CurrentConfirmedGrade.IsKnown() {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - category result is incomplete: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
decision, err := RestoreAssessmentCategoryDecision(*entry.CategoryDecision)
|
||||
if err != nil {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - restore category decision: %w", location, err)
|
||||
}
|
||||
snapshot := decision.Snapshot()
|
||||
if !categoryDecisionMatchesResult(snapshot, result) || !sameGrade(entry.CurrentConfirmedGrade, snapshot.CurrentGrade) {
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - category result pins or current grade do not match: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
entry.CategoryDecision = pointer(snapshot)
|
||||
entry.CurrentConfirmedGrade = clonePointer(entry.CurrentConfirmedGrade)
|
||||
return entry, nil
|
||||
default:
|
||||
return AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - unsupported result history version: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
}
|
||||
|
||||
func categoryDecisionMatchesResult(
|
||||
decision AssessmentCategoryDecisionSnapshot,
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
) bool {
|
||||
return validCategoryResultDecisionStatus(decision.Status) &&
|
||||
decision.AttemptID == result.Attempt.ID && decision.DecidedAt.Equal(result.DecidedAt) &&
|
||||
categoryDecisionPinsMatchResult(decision, result) && categoryDecisionTrackMatchesResult(decision, result)
|
||||
}
|
||||
|
||||
func validCategoryResultDecisionStatus(status AssessmentCategoryDecisionStatus) bool {
|
||||
switch status {
|
||||
case AssessmentCategoryDecisionNotEligible, AssessmentCategoryDecisionNotConfirmed,
|
||||
AssessmentCategoryDecisionAssigned, AssessmentCategoryDecisionUnchanged:
|
||||
return true
|
||||
case AssessmentCategoryDecisionTrainingOnly:
|
||||
return false
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func categoryDecisionPinsMatchResult(
|
||||
decision AssessmentCategoryDecisionSnapshot,
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
) bool {
|
||||
return decision.ProductPolicyVersionID == result.Pins.ProductPolicyVersionID &&
|
||||
decision.ProductPolicyVersion == result.Pins.ProductPolicyVersion &&
|
||||
decision.GradingPolicyVersionID == result.Pins.GradingPolicyVersionID &&
|
||||
decision.OpeningID == result.Pins.OpeningID && decision.OpeningManifestHash == result.Pins.OpeningManifestHash
|
||||
}
|
||||
|
||||
func categoryDecisionTrackMatchesResult(
|
||||
decision AssessmentCategoryDecisionSnapshot,
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
) bool {
|
||||
return decision.Specialization != nil && sameSpecialization(decision.Specialization, result.Attempt.Specialization) &&
|
||||
sameGrade(decision.AttemptedGrade, result.Attempt.TargetGrade) &&
|
||||
(result.Attempt.Kind == AssessmentAttemptKindRoot || result.Attempt.Kind == AssessmentAttemptKindCorrective) &&
|
||||
result.Attempt.Mode == AssessmentAttemptModeDemoBasic
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestDecideAssessmentCategoryUsesReviewedPinnedThreshold(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
previous := testCurrentAssessmentCategory(t, uuid.New(), GradeIntern, policy)
|
||||
userID := previous.snapshot.CandidateID
|
||||
|
||||
failedAttempt := newCategoryTestAttempt(t, policy, GradeJunior, userID)
|
||||
failedAttempt, failedResult := finishCategoryTestAttempt(t, failedAttempt, policy, 18)
|
||||
failedReview := categoryReviewForAttempt(t, failedAttempt, policy)
|
||||
failed, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: failedAttempt, Result: failedResult, Policy: policy, Review: &failedReview, Current: &previous,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DecideAssessmentCategory(k-1) error = %v", err)
|
||||
}
|
||||
if snapshot := failed.Snapshot(); snapshot.Status != AssessmentCategoryDecisionNotConfirmed ||
|
||||
snapshot.PreviousGrade == nil || *snapshot.PreviousGrade != GradeIntern ||
|
||||
snapshot.CurrentGrade == nil || *snapshot.CurrentGrade != GradeIntern || failed.ShouldUpdateCurrent() {
|
||||
t.Fatalf("k-1 decision = %+v, want failed attempt preserving the current intern grade", snapshot)
|
||||
}
|
||||
if current, ok := failed.CurrentCategory(); !ok || current.Snapshot().Grade != GradeIntern {
|
||||
t.Fatalf("current category after k-1 = (%+v, %v), want the previous grade", current.Snapshot(), ok)
|
||||
}
|
||||
|
||||
passingAttempt := newCategoryTestAttempt(t, policy, GradeJunior, userID)
|
||||
passingAttempt, passingResult := finishCategoryTestAttempt(t, passingAttempt, policy, 19)
|
||||
passingReview := categoryReviewForAttempt(t, passingAttempt, policy)
|
||||
passing, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: passingAttempt, Result: passingResult, Policy: policy, Review: &passingReview, Current: &previous,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DecideAssessmentCategory(k) error = %v", err)
|
||||
}
|
||||
snapshot := passing.Snapshot()
|
||||
if snapshot.Status != AssessmentCategoryDecisionAssigned || snapshot.Method != AssessmentCategoryDecisionDemoBasicPassMark ||
|
||||
snapshot.PreviousGrade == nil || *snapshot.PreviousGrade != GradeIntern ||
|
||||
snapshot.CurrentGrade == nil || *snapshot.CurrentGrade != GradeJunior ||
|
||||
snapshot.CalibrationStatus != AssessmentCategoryCalibrationUncalibrated ||
|
||||
snapshot.Source != AssessmentCategorySourceSyntheticDemo || !passing.ShouldUpdateCurrent() {
|
||||
t.Fatalf("k decision = %+v, want explicit uncalibrated synthetic assignment", snapshot)
|
||||
}
|
||||
current, ok := passing.CurrentCategory()
|
||||
if !ok || current.Snapshot().Grade != GradeJunior || current.Snapshot().SourceReviewID != passingReview.Snapshot().ID {
|
||||
t.Fatalf("assigned current category = (%+v, %v), want the reviewed junior grade", current.Snapshot(), ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecideAssessmentCategoryRejectsReviewAfterResult(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
attempt := newCategoryTestAttempt(t, policy, GradeJunior, uuid.New())
|
||||
attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19)
|
||||
review := categoryReviewForAttempt(t, attempt, policy)
|
||||
reviewSnapshot := review.Snapshot()
|
||||
reviewSnapshot.ReviewedAt = result.DecidedAt
|
||||
boundaryReview, err := RestoreAssessmentSyntheticCategoryReview(reviewSnapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentSyntheticCategoryReview(at decision time) error = %v", err)
|
||||
}
|
||||
boundary, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: policy, Review: &boundaryReview,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil || boundary.Snapshot().Status != AssessmentCategoryDecisionAssigned {
|
||||
t.Fatalf("DecideAssessmentCategory(review at decision time) = (%+v, %v), want assignment", boundary.Snapshot(), err)
|
||||
}
|
||||
|
||||
reviewSnapshot.ReviewedAt = result.DecidedAt.Add(time.Microsecond)
|
||||
futureReview, err := RestoreAssessmentSyntheticCategoryReview(reviewSnapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentSyntheticCategoryReview(after decision time) error = %v", err)
|
||||
}
|
||||
future, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: policy, Review: &futureReview,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil || future.Snapshot().Status != AssessmentCategoryDecisionNotEligible || future.ShouldUpdateCurrent() {
|
||||
t.Fatalf("DecideAssessmentCategory(review after decision time) = (%+v, %v), want no assignment", future.Snapshot(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecideAssessmentCategoryFailsClosedWithoutMatchingReview(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
attempt := newCategoryTestAttempt(t, policy, GradeJunior, uuid.New())
|
||||
attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19)
|
||||
|
||||
decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: policy, SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DecideAssessmentCategory(no review) error = %v", err)
|
||||
}
|
||||
if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionNotEligible ||
|
||||
snapshot.CurrentGrade != nil || snapshot.ReviewID != uuid.Nil || decision.ShouldUpdateCurrent() {
|
||||
t.Fatalf("unreviewed decision = %+v, want no category evidence", snapshot)
|
||||
}
|
||||
|
||||
review := categoryReviewForAttempt(t, attempt, policy)
|
||||
reviewSnapshot := review.Snapshot()
|
||||
reviewSnapshot.ProductPolicyVersion++
|
||||
wrongPolicyReview, err := RestoreAssessmentSyntheticCategoryReview(reviewSnapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentSyntheticCategoryReview(wrong policy) error = %v", err)
|
||||
}
|
||||
decision, err = DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: policy, Review: &wrongPolicyReview,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil || decision.Snapshot().Status != AssessmentCategoryDecisionNotEligible || decision.ShouldUpdateCurrent() {
|
||||
t.Fatalf("DecideAssessmentCategory(mismatched review) = (%+v, %v), want no assignment", decision.Snapshot(), err)
|
||||
}
|
||||
|
||||
otherPolicy := testCategoryPolicyVersion(t)
|
||||
if _, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: otherPolicy, Review: &review,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
}); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("DecideAssessmentCategory(unpinned policy) error = %v, want invalid category", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecideAssessmentCategoryNeverLowersCurrentGrade(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
userID := uuid.New()
|
||||
current := testCurrentAssessmentCategory(t, userID, GradeMiddle, policy)
|
||||
attempt := newCategoryTestAttempt(t, policy, GradeJunior, userID)
|
||||
attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19)
|
||||
review := categoryReviewForAttempt(t, attempt, policy)
|
||||
decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: policy, Review: &review, Current: ¤t,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DecideAssessmentCategory(lower passing grade) error = %v", err)
|
||||
}
|
||||
if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionUnchanged ||
|
||||
snapshot.PreviousGrade == nil || *snapshot.PreviousGrade != GradeMiddle ||
|
||||
snapshot.CurrentGrade == nil || *snapshot.CurrentGrade != GradeMiddle || decision.ShouldUpdateCurrent() {
|
||||
t.Fatalf("lower-grade decision = %+v, want the existing middle grade unchanged", snapshot)
|
||||
}
|
||||
unchanged, ok := decision.CurrentCategory()
|
||||
if !ok || unchanged.Snapshot().Grade != GradeMiddle || unchanged.Snapshot().SourceAttemptID != current.Snapshot().SourceAttemptID {
|
||||
t.Fatalf("current category changed after a lower pass: %+v", unchanged.Snapshot())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecideAssessmentCategoryAllowsCorrectiveDemoBasic(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
userID := uuid.New()
|
||||
root := newCategoryTestAttempt(t, policy, GradeSenior, userID)
|
||||
root, _ = finishCategoryTestAttempt(t, root, policy, 18)
|
||||
corrective := newCategoryTestAttemptAt(
|
||||
t, policy, AssessmentAttemptKindCorrective, GradeMiddle, userID, []AssessmentAttempt{root},
|
||||
root.Snapshot().UpdatedAt.Add(time.Second),
|
||||
)
|
||||
corrective, result := finishCategoryTestAttempt(t, corrective, policy, 19)
|
||||
review := categoryReviewForAttempt(t, corrective, policy)
|
||||
decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: corrective, Result: result, Policy: policy, Review: &review,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DecideAssessmentCategory(corrective) error = %v", err)
|
||||
}
|
||||
if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionAssigned ||
|
||||
snapshot.CurrentGrade == nil || *snapshot.CurrentGrade != GradeMiddle {
|
||||
t.Fatalf("corrective decision = %+v, want a middle-grade assignment", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecideAssessmentCategoryExpressNeverCreatesEvidence(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
userID := uuid.New()
|
||||
current := testCurrentAssessmentCategory(t, userID, GradeJunior, policy)
|
||||
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
|
||||
UserID: userID, Kind: AssessmentAttemptKindDemoExpress, BankCategory: "unit-training",
|
||||
Versions: testTrainingAssessmentAttemptVersions(policy), Policy: policy,
|
||||
CreatedAt: testAssessmentAttemptCreatedAt, Items: testAssessmentAttemptItems(t, 3),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttempt(express) error = %v", err)
|
||||
}
|
||||
attempt, result := finishCategoryTestAttempt(t, attempt, policy, 3)
|
||||
decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: policy, Current: ¤t,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DecideAssessmentCategory(express) error = %v", err)
|
||||
}
|
||||
if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionTrainingOnly ||
|
||||
snapshot.Specialization != nil || snapshot.AttemptedGrade != nil || snapshot.ReviewID != uuid.Nil ||
|
||||
decision.ShouldUpdateCurrent() {
|
||||
t.Fatalf("express decision = %+v, want no category fields or update", snapshot)
|
||||
}
|
||||
unchanged, ok := decision.CurrentCategory()
|
||||
if !ok || unchanged.Snapshot().Grade != GradeJunior || unchanged.Snapshot().SourceAttemptID != current.Snapshot().SourceAttemptID {
|
||||
t.Fatalf("express changed current category: %+v", unchanged.Snapshot())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecideAssessmentCategoryIsDefaultOffEvenWithReviewedSource(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
attempt := newCategoryTestAttempt(t, policy, GradeJunior, uuid.New())
|
||||
attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19)
|
||||
review := categoryReviewForAttempt(t, attempt, policy)
|
||||
|
||||
decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: policy, Review: &review,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DecideAssessmentCategory(default gate) error = %v", err)
|
||||
}
|
||||
if snapshot := decision.Snapshot(); snapshot.Status != AssessmentCategoryDecisionNotEligible ||
|
||||
snapshot.ReviewID != uuid.Nil || snapshot.CurrentGrade != nil || decision.ShouldUpdateCurrent() {
|
||||
t.Fatalf("default-off decision = %+v, want no assignment without an explicit feature gate", snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyntheticCategoryPolicyRequiresTheCompleteAcceptedAssessmentPolicy(t *testing.T) {
|
||||
accepted := DemoProductPolicyV2().Assessment
|
||||
if !sameAssessmentPolicy(accepted, DemoProductPolicyV2().Assessment) {
|
||||
t.Fatal("sameAssessmentPolicy(accepted) = false, want exact accepted policy")
|
||||
}
|
||||
changed := DemoProductPolicyV2().Assessment
|
||||
changed.StopRule.SeedItems++
|
||||
if sameAssessmentPolicy(changed, accepted) {
|
||||
t.Fatal("sameAssessmentPolicy(changed stop rule) = true, want false")
|
||||
}
|
||||
changed = DemoProductPolicyV2().Assessment
|
||||
changed.Attempt.IdleTimeoutSeconds++
|
||||
if sameAssessmentPolicy(changed, accepted) {
|
||||
t.Fatal("sameAssessmentPolicy(changed session settings) = true, want false")
|
||||
}
|
||||
changed = DemoProductPolicyV2().Assessment
|
||||
changed.Training = nil
|
||||
if sameAssessmentPolicy(changed, accepted) {
|
||||
t.Fatal("sameAssessmentPolicy(missing training settings) = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentAttemptResultHistoryKeepsV1CategoryUnknown(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
userID := uuid.New()
|
||||
current := testCurrentAssessmentCategory(t, userID, GradeMiddle, policy)
|
||||
attempt := newCategoryTestAttempt(t, policy, GradeSenior, userID)
|
||||
attempt, result := finishCategoryTestAttempt(t, attempt, policy, 19)
|
||||
review := categoryReviewForAttempt(t, attempt, policy)
|
||||
decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: policy, Review: &review, Current: ¤t,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DecideAssessmentCategory() error = %v", err)
|
||||
}
|
||||
|
||||
legacy, err := NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
if legacy.SchemaVersion != AssessmentAttemptResultHistorySchemaV1 || legacy.CategoryDecision != nil || legacy.CurrentConfirmedGrade != nil {
|
||||
t.Fatalf("legacy history entry = %+v, want v1 with category grade unknown", legacy)
|
||||
}
|
||||
|
||||
v2, err := NewCategoryAssessmentAttemptResultHistoryEntry(result, decision.Snapshot())
|
||||
if err != nil {
|
||||
t.Fatalf("NewCategoryAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
if v2.SchemaVersion != AssessmentAttemptResultHistorySchemaV2 || v2.CurrentConfirmedGrade == nil ||
|
||||
*v2.CurrentConfirmedGrade != GradeSenior || v2.CategoryDecision == nil ||
|
||||
v2.CategoryDecision.PreviousGrade == nil || *v2.CategoryDecision.PreviousGrade != GradeMiddle ||
|
||||
v2.CategoryDecision.CurrentGrade == nil || *v2.CategoryDecision.CurrentGrade != GradeSenior {
|
||||
t.Fatalf("v2 history entry = %+v, want previous middle and captured current senior", v2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentAttemptResultHistoryRejectsInventedLegacyGradeAndMismatchedV2(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
attempt := newCategoryTestAttempt(t, policy, GradeJunior, uuid.New())
|
||||
attempt, result := finishCategoryTestAttempt(t, attempt, policy, 3)
|
||||
review := categoryReviewForAttempt(t, attempt, policy)
|
||||
decision, err := DecideAssessmentCategory(AssessmentCategoryDecisionInput{
|
||||
Attempt: attempt, Result: result, Policy: policy, Review: &review,
|
||||
SyntheticDemoCategoryAssignmentEnabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DecideAssessmentCategory() error = %v", err)
|
||||
}
|
||||
|
||||
legacy, err := NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
legacy.CurrentConfirmedGrade = pointer(GradeIntern)
|
||||
if _, err := RestoreAssessmentAttemptResultHistoryEntry(legacy); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("RestoreAssessmentAttemptResultHistoryEntry(v1 with inferred grade) error = %v, want invalid category", err)
|
||||
}
|
||||
|
||||
v2, err := NewCategoryAssessmentAttemptResultHistoryEntry(result, decision.Snapshot())
|
||||
if err != nil {
|
||||
t.Fatalf("NewCategoryAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
v2.CategoryDecision.OpeningManifestHash = testManifestHash(200)
|
||||
if _, err := RestoreAssessmentAttemptResultHistoryEntry(v2); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("RestoreAssessmentAttemptResultHistoryEntry(mismatched pins) error = %v, want invalid category", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentCategorySnapshotsRejectUnknownOrIncompleteProvenance(t *testing.T) {
|
||||
policy := testCategoryPolicyVersion(t)
|
||||
current := testCurrentAssessmentCategory(t, uuid.New(), GradeJunior, policy)
|
||||
corrupt := current.Snapshot()
|
||||
corrupt.SourceReviewID = uuid.Nil
|
||||
if _, err := RestoreCandidateAssessmentCategory(corrupt); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("RestoreCandidateAssessmentCategory(missing review) error = %v, want invalid category", err)
|
||||
}
|
||||
|
||||
operator, err := ParseAssessmentOperator("operator:assessment-reviewer")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseAssessmentOperator() error = %v", err)
|
||||
}
|
||||
if _, err := RestoreAssessmentSyntheticCategoryReview(AssessmentSyntheticCategoryReviewSnapshot{
|
||||
ID: uuid.New(), OpeningID: uuid.New(), Category: "backend", Source: AssessmentCategorySourceSyntheticDemo,
|
||||
OpeningManifestHash: testManifestHash(1),
|
||||
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), ReviewedBy: operator,
|
||||
}); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("RestoreAssessmentSyntheticCategoryReview(missing time) error = %v, want invalid category", err)
|
||||
}
|
||||
if _, err := RestoreAssessmentSyntheticCategoryReview(AssessmentSyntheticCategoryReviewSnapshot{
|
||||
ID: uuid.New(), OpeningID: uuid.New(), Category: "backend", OpeningManifestHash: testManifestHash(1),
|
||||
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), ReviewedBy: operator,
|
||||
ReviewedAt: testAssessmentAttemptCreatedAt,
|
||||
}); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("RestoreAssessmentSyntheticCategoryReview(missing source) error = %v, want invalid category", err)
|
||||
}
|
||||
if _, err := RestoreAssessmentSyntheticCategoryReview(AssessmentSyntheticCategoryReviewSnapshot{
|
||||
ID: uuid.New(), OpeningID: uuid.New(), Category: "backend", Source: AssessmentCategorySource("operator_import"),
|
||||
OpeningManifestHash: testManifestHash(1), ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
|
||||
ReviewedBy: operator, ReviewedAt: testAssessmentAttemptCreatedAt,
|
||||
}); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("RestoreAssessmentSyntheticCategoryReview(wrong source) error = %v, want invalid category", err)
|
||||
}
|
||||
}
|
||||
|
||||
func testCategoryPolicyVersion(t *testing.T) PolicyVersion {
|
||||
t.Helper()
|
||||
policy := DemoProductPolicyV2()
|
||||
draft, err := NewPolicyVersionDraft(NewPolicyVersionDraftInput{
|
||||
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor,
|
||||
EffectiveAt: testPolicyEffectiveAt, Policy: policy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft(category policy) error = %v", err)
|
||||
}
|
||||
numbered, err := draft.WithVersion(2)
|
||||
if err != nil {
|
||||
t.Fatalf("PolicyVersionDraft.WithVersion(category policy) error = %v", err)
|
||||
}
|
||||
return mustRestore(t, storedFrom(numbered))
|
||||
}
|
||||
|
||||
func newCategoryTestAttempt(
|
||||
t *testing.T,
|
||||
policy PolicyVersion,
|
||||
grade GradeCode,
|
||||
userID uuid.UUID,
|
||||
) AssessmentAttempt {
|
||||
t.Helper()
|
||||
return newCategoryTestAttemptAt(t, policy, AssessmentAttemptKindRoot, grade, userID, nil, testAssessmentAttemptCreatedAt)
|
||||
}
|
||||
|
||||
func newCategoryTestAttemptAt(
|
||||
t *testing.T,
|
||||
policy PolicyVersion,
|
||||
kind AssessmentAttemptKind,
|
||||
grade GradeCode,
|
||||
userID uuid.UUID,
|
||||
chain []AssessmentAttempt,
|
||||
createdAt time.Time,
|
||||
) AssessmentAttempt {
|
||||
t.Helper()
|
||||
specialization := SpecializationBackend
|
||||
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
|
||||
UserID: userID, Kind: kind, BankCategory: "unit-category", Specialization: &specialization,
|
||||
TargetGrade: &grade, Chain: chain, Versions: testAssessmentAttemptVersions(t, policy),
|
||||
Policy: policy, CreatedAt: createdAt, Items: testAssessmentAttemptItems(t, int(policy.Policy().Assessment.StopRule.MaxScoredItems+policy.Policy().Assessment.StopRule.SeedItems)),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttempt(category test) error = %v", err)
|
||||
}
|
||||
return attempt
|
||||
}
|
||||
|
||||
func finishCategoryTestAttempt(
|
||||
t *testing.T,
|
||||
attempt AssessmentAttempt,
|
||||
policy PolicyVersion,
|
||||
correctCount int,
|
||||
) (AssessmentAttempt, AssessmentAttemptResultSnapshot) {
|
||||
t.Helper()
|
||||
items := attempt.Snapshot().Items
|
||||
if correctCount < 0 || correctCount > len(items) {
|
||||
t.Fatalf("correct count %d outside %d attempt items", correctCount, len(items))
|
||||
}
|
||||
startedAt := attempt.Snapshot().CreatedAt
|
||||
for index, item := range items {
|
||||
answer := incorrectAssessmentTestAnswer(t, item.Variant)
|
||||
if index < correctCount {
|
||||
answer = correctAssessmentTestAnswer(t, item.Variant)
|
||||
}
|
||||
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, startedAt.Add(time.Duration(index+1)*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("SubmitAnswer(category item %d) = changed %v, error %v", index, changed, err)
|
||||
}
|
||||
attempt = updated
|
||||
}
|
||||
finalized, changed, answerDecision, err := attempt.FinalizeDemo(
|
||||
attempt.Version(), policy.Policy().Assessment, startedAt.Add(time.Duration(len(items)+1)*time.Second),
|
||||
)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("FinalizeDemo(category attempt) = changed %v, error %v", changed, err)
|
||||
}
|
||||
summary := ""
|
||||
limitations := []string{"uncalibrated_thresholds"}
|
||||
if finalized.Kind() == AssessmentAttemptKindDemoExpress {
|
||||
summary = "This training run is educational only."
|
||||
limitations = []string{"demonstration_only"}
|
||||
}
|
||||
result, err := NewAssessmentAttemptResultSnapshot(finalized, answerDecision, summary, limitations)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttemptResultSnapshot(category attempt) error = %v", err)
|
||||
}
|
||||
return finalized, result
|
||||
}
|
||||
|
||||
func categoryReviewForAttempt(
|
||||
t *testing.T,
|
||||
attempt AssessmentAttempt,
|
||||
policy PolicyVersion,
|
||||
) AssessmentSyntheticCategoryReview {
|
||||
t.Helper()
|
||||
reviewer, err := ParseAssessmentOperator("operator:assessment-reviewer")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseAssessmentOperator() error = %v", err)
|
||||
}
|
||||
snapshot := attempt.Snapshot()
|
||||
review, err := NewAssessmentSyntheticCategoryReview(AssessmentSyntheticCategoryReviewSnapshot{
|
||||
ID: uuid.New(), OpeningID: snapshot.Versions.OpeningID, Category: snapshot.BankCategory,
|
||||
Source: AssessmentCategorySourceSyntheticDemo,
|
||||
OpeningManifestHash: snapshot.Versions.OpeningManifestHash,
|
||||
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
|
||||
ReviewedBy: reviewer, ReviewedAt: testAssessmentAttemptCreatedAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentSyntheticCategoryReview() error = %v", err)
|
||||
}
|
||||
return review
|
||||
}
|
||||
|
||||
func testCurrentAssessmentCategory(
|
||||
t *testing.T,
|
||||
userID uuid.UUID,
|
||||
grade GradeCode,
|
||||
policy PolicyVersion,
|
||||
) CandidateAssessmentCategory {
|
||||
t.Helper()
|
||||
return restoredTestCategory(t, CandidateAssessmentCategorySnapshot{
|
||||
CandidateID: userID, Specialization: SpecializationBackend, Grade: grade,
|
||||
SourceAttemptID: AssessmentAttemptID(uuid.New()), SourceReviewID: uuid.New(),
|
||||
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
|
||||
OpeningID: uuid.New(), OpeningManifestHash: testManifestHash(9),
|
||||
Source: AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: AssessmentCategoryCalibrationUncalibrated,
|
||||
AssignedAt: testAssessmentAttemptCreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func restoredTestCategory(t *testing.T, snapshot CandidateAssessmentCategorySnapshot) CandidateAssessmentCategory {
|
||||
t.Helper()
|
||||
category, err := RestoreCandidateAssessmentCategory(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateAssessmentCategory() error = %v", err)
|
||||
}
|
||||
return category
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrInvalidNotificationInboxEntry = errors.New("invalid notification inbox entry")
|
||||
|
||||
// NotificationInboxEventType is an allowlisted source event that can appear
|
||||
// in the internal inbox.
|
||||
type NotificationInboxEventType string
|
||||
|
||||
const NotificationInboxInvitationDelivered NotificationInboxEventType = "invitation.delivered"
|
||||
|
||||
// NotificationInboxSourceType identifies the current source-of-truth record
|
||||
// used to resolve an inbox item's content.
|
||||
type NotificationInboxSourceType string
|
||||
|
||||
const NotificationInboxSourceInvitation NotificationInboxSourceType = "invitation"
|
||||
|
||||
// NotificationInboxEntryInput contains identifiers and event metadata only.
|
||||
// It deliberately has no content snapshot: presentation is resolved from the
|
||||
// current source and its visibility rules when the item is read.
|
||||
type NotificationInboxEntryInput struct {
|
||||
EventID uuid.UUID
|
||||
RecipientUserID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
EventType NotificationInboxEventType
|
||||
SchemaVersion int32
|
||||
SourceType NotificationInboxSourceType
|
||||
SourceID uuid.UUID
|
||||
OccurredAt time.Time
|
||||
ReadAt *time.Time
|
||||
}
|
||||
|
||||
// NotificationInboxEntry is an immutable delivered event plus its
|
||||
// recipient-specific read state. EventID is the idempotency identity for one
|
||||
// recipient; the same source event can be delivered to different recipients.
|
||||
type NotificationInboxEntry struct {
|
||||
eventID uuid.UUID
|
||||
recipientUserID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
eventType NotificationInboxEventType
|
||||
schemaVersion int32
|
||||
sourceType NotificationInboxSourceType
|
||||
sourceID uuid.UUID
|
||||
occurredAt time.Time
|
||||
readAt *time.Time
|
||||
}
|
||||
|
||||
// NewNotificationInboxEntry validates an event record before it is stored.
|
||||
func NewNotificationInboxEntry(input NotificationInboxEntryInput) (NotificationInboxEntry, error) {
|
||||
const location = "domain.NewNotificationInboxEntry"
|
||||
if input.ReadAt != nil {
|
||||
return NotificationInboxEntry{}, fmt.Errorf("%s - new entries cannot start as read: %w", location, ErrInvalidNotificationInboxEntry)
|
||||
}
|
||||
return restoreNotificationInboxEntry(input)
|
||||
}
|
||||
|
||||
// RestoreNotificationInboxEntry validates inbox metadata loaded from storage.
|
||||
func RestoreNotificationInboxEntry(input NotificationInboxEntryInput) (NotificationInboxEntry, error) {
|
||||
const location = "domain.RestoreNotificationInboxEntry"
|
||||
return restoreNotificationInboxEntryWithLocation(input, location)
|
||||
}
|
||||
|
||||
func restoreNotificationInboxEntry(input NotificationInboxEntryInput) (NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryWithLocation(input, "domain.NewNotificationInboxEntry")
|
||||
}
|
||||
|
||||
func restoreNotificationInboxEntryWithLocation(
|
||||
input NotificationInboxEntryInput,
|
||||
location string,
|
||||
) (NotificationInboxEntry, error) {
|
||||
if input.EventID == uuid.Nil || input.RecipientUserID == uuid.Nil || input.OrganizationID == uuid.Nil || input.SourceID == uuid.Nil {
|
||||
return NotificationInboxEntry{}, fmt.Errorf("%s - event, recipient, organization, and source IDs are required: %w", location, ErrInvalidNotificationInboxEntry)
|
||||
}
|
||||
if input.EventType != NotificationInboxInvitationDelivered || input.SchemaVersion != 1 || input.SourceType != NotificationInboxSourceInvitation {
|
||||
return NotificationInboxEntry{}, fmt.Errorf("%s - event type, schema version, and source type are unsupported: %w", location, ErrInvalidNotificationInboxEntry)
|
||||
}
|
||||
if input.OccurredAt.IsZero() {
|
||||
return NotificationInboxEntry{}, fmt.Errorf("%s - occurrence time is required: %w", location, ErrInvalidNotificationInboxEntry)
|
||||
}
|
||||
occurredAt := canonicalNotificationInboxTime(input.OccurredAt)
|
||||
var readAt *time.Time
|
||||
if input.ReadAt != nil {
|
||||
if input.ReadAt.IsZero() {
|
||||
return NotificationInboxEntry{}, fmt.Errorf("%s - read time cannot be zero: %w", location, ErrInvalidNotificationInboxEntry)
|
||||
}
|
||||
canonical := canonicalNotificationInboxTime(*input.ReadAt)
|
||||
readAt = &canonical
|
||||
}
|
||||
return NotificationInboxEntry{
|
||||
eventID: input.EventID,
|
||||
recipientUserID: input.RecipientUserID,
|
||||
organizationID: input.OrganizationID,
|
||||
eventType: input.EventType,
|
||||
schemaVersion: input.SchemaVersion,
|
||||
sourceType: input.SourceType,
|
||||
sourceID: input.SourceID,
|
||||
occurredAt: occurredAt,
|
||||
readAt: readAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// MarkRead returns the same entry with its first read timestamp. A retry does
|
||||
// not replace the original timestamp.
|
||||
func (entry NotificationInboxEntry) MarkRead(at time.Time) (NotificationInboxEntry, error) {
|
||||
const location = "NotificationInboxEntry.MarkRead"
|
||||
if entry.IsZero() || at.IsZero() {
|
||||
return NotificationInboxEntry{}, fmt.Errorf("%s - entry and read time are required: %w", location, ErrInvalidNotificationInboxEntry)
|
||||
}
|
||||
if entry.readAt != nil {
|
||||
return entry, nil
|
||||
}
|
||||
readAt := canonicalNotificationInboxTime(at)
|
||||
entry.readAt = &readAt
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
func canonicalNotificationInboxTime(value time.Time) time.Time {
|
||||
return value.UTC().Truncate(time.Microsecond)
|
||||
}
|
||||
|
||||
func (entry NotificationInboxEntry) EventID() uuid.UUID { return entry.eventID }
|
||||
func (entry NotificationInboxEntry) RecipientUserID() uuid.UUID { return entry.recipientUserID }
|
||||
func (entry NotificationInboxEntry) OrganizationID() uuid.UUID { return entry.organizationID }
|
||||
func (entry NotificationInboxEntry) EventType() NotificationInboxEventType {
|
||||
return entry.eventType
|
||||
}
|
||||
func (entry NotificationInboxEntry) SchemaVersion() int32 { return entry.schemaVersion }
|
||||
func (entry NotificationInboxEntry) SourceType() NotificationInboxSourceType {
|
||||
return entry.sourceType
|
||||
}
|
||||
func (entry NotificationInboxEntry) SourceID() uuid.UUID { return entry.sourceID }
|
||||
func (entry NotificationInboxEntry) OccurredAt() time.Time { return entry.occurredAt }
|
||||
func (entry NotificationInboxEntry) ReadAt() (time.Time, bool) {
|
||||
if entry.readAt == nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return *entry.readAt, true
|
||||
}
|
||||
|
||||
func (entry NotificationInboxEntry) IsZero() bool {
|
||||
return entry.eventID == uuid.Nil || entry.recipientUserID == uuid.Nil || entry.organizationID == uuid.Nil || entry.sourceID == uuid.Nil
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestNewNotificationInboxEntry(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
occurredAt := time.Date(2026, time.October, 8, 12, 30, 0, 123456789, time.FixedZone("test", 3*60*60))
|
||||
input := NotificationInboxEntryInput{
|
||||
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
|
||||
EventType: NotificationInboxInvitationDelivered, SchemaVersion: 1,
|
||||
SourceType: NotificationInboxSourceInvitation, SourceID: uuid.New(), OccurredAt: occurredAt,
|
||||
}
|
||||
entry, err := NewNotificationInboxEntry(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewNotificationInboxEntry() error = %v", err)
|
||||
}
|
||||
if entry.EventID() != input.EventID || entry.RecipientUserID() != input.RecipientUserID || entry.OrganizationID() != input.OrganizationID {
|
||||
t.Fatal("entry identities do not match input")
|
||||
}
|
||||
if entry.SourceID() != input.SourceID || entry.SourceType() != input.SourceType || entry.EventType() != input.EventType || entry.SchemaVersion() != input.SchemaVersion {
|
||||
t.Fatal("entry source metadata does not match input")
|
||||
}
|
||||
wantOccurredAt := occurredAt.UTC().Truncate(time.Microsecond)
|
||||
if !entry.OccurredAt().Equal(wantOccurredAt) {
|
||||
t.Fatalf("OccurredAt() = %s, want %s", entry.OccurredAt(), wantOccurredAt)
|
||||
}
|
||||
if _, isRead := entry.ReadAt(); isRead {
|
||||
t.Fatal("new entry is already read")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreNotificationInboxEntryRejectsInvalidMetadata(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
base := NotificationInboxEntryInput{
|
||||
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
|
||||
EventType: NotificationInboxInvitationDelivered, SchemaVersion: 1,
|
||||
SourceType: NotificationInboxSourceInvitation, SourceID: uuid.New(),
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 30, 0, 0, time.UTC),
|
||||
}
|
||||
zeroTime := time.Time{}
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*NotificationInboxEntryInput)
|
||||
}{
|
||||
{name: "missing event ID", mutate: func(input *NotificationInboxEntryInput) { input.EventID = uuid.Nil }},
|
||||
{name: "missing recipient ID", mutate: func(input *NotificationInboxEntryInput) { input.RecipientUserID = uuid.Nil }},
|
||||
{name: "missing organization ID", mutate: func(input *NotificationInboxEntryInput) { input.OrganizationID = uuid.Nil }},
|
||||
{name: "missing source ID", mutate: func(input *NotificationInboxEntryInput) { input.SourceID = uuid.Nil }},
|
||||
{name: "unknown event type", mutate: func(input *NotificationInboxEntryInput) { input.EventType = "notification.mail_requested" }},
|
||||
{name: "unsupported schema version", mutate: func(input *NotificationInboxEntryInput) { input.SchemaVersion = 2 }},
|
||||
{name: "unknown source type", mutate: func(input *NotificationInboxEntryInput) { input.SourceType = "mail_request" }},
|
||||
{name: "missing occurrence time", mutate: func(input *NotificationInboxEntryInput) { input.OccurredAt = time.Time{} }},
|
||||
{name: "zero read time", mutate: func(input *NotificationInboxEntryInput) { input.ReadAt = &zeroTime }},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := base
|
||||
test.mutate(&input)
|
||||
if _, err := RestoreNotificationInboxEntry(input); !errors.Is(err, ErrInvalidNotificationInboxEntry) {
|
||||
t.Fatalf("RestoreNotificationInboxEntry() error = %v, want ErrInvalidNotificationInboxEntry", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewNotificationInboxEntryRejectsReadState(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
readAt := time.Date(2026, time.October, 8, 13, 0, 0, 0, time.UTC)
|
||||
input := NotificationInboxEntryInput{
|
||||
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
|
||||
EventType: NotificationInboxInvitationDelivered, SchemaVersion: 1,
|
||||
SourceType: NotificationInboxSourceInvitation, SourceID: uuid.New(),
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 30, 0, 0, time.UTC), ReadAt: &readAt,
|
||||
}
|
||||
if _, err := NewNotificationInboxEntry(input); !errors.Is(err, ErrInvalidNotificationInboxEntry) {
|
||||
t.Fatalf("NewNotificationInboxEntry() error = %v, want ErrInvalidNotificationInboxEntry", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationInboxEntryMarkReadPreservesFirstTimestamp(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
entry, err := NewNotificationInboxEntry(NotificationInboxEntryInput{
|
||||
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
|
||||
EventType: NotificationInboxInvitationDelivered, SchemaVersion: 1,
|
||||
SourceType: NotificationInboxSourceInvitation, SourceID: uuid.New(),
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 30, 0, 0, time.UTC),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewNotificationInboxEntry() error = %v", err)
|
||||
}
|
||||
first := time.Date(2026, time.October, 8, 13, 0, 0, 987654321, time.FixedZone("test", -4*60*60))
|
||||
marked, err := entry.MarkRead(first)
|
||||
if err != nil {
|
||||
t.Fatalf("MarkRead(first) error = %v", err)
|
||||
}
|
||||
second := first.Add(time.Hour)
|
||||
retried, err := marked.MarkRead(second)
|
||||
if err != nil {
|
||||
t.Fatalf("MarkRead(retry) error = %v", err)
|
||||
}
|
||||
want := first.UTC().Truncate(time.Microsecond)
|
||||
got, isRead := retried.ReadAt()
|
||||
if !isRead || !got.Equal(want) {
|
||||
t.Fatalf("ReadAt() = %s, %t, want %s, true", got, isRead, want)
|
||||
}
|
||||
if retried.EventID() != entry.EventID() || retried.SourceID() != entry.SourceID() {
|
||||
t.Fatal("MarkRead changed immutable source identity")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user