RezinaLMS-BackEnd/internal/web_server/handlers/initial_assessment.go
Yared Yemane efed1b366f 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>
2026-07-31 04:22:19 -07:00

358 lines
11 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
// @Summary Create assessment question
// @Description Creates a new assessment question using the unified questions system
// @Tags assessment-question
// @Accept json
// @Produce json
// @Param body body createQuestionReq true "Create question payload"
// @Success 201 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/assessment/questions [post]
func (h *Handler) CreateAssessmentQuestion(c *fiber.Ctx) error {
var req createQuestionReq
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
questionType := normalizeRuntimeQuestionType(req.QuestionType)
questionText, err := resolveStoredQuestionText(questionType, req.QuestionText, req.DynamicPayload, "")
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid question_text",
Error: err.Error(),
})
}
var options []domain.CreateQuestionOptionInput
for _, opt := range req.Options {
options = append(options, domain.CreateQuestionOptionInput{
OptionText: opt.OptionText,
OptionOrder: opt.OptionOrder,
IsCorrect: opt.IsCorrect,
})
}
var shortAnswers []domain.CreateShortAnswerInput
for _, sa := range req.ShortAnswers {
shortAnswers = append(shortAnswers, domain.CreateShortAnswerInput{
AcceptableAnswer: sa.AcceptableAnswer,
MatchType: sa.MatchType,
})
}
input := domain.CreateQuestionInput{
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)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to create assessment question",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionAssessmentQuestionCreated, domain.ResourceAssessmentQuestion, &question.ID, fmt.Sprintf("Created assessment question ID: %d", question.ID), nil)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Assessment question created successfully",
StatusCode: fiber.StatusCreated,
Success: true,
Data: questionRes{
ID: question.ID,
QuestionText: questionTextField(question.QuestionType, question.QuestionText),
QuestionType: question.QuestionType,
Status: question.Status,
CreatedAt: question.CreatedAt.String(),
},
})
}
// ListAssessmentQuestions godoc
// @Summary List assessment questions
// @Description Returns all active assessment questions from the initial assessment set
// @Tags assessment-question
// @Produce json
// @Success 200 {array} domain.QuestionWithDetails
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/assessment/questions [get]
func (h *Handler) ListAssessmentQuestions(c *fiber.Ctx) error {
questions, err := h.assessmentSvc.ListQuestions(c.Context())
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to fetch assessment questions",
Error: err.Error(),
})
}
catalog, _ := h.activeQuestionTypeDefinitionCatalog(c.Context())
var questionResponses []questionRes
for _, q := range questions {
res := buildQuestionRes(q, catalog)
for i := range res.Options {
res.Options[i].IsCorrect = false
}
res.ShortAnswers = nil
res.AudioCorrectAnswerText = nil
if res.DynamicPayload != nil {
res.DynamicPayload = scrubDynamicCorrectness(res.DynamicPayload)
}
questionResponses = append(questionResponses, res)
}
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "Questions fetched successfully",
Data: questionResponses,
Success: true,
StatusCode: 200,
})
}
// GetAssessmentQuestionByID godoc
// @Summary Get assessment question by ID
// @Description Returns a single assessment question with its options or answer
// @Tags assessment-question
// @Produce json
// @Param id path int true "Question ID"
// @Success 200 {object} domain.QuestionWithDetails
// @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Failure 500 {object} domain.ErrorResponse
// @Router /api/v1/assessment/questions/{id} [get]
func (h *Handler) GetAssessmentQuestionByID(c *fiber.Ctx) error {
idStr := c.Params("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil || id <= 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid question ID",
Error: "question ID must be a positive integer",
})
}
question, err := h.assessmentSvc.GetQuestionByID(c.Context(), id)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to fetch assessment question",
Error: err.Error(),
})
}
catalog, _ := h.activeQuestionTypeDefinitionCatalog(c.Context())
res := buildQuestionRes(question, catalog)
for i := range res.Options {
res.Options[i].IsCorrect = false
}
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: 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,
})
}