RezinaLMS-BackEnd/internal/web_server/handlers/exam_prep_practice_handler.go

690 lines
29 KiB
Go

package handlers
import (
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/services/examprep"
"errors"
"fmt"
"strconv"
"github.com/gofiber/fiber/v2"
)
// CreateExamPrepPracticeFromInput godoc
// @Summary Create practice (optional parents; link later via PUT /practices/:id/parents)
// @Tags learning
// @Param body body domain.CreateExamPrepPracticeInput true "Practice"
// @Router /api/v1/admin/practices [post]
// @Security Bearer
// @Success 201 {object} domain.Response{data=domain.ExamPrepPractice}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) CreateExamPrepPracticeFromInput(c *fiber.Ctx) error {
var req domain.CreateExamPrepPracticeInput
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),
})
}
p, err := h.examPrepSvc.CreateExamPrepPracticeFromInput(c.Context(), req)
if err != nil {
if resp := h.mapCreateExamPrepPracticeError(c, err); resp != nil {
return resp
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to create practice",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionExamPrepPracticeCreated, domain.ResourceExamPrepPractice, &p.ID, "Created exam prep practice: "+p.Title, nil)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Practice created successfully",
Data: p,
Success: true,
StatusCode: fiber.StatusCreated,
})
}
// ListAllExamPrepPractices godoc
// @Summary List practices globally
// @Tags learning
// @Param limit query int false "Page size. Omit (with offset) to return all practices."
// @Param offset query int false "Offset. Defaults to 0 when limit is provided; ignored semantics when both omitted (all rows)."
// @Param unlinked_only query bool false "When true, return only practices with no parent links (admin)"
// @Router /api/v1/admin/practices [get]
// @Router /api/v1/practices [get]
// @Security Bearer
// @Success 200 {object} domain.Response{data=ListAllExamPrepPracticesData}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ListAllExamPrepPractices(c *fiber.Ctx) error {
limit, offset, err := parseOptionalExamPrepPracticePagination(c)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid pagination",
Error: err.Error(),
})
}
publishedOnly := h.hideUnpublishedPractices(c)
unlinkedOnly := false
if h.canManageExamPrepPractices(c) {
unlinkedOnly, _ = strconv.ParseBool(c.Query("unlinked_only", "false"))
}
items, total, err := h.examPrepSvc.ListAllExamPrepPractices(c.Context(), publishedOnly, unlinkedOnly, limit, offset)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to list practices",
Error: err.Error(),
})
}
return h.listExamPrepPracticesResponse(c, items, total, int(limit), int(offset), nil)
}
// CreateExamPrepPractice godoc
// @Summary Create practice (under a lesson; uses shared question_sets)
// @Tags learning
// @Param lessonId path int true "Exam prep lesson ID (unit_module_lessons.id)"
// @Param body body domain.CreateExamPrepPracticeInput true "Practice"
func (h *Handler) CreateExamPrepPractice(c *fiber.Ctx) error {
lessonID, err := strconv.ParseInt(c.Params("lessonId"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid lesson id",
Error: err.Error(),
})
}
var req domain.CreateExamPrepPracticeInput
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),
})
}
p, err := h.examPrepSvc.CreateExamPrepPractice(c.Context(), lessonID, req)
if err != nil {
if resp := h.mapCreateExamPrepPracticeError(c, err); resp != nil {
return resp
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to create practice",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionExamPrepPracticeCreated, domain.ResourceExamPrepPractice, &p.ID, "Created exam prep practice: "+p.Title, nil)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Practice created successfully",
Data: p,
Success: true,
StatusCode: fiber.StatusCreated,
})
}
// ListExamPrepPracticesByLesson godoc
// @Summary List practices for a lesson
// @Tags learning
// @Param lessonId path int true "Exam prep lesson ID"
// @Param limit query int false "Page size. Omit to return all practices for the lesson."
// @Param offset query int false "Offset (used when limit is provided)"
// @Router /api/v1/admin/lessons/{lessonId}/practices [get]
// @Router /api/v1/lessons/{lessonId}/practices [get]
// @Security Bearer
// @Success 200 {object} domain.Response{data=ListExamPrepPracticesByLessonData}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ListExamPrepPracticesByLesson(c *fiber.Ctx) error {
lessonID, err := strconv.ParseInt(c.Params("lessonId"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid lesson id",
Error: err.Error(),
})
}
limit, offset, err := parseOptionalExamPrepPracticePagination(c)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid pagination",
Error: err.Error(),
})
}
publishedOnly := h.hideUnpublishedPractices(c)
items, total, err := h.examPrepSvc.ListExamPrepPracticesByLesson(c.Context(), lessonID, publishedOnly, limit, offset)
if err != nil {
if resp := h.listExamPrepPracticesResponse(c, nil, 0, int(limit), int(offset), err); resp != nil {
return resp
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to list practices",
Error: err.Error(),
})
}
return h.listExamPrepPracticesResponse(c, items, total, int(limit), int(offset), nil)
}
// GetExamPrepPracticeByID godoc
// @Summary Get practice by ID
// @Tags learning
// @Param id path int true "Exam prep practice ID"
// @Router /api/v1/admin/practices/{id} [get]
// @Router /api/v1/practices/{id} [get]
// @Security Bearer
// @Success 200 {object} domain.Response{data=domain.ExamPrepPractice}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) GetExamPrepPracticeByID(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(),
})
}
p, err := h.examPrepSvc.GetExamPrepPracticeByID(c.Context(), id)
if err != nil {
if errors.Is(err, examprep.ErrPracticeNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Practice not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load practice",
Error: err.Error(),
})
}
if !p.VisibleToLearners() && !h.canManageExamPrepPractices(c) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found"})
}
if err := h.enforceExamPrepPracticeSequenceForStudent(c, p.QuestionSetID); err != nil {
return practiceSequenceErrorResponse(c, err)
}
return c.JSON(domain.Response{
Message: "Practice retrieved successfully",
Data: p,
Success: true,
StatusCode: fiber.StatusOK,
})
}
// UpdateExamPrepPractice godoc
// @Summary Update practice
// @Tags learning
// @Param id path int true "Exam prep practice ID"
// @Param body body domain.UpdateExamPrepPracticeInput true "Fields to update"
// @Router /api/v1/admin/practices/{id} [put]
// @Security Bearer
// @Success 200 {object} domain.Response{data=domain.ExamPrepPractice}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) UpdateExamPrepPractice(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.UpdateExamPrepPracticeInput
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
p, err := h.examPrepSvc.UpdateExamPrepPractice(c.Context(), id, req)
if err != nil {
if resp := h.mapCreateExamPrepPracticeError(c, err); resp != nil {
return resp
}
if errors.Is(err, examprep.ErrPracticeNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Practice not found",
Error: err.Error(),
})
}
if errors.Is(err, domain.ErrPersonaNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Persona not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to update practice",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &p.ID, "Updated exam prep practice: "+p.Title, nil)
return c.JSON(domain.Response{
Message: "Practice updated successfully",
Data: p,
Success: true,
StatusCode: fiber.StatusOK,
})
}
// UpdateExamPrepPracticeParents godoc
// @Summary Replace practice parent links
// @Tags learning
// @Param id path int true "Exam prep practice ID"
// @Param body body domain.UpdateExamPrepPracticeParentsInput true "Parent links (replaces all; use empty array to detach)"
// @Router /api/v1/admin/practices/{id}/parents [put]
// @Security Bearer
// @Success 200 {object} domain.Response{data=domain.ExamPrepPractice}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) UpdateExamPrepPracticeParents(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.UpdateExamPrepPracticeParentsInput
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),
})
}
p, err := h.examPrepSvc.UpdateExamPrepPracticeParents(c.Context(), id, req)
if err != nil {
switch {
case errors.Is(err, examprep.ErrPracticeNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found", Error: err.Error()})
case errors.Is(err, examprep.ErrLessonNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Lesson not found", Error: err.Error()})
case errors.Is(err, examprep.ErrUnitNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Chapter not found", Error: err.Error()})
case errors.Is(err, examprep.ErrCatalogCourseNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Course not found", Error: err.Error()})
case errors.Is(err, examprep.ErrInvalidExamPrepPracticeParent):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid parent", Error: err.Error()})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to update practice parents",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &p.ID, "Updated exam prep practice parents: "+p.Title, nil)
return c.JSON(domain.Response{
Message: "Practice parents updated successfully",
Data: p,
Success: true,
StatusCode: fiber.StatusOK,
})
}
// UnlinkExamPrepPracticeParent godoc
// @Summary Unlink one practice parent
// @Tags learning
// @Param id path int true "Exam prep practice ID"
// @Param parentKind path string true "Parent kind (CATALOG_COURSE, UNIT, LESSON)"
// @Param parentId path int true "Parent entity ID"
// @Router /api/v1/admin/practices/{id}/parents/{parentKind}/{parentId} [delete]
// @Security Bearer
// @Success 200 {object} domain.Response{data=domain.ExamPrepPractice}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) UnlinkExamPrepPracticeParent(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(),
})
}
parentID, err := strconv.ParseInt(c.Params("parentId"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid parent id",
Error: err.Error(),
})
}
kind, ok := domain.ParseExamPrepParentKind(c.Params("parentKind"))
if !ok {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid parent kind",
Error: "parent_kind must be CATALOG_COURSE, UNIT, or LESSON",
})
}
p, err := h.examPrepSvc.UnlinkExamPrepPracticeParent(c.Context(), id, domain.ExamPrepPracticeParent{Kind: kind, ID: parentID})
if err != nil {
switch {
case errors.Is(err, examprep.ErrPracticeNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Practice not found", Error: err.Error()})
case errors.Is(err, examprep.ErrInvalidExamPrepPracticeParent):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid parent", Error: err.Error()})
case errors.Is(err, examprep.ErrExamPrepPracticeParentLinkNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Practice is not linked to that parent",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to unlink practice parent",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionExamPrepPracticeUpdated, domain.ResourceExamPrepPractice, &p.ID, "Unlinked exam prep practice parent "+string(kind)+": "+p.Title, nil)
return c.JSON(domain.Response{
Message: "Practice parent unlinked successfully",
Data: p,
Success: true,
StatusCode: fiber.StatusOK,
})
}
// DeleteExamPrepPractice godoc
// @Summary Delete practice
// @Tags learning
// @Param id path int true "Exam prep practice ID"
// @Router /api/v1/admin/practices/{id} [delete]
// @Security Bearer
// @Success 200 {object} MessageResponse
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 404 {object} domain.ErrorResponse "Resource not found"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) DeleteExamPrepPractice(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(),
})
}
if err := h.examPrepSvc.DeleteExamPrepPractice(c.Context(), id); err != nil {
if errors.Is(err, examprep.ErrPracticeNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Practice not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to delete practice",
Error: err.Error(),
})
}
h.recordActivity(c, domain.ActionExamPrepPracticeDeleted, domain.ResourceExamPrepPractice, &id, fmt.Sprintf("Deleted exam prep practice ID: %d", id), nil)
return c.JSON(domain.Response{
Message: "Practice deleted successfully",
Success: true,
StatusCode: fiber.StatusOK,
})
}
func (h *Handler) mapCreateExamPrepPracticeError(c *fiber.Ctx, err error) error {
switch {
case errors.Is(err, examprep.ErrLessonNotFound), errors.Is(err, examprep.ErrUnitNotFound), errors.Is(err, examprep.ErrCatalogCourseNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Parent not found",
Error: err.Error(),
})
case errors.Is(err, domain.ErrPersonaNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Persona not found",
Error: err.Error(),
})
case errors.Is(err, examprep.ErrQuestionSetNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Question set not found",
Error: err.Error(),
})
case errors.Is(err, examprep.ErrInvalidExamPrepPracticeParent):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid parent",
Error: err.Error(),
})
case errors.Is(err, examprep.ErrExamPrepPracticeRequiresPracticeSet), errors.Is(err, examprep.ErrExamPrepQuizRequiresQuizSet):
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: err.Error(),
Error: err.Error(),
})
default:
return nil
}
}
func (h *Handler) listExamPrepPracticesResponse(c *fiber.Ctx, items []domain.ExamPrepPractice, total int64, limit, offset int, notFound error) error {
if notFound != nil {
switch {
case errors.Is(notFound, examprep.ErrLessonNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Lesson not found", Error: notFound.Error()})
case errors.Is(notFound, examprep.ErrUnitNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Chapter not found", Error: notFound.Error()})
case errors.Is(notFound, examprep.ErrCatalogCourseNotFound):
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{Message: "Course not found", Error: notFound.Error()})
}
}
return c.JSON(domain.Response{
Message: "Practices retrieved successfully",
Data: fiber.Map{
"practices": items,
"total_count": total,
"limit": limit,
"offset": offset,
},
Success: true,
StatusCode: fiber.StatusOK,
})
}
// CreateExamPrepPracticeForCatalogCourse godoc
// @Summary Create practice under a course
// @Tags learning
// @Param courseId path int true "Exam prep course ID"
// @Param body body domain.CreateExamPrepPracticeInput true "Practice"
// @Router /api/v1/admin/courses/{courseId}/practices [post]
// @Security Bearer
// @Success 201 {object} domain.Response{data=domain.ExamPrepPractice}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) CreateExamPrepPracticeForCatalogCourse(c *fiber.Ctx) error {
catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid course id", Error: err.Error()})
}
var req domain.CreateExamPrepPracticeInput
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)})
}
p, err := h.examPrepSvc.CreateExamPrepPracticeForCatalogCourse(c.Context(), catalogCourseID, req)
if err != nil {
if resp := h.mapCreateExamPrepPracticeError(c, err); resp != nil {
return resp
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to create practice", Error: err.Error()})
}
h.recordActivity(c, domain.ActionExamPrepPracticeCreated, domain.ResourceExamPrepPractice, &p.ID, "Created exam prep practice: "+p.Title, nil)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Practice created successfully", Data: p, Success: true, StatusCode: fiber.StatusCreated,
})
}
// ListExamPrepPracticesByCatalogCourse godoc
// @Summary List practices for a course
// @Tags learning
// @Param courseId path int true "Exam prep course ID"
// @Param limit query int false "Page size. Omit to return all practices for the course."
// @Param offset query int false "Offset (used when limit is provided)"
// @Router /api/v1/admin/courses/{courseId}/practices [get]
// @Router /api/v1/courses/{courseId}/practices [get]
// @Security Bearer
// @Success 200 {object} domain.Response{data=ListExamPrepPracticesByCatalogCourseData}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ListExamPrepPracticesByCatalogCourse(c *fiber.Ctx) error {
catalogCourseID, err := strconv.ParseInt(c.Params("courseId"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid course id", Error: err.Error()})
}
limit, offset, err := parseOptionalExamPrepPracticePagination(c)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid pagination",
Error: err.Error(),
})
}
publishedOnly := h.hideUnpublishedPractices(c)
items, total, err := h.examPrepSvc.ListExamPrepPracticesByCatalogCourse(c.Context(), catalogCourseID, publishedOnly, limit, offset)
if err != nil {
if resp := h.listExamPrepPracticesResponse(c, nil, 0, int(limit), int(offset), err); resp != nil {
return resp
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to list practices", Error: err.Error()})
}
return h.listExamPrepPracticesResponse(c, items, total, int(limit), int(offset), nil)
}
// CreateExamPrepPracticeForUnit godoc
// @Summary Create practice under a unit
// @Tags learning
// @Param chapterId path int true "Exam prep unit ID"
// @Param body body domain.CreateExamPrepPracticeInput true "Practice"
// @Router /api/v1/admin/chapters/{chapterId}/practices [post]
// @Security Bearer
// @Success 201 {object} domain.Response{data=domain.ExamPrepPractice}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) CreateExamPrepPracticeForUnit(c *fiber.Ctx) error {
unitID, err := strconv.ParseInt(c.Params("chapterId"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid chapter id", Error: err.Error()})
}
var req domain.CreateExamPrepPracticeInput
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)})
}
p, err := h.examPrepSvc.CreateExamPrepPracticeForUnit(c.Context(), unitID, req)
if err != nil {
if resp := h.mapCreateExamPrepPracticeError(c, err); resp != nil {
return resp
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to create practice", Error: err.Error()})
}
h.recordActivity(c, domain.ActionExamPrepPracticeCreated, domain.ResourceExamPrepPractice, &p.ID, "Created exam prep practice: "+p.Title, nil)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Practice created successfully", Data: p, Success: true, StatusCode: fiber.StatusCreated,
})
}
// ListExamPrepPracticesByUnit godoc
// @Summary List practices for a unit
// @Tags learning
// @Param chapterId path int true "Exam prep unit ID"
// @Param limit query int false "Page size. Omit to return all practices for the unit."
// @Param offset query int false "Offset (used when limit is provided)"
// @Router /api/v1/admin/chapters/{chapterId}/practices [get]
// @Router /api/v1/chapters/{chapterId}/practices [get]
// @Security Bearer
// @Success 200 {object} domain.Response{data=ListExamPrepPracticesByUnitData}
// @Produce json
// @Failure 401 {string} string "Missing, invalid, or expired Bearer token"
// @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation"
// @Failure 400 {object} domain.ErrorResponse "Invalid request"
// @Failure 500 {object} domain.ErrorResponse "Internal server error"
func (h *Handler) ListExamPrepPracticesByUnit(c *fiber.Ctx) error {
unitID, err := strconv.ParseInt(c.Params("chapterId"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid chapter id", Error: err.Error()})
}
limit, offset, err := parseOptionalExamPrepPracticePagination(c)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid pagination",
Error: err.Error(),
})
}
publishedOnly := h.hideUnpublishedPractices(c)
items, total, err := h.examPrepSvc.ListExamPrepPracticesByUnit(c.Context(), unitID, publishedOnly, limit, offset)
if err != nil {
if resp := h.listExamPrepPracticesResponse(c, nil, 0, int(limit), int(offset), err); resp != nil {
return resp
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to list practices", Error: err.Error()})
}
return h.listExamPrepPracticesResponse(c, items, total, int(limit), int(offset), nil)
}
// parseOptionalExamPrepPracticePagination returns limit/offset for practice lists.
// When limit is omitted, limit=0 means "return all" (no SQL LIMIT).
// When offset is omitted, offset defaults to 0.
func parseOptionalExamPrepPracticePagination(c *fiber.Ctx) (limit, offset int32, err error) {
if ls := c.Query("limit"); ls != "" {
n, parseErr := strconv.ParseInt(ls, 10, 32)
if parseErr != nil || n < 1 {
return 0, 0, fmt.Errorf("limit must be a positive integer")
}
limit = int32(n)
}
if os := c.Query("offset"); os != "" {
n, parseErr := strconv.ParseInt(os, 10, 32)
if parseErr != nil || n < 0 {
return 0, 0, fmt.Errorf("offset must be a non-negative integer")
}
offset = int32(n)
}
return limit, offset, nil
}