Add graded initial placement assessment with configurable A1–C2 thresholds.

Learners submit answers to one published placement set; the API scores auto-gradable questions, maps percent to CEFR, and updates knowledge_level.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-31 04:22:19 -07:00
parent 703f2b0041
commit efed1b366f
12 changed files with 974 additions and 113 deletions

View File

@ -0,0 +1 @@
DROP TABLE IF EXISTS initial_assessment_level_thresholds;

View File

@ -0,0 +1,16 @@
CREATE TABLE IF NOT EXISTS initial_assessment_level_thresholds (
level VARCHAR(8) PRIMARY KEY,
min_percent INT NOT NULL CHECK (min_percent >= 0 AND min_percent <= 100),
display_order INT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
INSERT INTO initial_assessment_level_thresholds (level, min_percent, display_order)
VALUES
('A1', 0, 1),
('A2', 17, 2),
('B1', 34, 3),
('B2', 51, 4),
('C1', 68, 5),
('C2', 85, 6)
ON CONFLICT (level) DO NOTHING;

View File

@ -0,0 +1,405 @@
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.
func DefaultInitialAssessmentThresholds() []InitialAssessmentLevelThreshold {
return []InitialAssessmentLevelThreshold{
{Level: "A1", MinPercent: 0, DisplayOrder: 1},
{Level: "A2", MinPercent: 17, DisplayOrder: 2},
{Level: "B1", MinPercent: 34, DisplayOrder: 3},
{Level: "B2", MinPercent: 51, DisplayOrder: 4},
{Level: "C1", MinPercent: 68, DisplayOrder: 5},
{Level: "C2", MinPercent: 85, 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"`
ScorePercent float64 `json:"score_percent"`
Level string `json:"level"`
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"`
InitialAssessmentCompleted bool `json:"initial_assessment_completed"`
}
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, ", "))
}
// ValidateInitialAssessmentThresholds ensures every CEFR level is present once,
// mins are ordered ascending, and A1 starts at 0.
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,
}
}
ordered := make([]InitialAssessmentLevelThreshold, 0, len(InitialAssessmentCEFRLevels))
for i, level := range InitialAssessmentCEFRLevels {
row, ok := byLevel[level]
if !ok {
return fmt.Errorf("missing threshold for level %s", level)
}
if row.DisplayOrder <= 0 {
row.DisplayOrder = i + 1
}
ordered = append(ordered, row)
}
if ordered[0].MinPercent != 0 {
return fmt.Errorf("A1 min_percent must be 0")
}
for i := 1; i < len(ordered); i++ {
if ordered[i].MinPercent <= ordered[i-1].MinPercent {
return fmt.Errorf("%s min_percent must be greater than %s", ordered[i].Level, ordered[i-1].Level)
}
}
return nil
}
// ResolveCEFRLevelFromScore returns the highest level whose min_percent <= scorePercent.
func ResolveCEFRLevelFromScore(scorePercent float64, thresholds []InitialAssessmentLevelThreshold) (string, error) {
if len(thresholds) == 0 {
thresholds = DefaultInitialAssessmentThresholds()
}
if err := ValidateInitialAssessmentThresholds(thresholds); err != nil {
// tolerate legacy/unsorted rows by sorting and filling defaults for missing
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
}

View File

@ -0,0 +1,77 @@
package domain
import "testing"
func TestResolveCEFRLevelFromScore(t *testing.T) {
thresholds := DefaultInitialAssessmentThresholds()
cases := []struct {
score float64
want string
}{
{0, "A1"},
{16.9, "A1"},
{17, "A2"},
{50, "B1"},
{51, "B2"},
{84.9, "C1"},
{85, "C2"},
{100, "C2"},
}
for _, tc := range cases {
got, err := ResolveCEFRLevelFromScore(tc.score, thresholds)
if err != nil {
t.Fatalf("score %.1f: %v", tc.score, err)
}
if got != tc.want {
t.Fatalf("score %.1f: got %s want %s", tc.score, got, tc.want)
}
}
}
func TestValidateInitialAssessmentThresholds_rejectsUnordered(t *testing.T) {
rows := DefaultInitialAssessmentThresholds()
rows[2].MinPercent = 10
if err := ValidateInitialAssessmentThresholds(rows); err == nil {
t.Fatal("expected validation error")
}
}
func TestGradePlacementAnswers_mcqAndShort(t *testing.T) {
questions := []QuestionWithDetails{
{
Question: Question{ID: 1, QuestionType: "MCQ", Points: 2},
Options: []QuestionOption{
{ID: 10, IsCorrect: true},
{ID: 11, IsCorrect: false},
},
},
{
Question: Question{ID: 2, QuestionType: "SHORT_ANSWER", Points: 1},
ShortAnswers: []QuestionShortAnswer{
{AcceptableAnswer: "hello", MatchType: "CASE_INSENSITIVE"},
},
},
{
Question: Question{ID: 3, QuestionType: "AUDIO", Points: 5},
},
}
answers := []PlacementAnswerInput{
{QuestionID: 1, SelectedOptionIDs: []int64{10}},
{QuestionID: 2, TextAnswer: stringPtr("Hello")},
}
got := GradePlacementAnswers(questions, answers)
if got.PointsMax != 3 {
t.Fatalf("points max=%d want 3", got.PointsMax)
}
if got.PointsEarned != 3 {
t.Fatalf("points earned=%d want 3", got.PointsEarned)
}
if got.SkippedUngradableQuestions != 1 {
t.Fatalf("skipped=%d want 1", got.SkippedUngradableQuestions)
}
if got.ScorePercent != 100 {
t.Fatalf("score=%v want 100", got.ScorePercent)
}
}
func stringPtr(s string) *string { return &s }

View File

@ -52,6 +52,8 @@ type QuestionStore interface {
GetQuestionSetsByType(ctx context.Context, setType string, limit, offset int32) ([]domain.QuestionSet, int64, error)
GetPublishedQuestionSetsByOwner(ctx context.Context, ownerType string, ownerID int64) ([]domain.QuestionSet, error)
GetInitialAssessmentSet(ctx context.Context) (domain.QuestionSet, error)
ListInitialAssessmentLevelThresholds(ctx context.Context) ([]domain.InitialAssessmentLevelThreshold, error)
ReplaceInitialAssessmentLevelThresholds(ctx context.Context, rows []domain.InitialAssessmentLevelThreshold) error
GetFirstIncompletePreviousPractice(ctx context.Context, userID int64, questionSetID int64) (*domain.PracticeAccessBlock, error)
MarkPracticeCompleted(ctx context.Context, userID int64, questionSetID int64) error
UpdateQuestionSet(ctx context.Context, id int64, input domain.CreateQuestionSetInput) error

View File

@ -28,6 +28,7 @@ type UserStore interface {
// userID int64,
// ) (*dbgen.AssessmentAttempt, error)
UpdateUserKnowledgeLevel(ctx context.Context, userID int64, knowledgeLevel string) error
CompleteInitialAssessment(ctx context.Context, userID int64, knowledgeLevel string) error
// IsUserNameUnique(ctx context.Context, userName string) (bool, error)
IsUserPending(ctx context.Context, userID int64) (bool, error)
// GetUserByUserName(

View File

@ -0,0 +1,105 @@
package repository
import (
"context"
"fmt"
"Yimaru-Backend/internal/domain"
"github.com/jackc/pgx/v5"
)
func (s *Store) ListInitialAssessmentLevelThresholds(ctx context.Context) ([]domain.InitialAssessmentLevelThreshold, error) {
rows, err := s.conn.Query(ctx, `
SELECT level, min_percent, display_order
FROM initial_assessment_level_thresholds
ORDER BY display_order ASC, level ASC
`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []domain.InitialAssessmentLevelThreshold
for rows.Next() {
var row domain.InitialAssessmentLevelThreshold
if err := rows.Scan(&row.Level, &row.MinPercent, &row.DisplayOrder); err != nil {
return nil, err
}
out = append(out, row)
}
if err := rows.Err(); err != nil {
return nil, err
}
if len(out) == 0 {
return domain.DefaultInitialAssessmentThresholds(), nil
}
return out, nil
}
func (s *Store) ReplaceInitialAssessmentLevelThresholds(ctx context.Context, rows []domain.InitialAssessmentLevelThreshold) error {
if err := domain.ValidateInitialAssessmentThresholds(rows); err != nil {
return err
}
tx, err := s.conn.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `DELETE FROM initial_assessment_level_thresholds`); err != nil {
return err
}
for i, level := range domain.InitialAssessmentCEFRLevels {
var row domain.InitialAssessmentLevelThreshold
for _, candidate := range rows {
normalized, err := domain.NormalizeCEFRLevel(candidate.Level)
if err != nil {
return err
}
if normalized == level {
row = candidate
row.Level = normalized
break
}
}
if row.Level == "" {
return fmt.Errorf("missing threshold for level %s", level)
}
displayOrder := row.DisplayOrder
if displayOrder <= 0 {
displayOrder = i + 1
}
if _, err := tx.Exec(ctx, `
INSERT INTO initial_assessment_level_thresholds (level, min_percent, display_order, updated_at)
VALUES ($1, $2, $3, NOW())
`, row.Level, row.MinPercent, displayOrder); err != nil {
return err
}
}
return tx.Commit(ctx)
}
func (s *Store) CompleteInitialAssessment(ctx context.Context, userID int64, knowledgeLevel string) error {
level, err := domain.NormalizeCEFRLevel(knowledgeLevel)
if err != nil {
return err
}
cmd, err := s.conn.Exec(ctx, `
UPDATE users
SET knowledge_level = $1,
initial_assessment_completed = TRUE,
updated_at = CURRENT_TIMESTAMP
WHERE id = $2
`, level, userID)
if err != nil {
return err
}
if cmd.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}

View File

@ -1076,11 +1076,47 @@ func (s *Store) GetPublishedQuestionSetsByOwner(ctx context.Context, ownerType s
}
func (s *Store) GetInitialAssessmentSet(ctx context.Context) (domain.QuestionSet, error) {
qs, err := s.queries.GetInitialAssessmentSet(ctx)
row := s.conn.QueryRow(ctx, `
SELECT id, title, description, set_type, owner_type, owner_id, banner_image, persona,
time_limit_minutes, passing_score, shuffle_questions, status, created_at, updated_at,
display_order, intro_video_url
FROM question_sets
WHERE set_type = 'INITIAL_ASSESSMENT'
AND status = 'PUBLISHED'
ORDER BY
CASE
WHEN owner_type IS NULL OR UPPER(TRIM(owner_type)) = 'STANDALONE' THEN 0
ELSE 1
END,
created_at DESC
LIMIT 1
`)
var (
qs domain.QuestionSet
ownerType, banner, persona, introURL *string
ownerID *int64
timeLimit, passing *int32
displayOrder int32
updatedAt *time.Time
)
err := row.Scan(
&qs.ID, &qs.Title, &qs.Description, &qs.SetType, &ownerType, &ownerID, &banner, &persona,
&timeLimit, &passing, &qs.ShuffleQuestions, &qs.Status, &qs.CreatedAt, &updatedAt,
&displayOrder, &introURL,
)
if err != nil {
return domain.QuestionSet{}, err
}
return questionSetToDomain(qs), nil
qs.OwnerType = ownerType
qs.OwnerID = ownerID
qs.BannerImage = banner
qs.Persona = persona
qs.TimeLimitMinutes = timeLimit
qs.PassingScore = passing
qs.UpdatedAt = updatedAt
qs.IntroVideoURL = introURL
return qs, nil
}
func (s *Store) GetFirstIncompletePreviousPractice(ctx context.Context, userID int64, questionSetID int64) (*domain.PracticeAccessBlock, error) {

View File

@ -0,0 +1,96 @@
package assessment
import (
"context"
"errors"
"fmt"
"Yimaru-Backend/internal/domain"
"github.com/jackc/pgx/v5"
)
var (
ErrPlacementSetNotFound = errors.New("published initial assessment set not found")
ErrNoGradableQuestions = errors.New("placement set has no auto-gradable questions")
)
func (s *Service) ListLevelThresholds(ctx context.Context) ([]domain.InitialAssessmentLevelThreshold, error) {
rows, err := s.questionStore.ListInitialAssessmentLevelThresholds(ctx)
if err != nil {
return nil, err
}
if len(rows) == 0 {
return domain.DefaultInitialAssessmentThresholds(), nil
}
return rows, nil
}
func (s *Service) UpdateLevelThresholds(ctx context.Context, rows []domain.InitialAssessmentLevelThreshold) ([]domain.InitialAssessmentLevelThreshold, error) {
if err := domain.ValidateInitialAssessmentThresholds(rows); err != nil {
return nil, err
}
if err := s.questionStore.ReplaceInitialAssessmentLevelThresholds(ctx, rows); err != nil {
return nil, err
}
return s.ListLevelThresholds(ctx)
}
// SubmitPlacement grades answers against the published placement set, maps score to CEFR,
// and persists knowledge_level + initial_assessment_completed on the user.
func (s *Service) SubmitPlacement(ctx context.Context, userID int64, answers []domain.PlacementAnswerInput) (domain.PlacementAssessmentResult, error) {
set, err := s.questionStore.GetInitialAssessmentSet(ctx)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.PlacementAssessmentResult{}, ErrPlacementSetNotFound
}
return domain.PlacementAssessmentResult{}, err
}
items, err := s.questionStore.GetPublishedQuestionsInSet(ctx, set.ID)
if err != nil {
return domain.PlacementAssessmentResult{}, err
}
if len(items) == 0 {
return domain.PlacementAssessmentResult{}, fmt.Errorf("%w: set is empty", ErrNoGradableQuestions)
}
questions := make([]domain.QuestionWithDetails, 0, len(items))
for _, item := range items {
qwd, err := s.questionStore.GetQuestionWithDetails(ctx, item.QuestionID)
if err != nil {
continue
}
questions = append(questions, qwd)
}
if len(questions) == 0 {
return domain.PlacementAssessmentResult{}, ErrNoGradableQuestions
}
graded := domain.GradePlacementAnswers(questions, answers)
graded.QuestionSetID = set.ID
if graded.GradableQuestions == 0 {
return domain.PlacementAssessmentResult{}, ErrNoGradableQuestions
}
thresholds, err := s.ListLevelThresholds(ctx)
if err != nil {
return domain.PlacementAssessmentResult{}, err
}
level, err := domain.ResolveCEFRLevelFromScore(graded.ScorePercent, thresholds)
if err != nil {
return domain.PlacementAssessmentResult{}, err
}
graded.Level = level
graded.KnowledgeLevel = level
graded.InitialAssessmentCompleted = true
if err := s.userStore.CompleteInitialAssessment(ctx, userID, level); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.PlacementAssessmentResult{}, fmt.Errorf("user not found")
}
return domain.PlacementAssessmentResult{}, err
}
return graded, nil
}

