RezinaLMS-BackEnd/internal/web_server/handlers/course_handler.go
Yared Yemane eb1d0c68e2 Speed up API paths with batch question loads, request memoization, and soft caches.
Also replace question options on update so placement grading stays consistent with admin edits, and tune the Postgres pool defaults.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 00:06:43 -07:00

340 lines
11 KiB
Go

package handlers
import (
"Yimaru-Backend/internal/domain"
"Yimaru-Backend/internal/services/courses"
"Yimaru-Backend/internal/services/programs"
lmsprogress "Yimaru-Backend/internal/services/lmsprogress"
"context"
"errors"
"strconv"
"github.com/gofiber/fiber/v2"
)
// CreateCourse godoc
// @Summary Create course
// @Description Create a course under a program. Optional sort_order assigns position within that program (siblings shifted); omit to append after the current highest sort_order in the program.
// @Tags courses
// @Accept json
// @Produce json
// @Param id path int true "Program ID"
// @Param body body domain.CreateCourseInput true "Course"
// @Success 201 {object} domain.Response
// @Failure 400 {object} domain.ErrorResponse
// @Failure 404 {object} domain.ErrorResponse
// @Router /api/v1/programs/{id}/courses [post]
func (h *Handler) CreateCourse(c *fiber.Ctx) error {
programID, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid program id",
Error: err.Error(),
})
}
var req domain.CreateCourseInput
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),
})
}
course, err := h.courseSvc.Create(c.Context(), programID, req)
if err != nil {
if errors.Is(err, programs.ErrProgramNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Program not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to create course",
Error: err.Error(),
})
}
actorID := c.Locals("user_id").(int64)
actorRole := string(c.Locals("role").(domain.Role))
ip := c.IP()
ua := c.Get("User-Agent")
rid := course.ID
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionCourseCreated, domain.ResourceCourse, &rid, "Created course: "+course.Name, nil, &ip, &ua)
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Course created successfully",
Data: course,
Success: true,
StatusCode: fiber.StatusCreated,
})
}
// ListCoursesByProgram godoc
// @Summary List courses by program
// @Tags courses
// @Produce json
// @Param id path int true "Program ID"
// @Param limit query int false "Page size" default(20)
// @Param offset query int false "Offset" default(0)
// @Success 200 {object} domain.Response
// @Failure 404 {object} domain.ErrorResponse
// @Router /api/v1/programs/{id}/courses [get]
func (h *Handler) ListCoursesByProgram(c *fiber.Ctx) error {
programID, err := strconv.ParseInt(c.Params("id"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid program id",
Error: err.Error(),
})
}
limit, _ := strconv.Atoi(c.Query("limit", "20"))
offset, _ := strconv.Atoi(c.Query("offset", "0"))
publishedOnly := !h.canManageLMSCourses(c)
role := c.Locals("role").(domain.Role)
var program domain.Program
if publishedOnly {
// Draft programs hide their courses from non-managers.
p, err := h.programSvc.GetByID(c.Context(), programID)
if err != nil {
if errors.Is(err, programs.ErrProgramNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Program not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load program",
Error: err.Error(),
})
}
if !p.VisibleToLearners() {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Program not found",
Error: programs.ErrProgramNotFound.Error(),
})
}
if err := h.blockLearnerIfNotLMSProgram(c, p); err != nil {
return err
}
program = p
}
items, total, err := h.courseSvc.ListByProgram(c.Context(), programID, publishedOnly, int32(limit), int32(offset))
if err != nil {
if errors.Is(err, programs.ErrProgramNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Program not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to list courses",
Error: err.Error(),
})
}
if publishedOnly {
if program.ID == 0 {
p, err := h.programSvc.GetByID(c.Context(), programID)
if err != nil {
if errors.Is(err, programs.ErrProgramNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Program not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load program",
Error: err.Error(),
})
}
program = p
}
annotateCoursesEffectiveAccessTier(role, items, program)
}
uid := c.Locals("user_id").(int64)
ctx := lmsprogress.WithRequestMemo(c.Context())
for i := range items {
if err := h.lmsProgressSvc.ApplyAccessCourse(ctx, role, uid, &items[i]); err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to build course list",
Error: err.Error(),
})
}
}
return c.JSON(domain.Response{
Message: "Courses retrieved successfully",
Data: fiber.Map{
"courses": items,
"total_count": total,
"limit": limit,
"offset": offset,
},
Success: true,
StatusCode: fiber.StatusOK,
})
}
// GetCourse godoc
// @Summary Get course by ID
// @Tags courses
// @Produce json
// @Param id path int true "Course ID"
// @Success 200 {object} domain.Response
// @Failure 404 {object} domain.ErrorResponse
// @Router /api/v1/courses/{id} [get]
func (h *Handler) GetCourse(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 course id",
Error: err.Error(),
})
}
course, err := h.courseSvc.GetByID(c.Context(), id)
if err != nil {
if errors.Is(err, courses.ErrCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Course not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load course",
Error: err.Error(),
})
}
if !course.VisibleToLearners() && !h.canManageLMSCourses(c) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Course not found",
Error: courses.ErrCourseNotFound.Error(),
})
}
p, err := h.programSvc.GetByID(c.Context(), course.ProgramID)
if err != nil {
if errors.Is(err, programs.ErrProgramNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Course not found",
Error: courses.ErrCourseNotFound.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to load course",
Error: err.Error(),
})
}
if err := h.blockLearnerIfNotLMSProgram(c, p); err != nil {
return err
}
role := c.Locals("role").(domain.Role)
applyCourseEffectiveAccessTier(&course, p, role)
uid := c.Locals("user_id").(int64)
if err := h.lmsProgressSvc.ApplyAccessCourse(c.Context(), role, uid, &course); err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to evaluate course access",
Error: err.Error(),
})
}
return c.JSON(domain.Response{
Message: "Course retrieved successfully",
Data: course,
Success: true,
StatusCode: fiber.StatusOK,
})
}
// UpdateCourse godoc
// @Summary Update course
// @Tags courses
// @Accept json
// @Produce json
// @Param id path int true "Course ID"
// @Param body body domain.UpdateCourseInput true "Fields to update"
// @Success 200 {object} domain.Response
// @Failure 404 {object} domain.ErrorResponse
// @Router /api/v1/courses/{id} [put]
func (h *Handler) UpdateCourse(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 course id",
Error: err.Error(),
})
}
var req domain.UpdateCourseInput
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
course, err := h.courseSvc.Update(c.Context(), id, req)
if err != nil {
if errors.Is(err, courses.ErrCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Course not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to update course",
Error: err.Error(),
})
}
actorID := c.Locals("user_id").(int64)
actorRole := string(c.Locals("role").(domain.Role))
ip := c.IP()
ua := c.Get("User-Agent")
rid := course.ID
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionCourseUpdated, domain.ResourceCourse, &rid, "Updated course: "+course.Name, nil, &ip, &ua)
return c.JSON(domain.Response{
Message: "Course updated successfully",
Data: course,
Success: true,
StatusCode: fiber.StatusOK,
})
}
// DeleteCourse godoc
// @Summary Delete course
// @Tags courses
// @Param id path int true "Course ID"
// @Success 200 {object} domain.Response
// @Failure 404 {object} domain.ErrorResponse
// @Router /api/v1/courses/{id} [delete]
func (h *Handler) DeleteCourse(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 course id",
Error: err.Error(),
})
}
if err := h.courseSvc.Delete(c.Context(), id); err != nil {
if errors.Is(err, courses.ErrCourseNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Course not found",
Error: err.Error(),
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to delete course",
Error: err.Error(),
})
}
actorID := c.Locals("user_id").(int64)
actorRole := string(c.Locals("role").(domain.Role))
ip := c.IP()
ua := c.Get("User-Agent")
go h.activityLogSvc.RecordAction(context.Background(), &actorID, &actorRole, domain.ActionCourseDeleted, domain.ResourceCourse, &id, "Deleted course", nil, &ip, &ua)
return c.JSON(domain.Response{
Message: "Course deleted successfully",
Success: true,
StatusCode: fiber.StatusOK,
})
}