Files
smartmate/backend/api/course.go
LoveLosita 75a44f2edd Version: 0.1.2.dev.260207
feat: ⚠️ 批量导入课程接口支持冲突预检测与冲突提示

- 批量导入课程接口支持预先检测冲突
- 返回并展示具体发生冲突的课程信息 📚💥
- 补全此前规划的冲突提示功能(把大饼补上了 🍞)

refactor: 🧱 使用工作单元模式管理 dao 层事务

- 引入工作单元模式(Unit of Work)统一管理 dao 层
- 新建全局事务,使跨 repo 的 gorm 事务管理更加方便 🔁

fix: 🐛 修复将任务块添加进日程接口的多个问题

- 修复核心逻辑 bug(费了老大劲 😵‍💫)
- 补充并覆盖该接口的多种异常与错误场景测试 🧪
2026-02-07 22:08:13 +08:00

75 lines
2.1 KiB
Go

package api
import (
"context"
"errors"
"net/http"
"time"
"github.com/LoveLosita/smartflow/backend/model"
"github.com/LoveLosita/smartflow/backend/respond"
"github.com/LoveLosita/smartflow/backend/service"
"github.com/gin-gonic/gin"
)
type CourseHandler struct {
// 伸出手:准备接住 Service
service *service.CourseService
}
// NewCourseHandler 创建 CourseHandler 实例
func NewCourseHandler(service *service.CourseService) *CourseHandler {
return &CourseHandler{
service: service,
}
}
func (sa *CourseHandler) CheckUserCourse(c *gin.Context) {
//1.从请求中获取课程信息
var req model.UserCheckCourseRequest
err := c.ShouldBindJSON(&req)
if err != nil {
c.JSON(http.StatusBadRequest, respond.WrongParamType)
return
}
//2.调用 service 层的 CheckSingleCourse 方法进行校验
result := service.CheckSingleCourse(req)
//3.根据校验结果返回响应
if result {
c.JSON(http.StatusOK, respond.Ok)
} else {
c.JSON(http.StatusBadRequest, respond.WrongCourseInfo)
}
}
func (sa *CourseHandler) AddUserCourses(c *gin.Context) {
//1.从请求中获取课程信息
var req model.UserImportCoursesRequest
err := c.ShouldBindJSON(&req)
if err != nil {
c.JSON(http.StatusBadRequest, respond.WrongParamType)
return
}
//2.从上下文获取用户ID
userIDInterface := c.GetInt("user_id")
//3.调用 service 层的 AddUserCoursesIntoSchedule 方法添加课程
// 创建一个带 1 秒超时的上下文
ctx, cancel := context.WithTimeout(c.Request.Context(), 1*time.Second)
defer cancel() // 记得释放资源
conflicts, err := sa.service.AddUserCourses(ctx, req, userIDInterface)
if err != nil {
switch {
case errors.Is(err, respond.WrongParamType), errors.Is(err, respond.WrongCourseInfo),
errors.Is(err, respond.InsertCourseTwice):
c.JSON(http.StatusBadRequest, err)
case errors.Is(err, respond.ScheduleConflict):
c.JSON(http.StatusConflict, respond.RespWithData(respond.ScheduleConflict, conflicts))
default:
c.JSON(http.StatusInternalServerError, respond.InternalError(err))
}
return
}
//4.返回成功响应
c.JSON(http.StatusOK, respond.Ok)
}