View File

@ -2,10 +2,13 @@ package handlers
import (
"Yimaru-Backend/internal/domain"
"Yimaru-Backend/internal/services/assessment"
"errors"
"fmt"
"strconv"
"github.com/gofiber/fiber/v2"
"github.com/jackc/pgx/v5"
)
// CreateAssessmentQuestion godoc
@ -37,7 +40,6 @@ func (h *Handler) CreateAssessmentQuestion(c *fiber.Ctx) error {
})
}
// Build options input
var options []domain.CreateQuestionOptionInput
for _, opt := range req.Options {
options = append(options, domain.CreateQuestionOptionInput{
@ -47,7 +49,6 @@ func (h *Handler) CreateAssessmentQuestion(c *fiber.Ctx) error {
})
}
// Build short answers input
var shortAnswers []domain.CreateShortAnswerInput
for _, sa := range req.ShortAnswers {
shortAnswers = append(shortAnswers, domain.CreateShortAnswerInput{
@ -57,17 +58,19 @@ func (h *Handler) CreateAssessmentQuestion(c *fiber.Ctx) error {
}
input := domain.CreateQuestionInput{
QuestionText: questionText,
QuestionType: questionType,
DifficultyLevel: req.DifficultyLevel,
Points: req.Points,
Explanation: req.Explanation,
Tips: req.Tips,
VoicePrompt: req.VoicePrompt,
SampleAnswerVoicePrompt: req.SampleAnswerVoicePrompt,
Status: req.Status,
Options: options,
ShortAnswers: shortAnswers,
QuestionText: questionText,
QuestionType: questionType,
QuestionTypeDefinitionID: req.QuestionTypeDefinitionID,
DynamicPayload: req.DynamicPayload,
DifficultyLevel: req.DifficultyLevel,
Points: req.Points,
Explanation: req.Explanation,
Tips: req.Tips,
VoicePrompt: req.VoicePrompt,
SampleAnswerVoicePrompt: req.SampleAnswerVoicePrompt,
Status: req.Status,
Options: options,
ShortAnswers: shortAnswers,
}
question, err := h.assessmentSvc.CreateQuestion(c.Context(), input)
@ -111,38 +114,19 @@ func (h *Handler) ListAssessmentQuestions(c *fiber.Ctx) error {
})
}
catalog, _ := h.activeQuestionTypeDefinitionCatalog(c.Context())
var questionResponses []questionRes
for _, q := range questions {
var options []optionRes
for _, opt := range q.Options {
options = append(options, optionRes{
ID: opt.ID,
OptionText: opt.OptionText,
OptionOrder: opt.OptionOrder,
IsCorrect: opt.IsCorrect,
})
res := buildQuestionRes(q, catalog)
for i := range res.Options {
res.Options[i].IsCorrect = false
}
var shortAnswers []shortAnswerRes
for _, sa := range q.ShortAnswers {
shortAnswers = append(shortAnswers, shortAnswerRes{
ID: sa.ID,
AcceptableAnswer: sa.AcceptableAnswer,
MatchType: sa.MatchType,
})
res.ShortAnswers = nil
res.AudioCorrectAnswerText = nil
if res.DynamicPayload != nil {
res.DynamicPayload = scrubDynamicCorrectness(res.DynamicPayload)
}
questionResponses = append(questionResponses, questionRes{
ID: q.ID,
QuestionText: questionTextField(q.QuestionType, q.QuestionText),
QuestionType: q.QuestionType,
DifficultyLevel: q.DifficultyLevel,
Points: q.Points,
Status: q.Status,
CreatedAt: q.CreatedAt.String(),
Options: options,
ShortAnswers: shortAnswers,
})
questionResponses = append(questionResponses, res)
}
return c.Status(fiber.StatusOK).JSON(domain.Response{
@ -182,39 +166,192 @@ func (h *Handler) GetAssessmentQuestionByID(c *fiber.Ctx) error {
})
}
var options []optionRes
for _, opt := range question.Options {
options = append(options, optionRes{
ID: opt.ID,
OptionText: opt.OptionText,
OptionOrder: opt.OptionOrder,
IsCorrect: opt.IsCorrect,
})
catalog, _ := h.activeQuestionTypeDefinitionCatalog(c.Context())
res := buildQuestionRes(question, catalog)
for i := range res.Options {
res.Options[i].IsCorrect = false
}
var shortAnswers []shortAnswerRes
for _, sa := range question.ShortAnswers {
shortAnswers = append(shortAnswers, shortAnswerRes{
ID: sa.ID,
AcceptableAnswer: sa.AcceptableAnswer,
MatchType: sa.MatchType,
})
res.ShortAnswers = nil
res.AudioCorrectAnswerText = nil
if res.DynamicPayload != nil {
res.DynamicPayload = scrubDynamicCorrectness(res.DynamicPayload)
}
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Question fetched successfully",
Data: questionRes{
ID: question.ID,
QuestionText: questionTextField(question.QuestionType, question.QuestionText),
QuestionType: question.QuestionType,
DifficultyLevel: question.DifficultyLevel,
Points: question.Points,
Status: question.Status,
CreatedAt: question.CreatedAt.String(),
Options: options,
ShortAnswers: shortAnswers,
},
Message: "Question fetched successfully",
Data: res,
Success: true,
StatusCode: 200,
})
}
func scrubDynamicCorrectness(payload *domain.DynamicQuestionPayload) *domain.DynamicQuestionPayload {
if payload == nil {
return nil
}
clone := *payload
clone.Stimulus = scrubDynamicElements(payload.Stimulus)
clone.Response = scrubDynamicElements(payload.Response)
return &clone
}
func scrubDynamicElements(els []domain.DynamicElementInstance) []domain.DynamicElementInstance {
if len(els) == 0 {
return els
}
out := make([]domain.DynamicElementInstance, len(els))
for i, el := range els {
out[i] = el
m, ok := el.Value.(map[string]interface{})
if !ok {
continue
}
rawOpts, ok := m["options"].([]interface{})
if !ok {
continue
}
copied := make(map[string]interface{}, len(m))
for k, v := range m {
copied[k] = v
}
opts := make([]interface{}, 0, len(rawOpts))
for _, o := range rawOpts {
om, ok := o.(map[string]interface{})
if !ok {
opts = append(opts, o)
continue
}
clean := make(map[string]interface{}, len(om))
for k, v := range om {
if k == "is_correct" {
continue
}
clean[k] = v
}
opts = append(opts, clean)
}
copied["options"] = opts
out[i].Value = copied
}
return out
}
type submitPlacementAssessmentReq struct {
Answers []domain.PlacementAnswerInput `json:"answers"`
}
// SubmitPlacementAssessment godoc
// @Summary Submit initial placement assessment answers
// @Description Grades answers against the published placement set, maps the score to A1–C2 using admin thresholds, and updates the learner knowledge_level
// @Tags assessment
// @Accept json
// @Produce json
// @Param body body submitPlacementAssessmentReq true "Placement answers"
// @Success 200 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/assessment/submit [post]
func (h *Handler) SubmitPlacementAssessment(c *fiber.Ctx) error {
userID, ok := c.Locals("user_id").(int64)
if !ok || userID <= 0 {
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
Message: "Unauthorized",
Error: "user context required",
})
}
var req submitPlacementAssessmentReq
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
result, err := h.assessmentSvc.SubmitPlacement(c.Context(), userID, req.Answers)
if err != nil {
if errors.Is(err, assessment.ErrPlacementSetNotFound) || errors.Is(err, pgx.ErrNoRows) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Placement assessment not found",
Error: err.Error(),
})
}
if errors.Is(err, assessment.ErrNoGradableQuestions) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Placement assessment has no gradable questions",
Error: err.Error(),
})
}
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Unable to submit placement assessment",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionUserUpdated, domain.ResourceUser, &userID,
fmt.Sprintf("Completed initial assessment with level %s (%.1f%%)", result.Level, result.ScorePercent), nil)
return c.JSON(domain.Response{
Message: "Placement assessment graded successfully",
Data: result,
Success: true,
})
}
// ListInitialAssessmentLevelThresholds godoc
// @Summary List CEFR score thresholds for placement
// @Tags assessment
// @Produce json
// @Success 200 {object} domain.Response
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/assessment/level-thresholds [get]
func (h *Handler) ListInitialAssessmentLevelThresholds(c *fiber.Ctx) error {
rows, err := h.assessmentSvc.ListLevelThresholds(c.Context())
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load level thresholds",
Error: err.Error(),
})
}
return c.JSON(domain.Response{
Message: "Level thresholds fetched successfully",
Data: rows,
Success: true,
})
}
type updateLevelThresholdsReq struct {
Thresholds []domain.InitialAssessmentLevelThreshold `json:"thresholds"`
}
// UpdateInitialAssessmentLevelThresholds godoc
// @Summary Update CEFR score thresholds for placement
// @Tags assessment
// @Accept json
// @Produce json
// @Param body body updateLevelThresholdsReq true "Thresholds A1–C2"
// @Success 200 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/admin/assessment/level-thresholds [put]
func (h *Handler) UpdateInitialAssessmentLevelThresholds(c *fiber.Ctx) error {
var req updateLevelThresholdsReq
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
rows, err := h.assessmentSvc.UpdateLevelThresholds(c.Context(), req.Thresholds)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Unable to update level thresholds",
Error: err.Error(),
})
}
return c.JSON(domain.Response{
Message: "Level thresholds updated successfully",
Data: rows,
Success: true,
})
}

