2214 lines
77 KiB
Go
2214 lines
77 KiB
Go
package handlers
|
||
|
||
import (
|
||
"Yimaru-Backend/internal/domain"
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"strconv"
|
||
"strings"
|
||
|
||
"github.com/gofiber/fiber/v2"
|
||
)
|
||
|
||
// Request/Response types for Questions
|
||
|
||
type optionInput struct {
|
||
OptionText string `json:"option_text" validate:"required"`
|
||
OptionOrder *int32 `json:"option_order"`
|
||
IsCorrect bool `json:"is_correct"`
|
||
}
|
||
|
||
type shortAnswerInput struct {
|
||
AcceptableAnswer string `json:"acceptable_answer" validate:"required"`
|
||
MatchType *string `json:"match_type"`
|
||
}
|
||
|
||
type createQuestionReq struct {
|
||
QuestionText *string `json:"question_text,omitempty"`
|
||
QuestionType string `json:"question_type"`
|
||
QuestionTypeDefinitionID *int64 `json:"question_type_definition_id"`
|
||
DynamicPayload *domain.DynamicQuestionPayload `json:"dynamic_payload"`
|
||
DifficultyLevel *string `json:"difficulty_level"`
|
||
Points *int32 `json:"points"`
|
||
Explanation *string `json:"explanation"`
|
||
Tips *string `json:"tips"`
|
||
VoicePrompt *string `json:"voice_prompt"`
|
||
SampleAnswerVoicePrompt *string `json:"sample_answer_voice_prompt"`
|
||
ImageURL *string `json:"image_url"`
|
||
Status *string `json:"status"`
|
||
Options []optionInput `json:"options"`
|
||
ShortAnswers []shortAnswerInput `json:"short_answers"`
|
||
AudioCorrectAnswerText *string `json:"audio_correct_answer_text"`
|
||
}
|
||
|
||
type optionRes struct {
|
||
ID int64 `json:"id"`
|
||
OptionText string `json:"option_text"`
|
||
OptionOrder int32 `json:"option_order"`
|
||
IsCorrect bool `json:"is_correct"`
|
||
}
|
||
|
||
type shortAnswerRes struct {
|
||
ID int64 `json:"id"`
|
||
AcceptableAnswer string `json:"acceptable_answer"`
|
||
MatchType string `json:"match_type"`
|
||
}
|
||
|
||
type questionSharedStimulusRes struct {
|
||
PracticeKind string `json:"practice_kind"`
|
||
PracticeID int64 `json:"practice_id"`
|
||
BlockKey string `json:"block_key"`
|
||
DisplayOrder int32 `json:"display_order"`
|
||
Stimulus []domain.DynamicElementInstance `json:"stimulus"`
|
||
EffectiveDynamicPayload *domain.DynamicQuestionPayload `json:"effective_dynamic_payload,omitempty"`
|
||
}
|
||
|
||
type questionRes struct {
|
||
ID int64 `json:"id"`
|
||
DisplayOrder *int32 `json:"display_order,omitempty"`
|
||
AssociatedQuestionID *int64 `json:"associated_question_id,omitempty"`
|
||
PrerequisiteQuestionIDs []int64 `json:"prerequisite_question_ids,omitempty"`
|
||
StimulusBlockKey *string `json:"stimulus_block_key,omitempty"`
|
||
SharedStimulus []questionSharedStimulusRes `json:"shared_stimulus,omitempty"`
|
||
EffectiveDynamicPayload *domain.DynamicQuestionPayload `json:"effective_dynamic_payload,omitempty"`
|
||
QuestionText *string `json:"question_text,omitempty"`
|
||
QuestionType string `json:"question_type"`
|
||
QuestionTypeDefinitionID *int64 `json:"question_type_definition_id,omitempty"`
|
||
DynamicPayload *domain.DynamicQuestionPayload `json:"dynamic_payload,omitempty"`
|
||
DifficultyLevel *string `json:"difficulty_level,omitempty"`
|
||
Points int32 `json:"points"`
|
||
Explanation *string `json:"explanation,omitempty"`
|
||
Tips *string `json:"tips,omitempty"`
|
||
VoicePrompt *string `json:"voice_prompt,omitempty"`
|
||
SampleAnswerVoicePrompt *string `json:"sample_answer_voice_prompt,omitempty"`
|
||
ImageURL *string `json:"image_url,omitempty"`
|
||
Status string `json:"status"`
|
||
CreatedAt string `json:"created_at"`
|
||
Options []optionRes `json:"options,omitempty"`
|
||
ShortAnswers []shortAnswerRes `json:"short_answers,omitempty"`
|
||
AudioCorrectAnswerText *string `json:"audio_correct_answer_text,omitempty"`
|
||
}
|
||
|
||
type listQuestionsRes struct {
|
||
Questions []questionRes `json:"questions"`
|
||
TotalCount int64 `json:"total_count"`
|
||
}
|
||
|
||
func (h *Handler) activeQuestionTypeDefinitionCatalog(ctx context.Context) ([]domain.QuestionTypeDefinition, error) {
|
||
return h.questionsSvc.ActiveQuestionTypeDefinitionCatalog(ctx)
|
||
}
|
||
|
||
func buildQuestionRes(q domain.QuestionWithDetails, catalog []domain.QuestionTypeDefinition) questionRes {
|
||
outbound := domain.ResolveOutboundQuestionContent(q, catalog)
|
||
|
||
options := make([]optionRes, 0, len(outbound.Options))
|
||
for _, opt := range outbound.Options {
|
||
options = append(options, optionRes{
|
||
ID: opt.ID,
|
||
OptionText: opt.OptionText,
|
||
OptionOrder: opt.OptionOrder,
|
||
IsCorrect: opt.IsCorrect,
|
||
})
|
||
}
|
||
|
||
shortAnswers := make([]shortAnswerRes, 0, len(outbound.ShortAnswers))
|
||
for _, sa := range outbound.ShortAnswers {
|
||
shortAnswers = append(shortAnswers, shortAnswerRes{
|
||
ID: sa.ID,
|
||
AcceptableAnswer: sa.AcceptableAnswer,
|
||
MatchType: sa.MatchType,
|
||
})
|
||
}
|
||
|
||
var optionsPtr []optionRes
|
||
if len(options) > 0 {
|
||
optionsPtr = options
|
||
}
|
||
var shortAnswersPtr []shortAnswerRes
|
||
if len(shortAnswers) > 0 {
|
||
shortAnswersPtr = shortAnswers
|
||
}
|
||
|
||
return questionRes{
|
||
ID: q.ID,
|
||
QuestionText: outbound.QuestionText,
|
||
QuestionType: q.QuestionType,
|
||
QuestionTypeDefinitionID: domain.ResolveEffectiveQuestionTypeDefinitionID(
|
||
q.QuestionTypeDefinitionID,
|
||
q.QuestionType,
|
||
catalog,
|
||
outbound.DynamicPayload,
|
||
),
|
||
DynamicPayload: outbound.DynamicPayload,
|
||
DifficultyLevel: q.DifficultyLevel,
|
||
Points: q.Points,
|
||
Explanation: q.Explanation,
|
||
Tips: q.Tips,
|
||
VoicePrompt: outbound.VoicePrompt,
|
||
SampleAnswerVoicePrompt: outbound.SampleAnswerVoicePrompt,
|
||
ImageURL: outbound.ImageURL,
|
||
Status: q.Status,
|
||
CreatedAt: q.CreatedAt.String(),
|
||
Options: optionsPtr,
|
||
ShortAnswers: shortAnswersPtr,
|
||
AudioCorrectAnswerText: outbound.AudioCorrectAnswerText,
|
||
}
|
||
}
|
||
|
||
func buildQuestionResFromQuestion(q domain.Question, catalog []domain.QuestionTypeDefinition) questionRes {
|
||
return buildQuestionRes(domain.QuestionWithDetails{Question: q}, catalog)
|
||
}
|
||
|
||
func resolveQuestionTypeFromDefinition(def domain.QuestionTypeDefinition) string {
|
||
return domain.ResolveRuntimeQuestionTypeFromDefinition(def.Key, def.ResponseComponentKinds)
|
||
}
|
||
|
||
func normalizeRuntimeQuestionType(v string) string {
|
||
return strings.ToUpper(strings.TrimSpace(v))
|
||
}
|
||
|
||
func optionalTrimmedString(s *string) string {
|
||
if s == nil {
|
||
return ""
|
||
}
|
||
return strings.TrimSpace(*s)
|
||
}
|
||
|
||
func resolveStoredQuestionText(questionType string, explicit *string, payload *domain.DynamicQuestionPayload, existing string) (string, error) {
|
||
exp := optionalTrimmedString(explicit)
|
||
if err := domain.ValidateQuestionTextNotAllowedForDynamic(questionType, exp); err != nil {
|
||
return "", err
|
||
}
|
||
if domain.UsesDynamicQuestionPayload(questionType) {
|
||
return domain.ResolveDynamicStoredQuestionText(payload, existing)
|
||
}
|
||
if exp == "" {
|
||
return "", fmt.Errorf("question_text is required")
|
||
}
|
||
return exp, nil
|
||
}
|
||
|
||
func questionTextField(questionType string, stored string) *string {
|
||
return domain.QuestionTextJSONField(questionType, stored)
|
||
}
|
||
|
||
func activityLogQuestionSummary(questionType string, stored string, payload *domain.DynamicQuestionPayload) string {
|
||
if domain.UsesDynamicQuestionPayload(questionType) {
|
||
if s := domain.StimulusTextFromPayload(payload); s != "" {
|
||
return s
|
||
}
|
||
}
|
||
return stored
|
||
}
|
||
|
||
// CreateQuestion godoc
|
||
// @Summary Create a new question
|
||
// @Description Creates a new question with options (for MCQ/TRUE_FALSE) or short answers (for SHORT_ANSWER). DYNAMIC questions must not send question_text; use dynamic_payload stimulus instead. Legacy types require question_text.
|
||
// @Tags questions
|
||
// @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/questions [post]
|
||
func (h *Handler) CreateQuestion(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)
|
||
if req.QuestionTypeDefinitionID != nil {
|
||
def, err := h.questionsSvc.GetQuestionTypeDefinitionByID(c.Context(), *req.QuestionTypeDefinitionID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question_type_definition_id",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
if questionType == "" {
|
||
questionType = "DYNAMIC"
|
||
}
|
||
if questionType != "DYNAMIC" {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question_type for dynamic definition",
|
||
Error: "question_type must be DYNAMIC when question_type_definition_id is provided",
|
||
})
|
||
}
|
||
if req.DynamicPayload == nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Missing dynamic_payload",
|
||
Error: "dynamic_payload is required when question_type_definition_id is provided",
|
||
})
|
||
}
|
||
if err := domain.ValidateDynamicPayloadAgainstDefinition(*req.DynamicPayload, def); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid dynamic_payload",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
}
|
||
if req.QuestionTypeDefinitionID == nil && req.DynamicPayload != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid dynamic_payload usage",
|
||
Error: "dynamic_payload requires question_type_definition_id",
|
||
})
|
||
}
|
||
if questionType == "" {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question_type",
|
||
Error: "question_type is required when no question_type_definition_id is provided",
|
||
})
|
||
}
|
||
switch questionType {
|
||
case "MCQ", "TRUE_FALSE", "SHORT_ANSWER", "AUDIO", "DYNAMIC":
|
||
default:
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question_type",
|
||
Error: "question_type must be one of MCQ, TRUE_FALSE, SHORT_ANSWER, AUDIO, DYNAMIC",
|
||
})
|
||
}
|
||
if questionType == "DYNAMIC" && req.QuestionTypeDefinitionID == nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid dynamic question",
|
||
Error: "question_type_definition_id is required for DYNAMIC question_type",
|
||
})
|
||
}
|
||
|
||
// Build options input
|
||
var options []domain.CreateQuestionOptionInput
|
||
for _, opt := range req.Options {
|
||
options = append(options, domain.CreateQuestionOptionInput{
|
||
OptionText: opt.OptionText,
|
||
OptionOrder: opt.OptionOrder,
|
||
IsCorrect: opt.IsCorrect,
|
||
})
|
||
}
|
||
|
||
// Build short answers input
|
||
var shortAnswers []domain.CreateShortAnswerInput
|
||
for _, sa := range req.ShortAnswers {
|
||
shortAnswers = append(shortAnswers, domain.CreateShortAnswerInput{
|
||
AcceptableAnswer: sa.AcceptableAnswer,
|
||
MatchType: sa.MatchType,
|
||
})
|
||
}
|
||
|
||
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(),
|
||
})
|
||
}
|
||
|
||
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,
|
||
ImageURL: req.ImageURL,
|
||
Status: req.Status,
|
||
Options: options,
|
||
ShortAnswers: shortAnswers,
|
||
AudioCorrectAnswerText: req.AudioCorrectAnswerText,
|
||
}
|
||
|
||
question, err := h.questionsSvc.CreateQuestion(c.Context(), input)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to create question",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{
|
||
"question_type": question.QuestionType,
|
||
"question_type_definition_id": req.QuestionTypeDefinitionID,
|
||
})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionCreated, domain.ResourceQuestion, &question.ID, "Created question: "+activityLogQuestionSummary(question.QuestionType, question.QuestionText, question.DynamicPayload), meta, &ip, &ua)
|
||
|
||
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(),
|
||
})
|
||
}
|
||
|
||
return c.Status(fiber.StatusCreated).JSON(domain.Response{
|
||
Message: "Question created successfully",
|
||
Data: buildQuestionResFromQuestion(question, catalog),
|
||
})
|
||
}
|
||
|
||
// GetQuestionByID godoc
|
||
// @Summary Get question by ID
|
||
// @Description Returns a question with its options/short answers
|
||
// @Tags questions
|
||
// @Produce json
|
||
// @Param id path int true "Question ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 404 {object} domain.ErrorResponse
|
||
// @Router /api/v1/questions/{id} [get]
|
||
func (h *Handler) GetQuestionByID(c *fiber.Ctx) error {
|
||
idStr := c.Params("id")
|
||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
question, err := h.questionsSvc.GetQuestionWithDetails(c.Context(), id)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||
Message: "Question not found",
|
||
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(),
|
||
})
|
||
}
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question retrieved successfully",
|
||
Data: buildQuestionRes(question, catalog),
|
||
})
|
||
}
|
||
|
||
// ListQuestions godoc
|
||
// @Summary List questions
|
||
// @Description Returns a paginated list of questions with optional filters
|
||
// @Tags questions
|
||
// @Produce json
|
||
// @Param question_type query string false "Question type filter (MCQ, TRUE_FALSE, SHORT_ANSWER)"
|
||
// @Param difficulty query string false "Difficulty level filter (EASY, MEDIUM, HARD)"
|
||
// @Param status query string false "Status filter (DRAFT, PUBLISHED, INACTIVE)"
|
||
// @Param limit query int false "Limit" default(10)
|
||
// @Param offset query int false "Offset" default(0)
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/questions [get]
|
||
func (h *Handler) ListQuestions(c *fiber.Ctx) error {
|
||
questionType := c.Query("question_type")
|
||
difficulty := c.Query("difficulty")
|
||
status := c.Query("status")
|
||
limitStr := c.Query("limit", "10")
|
||
offsetStr := c.Query("offset", "0")
|
||
|
||
limit, _ := strconv.Atoi(limitStr)
|
||
offset, _ := strconv.Atoi(offsetStr)
|
||
|
||
var qTypePtr, diffPtr, statusPtr *string
|
||
if questionType != "" {
|
||
qTypePtr = &questionType
|
||
}
|
||
if difficulty != "" {
|
||
diffPtr = &difficulty
|
||
}
|
||
if status != "" {
|
||
statusPtr = &status
|
||
}
|
||
|
||
questions, totalCount, err := h.questionsSvc.ListQuestions(c.Context(), qTypePtr, diffPtr, statusPtr, int32(limit), int32(offset))
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to list questions",
|
||
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(),
|
||
})
|
||
}
|
||
|
||
questionResponses := make([]questionRes, 0, len(questions))
|
||
for _, q := range questions {
|
||
questionResponses = append(questionResponses, buildQuestionResFromQuestion(q, catalog))
|
||
}
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Questions retrieved successfully",
|
||
Data: listQuestionsRes{
|
||
Questions: questionResponses,
|
||
TotalCount: totalCount,
|
||
},
|
||
})
|
||
}
|
||
|
||
// SearchQuestions godoc
|
||
// @Summary Search questions
|
||
// @Description Search questions by text
|
||
// @Tags questions
|
||
// @Produce json
|
||
// @Param q query string true "Search query"
|
||
// @Param limit query int false "Limit" default(10)
|
||
// @Param offset query int false "Offset" default(0)
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/questions/search [get]
|
||
func (h *Handler) SearchQuestions(c *fiber.Ctx) error {
|
||
query := c.Query("q")
|
||
if query == "" {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Search query is required",
|
||
})
|
||
}
|
||
|
||
limitStr := c.Query("limit", "10")
|
||
offsetStr := c.Query("offset", "0")
|
||
limit, _ := strconv.Atoi(limitStr)
|
||
offset, _ := strconv.Atoi(offsetStr)
|
||
|
||
questions, totalCount, err := h.questionsSvc.SearchQuestions(c.Context(), query, int32(limit), int32(offset))
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to search questions",
|
||
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(),
|
||
})
|
||
}
|
||
|
||
questionResponses := make([]questionRes, 0, len(questions))
|
||
for _, q := range questions {
|
||
questionResponses = append(questionResponses, buildQuestionResFromQuestion(q, catalog))
|
||
}
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Questions retrieved successfully",
|
||
Data: listQuestionsRes{
|
||
Questions: questionResponses,
|
||
TotalCount: totalCount,
|
||
},
|
||
})
|
||
}
|
||
|
||
type updateQuestionReq struct {
|
||
QuestionText *string `json:"question_text"`
|
||
QuestionType *string `json:"question_type"`
|
||
QuestionTypeDefinitionID *int64 `json:"question_type_definition_id"`
|
||
DynamicPayload *domain.DynamicQuestionPayload `json:"dynamic_payload"`
|
||
DifficultyLevel *string `json:"difficulty_level"`
|
||
Points *int32 `json:"points"`
|
||
Explanation *string `json:"explanation"`
|
||
Tips *string `json:"tips"`
|
||
VoicePrompt *string `json:"voice_prompt"`
|
||
SampleAnswerVoicePrompt *string `json:"sample_answer_voice_prompt"`
|
||
ImageURL *string `json:"image_url"`
|
||
Status *string `json:"status"`
|
||
Options []optionInput `json:"options"`
|
||
ShortAnswers []shortAnswerInput `json:"short_answers"`
|
||
AudioCorrectAnswerText *string `json:"audio_correct_answer_text"`
|
||
}
|
||
|
||
// UpdateQuestion godoc
|
||
// @Summary Update a question
|
||
// @Description Updates a question and optionally replaces its options/short answers. Supports question_type_definition_id for dynamic builder-linked questions.
|
||
// @Tags questions
|
||
// @Accept json
|
||
// @Produce json
|
||
// @Param id path int true "Question ID"
|
||
// @Param body body updateQuestionReq true "Update question payload"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/questions/{id} [put]
|
||
func (h *Handler) UpdateQuestion(c *fiber.Ctx) error {
|
||
idStr := c.Params("id")
|
||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
var req updateQuestionReq
|
||
if err := c.BodyParser(&req); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid request body",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
existingQuestion, err := h.questionsSvc.GetQuestionByID(c.Context(), id)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||
Message: "Question not found",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
var options []domain.CreateQuestionOptionInput
|
||
if req.Options != nil {
|
||
options = make([]domain.CreateQuestionOptionInput, 0, len(req.Options))
|
||
for _, opt := range req.Options {
|
||
options = append(options, domain.CreateQuestionOptionInput{
|
||
OptionText: opt.OptionText,
|
||
OptionOrder: opt.OptionOrder,
|
||
IsCorrect: opt.IsCorrect,
|
||
})
|
||
}
|
||
}
|
||
|
||
var shortAnswers []domain.CreateShortAnswerInput
|
||
if req.ShortAnswers != nil {
|
||
shortAnswers = make([]domain.CreateShortAnswerInput, 0, len(req.ShortAnswers))
|
||
for _, sa := range req.ShortAnswers {
|
||
shortAnswers = append(shortAnswers, domain.CreateShortAnswerInput{
|
||
AcceptableAnswer: sa.AcceptableAnswer,
|
||
MatchType: sa.MatchType,
|
||
})
|
||
}
|
||
}
|
||
|
||
questionType := normalizeRuntimeQuestionType(existingQuestion.QuestionType)
|
||
if req.QuestionType != nil {
|
||
questionType = normalizeRuntimeQuestionType(*req.QuestionType)
|
||
}
|
||
effectiveDefinitionID := existingQuestion.QuestionTypeDefinitionID
|
||
if req.QuestionTypeDefinitionID != nil {
|
||
effectiveDefinitionID = req.QuestionTypeDefinitionID
|
||
}
|
||
effectiveDynamicPayload := existingQuestion.DynamicPayload
|
||
if req.DynamicPayload != nil {
|
||
effectiveDynamicPayload = req.DynamicPayload
|
||
}
|
||
|
||
if effectiveDefinitionID != nil {
|
||
def, err := h.questionsSvc.GetQuestionTypeDefinitionByID(c.Context(), *effectiveDefinitionID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question_type_definition_id",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
if questionType == "" {
|
||
questionType = "DYNAMIC"
|
||
}
|
||
if questionType != "DYNAMIC" {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question_type for dynamic definition",
|
||
Error: "question_type must be DYNAMIC when question_type_definition_id is provided",
|
||
})
|
||
}
|
||
if effectiveDynamicPayload == nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Missing dynamic_payload",
|
||
Error: "dynamic_payload is required for dynamic questions",
|
||
})
|
||
}
|
||
if err := domain.ValidateDynamicPayloadAgainstDefinition(*effectiveDynamicPayload, def); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid dynamic_payload",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
}
|
||
if effectiveDefinitionID == nil && req.DynamicPayload != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid dynamic_payload usage",
|
||
Error: "dynamic_payload requires question_type_definition_id",
|
||
})
|
||
}
|
||
|
||
switch questionType {
|
||
case "MCQ", "TRUE_FALSE", "SHORT_ANSWER", "AUDIO", "DYNAMIC":
|
||
default:
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question_type",
|
||
Error: "question_type must be one of MCQ, TRUE_FALSE, SHORT_ANSWER, AUDIO, DYNAMIC",
|
||
})
|
||
}
|
||
if questionType == "DYNAMIC" && effectiveDefinitionID == nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid dynamic question",
|
||
Error: "question_type_definition_id is required for DYNAMIC question_type",
|
||
})
|
||
}
|
||
|
||
questionText, err := resolveStoredQuestionText(questionType, req.QuestionText, effectiveDynamicPayload, existingQuestion.QuestionText)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question_text",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
input := domain.CreateQuestionInput{
|
||
QuestionText: questionText,
|
||
QuestionType: questionType,
|
||
QuestionTypeDefinitionID: effectiveDefinitionID,
|
||
DynamicPayload: effectiveDynamicPayload,
|
||
DifficultyLevel: req.DifficultyLevel,
|
||
Points: req.Points,
|
||
Explanation: req.Explanation,
|
||
Tips: req.Tips,
|
||
VoicePrompt: req.VoicePrompt,
|
||
SampleAnswerVoicePrompt: req.SampleAnswerVoicePrompt,
|
||
ImageURL: req.ImageURL,
|
||
Status: req.Status,
|
||
Options: options,
|
||
ShortAnswers: shortAnswers,
|
||
AudioCorrectAnswerText: req.AudioCorrectAnswerText,
|
||
}
|
||
|
||
err = h.questionsSvc.UpdateQuestion(c.Context(), id, input)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to update question",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{"question_id": id})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionUpdated, domain.ResourceQuestion, &id, fmt.Sprintf("Updated question ID: %d", id), meta, &ip, &ua)
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question updated successfully",
|
||
})
|
||
}
|
||
|
||
// DeleteQuestion godoc
|
||
// @Summary Delete a question
|
||
// @Description Archives a question (soft delete)
|
||
// @Tags questions
|
||
// @Produce json
|
||
// @Param id path int true "Question ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/questions/{id} [delete]
|
||
func (h *Handler) DeleteQuestion(c *fiber.Ctx) error {
|
||
idStr := c.Params("id")
|
||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
err = h.questionsSvc.ArchiveQuestion(c.Context(), id)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to delete question",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{"question_id": id})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionDeleted, domain.ResourceQuestion, &id, fmt.Sprintf("Deleted question ID: %d", id), meta, &ip, &ua)
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question deleted successfully",
|
||
})
|
||
}
|
||
|
||
// Question Set types
|
||
|
||
type createQuestionSetReq struct {
|
||
Title string `json:"title" validate:"required"`
|
||
Description *string `json:"description"`
|
||
SetType string `json:"set_type" validate:"required,oneof=PRACTICE INITIAL_ASSESSMENT QUIZ EXAM SURVEY CAPSTONE"`
|
||
OwnerType *string `json:"owner_type"`
|
||
OwnerID *int64 `json:"owner_id"`
|
||
BannerImage *string `json:"banner_image"`
|
||
Persona *string `json:"persona"`
|
||
TimeLimitMinutes *int32 `json:"time_limit_minutes"`
|
||
PassingScore *int32 `json:"passing_score"`
|
||
ShuffleQuestions *bool `json:"shuffle_questions"`
|
||
Status *string `json:"status"`
|
||
IntroVideoURL *string `json:"intro_video_url"`
|
||
}
|
||
|
||
type questionSetRes struct {
|
||
ID int64 `json:"id"`
|
||
Title string `json:"title"`
|
||
Description *string `json:"description,omitempty"`
|
||
SetType string `json:"set_type"`
|
||
OwnerType *string `json:"owner_type,omitempty"`
|
||
OwnerID *int64 `json:"owner_id,omitempty"`
|
||
BannerImage *string `json:"banner_image,omitempty"`
|
||
Persona *string `json:"persona,omitempty"`
|
||
TimeLimitMinutes *int32 `json:"time_limit_minutes,omitempty"`
|
||
PassingScore *int32 `json:"passing_score,omitempty"`
|
||
ShuffleQuestions bool `json:"shuffle_questions"`
|
||
Status string `json:"status"`
|
||
IntroVideoURL *string `json:"intro_video_url,omitempty"`
|
||
CreatedAt string `json:"created_at"`
|
||
QuestionCount *int64 `json:"question_count,omitempty"`
|
||
}
|
||
|
||
type listQuestionSetsRes struct {
|
||
QuestionSets []questionSetRes `json:"question_sets"`
|
||
TotalCount int64 `json:"total_count"`
|
||
}
|
||
|
||
var validInitialAssessmentLevels = map[string]struct{}{
|
||
"A1": {},
|
||
"A2": {},
|
||
"B1": {},
|
||
"B2": {},
|
||
"C1": {},
|
||
"C2": {},
|
||
}
|
||
|
||
// normalizeInitialAssessmentDescription stores the CEFR band for per-level placement sets.
|
||
func normalizeInitialAssessmentDescription(description *string) string {
|
||
if description == nil {
|
||
return ""
|
||
}
|
||
text := strings.TrimSpace(*description)
|
||
if text == "" {
|
||
return ""
|
||
}
|
||
upper := strings.ToUpper(text)
|
||
if _, ok := validInitialAssessmentLevels[upper]; ok {
|
||
return upper
|
||
}
|
||
return text
|
||
}
|
||
|
||
func requireInitialAssessmentCEFRDescription(description string) error {
|
||
if _, err := domain.NormalizeCEFRLevel(description); err != nil {
|
||
return fmt.Errorf("INITIAL_ASSESSMENT description must be a CEFR level (A1–C2)")
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func isSequenceGatedPractice(set domain.QuestionSet) bool {
|
||
if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) || set.OwnerType == nil {
|
||
return false
|
||
}
|
||
ot := strings.ToUpper(strings.TrimSpace(*set.OwnerType))
|
||
return ot == "SUB_COURSE" || ot == "SUB_MODULE" || ot == "COURSE" || ot == "MODULE" || ot == "LESSON"
|
||
}
|
||
|
||
func (h *Handler) enforcePracticeSequenceForStudent(c *fiber.Ctx, set domain.QuestionSet) error {
|
||
role := c.Locals("role").(domain.Role)
|
||
if !role.UsesLMSSequentialGating() {
|
||
return nil
|
||
}
|
||
|
||
userID := c.Locals("user_id").(int64)
|
||
|
||
if isSequenceGatedPractice(set) {
|
||
if !strings.EqualFold(set.Status, "PUBLISHED") {
|
||
return fiber.NewError(fiber.StatusNotFound, "Practice not found")
|
||
}
|
||
blockedBy, err := h.questionsSvc.GetFirstIncompletePreviousPractice(c.Context(), userID, set.ID)
|
||
if err != nil {
|
||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to validate practice access")
|
||
}
|
||
if blockedBy != nil {
|
||
return fiber.NewError(
|
||
fiber.StatusForbidden,
|
||
fmt.Sprintf(
|
||
"Complete practice '%s' (display_order=%d) before accessing this one",
|
||
blockedBy.Title,
|
||
blockedBy.DisplayOrder,
|
||
),
|
||
)
|
||
}
|
||
}
|
||
|
||
return h.enforceExamPrepPracticeSequenceForStudent(c, set.ID)
|
||
}
|
||
|
||
// CreateQuestionSet godoc
|
||
// @Summary Create a new question set
|
||
// @Description Creates a new question set (practice, assessment, quiz, exam, or survey)
|
||
// @Tags question-sets
|
||
// @Accept json
|
||
// @Produce json
|
||
// @Param body body createQuestionSetReq true "Create question set payload"
|
||
// @Success 201 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets [post]
|
||
func (h *Handler) CreateQuestionSet(c *fiber.Ctx) error {
|
||
var req createQuestionSetReq
|
||
if err := c.BodyParser(&req); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid request body",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
if strings.EqualFold(req.SetType, string(domain.QuestionSetTypeInitialAssessment)) {
|
||
normalized := normalizeInitialAssessmentDescription(req.Description)
|
||
if err := requireInitialAssessmentCEFRDescription(normalized); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid placement level",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
req.Description = &normalized
|
||
if req.OwnerType == nil || strings.TrimSpace(*req.OwnerType) == "" {
|
||
standalone := "STANDALONE"
|
||
req.OwnerType = &standalone
|
||
req.OwnerID = nil
|
||
}
|
||
}
|
||
|
||
input := domain.CreateQuestionSetInput{
|
||
Title: req.Title,
|
||
Description: req.Description,
|
||
SetType: req.SetType,
|
||
OwnerType: req.OwnerType,
|
||
OwnerID: req.OwnerID,
|
||
BannerImage: req.BannerImage,
|
||
Persona: req.Persona,
|
||
TimeLimitMinutes: req.TimeLimitMinutes,
|
||
PassingScore: req.PassingScore,
|
||
ShuffleQuestions: req.ShuffleQuestions,
|
||
Status: req.Status,
|
||
IntroVideoURL: req.IntroVideoURL,
|
||
}
|
||
|
||
set, err := h.questionsSvc.CreateQuestionSet(c.Context(), input)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to create question set",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
qsMeta, _ := json.Marshal(map[string]interface{}{"title": set.Title, "set_type": set.SetType})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionSetCreated, domain.ResourceQuestionSet, &set.ID, "Created question set: "+set.Title, qsMeta, &ip, &ua)
|
||
|
||
return c.Status(fiber.StatusCreated).JSON(domain.Response{
|
||
Message: "Question set created successfully",
|
||
Data: 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(),
|
||
},
|
||
})
|
||
}
|
||
|
||
// GetQuestionSetByID godoc
|
||
// @Summary Get question set by ID
|
||
// @Description Returns a question set with question count
|
||
// @Tags question-sets
|
||
// @Produce json
|
||
// @Param id path int true "Question Set ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 404 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{id} [get]
|
||
func (h *Handler) GetQuestionSetByID(c *fiber.Ctx) error {
|
||
idStr := c.Params("id")
|
||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
set, err := h.questionsSvc.GetQuestionSetByID(c.Context(), id)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||
Message: "Question set not found",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
if err := h.enforcePracticeSequenceForStudent(c, set); err != nil {
|
||
status := fiber.StatusForbidden
|
||
if ferr, ok := err.(*fiber.Error); ok {
|
||
status = ferr.Code
|
||
}
|
||
return c.Status(status).JSON(domain.ErrorResponse{
|
||
Message: "Practice is locked",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
count, _ := h.questionsSvc.CountQuestionsInSet(c.Context(), id)
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question set retrieved successfully",
|
||
Data: 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(),
|
||
QuestionCount: &count,
|
||
},
|
||
})
|
||
}
|
||
|
||
// GetQuestionSetsByType godoc
|
||
// @Summary Get question sets by type
|
||
// @Description Returns a paginated list of question sets filtered by type
|
||
// @Tags question-sets
|
||
// @Produce json
|
||
// @Param set_type query string true "Set type (PRACTICE, INITIAL_ASSESSMENT, QUIZ, EXAM, SURVEY, CAPSTONE)"
|
||
// @Param limit query int false "Limit" default(10)
|
||
// @Param offset query int false "Offset" default(0)
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets [get]
|
||
func (h *Handler) GetQuestionSetsByType(c *fiber.Ctx) error {
|
||
setType := c.Query("set_type")
|
||
if setType == "" {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "set_type query parameter is required",
|
||
})
|
||
}
|
||
|
||
limitStr := c.Query("limit", "10")
|
||
offsetStr := c.Query("offset", "0")
|
||
limit, _ := strconv.Atoi(limitStr)
|
||
offset, _ := strconv.Atoi(offsetStr)
|
||
|
||
sets, totalCount, err := h.questionsSvc.GetQuestionSetsByType(c.Context(), setType, int32(limit), int32(offset))
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to get question sets",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
setResponses := make([]questionSetRes, 0, len(sets))
|
||
for _, s := range sets {
|
||
setResponses = append(setResponses, questionSetRes{
|
||
ID: s.ID,
|
||
Title: s.Title,
|
||
Description: s.Description,
|
||
SetType: s.SetType,
|
||
OwnerType: s.OwnerType,
|
||
OwnerID: s.OwnerID,
|
||
BannerImage: s.BannerImage,
|
||
Persona: s.Persona,
|
||
TimeLimitMinutes: s.TimeLimitMinutes,
|
||
PassingScore: s.PassingScore,
|
||
ShuffleQuestions: s.ShuffleQuestions,
|
||
Status: s.Status,
|
||
IntroVideoURL: s.IntroVideoURL,
|
||
CreatedAt: s.CreatedAt.String(),
|
||
})
|
||
}
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question sets retrieved successfully",
|
||
Success: true,
|
||
StatusCode: fiber.StatusOK,
|
||
Data: listQuestionSetsRes{
|
||
QuestionSets: setResponses,
|
||
TotalCount: totalCount,
|
||
},
|
||
})
|
||
}
|
||
|
||
// GetQuestionSetsByOwner godoc
|
||
// @Summary Get question sets by owner
|
||
// @Description Returns question sets for a specific owner (e.g., sub-course)
|
||
// @Tags question-sets
|
||
// @Produce json
|
||
// @Param owner_type query string true "Owner type (SUB_COURSE, COURSE, CATEGORY, STANDALONE)"
|
||
// @Param owner_id query int true "Owner ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/by-owner [get]
|
||
func (h *Handler) GetQuestionSetsByOwner(c *fiber.Ctx) error {
|
||
ownerType := c.Query("owner_type")
|
||
ownerIDStr := c.Query("owner_id")
|
||
|
||
if ownerType == "" || ownerIDStr == "" {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "owner_type and owner_id query parameters are required",
|
||
})
|
||
}
|
||
|
||
ownerID, err := strconv.ParseInt(ownerIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid owner_id",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
sets, err := h.questionsSvc.GetQuestionSetsByOwner(c.Context(), ownerType, ownerID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to get question sets",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
var setResponses []questionSetRes
|
||
for _, s := range sets {
|
||
setResponses = append(setResponses, questionSetRes{
|
||
ID: s.ID,
|
||
Title: s.Title,
|
||
Description: s.Description,
|
||
SetType: s.SetType,
|
||
OwnerType: s.OwnerType,
|
||
OwnerID: s.OwnerID,
|
||
BannerImage: s.BannerImage,
|
||
Persona: s.Persona,
|
||
TimeLimitMinutes: s.TimeLimitMinutes,
|
||
PassingScore: s.PassingScore,
|
||
ShuffleQuestions: s.ShuffleQuestions,
|
||
Status: s.Status,
|
||
IntroVideoURL: s.IntroVideoURL,
|
||
CreatedAt: s.CreatedAt.String(),
|
||
})
|
||
}
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question sets retrieved successfully",
|
||
Success: true,
|
||
StatusCode: fiber.StatusOK,
|
||
Data: setResponses,
|
||
})
|
||
}
|
||
|
||
type updateQuestionSetReq struct {
|
||
Title *string `json:"title"`
|
||
Description *string `json:"description"`
|
||
BannerImage *string `json:"banner_image"`
|
||
Persona *string `json:"persona"`
|
||
TimeLimitMinutes *int32 `json:"time_limit_minutes"`
|
||
PassingScore *int32 `json:"passing_score"`
|
||
ShuffleQuestions *bool `json:"shuffle_questions"`
|
||
Status *string `json:"status"`
|
||
IntroVideoURL *string `json:"intro_video_url"`
|
||
}
|
||
|
||
// UpdateQuestionSet godoc
|
||
// @Summary Update a question set
|
||
// @Description Updates a question set's properties
|
||
// @Tags question-sets
|
||
// @Accept json
|
||
// @Produce json
|
||
// @Param id path int true "Question Set ID"
|
||
// @Param body body updateQuestionSetReq true "Update question set payload"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{id} [put]
|
||
func (h *Handler) UpdateQuestionSet(c *fiber.Ctx) error {
|
||
idStr := c.Params("id")
|
||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
existingSet, err := h.questionsSvc.GetQuestionSetByID(c.Context(), id)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||
Message: "Question set not found",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
var req updateQuestionSetReq
|
||
if err := c.BodyParser(&req); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid request body",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
title := existingSet.Title
|
||
if req.Title != nil {
|
||
title = *req.Title
|
||
}
|
||
|
||
if strings.EqualFold(existingSet.SetType, string(domain.QuestionSetTypeInitialAssessment)) {
|
||
effectiveDescription := existingSet.Description
|
||
if req.Description != nil {
|
||
effectiveDescription = req.Description
|
||
}
|
||
normalized := normalizeInitialAssessmentDescription(effectiveDescription)
|
||
if err := requireInitialAssessmentCEFRDescription(normalized); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid placement level",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
req.Description = &normalized
|
||
}
|
||
|
||
status := req.Status
|
||
if status == nil {
|
||
status = &existingSet.Status
|
||
}
|
||
shuffleQuestions := req.ShuffleQuestions
|
||
if shuffleQuestions == nil {
|
||
shuffleQuestions = &existingSet.ShuffleQuestions
|
||
}
|
||
|
||
input := domain.CreateQuestionSetInput{
|
||
Title: title,
|
||
Description: req.Description,
|
||
BannerImage: req.BannerImage,
|
||
Persona: req.Persona,
|
||
TimeLimitMinutes: req.TimeLimitMinutes,
|
||
PassingScore: req.PassingScore,
|
||
ShuffleQuestions: shuffleQuestions,
|
||
Status: status,
|
||
IntroVideoURL: req.IntroVideoURL,
|
||
}
|
||
|
||
err = h.questionsSvc.UpdateQuestionSet(c.Context(), id, input)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to update question set",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{"question_set_id": id})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionSetUpdated, domain.ResourceQuestionSet, &id, fmt.Sprintf("Updated question set ID: %d", id), meta, &ip, &ua)
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question set updated successfully",
|
||
})
|
||
}
|
||
|
||
// DeleteQuestionSet godoc
|
||
// @Summary Delete a question set
|
||
// @Description Archives a question set (soft delete)
|
||
// @Tags question-sets
|
||
// @Produce json
|
||
// @Param id path int true "Question Set ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{id} [delete]
|
||
func (h *Handler) DeleteQuestionSet(c *fiber.Ctx) error {
|
||
idStr := c.Params("id")
|
||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
err = h.questionsSvc.ArchiveQuestionSet(c.Context(), id)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to delete question set",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{"question_set_id": id})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionSetDeleted, domain.ResourceQuestionSet, &id, fmt.Sprintf("Deleted question set ID: %d", id), meta, &ip, &ua)
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question set deleted successfully",
|
||
})
|
||
}
|
||
|
||
// Question Set Items
|
||
|
||
type addQuestionToSetReq struct {
|
||
QuestionID int64 `json:"question_id" validate:"required"`
|
||
// Omit to append after the current highest display_order in the set; set explicitly to insert at a position.
|
||
DisplayOrder *int32 `json:"display_order,omitempty" validate:"omitempty,min=0"`
|
||
// Section anchor question in the same set; must have a lower display_order and no association of its own.
|
||
AssociatedQuestionID *int64 `json:"associated_question_id,omitempty" validate:"omitempty,min=1"`
|
||
}
|
||
|
||
type questionSetItemRes struct {
|
||
ID int64 `json:"id"`
|
||
SetID int64 `json:"set_id"`
|
||
QuestionID int64 `json:"question_id"`
|
||
DisplayOrder int32 `json:"display_order"`
|
||
AssociatedQuestionID *int64 `json:"associated_question_id,omitempty"`
|
||
PrerequisiteQuestionIDs []int64 `json:"prerequisite_question_ids,omitempty"`
|
||
StimulusBlockKey *string `json:"stimulus_block_key,omitempty"`
|
||
EffectiveDynamicPayload *domain.DynamicQuestionPayload `json:"effective_dynamic_payload,omitempty"`
|
||
QuestionText *string `json:"question_text,omitempty"`
|
||
QuestionType string `json:"question_type"`
|
||
DynamicPayload *domain.DynamicQuestionPayload `json:"dynamic_payload,omitempty"`
|
||
DifficultyLevel *string `json:"difficulty_level,omitempty"`
|
||
Points int32 `json:"points"`
|
||
Explanation *string `json:"explanation,omitempty"`
|
||
Tips *string `json:"tips,omitempty"`
|
||
VoicePrompt *string `json:"voice_prompt,omitempty"`
|
||
SampleAnswerVoicePrompt *string `json:"sample_answer_voice_prompt,omitempty"`
|
||
ImageURL *string `json:"image_url,omitempty"`
|
||
AudioCorrectAnswerText *string `json:"audio_correct_answer_text,omitempty"`
|
||
QuestionStatus string `json:"question_status"`
|
||
}
|
||
|
||
type paginatedQuestionSetItemsRes struct {
|
||
StimulusBlocks []domain.PracticeStimulusBlock `json:"stimulus_blocks"`
|
||
Questions []questionSetItemRes `json:"questions"`
|
||
TotalCount int64 `json:"total_count"`
|
||
Limit int32 `json:"limit"`
|
||
Offset int32 `json:"offset"`
|
||
}
|
||
|
||
func questionSetItemsToRes(
|
||
items []domain.QuestionSetItemWithQuestion,
|
||
catalog []domain.QuestionTypeDefinition,
|
||
blockStimulusByKey map[string][]domain.DynamicElementInstance,
|
||
) []questionSetItemRes {
|
||
memberships := domain.MembershipsFromQuestionSetItems(items)
|
||
out := make([]questionSetItemRes, 0, len(items))
|
||
for _, item := range items {
|
||
q := domain.QuestionWithDetails{
|
||
Question: domain.Question{
|
||
QuestionText: item.QuestionText,
|
||
QuestionType: item.QuestionType,
|
||
DynamicPayload: item.DynamicPayload,
|
||
DifficultyLevel: item.DifficultyLevel,
|
||
Points: item.Points,
|
||
Explanation: item.Explanation,
|
||
Tips: item.Tips,
|
||
VoicePrompt: item.VoicePrompt,
|
||
SampleAnswerVoicePrompt: item.SampleAnswerVoicePrompt,
|
||
ImageURL: item.ImageURL,
|
||
},
|
||
}
|
||
if item.AudioCorrectAnswerText != nil && strings.TrimSpace(*item.AudioCorrectAnswerText) != "" {
|
||
text := strings.TrimSpace(*item.AudioCorrectAnswerText)
|
||
q.AudioAnswer = &domain.QuestionAudioAnswer{CorrectAnswerText: text}
|
||
}
|
||
outbound := domain.ResolveOutboundQuestionContent(q, catalog)
|
||
effectivePayload := outbound.DynamicPayload
|
||
if item.StimulusBlockKey != nil {
|
||
if blockStimulus, ok := blockStimulusByKey[strings.TrimSpace(*item.StimulusBlockKey)]; ok {
|
||
effectivePayload = domain.MergeEffectiveDynamicPayload(blockStimulus, outbound.DynamicPayload)
|
||
}
|
||
}
|
||
|
||
out = append(out, questionSetItemRes{
|
||
ID: item.ID,
|
||
SetID: item.SetID,
|
||
QuestionID: item.QuestionID,
|
||
DisplayOrder: item.DisplayOrder,
|
||
AssociatedQuestionID: item.AssociatedQuestionID,
|
||
PrerequisiteQuestionIDs: domain.PrerequisiteQuestionIDs(memberships, item.QuestionID),
|
||
StimulusBlockKey: item.StimulusBlockKey,
|
||
EffectiveDynamicPayload: effectivePayload,
|
||
QuestionText: outbound.QuestionText,
|
||
QuestionType: item.QuestionType,
|
||
DynamicPayload: outbound.DynamicPayload,
|
||
DifficultyLevel: item.DifficultyLevel,
|
||
Points: item.Points,
|
||
Explanation: item.Explanation,
|
||
Tips: item.Tips,
|
||
VoicePrompt: outbound.VoicePrompt,
|
||
SampleAnswerVoicePrompt: outbound.SampleAnswerVoicePrompt,
|
||
ImageURL: outbound.ImageURL,
|
||
AudioCorrectAnswerText: outbound.AudioCorrectAnswerText,
|
||
QuestionStatus: item.QuestionStatus,
|
||
})
|
||
}
|
||
return out
|
||
}
|
||
|
||
// AddQuestionToSet godoc
|
||
// @Summary Add question to set
|
||
// @Description Links a question to a question set. Omit display_order to append after the current max; the assigned value is returned in the response.
|
||
// @Tags question-set-items
|
||
// @Accept json
|
||
// @Produce json
|
||
// @Param setId path int true "Question Set ID"
|
||
// @Param body body addQuestionToSetReq true "Add question to set payload"
|
||
// @Success 201 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{setId}/questions [post]
|
||
func (h *Handler) AddQuestionToSet(c *fiber.Ctx) error {
|
||
setIDStr := c.Params("setId")
|
||
setID, err := strconv.ParseInt(setIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
var req addQuestionToSetReq
|
||
if err := c.BodyParser(&req); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid request body",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
if valErrs, ok := h.validator.Validate(c, req); !ok {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Validation failed",
|
||
Error: firstValidationError(valErrs),
|
||
})
|
||
}
|
||
|
||
item, err := h.questionsSvc.AddQuestionToSet(c.Context(), setID, req.QuestionID, req.DisplayOrder, req.AssociatedQuestionID)
|
||
if err != nil {
|
||
if errors.Is(err, domain.ErrInvalidQuestionAssociation) {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question association",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to add question to set",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{
|
||
"question_set_id": setID,
|
||
"question_id": req.QuestionID,
|
||
"display_order": req.DisplayOrder,
|
||
})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionSetUpdated, domain.ResourceQuestionSet, &setID, fmt.Sprintf("Added question %d to question set %d", req.QuestionID, setID), meta, &ip, &ua)
|
||
|
||
return c.Status(fiber.StatusCreated).JSON(domain.Response{
|
||
Message: "Question added to set successfully",
|
||
Data: map[string]interface{}{
|
||
"id": item.ID,
|
||
"set_id": item.SetID,
|
||
"question_id": item.QuestionID,
|
||
"display_order": item.DisplayOrder,
|
||
"associated_question_id": item.AssociatedQuestionID,
|
||
},
|
||
})
|
||
}
|
||
|
||
// GetQuestionTypesInSet godoc
|
||
// @Summary List question types in a question set
|
||
// @Description Returns distinct question type definitions (key, display_name, counts) for non-archived questions in the set. Legacy stored question_type values (e.g. AUDIO) are resolved to builder definitions when possible.
|
||
// @Tags question-set-items
|
||
// @Produce json
|
||
// @Param setId path int true "Question Set ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 404 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{setId}/question-types [get]
|
||
func (h *Handler) GetQuestionTypesInSet(c *fiber.Ctx) error {
|
||
setID, err := strconv.ParseInt(c.Params("setId"), 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
if _, err := h.questionsSvc.GetQuestionSetByID(c.Context(), setID); err != nil {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||
Message: "Question set not found",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
summary, err := h.questionsSvc.GetQuestionTypesInSet(c.Context(), setID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to get question types in set",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question types retrieved successfully",
|
||
Success: true,
|
||
StatusCode: fiber.StatusOK,
|
||
Data: summary,
|
||
})
|
||
}
|
||
|
||
type questionSetStimulusContext struct {
|
||
PracticeKind string
|
||
PracticeID int64
|
||
Blocks []domain.PracticeStimulusBlock
|
||
}
|
||
|
||
func (h *Handler) questionSetStimulusContexts(ctx context.Context, setID int64) ([]questionSetStimulusContext, error) {
|
||
contexts := make([]questionSetStimulusContext, 0, 2)
|
||
|
||
lmsPractice, found, err := h.practiceSvc.TryGetByQuestionSetID(ctx, setID)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if found {
|
||
blocks, err := h.practiceContentSvc.GetLmsPracticeStimulusBlocks(ctx, lmsPractice.ID)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
contexts = append(contexts, questionSetStimulusContext{
|
||
PracticeKind: domain.PracticeKindLMS,
|
||
PracticeID: lmsPractice.ID,
|
||
Blocks: blocks,
|
||
})
|
||
}
|
||
|
||
examPractice, found, err := h.examPrepSvc.TryGetExamPrepPracticeByQuestionSetID(ctx, setID)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if found {
|
||
blocks, err := h.practiceContentSvc.GetExamPrepPracticeStimulusBlocks(ctx, examPractice.ID)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
contexts = append(contexts, questionSetStimulusContext{
|
||
PracticeKind: domain.PracticeKindExamPrep,
|
||
PracticeID: examPractice.ID,
|
||
Blocks: blocks,
|
||
})
|
||
}
|
||
|
||
return contexts, nil
|
||
}
|
||
|
||
// GetQuestionSetItems godoc
|
||
// @Summary Get questions in set
|
||
// @Description Returns all questions in a question set with contextual shared stimulus data for linked LMS and exam-prep practices
|
||
// @Tags question-set-items
|
||
// @Produce json
|
||
// @Param setId path int true "Question Set ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{setId}/questions [get]
|
||
func (h *Handler) GetQuestionsInSet(c *fiber.Ctx) error {
|
||
setIDStr := c.Params("setId")
|
||
setID, err := strconv.ParseInt(setIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
set, err := h.questionsSvc.GetQuestionSetByID(c.Context(), setID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||
Message: "Question set not found",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
if err := h.enforcePracticeSequenceForStudent(c, set); err != nil {
|
||
status := fiber.StatusForbidden
|
||
if ferr, ok := err.(*fiber.Error); ok {
|
||
status = ferr.Code
|
||
}
|
||
return c.Status(status).JSON(domain.ErrorResponse{
|
||
Message: "Practice is locked",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
items, err := h.questionsSvc.GetQuestionSetItems(c.Context(), setID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to get questions in set",
|
||
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(),
|
||
})
|
||
}
|
||
|
||
stimulusContexts, err := h.questionSetStimulusContexts(c.Context(), setID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to load shared stimulus data",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
questionResponses := make([]questionRes, 0, len(items))
|
||
memberships := domain.MembershipsFromQuestionSetItems(items)
|
||
ids := make([]int64, 0, len(items))
|
||
for _, item := range items {
|
||
ids = append(ids, item.QuestionID)
|
||
}
|
||
questionsByID, err := h.questionsSvc.GetQuestionsWithDetailsByIDs(c.Context(), ids)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to get question details",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
for _, item := range items {
|
||
question, ok := questionsByID[item.QuestionID]
|
||
if !ok {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to get question details",
|
||
Error: "question not found",
|
||
})
|
||
}
|
||
|
||
res := buildQuestionRes(question, catalog)
|
||
order := item.DisplayOrder
|
||
res.DisplayOrder = &order
|
||
res.AssociatedQuestionID = item.AssociatedQuestionID
|
||
res.PrerequisiteQuestionIDs = domain.PrerequisiteQuestionIDs(memberships, item.QuestionID)
|
||
res.StimulusBlockKey = item.StimulusBlockKey
|
||
res.EffectiveDynamicPayload = domain.MergeEffectiveDynamicPayload(nil, res.DynamicPayload)
|
||
if item.StimulusBlockKey != nil {
|
||
blockKey := strings.TrimSpace(*item.StimulusBlockKey)
|
||
for _, stimulusContext := range stimulusContexts {
|
||
for _, block := range stimulusContext.Blocks {
|
||
if block.BlockKey != blockKey {
|
||
continue
|
||
}
|
||
effectivePayload := domain.MergeEffectiveDynamicPayload(block.Stimulus, res.DynamicPayload)
|
||
res.SharedStimulus = append(res.SharedStimulus, questionSharedStimulusRes{
|
||
PracticeKind: stimulusContext.PracticeKind,
|
||
PracticeID: stimulusContext.PracticeID,
|
||
BlockKey: block.BlockKey,
|
||
DisplayOrder: block.DisplayOrder,
|
||
Stimulus: block.Stimulus,
|
||
EffectiveDynamicPayload: effectivePayload,
|
||
})
|
||
if res.EffectiveDynamicPayload == nil || len(res.SharedStimulus) == 1 {
|
||
res.EffectiveDynamicPayload = effectivePayload
|
||
}
|
||
break
|
||
}
|
||
}
|
||
}
|
||
questionResponses = append(questionResponses, res)
|
||
}
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Questions retrieved successfully",
|
||
Success: true,
|
||
StatusCode: fiber.StatusOK,
|
||
Data: questionResponses,
|
||
})
|
||
}
|
||
|
||
// GetQuestionsByPractice godoc
|
||
// @Summary Get questions by practice
|
||
// @Description Returns paginated questions for an LMS practice, including shared stimulus blocks and each question's effective dynamic payload
|
||
// @Tags question-set-items
|
||
// @Produce json
|
||
// @Param practiceId path int true "LMS practice ID"
|
||
// @Param question_type query string false "Question type filter (e.g. AUDIO)"
|
||
// @Param limit query int false "Limit" default(10)
|
||
// @Param offset query int false "Offset" default(0)
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 404 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/practices/{practiceId}/questions [get]
|
||
func (h *Handler) GetQuestionsByPractice(c *fiber.Ctx) error {
|
||
practiceIDStr := c.Params("practiceId")
|
||
practiceID, err := strconv.ParseInt(practiceIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid practice ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
practice, err := h.practiceSvc.GetByID(c.Context(), practiceID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||
Message: "Practice not found",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
set, err := h.questionsSvc.GetQuestionSetByID(c.Context(), practice.QuestionSetID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||
Message: "Practice question set not found",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Question set is not a practice",
|
||
})
|
||
}
|
||
|
||
if err := h.forbidIfLinkedPracticeDraftForSubscriber(c, set.ID); err != nil {
|
||
code := fiber.StatusInternalServerError
|
||
msg := err.Error()
|
||
var ferr *fiber.Error
|
||
if errors.As(err, &ferr) {
|
||
code = ferr.Code
|
||
msg = ferr.Message
|
||
}
|
||
return c.Status(code).JSON(domain.ErrorResponse{
|
||
Message: msg,
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
if err := h.enforcePracticeSequenceForStudent(c, set); err != nil {
|
||
status := fiber.StatusForbidden
|
||
if ferr, ok := err.(*fiber.Error); ok {
|
||
status = ferr.Code
|
||
}
|
||
return c.Status(status).JSON(domain.ErrorResponse{
|
||
Message: "Practice is locked",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
limit, _ := strconv.Atoi(c.Query("limit", "10"))
|
||
offset, _ := strconv.Atoi(c.Query("offset", "0"))
|
||
questionType := strings.TrimSpace(c.Query("question_type"))
|
||
var qTypePtr *string
|
||
if questionType != "" {
|
||
qTypePtr = &questionType
|
||
}
|
||
if limit <= 0 {
|
||
limit = 10
|
||
}
|
||
if limit > 200 {
|
||
limit = 200
|
||
}
|
||
if offset < 0 {
|
||
offset = 0
|
||
}
|
||
|
||
items, totalCount, err := h.questionsSvc.GetQuestionSetItemsPaginated(c.Context(), practice.QuestionSetID, qTypePtr, int32(limit), int32(offset))
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to get practice questions",
|
||
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(),
|
||
})
|
||
}
|
||
|
||
stimulusBlocks, err := h.practiceContentSvc.GetLmsPracticeStimulusBlocks(c.Context(), practiceID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to load shared stimulus blocks",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
itemResponses := questionSetItemsToRes(items, catalog, domain.StimulusByBlockKey(stimulusBlocks))
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Practice questions retrieved successfully",
|
||
Data: paginatedQuestionSetItemsRes{
|
||
StimulusBlocks: stimulusBlocks,
|
||
Questions: itemResponses,
|
||
TotalCount: totalCount,
|
||
Limit: int32(limit),
|
||
Offset: int32(offset),
|
||
},
|
||
})
|
||
}
|
||
|
||
// CompletePractice godoc
|
||
// @Summary Mark practice as completed
|
||
// @Description Marks a practice question set as completed for the authenticated learner
|
||
// @Tags progression
|
||
// @Produce json
|
||
// @Param id path int true "Practice Question Set ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 403 {object} domain.ErrorResponse
|
||
// @Failure 404 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/progress/practices/{id}/complete [post]
|
||
func (h *Handler) CompletePractice(c *fiber.Ctx) error {
|
||
role := c.Locals("role").(domain.Role)
|
||
if !role.IsCustomerLearnerRole() {
|
||
return c.Status(fiber.StatusForbidden).JSON(domain.ErrorResponse{
|
||
Message: "Only learners can complete practices",
|
||
})
|
||
}
|
||
userID := c.Locals("user_id").(int64)
|
||
|
||
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(),
|
||
})
|
||
}
|
||
|
||
// Prefer LMS practice ID resolution to avoid accidental collisions with question_set IDs.
|
||
practice, practiceErr := h.practiceSvc.GetByID(c.Context(), id)
|
||
var set domain.QuestionSet
|
||
var setErr error
|
||
if practiceErr == nil {
|
||
if !practice.VisibleToLearners() {
|
||
return c.Status(fiber.StatusForbidden).JSON(domain.ErrorResponse{
|
||
Message: "Only published practices can be completed",
|
||
})
|
||
}
|
||
set, setErr = h.questionsSvc.GetQuestionSetByID(c.Context(), practice.QuestionSetID)
|
||
} else if examPractice, examPracticeErr := h.examPrepSvc.GetExamPrepPracticeByID(c.Context(), id); examPracticeErr == nil {
|
||
if !examPractice.VisibleToLearners() {
|
||
return c.Status(fiber.StatusForbidden).JSON(domain.ErrorResponse{
|
||
Message: "Only published practices can be completed",
|
||
})
|
||
}
|
||
set, setErr = h.questionsSvc.GetQuestionSetByID(c.Context(), examPractice.QuestionSetID)
|
||
practiceErr = nil
|
||
} else {
|
||
// Backward compatibility: also accept question_set.id directly.
|
||
set, setErr = h.questionsSvc.GetQuestionSetByID(c.Context(), id)
|
||
}
|
||
if setErr != nil {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
|
||
Message: "Practice not found",
|
||
Error: setErr.Error(),
|
||
})
|
||
}
|
||
if !strings.EqualFold(set.SetType, string(domain.QuestionSetTypePractice)) {
|
||
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found"})
|
||
}
|
||
if !strings.EqualFold(set.Status, "PUBLISHED") {
|
||
return c.Status(fiber.StatusForbidden).JSON(domain.ErrorResponse{
|
||
Message: "Only published practices can be completed",
|
||
})
|
||
}
|
||
if practiceErr != nil {
|
||
if err := h.forbidCompletingDraftPractice(c, set.ID); err != nil {
|
||
code := fiber.StatusInternalServerError
|
||
msg := err.Error()
|
||
var ferr *fiber.Error
|
||
if errors.As(err, &ferr) {
|
||
code = ferr.Code
|
||
msg = ferr.Message
|
||
}
|
||
return c.Status(code).JSON(domain.ErrorResponse{
|
||
Message: msg,
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
}
|
||
|
||
// Enforce sequential gating only for published practices.
|
||
if strings.EqualFold(set.Status, "PUBLISHED") {
|
||
if err := h.enforcePracticeSequenceForStudent(c, set); err != nil {
|
||
return c.Status(fiber.StatusForbidden).JSON(domain.ErrorResponse{
|
||
Message: "You must complete previous practices first",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
}
|
||
|
||
result, err := h.lmsProgressSvc.CompletePracticeForUser(c.Context(), userID, set.ID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to complete practice",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
if h.learnerNotifSvc != nil {
|
||
h.learnerNotifSvc.NotifyLMSPracticeMilestones(userID, result)
|
||
}
|
||
|
||
practiceID := id
|
||
h.recordActivity(c, domain.ActionPracticeCompleted, domain.ResourcePractice, &practiceID, fmt.Sprintf("Completed practice ID: %d", id), nil)
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Practice completed",
|
||
})
|
||
}
|
||
|
||
// RemoveQuestionFromSet godoc
|
||
// @Summary Remove question from set
|
||
// @Description Unlinks a question from a question set
|
||
// @Tags question-set-items
|
||
// @Produce json
|
||
// @Param setId path int true "Question Set ID"
|
||
// @Param questionId path int true "Question ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{setId}/questions/{questionId} [delete]
|
||
func (h *Handler) RemoveQuestionFromSet(c *fiber.Ctx) error {
|
||
setIDStr := c.Params("setId")
|
||
setID, err := strconv.ParseInt(setIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
questionIDStr := c.Params("questionId")
|
||
questionID, err := strconv.ParseInt(questionIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
err = h.questionsSvc.RemoveQuestionFromSet(c.Context(), setID, questionID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to remove question from set",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{
|
||
"question_set_id": setID,
|
||
"question_id": questionID,
|
||
})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionSetUpdated, domain.ResourceQuestionSet, &setID, fmt.Sprintf("Removed question %d from question set %d", questionID, setID), meta, &ip, &ua)
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question removed from set successfully",
|
||
})
|
||
}
|
||
|
||
type updateQuestionOrderReq struct {
|
||
DisplayOrder int32 `json:"display_order" validate:"required"`
|
||
AssociatedQuestionID *int64 `json:"associated_question_id,omitempty" validate:"omitempty,min=1"`
|
||
}
|
||
|
||
// UpdateQuestionOrder godoc
|
||
// @Summary Update question order in set
|
||
// @Description Updates the display order of a question in a set
|
||
// @Tags question-set-items
|
||
// @Accept json
|
||
// @Produce json
|
||
// @Param setId path int true "Question Set ID"
|
||
// @Param questionId path int true "Question ID"
|
||
// @Param body body updateQuestionOrderReq true "Update order payload"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{setId}/questions/{questionId}/order [put]
|
||
func (h *Handler) UpdateQuestionOrderInSet(c *fiber.Ctx) error {
|
||
setIDStr := c.Params("setId")
|
||
setID, err := strconv.ParseInt(setIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
questionIDStr := c.Params("questionId")
|
||
questionID, err := strconv.ParseInt(questionIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
var req updateQuestionOrderReq
|
||
if err := c.BodyParser(&req); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid request body",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
err = h.questionsSvc.UpdateQuestionSetItem(c.Context(), setID, questionID, req.DisplayOrder, req.AssociatedQuestionID)
|
||
if err != nil {
|
||
if errors.Is(err, domain.ErrInvalidQuestionAssociation) {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid question association",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to update question set item",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{
|
||
"question_set_id": setID,
|
||
"question_id": questionID,
|
||
"display_order": req.DisplayOrder,
|
||
})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionSetUpdated, domain.ResourceQuestionSet, &setID, fmt.Sprintf("Updated question %d display_order to %d in set %d", questionID, req.DisplayOrder, setID), meta, &ip, &ua)
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Question order updated successfully",
|
||
})
|
||
}
|
||
|
||
// User Persona types for question sets
|
||
|
||
type userPersonaRes struct {
|
||
ID int64 `json:"id"`
|
||
FirstName *string `json:"first_name,omitempty"`
|
||
LastName *string `json:"last_name,omitempty"`
|
||
NickName *string `json:"nick_name,omitempty"`
|
||
ProfilePictureURL *string `json:"profile_picture_url,omitempty"`
|
||
Role string `json:"role"`
|
||
DisplayOrder int32 `json:"display_order"`
|
||
}
|
||
|
||
type addUserPersonaReq struct {
|
||
UserID int64 `json:"user_id" validate:"required"`
|
||
DisplayOrder int32 `json:"display_order"`
|
||
}
|
||
|
||
// GetUserPersonasByQuestionSet godoc
|
||
// @Summary Get user personas for a question set
|
||
// @Description Returns all users assigned as personas to a question set (practice)
|
||
// @Tags question-sets
|
||
// @Produce json
|
||
// @Param setId path int true "Question Set ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{setId}/personas [get]
|
||
func (h *Handler) GetUserPersonasByQuestionSet(c *fiber.Ctx) error {
|
||
setIDStr := c.Params("setId")
|
||
setID, err := strconv.ParseInt(setIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
personas, err := h.questionsSvc.GetUserPersonasByQuestionSetID(c.Context(), setID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to get personas",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
result := make([]userPersonaRes, len(personas))
|
||
for i, p := range personas {
|
||
result[i] = userPersonaRes{
|
||
ID: p.ID,
|
||
FirstName: p.FirstName,
|
||
LastName: p.LastName,
|
||
NickName: p.NickName,
|
||
ProfilePictureURL: p.ProfilePictureURL,
|
||
Role: p.Role,
|
||
DisplayOrder: p.DisplayOrder,
|
||
}
|
||
}
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Personas retrieved successfully",
|
||
Data: result,
|
||
})
|
||
}
|
||
|
||
// AddUserPersonaToQuestionSet godoc
|
||
// @Summary Add a user as persona to a question set
|
||
// @Description Links a user as a persona to a question set (practice)
|
||
// @Tags question-sets
|
||
// @Accept json
|
||
// @Produce json
|
||
// @Param setId path int true "Question Set ID"
|
||
// @Param body body addUserPersonaReq true "Add user persona payload"
|
||
// @Success 201 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{setId}/personas [post]
|
||
func (h *Handler) AddUserPersonaToQuestionSet(c *fiber.Ctx) error {
|
||
setIDStr := c.Params("setId")
|
||
setID, err := strconv.ParseInt(setIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
var req addUserPersonaReq
|
||
if err := c.BodyParser(&req); err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid request body",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
err = h.questionsSvc.AddUserPersonaToQuestionSet(c.Context(), setID, req.UserID, req.DisplayOrder)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to add persona to question set",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{
|
||
"question_set_id": setID,
|
||
"user_id": req.UserID,
|
||
"display_order": req.DisplayOrder,
|
||
})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionSetUpdated, domain.ResourceQuestionSet, &setID, fmt.Sprintf("Added persona user %d to question set %d", req.UserID, setID), meta, &ip, &ua)
|
||
|
||
return c.Status(fiber.StatusCreated).JSON(domain.Response{
|
||
Message: "Persona added to question set successfully",
|
||
})
|
||
}
|
||
|
||
// RemoveUserPersonaFromQuestionSet godoc
|
||
// @Summary Remove a user persona from a question set
|
||
// @Description Unlinks a user as persona from a question set (practice)
|
||
// @Tags question-sets
|
||
// @Produce json
|
||
// @Param setId path int true "Question Set ID"
|
||
// @Param userId path int true "User ID"
|
||
// @Success 200 {object} domain.Response
|
||
// @Failure 400 {object} domain.ErrorResponse
|
||
// @Failure 500 {object} domain.ErrorResponse
|
||
// @Router /api/v1/question-sets/{setId}/personas/{userId} [delete]
|
||
func (h *Handler) RemoveUserPersonaFromQuestionSet(c *fiber.Ctx) error {
|
||
setIDStr := c.Params("setId")
|
||
setID, err := strconv.ParseInt(setIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid set ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
userIDStr := c.Params("userId")
|
||
userID, err := strconv.ParseInt(userIDStr, 10, 64)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||
Message: "Invalid user ID",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
err = h.questionsSvc.RemoveUserPersonaFromQuestionSet(c.Context(), setID, userID)
|
||
if err != nil {
|
||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||
Message: "Failed to remove persona from question set",
|
||
Error: err.Error(),
|
||
})
|
||
}
|
||
|
||
actorID := c.Locals("user_id").(int64)
|
||
actorRole := string(c.Locals("role").(domain.Role))
|
||
ip := c.IP()
|
||
ua := c.Get("User-Agent")
|
||
meta, _ := json.Marshal(map[string]interface{}{
|
||
"question_set_id": setID,
|
||
"user_id": userID,
|
||
})
|
||
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionQuestionSetUpdated, domain.ResourceQuestionSet, &setID, fmt.Sprintf("Removed persona user %d from question set %d", userID, setID), meta, &ip, &ua)
|
||
|
||
return c.JSON(domain.Response{
|
||
Message: "Persona removed from question set successfully",
|
||
})
|
||
}
|