445 lines
15 KiB
Go
445 lines
15 KiB
Go
package handlers
|
|
|
|
import (
|
|
"Rezina-Backend/internal/domain"
|
|
"Rezina-Backend/internal/services/practicecontent"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
func fullPracticeQuestionResponses(
|
|
questions []domain.QuestionWithDetails,
|
|
setItems []domain.QuestionSetItemWithQuestion,
|
|
catalog []domain.QuestionTypeDefinition,
|
|
blocks []domain.PracticeStimulusBlock,
|
|
) []questionRes {
|
|
memberships := domain.MembershipsFromQuestionSetItems(setItems)
|
|
itemByQuestionID := make(map[int64]domain.QuestionSetItemWithQuestion, len(setItems))
|
|
blockStimulusByKey := domain.StimulusByBlockKey(blocks)
|
|
for _, item := range setItems {
|
|
itemByQuestionID[item.QuestionID] = item
|
|
}
|
|
|
|
out := make([]questionRes, 0, len(questions))
|
|
for _, question := range questions {
|
|
res := buildQuestionRes(question, catalog)
|
|
if item, ok := itemByQuestionID[question.ID]; ok {
|
|
order := item.DisplayOrder
|
|
res.DisplayOrder = &order
|
|
res.AssociatedQuestionID = item.AssociatedQuestionID
|
|
res.StimulusBlockKey = item.StimulusBlockKey
|
|
res.PrerequisiteQuestionIDs = domain.PrerequisiteQuestionIDs(memberships, question.ID)
|
|
payloadForMerge := res.DynamicPayload
|
|
if item.StimulusBlockKey != nil {
|
|
if blockStimulus, ok := blockStimulusByKey[*item.StimulusBlockKey]; ok {
|
|
res.EffectiveDynamicPayload = domain.MergeEffectiveDynamicPayload(blockStimulus, payloadForMerge)
|
|
} else if payloadForMerge != nil {
|
|
res.EffectiveDynamicPayload = domain.MergeEffectiveDynamicPayload(nil, payloadForMerge)
|
|
}
|
|
} else if payloadForMerge != nil {
|
|
res.EffectiveDynamicPayload = domain.MergeEffectiveDynamicPayload(nil, payloadForMerge)
|
|
}
|
|
}
|
|
out = append(out, res)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func asLMSPractice(v interface{}) (domain.Practice, bool) {
|
|
switch p := v.(type) {
|
|
case domain.Practice:
|
|
return p, true
|
|
case *domain.Practice:
|
|
if p == nil {
|
|
return domain.Practice{}, false
|
|
}
|
|
return *p, true
|
|
default:
|
|
return domain.Practice{}, false
|
|
}
|
|
}
|
|
|
|
func asExamPrepPractice(v interface{}) (domain.ExamPrepPractice, bool) {
|
|
switch p := v.(type) {
|
|
case domain.ExamPrepPractice:
|
|
return p, true
|
|
case *domain.ExamPrepPractice:
|
|
if p == nil {
|
|
return domain.ExamPrepPractice{}, false
|
|
}
|
|
return *p, true
|
|
default:
|
|
return domain.ExamPrepPractice{}, false
|
|
}
|
|
}
|
|
|
|
func (h *Handler) buildFullPracticeResponse(
|
|
ctx context.Context,
|
|
result domain.FullUpdatePracticeResult,
|
|
catalog []domain.QuestionTypeDefinition,
|
|
) (fiber.Map, error) {
|
|
items, err := h.questionsSvc.GetQuestionSetItems(ctx, result.QuestionSet.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
present := make(map[int64]struct{}, len(result.Questions))
|
|
for _, q := range result.Questions {
|
|
present[q.ID] = struct{}{}
|
|
}
|
|
// Drop orphaned set membership rows (question deleted from bank) so response
|
|
// building stays aligned with the questions we successfully loaded.
|
|
filteredItems := make([]domain.QuestionSetItemWithQuestion, 0, len(items))
|
|
for _, item := range items {
|
|
if _, ok := present[item.QuestionID]; ok {
|
|
filteredItems = append(filteredItems, item)
|
|
}
|
|
}
|
|
questionCount := int64(len(filteredItems))
|
|
qsRes := questionSetResFromDomain(result.QuestionSet)
|
|
qsRes.QuestionCount = &questionCount
|
|
return fiber.Map{
|
|
"practice": result.Practice,
|
|
"question_set": qsRes,
|
|
"stimulus_blocks": result.StimulusBlocks,
|
|
"questions": fullPracticeQuestionResponses(result.Questions, filteredItems, catalog, result.StimulusBlocks),
|
|
}, nil
|
|
}
|
|
|
|
func questionSetResFromDomain(set domain.QuestionSet) questionSetRes {
|
|
return questionSetRes{
|
|
ID: set.ID,
|
|
Title: set.Title,
|
|
Description: set.Description,
|
|
SetType: set.SetType,
|
|
OwnerType: set.OwnerType,
|
|
OwnerID: set.OwnerID,
|
|
BannerImage: set.BannerImage,
|
|
Persona: set.Persona,
|
|
TimeLimitMinutes: set.TimeLimitMinutes,
|
|
PassingScore: set.PassingScore,
|
|
ShuffleQuestions: set.ShuffleQuestions,
|
|
Status: set.Status,
|
|
IntroVideoURL: set.IntroVideoURL,
|
|
CreatedAt: set.CreatedAt.String(),
|
|
}
|
|
}
|
|
|
|
func mapPracticeFullError(err error, action string) (int, string) {
|
|
switch {
|
|
case errors.Is(err, practicecontent.ErrPracticeNotFound):
|
|
return fiber.StatusNotFound, "Practice not found"
|
|
case errors.Is(err, practicecontent.ErrQuestionSetNotFound):
|
|
return fiber.StatusNotFound, "Question set not found"
|
|
case errors.Is(err, practicecontent.ErrQuestionNotFound):
|
|
return fiber.StatusNotFound, "Question not found"
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
return fiber.StatusNotFound, "Practice content not found"
|
|
case errors.Is(err, domain.ErrPersonaNotFound):
|
|
return fiber.StatusNotFound, "Persona not found"
|
|
case errors.Is(err, practicecontent.ErrInvalidQuestionItem):
|
|
return fiber.StatusBadRequest, "Invalid question item"
|
|
case errors.Is(err, practicecontent.ErrInvalidQuestionAssociation):
|
|
return fiber.StatusBadRequest, "Invalid question association"
|
|
case errors.Is(err, practicecontent.ErrInvalidStimulusBlock):
|
|
return fiber.StatusBadRequest, "Invalid stimulus block"
|
|
default:
|
|
if action == "load" {
|
|
// Include the underlying cause in Message so admin UIs that only
|
|
// surface `message` still show enough detail to diagnose.
|
|
if err != nil && err.Error() != "" {
|
|
return fiber.StatusInternalServerError, "Failed to load practice: " + err.Error()
|
|
}
|
|
return fiber.StatusInternalServerError, "Failed to load practice"
|
|
}
|
|
return fiber.StatusBadRequest, "Failed to update practice"
|
|
}
|
|
}
|
|
|
|
// GetLmsPracticeFull godoc
|
|
// @Summary Get LMS practice with question set and questions
|
|
// @Description Returns practice metadata, linked question set settings, and all questions in the set (same shape as PUT /practices/{id}/full).
|
|
// @Tags practices
|
|
// @Produce json
|
|
// @Param id path int true "Practice ID"
|
|
// @Success 200 {object} domain.Response
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 404 {object} domain.ErrorResponse
|
|
func (h *Handler) GetLmsPracticeFull(c *fiber.Ctx) error {
|
|
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid practice id",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
result, err := h.practiceContentSvc.GetLmsPracticeFull(c.Context(), id)
|
|
if err != nil {
|
|
status, msg := mapPracticeFullError(err, "load")
|
|
return c.Status(status).JSON(domain.ErrorResponse{
|
|
Message: msg,
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
practice, ok := asLMSPractice(result.Practice)
|
|
if !ok {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load practice",
|
|
Error: fmt.Sprintf("unexpected practice type %T", result.Practice),
|
|
})
|
|
}
|
|
if !practice.VisibleToLearners() && !h.canManageLMSPractices(c) {
|
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found"})
|
|
}
|
|
if err := h.applyPracticeAccess(c.Context(), c, []domain.Practice{practice}); err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to build practice",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
result.Practice = practice
|
|
|
|
catalog, err := h.activeQuestionTypeDefinitionCatalog(c.Context())
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load question type catalog",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
data, err := h.buildFullPracticeResponse(c.Context(), result, catalog)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load practice questions",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Practice retrieved successfully",
|
|
Data: data,
|
|
Success: true,
|
|
StatusCode: fiber.StatusOK,
|
|
})
|
|
}
|
|
|
|
// GetExamPrepPracticeFull godoc
|
|
// @Summary Get exam-prep practice with question set and questions
|
|
// @Description Returns exam-prep practice metadata, linked question set settings, and all questions in the set.
|
|
// @Tags exam-prep
|
|
// @Produce json
|
|
// @Param id path int true "Exam prep practice ID"
|
|
// @Success 200 {object} domain.Response
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 404 {object} domain.ErrorResponse
|
|
// @Router /api/v1/admin/exam-prep/practices/{id}/full [get]
|
|
func (h *Handler) GetExamPrepPracticeFull(c *fiber.Ctx) error {
|
|
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid practice id",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
result, err := h.practiceContentSvc.GetExamPrepPracticeFull(c.Context(), id)
|
|
if err != nil {
|
|
status, msg := mapPracticeFullError(err, "load")
|
|
return c.Status(status).JSON(domain.ErrorResponse{
|
|
Message: msg,
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
practice, ok := asExamPrepPractice(result.Practice)
|
|
if !ok {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load practice",
|
|
Error: fmt.Sprintf("unexpected practice type %T", result.Practice),
|
|
})
|
|
}
|
|
if !practice.VisibleToLearners() && !h.canManageExamPrepPractices(c) {
|
|
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found"})
|
|
}
|
|
if err := h.enforceExamPrepPracticeSequenceForStudent(c, practice.QuestionSetID); err != nil {
|
|
return practiceSequenceErrorResponse(c, err)
|
|
}
|
|
|
|
catalog, err := h.activeQuestionTypeDefinitionCatalog(c.Context())
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load question type catalog",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
data, err := h.buildFullPracticeResponse(c.Context(), result, catalog)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load practice questions",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Practice retrieved successfully",
|
|
Data: data,
|
|
Success: true,
|
|
StatusCode: fiber.StatusOK,
|
|
})
|
|
}
|
|
|
|
// UpdateLmsPracticeFull godoc
|
|
// @Summary Full update LMS practice with question set and questions
|
|
// @Description Updates practice metadata, linked question set settings, and syncs questions in one request. Questions omitted from the questions array are removed from the set (not deleted from the bank).
|
|
// @Tags practices
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param id path int true "Practice ID"
|
|
// @Param body body domain.FullUpdatePracticeInput true "Full practice update payload"
|
|
// @Success 200 {object} domain.Response
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 404 {object} domain.ErrorResponse
|
|
func (h *Handler) UpdateLmsPracticeFull(c *fiber.Ctx) error {
|
|
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid practice id",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
var req domain.FullUpdatePracticeInput
|
|
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.practiceContentSvc.UpdateLmsPracticeFull(c.Context(), id, req)
|
|
if err != nil {
|
|
status, msg := mapPracticeFullError(err, "update")
|
|
return c.Status(status).JSON(domain.ErrorResponse{
|
|
Message: msg,
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
catalog, err := h.activeQuestionTypeDefinitionCatalog(c.Context())
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load question type catalog",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
data, err := h.buildFullPracticeResponse(c.Context(), result, catalog)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load practice questions",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
meta, _ := json.Marshal(map[string]interface{}{
|
|
"update_type": "full",
|
|
"practice_id": id,
|
|
"question_set_id": result.QuestionSet.ID,
|
|
"question_count": len(result.Questions),
|
|
})
|
|
msg := fmt.Sprintf("Full update practice ID: %d", id)
|
|
if p, ok := result.Practice.(domain.Practice); ok {
|
|
msg = "Full update practice: " + p.Title
|
|
}
|
|
h.recordActivity(c, domain.ActionPracticeUpdated, domain.ResourcePractice, &id, msg, meta)
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Practice updated successfully",
|
|
Data: data,
|
|
Success: true,
|
|
StatusCode: fiber.StatusOK,
|
|
})
|
|
}
|
|
|
|
// UpdateExamPrepPracticeFull godoc
|
|
// @Summary Full update exam-prep practice with question set and questions
|
|
// @Description Updates exam-prep practice metadata, linked question set settings, and syncs questions in one request.
|
|
// @Tags exam-prep
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param id path int true "Exam prep practice ID"
|
|
// @Param body body domain.FullUpdatePracticeInput true "Full practice update payload"
|
|
// @Success 200 {object} domain.Response
|
|
// @Failure 400 {object} domain.ErrorResponse
|
|
// @Failure 404 {object} domain.ErrorResponse
|
|
// @Router /api/v1/admin/exam-prep/practices/{id}/full [put]
|
|
func (h *Handler) UpdateExamPrepPracticeFull(c *fiber.Ctx) error {
|
|
id, err := strconv.ParseInt(c.Params("id"), 10, 64)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
|
Message: "Invalid practice id",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
var req domain.FullUpdatePracticeInput
|
|
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.practiceContentSvc.UpdateExamPrepPracticeFull(c.Context(), id, req)
|
|
if err != nil {
|
|
status, msg := mapPracticeFullError(err, "update")
|
|
return c.Status(status).JSON(domain.ErrorResponse{
|
|
Message: msg,
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
catalog, err := h.activeQuestionTypeDefinitionCatalog(c.Context())
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load question type catalog",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
data, err := h.buildFullPracticeResponse(c.Context(), result, catalog)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
Message: "Failed to load practice questions",
|
|
Error: err.Error(),
|
|
})
|
|
}
|
|
|
|
meta, _ := json.Marshal(map[string]interface{}{
|
|
"update_type": "full",
|
|
"practice_id": id,
|
|
"question_set_id": result.QuestionSet.ID,
|
|
"question_count": len(result.Questions),
|
|
})
|
|
msg := fmt.Sprintf("Full update exam-prep practice ID: %d", id)
|
|
if p, ok := result.Practice.(domain.ExamPrepPractice); ok {
|
|
msg = "Full update exam-prep practice: " + p.Title
|
|
}
|
|
h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &id, msg, meta)
|
|
|
|
return c.JSON(domain.Response{
|
|
Message: "Practice updated successfully",
|
|
Data: data,
|
|
Success: true,
|
|
StatusCode: fiber.StatusOK,
|
|
})
|
|
}
|