View File

@ -789,20 +789,26 @@ var validInitialAssessmentLevels = map[string]struct{}{
"A2": {},
"B1": {},
"B2": {},
"C1": {},
"C2": {},
}
func normalizeInitialAssessmentLevel(description *string) (string, error) {
func normalizeInitialAssessmentDescription(description *string) string {
if description == nil {
return "", fmt.Errorf("description is required and must be one of: A1, A2, B1, B2")
return "PLACEMENT"
}
level := strings.ToUpper(strings.TrimSpace(*description))
if level == "" {
return "", fmt.Errorf("description is required and must be one of: A1, A2, B1, B2")
text := strings.TrimSpace(*description)
if text == "" {
return "PLACEMENT"
}
if _, ok := validInitialAssessmentLevels[level]; !ok {
return "", fmt.Errorf("description must be one of: A1, A2, B1, B2")
upper := strings.ToUpper(text)
if _, ok := validInitialAssessmentLevels[upper]; ok {
return upper
}
return level, nil
if strings.EqualFold(upper, "PLACEMENT") {
return "PLACEMENT"
}
return text
}
func isSequenceGatedPractice(set domain.QuestionSet) bool {
@ -864,19 +870,12 @@ func (h *Handler) CreateQuestionSet(c *fiber.Ctx) error {
})
}
if strings.EqualFold(req.SetType, string(domain.QuestionSetTypeInitialAssessment)) {
normalizedLevel, err := normalizeInitialAssessmentLevel(req.Description)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid initial assessment level",
Error: err.Error(),
})
}
req.Description = &normalizedLevel
if req.PassingScore == nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid initial assessment set",
Error: "passing_score is required for INITIAL_ASSESSMENT question sets",
})
normalized := normalizeInitialAssessmentDescription(req.Description)
req.Description = &normalized
if req.OwnerType == nil || strings.TrimSpace(*req.OwnerType) == "" {
standalone := "STANDALONE"
req.OwnerType = &standalone
req.OwnerID = nil
}
}
@ -1183,25 +1182,8 @@ func (h *Handler) UpdateQuestionSet(c *fiber.Ctx) error {
if req.Description != nil {
effectiveDescription = req.Description
}
normalizedLevel, err := normalizeInitialAssessmentLevel(effectiveDescription)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid initial assessment level",
Error: err.Error(),
})
}
req.Description = &normalizedLevel
effectivePassingScore := existingSet.PassingScore
if req.PassingScore != nil {
effectivePassingScore = req.PassingScore
}
if effectivePassingScore == nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid initial assessment set",
Error: "passing_score is required for INITIAL_ASSESSMENT question sets",
})
}
normalized := normalizeInitialAssessmentDescription(effectiveDescription)
req.Description = &normalized
}
status := req.Status

View File

@ -193,10 +193,13 @@ func (a *App) initAppRoutes() {
groupV1.Post("/files/audio", a.authMiddleware, h.UploadAudio)
groupV1.Post("/questions/audio-answer", a.authMiddleware, h.SubmitAudioAnswer)
// Assessment questions (public)
// Assessment questions (public list) + authenticated submit
groupV1.Post("/assessment/questions", h.CreateAssessmentQuestion)
groupV1.Get("/assessment/questions", h.ListAssessmentQuestions)
groupV1.Get("/assessment/questions/:id", h.GetAssessmentQuestionByID)
groupV1.Post("/assessment/submit", a.authMiddleware, h.SubmitPlacementAssessment)
groupV1.Get("/admin/assessment/level-thresholds", a.authMiddleware, a.RequirePermission("settings.get"), h.ListInitialAssessmentLevelThresholds)
groupV1.Put("/admin/assessment/level-thresholds", a.authMiddleware, a.RequirePermission("settings.update"), h.UpdateInitialAssessmentLevelThresholds)
// Questions
groupV1.Post("/questions", a.authMiddleware, a.RequirePermission("questions.create"), h.CreateQuestion)