package domain import ( "fmt" "sort" "strings" ) // CEFR placement levels returned by the initial assessment. var InitialAssessmentCEFRLevels = []string{"A1", "A2", "B1", "B2", "C1", "C2"} // DefaultInitialAssessmentThresholds are seeded when the table is empty / on first install. // min_percent is the pass mark for that CEFR level's question set (progressive placement). func DefaultInitialAssessmentThresholds() []InitialAssessmentLevelThreshold { return []InitialAssessmentLevelThreshold{ {Level: "A1", MinPercent: 70, DisplayOrder: 1}, {Level: "A2", MinPercent: 70, DisplayOrder: 2}, {Level: "B1", MinPercent: 70, DisplayOrder: 3}, {Level: "B2", MinPercent: 70, DisplayOrder: 4}, {Level: "C1", MinPercent: 70, DisplayOrder: 5}, {Level: "C2", MinPercent: 70, DisplayOrder: 6}, } } type InitialAssessmentLevelThreshold struct { Level string `json:"level"` MinPercent int `json:"min_percent"` DisplayOrder int `json:"display_order"` } type PlacementAnswerInput struct { QuestionID int64 `json:"question_id"` SelectedOptionIDs []int64 `json:"selected_option_ids,omitempty"` TextAnswer *string `json:"text_answer,omitempty"` DynamicAnswers []PlacementDynamicAnswerInput `json:"dynamic_answers,omitempty"` } type PlacementDynamicAnswerInput struct { ElementID string `json:"element_id"` SelectedOptionIDs []string `json:"selected_option_ids,omitempty"` TextAnswer *string `json:"text_answer,omitempty"` } type PlacementQuestionResult struct { QuestionID int64 `json:"question_id"` QuestionType string `json:"question_type"` Gradable bool `json:"gradable"` Correct bool `json:"correct"` PointsEarned int32 `json:"points_earned"` PointsMax int32 `json:"points_max"` Skipped bool `json:"skipped"` } type PlacementAssessmentResult struct { QuestionSetID int64 `json:"question_set_id"` LevelAttempted string `json:"level_attempted"` ScorePercent float64 `json:"score_percent"` Passed bool `json:"passed"` PassPercent int `json:"pass_percent"` NextLevel *string `json:"next_level,omitempty"` Completed bool `json:"completed"` Level string `json:"level"` // final knowledge level when completed; else last passed / attempted context PointsEarned int32 `json:"points_earned"` PointsMax int32 `json:"points_max"` GradableQuestions int `json:"gradable_questions"` CorrectQuestions int `json:"correct_questions"` SkippedUngradableQuestions int `json:"skipped_ungradable_questions"` Questions []PlacementQuestionResult `json:"questions"` KnowledgeLevel string `json:"knowledge_level,omitempty"` InitialAssessmentCompleted bool `json:"initial_assessment_completed"` } // PlacementSession is the learner's progressive placement state. type PlacementSession struct { NextLevel string `json:"next_level,omitempty"` HighestPassedLevel *string `json:"highest_passed_level,omitempty"` Completed bool `json:"completed"` KnowledgeLevel string `json:"knowledge_level,omitempty"` InitialAssessmentCompleted bool `json:"initial_assessment_completed"` PublishedLevels []string `json:"published_levels"` } // UserInitialAssessmentProgress persists in-progress progressive placement. type UserInitialAssessmentProgress struct { UserID int64 NextLevel string HighestPassedLevel *string Completed bool } func NormalizeCEFRLevel(level string) (string, error) { normalized := strings.ToUpper(strings.TrimSpace(level)) for _, allowed := range InitialAssessmentCEFRLevels { if normalized == allowed { return normalized, nil } } return "", fmt.Errorf("level must be one of: %s", strings.Join(InitialAssessmentCEFRLevels, ", ")) } // NextCEFRLevel returns the following CEFR band, or "" after C2. func NextCEFRLevel(level string) string { normalized, err := NormalizeCEFRLevel(level) if err != nil { return "" } for i, l := range InitialAssessmentCEFRLevels { if l == normalized { if i+1 < len(InitialAssessmentCEFRLevels) { return InitialAssessmentCEFRLevels[i+1] } return "" } } return "" } // ValidateInitialAssessmentThresholds ensures every CEFR level is present once // with a pass mark between 0 and 100. func ValidateInitialAssessmentThresholds(rows []InitialAssessmentLevelThreshold) error { if len(rows) != len(InitialAssessmentCEFRLevels) { return fmt.Errorf("expected exactly %d thresholds (A1–C2)", len(InitialAssessmentCEFRLevels)) } byLevel := make(map[string]InitialAssessmentLevelThreshold, len(rows)) for _, row := range rows { level, err := NormalizeCEFRLevel(row.Level) if err != nil { return err } if _, exists := byLevel[level]; exists { return fmt.Errorf("duplicate threshold for level %s", level) } if row.MinPercent < 0 || row.MinPercent > 100 { return fmt.Errorf("min_percent for %s must be between 0 and 100", level) } byLevel[level] = InitialAssessmentLevelThreshold{ Level: level, MinPercent: row.MinPercent, DisplayOrder: row.DisplayOrder, } } for _, level := range InitialAssessmentCEFRLevels { if _, ok := byLevel[level]; !ok { return fmt.Errorf("missing threshold for level %s", level) } } return nil } // PassPercentForLevel returns the configured pass mark for a CEFR level set. func PassPercentForLevel(level string, thresholds []InitialAssessmentLevelThreshold) (int, error) { normalized, err := NormalizeCEFRLevel(level) if err != nil { return 0, err } if len(thresholds) == 0 { thresholds = DefaultInitialAssessmentThresholds() } thresholds = mergeThresholdDefaults(thresholds) for _, row := range thresholds { if row.Level == normalized { return row.MinPercent, nil } } return 0, fmt.Errorf("missing threshold for level %s", normalized) } // ResolveCEFRLevelFromScore is retained for legacy single-test banding. // Progressive placement uses PassPercentForLevel instead. func ResolveCEFRLevelFromScore(scorePercent float64, thresholds []InitialAssessmentLevelThreshold) (string, error) { if len(thresholds) == 0 { thresholds = DefaultInitialAssessmentThresholds() } if err := ValidateInitialAssessmentThresholds(thresholds); err != nil { thresholds = mergeThresholdDefaults(thresholds) if err := ValidateInitialAssessmentThresholds(thresholds); err != nil { return "", err } } sorted := append([]InitialAssessmentLevelThreshold(nil), thresholds...) sort.Slice(sorted, func(i, j int) bool { return sorted[i].MinPercent < sorted[j].MinPercent }) level := sorted[0].Level for _, row := range sorted { if scorePercent+1e-9 >= float64(row.MinPercent) { level = row.Level } } return level, nil } func mergeThresholdDefaults(rows []InitialAssessmentLevelThreshold) []InitialAssessmentLevelThreshold { byLevel := make(map[string]InitialAssessmentLevelThreshold) for _, d := range DefaultInitialAssessmentThresholds() { byLevel[d.Level] = d } for _, row := range rows { level, err := NormalizeCEFRLevel(row.Level) if err != nil { continue } row.Level = level byLevel[level] = row } out := make([]InitialAssessmentLevelThreshold, 0, len(InitialAssessmentCEFRLevels)) for i, level := range InitialAssessmentCEFRLevels { row := byLevel[level] if row.DisplayOrder <= 0 { row.DisplayOrder = i + 1 } out = append(out, row) } return out } // GradePlacementAnswers scores published placement questions against submitted answers. // Auto-gradable: MCQ, TRUE_FALSE, SHORT_ANSWER, and DYNAMIC multiple-choice / option slots. // AUDIO and other dynamic kinds are skipped (not counted in score denominator). func GradePlacementAnswers( questions []QuestionWithDetails, answers []PlacementAnswerInput, ) PlacementAssessmentResult { byID := make(map[int64]PlacementAnswerInput, len(answers)) for _, a := range answers { byID[a.QuestionID] = a } result := PlacementAssessmentResult{ Questions: make([]PlacementQuestionResult, 0, len(questions)), } for _, q := range questions { points := q.Points if points <= 0 { points = 1 } qr := PlacementQuestionResult{ QuestionID: q.ID, QuestionType: q.QuestionType, PointsMax: points, } ans, answered := byID[q.ID] gradable, correct := gradeOnePlacementQuestion(q, ans, answered) qr.Gradable = gradable if !gradable { qr.Skipped = true result.SkippedUngradableQuestions++ result.Questions = append(result.Questions, qr) continue } result.GradableQuestions++ result.PointsMax += points qr.Correct = correct if correct { qr.PointsEarned = points result.PointsEarned += points result.CorrectQuestions++ } if !answered { qr.Skipped = true } result.Questions = append(result.Questions, qr) } if result.PointsMax > 0 { result.ScorePercent = (float64(result.PointsEarned) / float64(result.PointsMax)) * 100 } return result } func gradeOnePlacementQuestion(q QuestionWithDetails, ans PlacementAnswerInput, answered bool) (gradable bool, correct bool) { qType := strings.ToUpper(strings.TrimSpace(q.QuestionType)) switch qType { case "MCQ", "TRUE_FALSE": return true, answered && gradeSelectedOptionIDs(q.Options, ans.SelectedOptionIDs) case "SHORT_ANSWER": text := "" if ans.TextAnswer != nil { text = *ans.TextAnswer } return true, answered && gradeShortAnswer(q.ShortAnswers, text) case "DYNAMIC": return gradeDynamicPlacementQuestion(q, ans, answered) default: // AUDIO and unknown types are not auto-graded in v1. return false, false } } func gradeSelectedOptionIDs(options []QuestionOption, selected []int64) bool { correctIDs := make(map[int64]struct{}) for _, opt := range options { if opt.IsCorrect { correctIDs[opt.ID] = struct{}{} } } if len(correctIDs) == 0 { return false } if len(selected) != len(correctIDs) { return false } seen := make(map[int64]struct{}, len(selected)) for _, id := range selected { if _, ok := correctIDs[id]; !ok { return false } seen[id] = struct{}{} } return len(seen) == len(correctIDs) } func gradeShortAnswer(acceptable []QuestionShortAnswer, given string) bool { given = strings.TrimSpace(given) if given == "" || len(acceptable) == 0 { return false } for _, sa := range acceptable { want := strings.TrimSpace(sa.AcceptableAnswer) match := strings.ToUpper(strings.TrimSpace(sa.MatchType)) switch match { case string(MatchTypeContains): if strings.Contains(strings.ToLower(given), strings.ToLower(want)) { return true } case string(MatchTypeCaseInsensitive), "": if strings.EqualFold(given, want) { return true } default: // EXACT if given == want { return true } } } return false } func gradeDynamicPlacementQuestion(q QuestionWithDetails, ans PlacementAnswerInput, answered bool) (gradable bool, correct bool) { if q.DynamicPayload == nil { return false, false } type slotSpec struct { kind string correct []string short []string match string } slots := make(map[string]slotSpec) collect := func(els []DynamicElementInstance) { for _, el := range els { id := strings.TrimSpace(el.ID) kind := strings.TrimSpace(el.Kind) if id == "" { continue } if isMultipleChoiceComponentKind(kind) { correctOpts := extractCorrectDynamicOptionIDs(el.Value) if len(correctOpts) == 0 { continue } slots[id] = slotSpec{kind: kind, correct: correctOpts} } } } collect(q.DynamicPayload.Stimulus) collect(q.DynamicPayload.Response) if len(slots) == 0 { return false, false } if !answered { return true, false } byElement := make(map[string]PlacementDynamicAnswerInput, len(ans.DynamicAnswers)) for _, da := range ans.DynamicAnswers { byElement[strings.TrimSpace(da.ElementID)] = da } for id, spec := range slots { da, ok := byElement[id] if !ok { return true, false } if isMultipleChoiceComponentKind(spec.kind) { if !sameStringSet(spec.correct, da.SelectedOptionIDs) { return true, false } } } return true, true } func extractCorrectDynamicOptionIDs(value interface{}) []string { m, ok := value.(map[string]interface{}) if !ok { return nil } rawOpts, ok := m["options"].([]interface{}) if !ok { return nil } var out []string for _, o := range rawOpts { om, ok := o.(map[string]interface{}) if !ok { continue } if c, _ := om["is_correct"].(bool); !c { continue } id, _ := om["id"].(string) id = strings.TrimSpace(id) if id != "" { out = append(out, id) } } return out } func sameStringSet(want, got []string) bool { if len(want) != len(got) { return false } set := make(map[string]struct{}, len(want)) for _, w := range want { set[strings.TrimSpace(w)] = struct{}{} } if len(set) != len(want) { return false } for _, g := range got { if _, ok := set[strings.TrimSpace(g)]; !ok { return false } } return true }