Browse Source

重新实现选课接口逻辑,前端传学生Id、班级码classCode和课程ID

zhi.li102 1 year ago
parent
commit
72a8cd6221

+ 0 - 5
add_class_code_column.sql

@@ -1,5 +0,0 @@
--- 在class表中添加class_code字段
-ALTER TABLE class ADD COLUMN class_code VARCHAR(20) NOT NULL COMMENT '班级码' AFTER teacher_id;
-
--- 创建唯一索引确保班级码唯一性
-CREATE UNIQUE INDEX idx_class_code ON class(class_code);

+ 2 - 4
src/main/java/com/njuzr/eaibackend/controller/CourseController.java

@@ -266,19 +266,17 @@ public class CourseController {
      * 新的选课接口,通过班级码将学生加入对应班级
      * @param studentId
      * @param enrollDTO
-     * @param classCode
      * @return
      */
     @PreAuthorize("hasRole('STUDENT')")
     @PostMapping("/enroll")
     public MyResponse enrollByClassCode(
             @AuthenticationPrincipal(expression = "id") Long studentId,
-            @RequestBody EnrollDTO enrollDTO,
-            @RequestParam String classCode
+            @RequestBody EnrollDTO enrollDTO
     ) {
         try {
             enrollDTO.setStudentId(studentId);
-            courseService.enrollByClassCode(enrollDTO, classCode);
+            courseService.enrollByClassCode(enrollDTO);
             return MyResponse.success("选课成功");
         }
         catch (MyException e){

+ 1 - 0
src/main/java/com/njuzr/eaibackend/dto/course/EnrollDTO.java

@@ -14,4 +14,5 @@ import lombok.Data;
 public class EnrollDTO {
     private Long studentId;
     private Long courseId;
+    private String classCode;
 }

+ 1 - 1
src/main/java/com/njuzr/eaibackend/service/CourseService.java

@@ -35,7 +35,7 @@ public interface CourseService {
     void enroll(EnrollDTO enrollDTO);
 
     // 通过班级码选课
-    void enrollByClassCode(EnrollDTO enrollDTO, String classCode);
+    void enrollByClassCode(EnrollDTO enrollDTO);
 
     IPage<UserVO> getEnrollmentsByCourse(Page<User> page, Long teacherId, Long courseId);
 

+ 85 - 80
src/main/java/com/njuzr/eaibackend/service/impl/CourseServiceImpl.java

@@ -11,6 +11,7 @@ import com.njuzr.eaibackend.dto.course.EnrollDTO;
 import com.njuzr.eaibackend.enums.AssignmentCompletionStatus;
 import com.njuzr.eaibackend.enums.Role;
 import com.njuzr.eaibackend.exception.MyException;
+import com.njuzr.eaibackend.mapper.ClassMapper;
 import com.njuzr.eaibackend.mapper.*;
 import com.njuzr.eaibackend.po.*;
 import com.njuzr.eaibackend.service.CourseService;
@@ -63,14 +64,17 @@ public class CourseServiceImpl implements CourseService {
 
     private final ClassStudentMapper classStudentMapper;
 
+    private final ClassMapper classMapper;
+
     @Autowired
-    public CourseServiceImpl(CourseMapper courseMapper, UserMapper userMapper, CourseStudentMapper courseStudentMapper, AssignmentMapper assignmentMapper, StudentAssignmentMapper studentAssignmentMapper, ClassStudentMapper classStudentMapper) {
+    public CourseServiceImpl(CourseMapper courseMapper, UserMapper userMapper, CourseStudentMapper courseStudentMapper, AssignmentMapper assignmentMapper, StudentAssignmentMapper studentAssignmentMapper, ClassStudentMapper classStudentMapper, ClassMapper classMapper) {
         this.courseMapper = courseMapper;
         this.userMapper = userMapper;
         this.courseStudentMapper = courseStudentMapper;
         this.assignmentMapper = assignmentMapper;
         this.studentAssignmentMapper = studentAssignmentMapper;
         this.classStudentMapper = classStudentMapper;
+        this.classMapper = classMapper;
     }
 
 
@@ -327,16 +331,6 @@ public class CourseServiceImpl implements CourseService {
         if (!target.getEnrollCode().equals(enrollDTO.getEnrollCode()))
             throw MyException.create(HttpStatus.BAD_REQUEST, "选课码错误");
 
-        // 检查学生是否已经选过该课程
-        QueryWrapper<CourseStudent> wrapper = new QueryWrapper<>();
-        wrapper.eq("student_id", enrollDTO.getStudentId());
-        wrapper.eq("course_id", enrollDTO.getCourseId());
-        CourseStudent existingCourseStudent = courseStudentMapper.selectOne(wrapper);
-
-        if (existingCourseStudent != null) {
-            throw MyException.create(HttpStatus.BAD_REQUEST, "学生已经选过该课程");
-        }
-
         Enrollment enrollment = ModelMapperUtil.map(enrollDTO, Enrollment.class);
         courseStudentMapper.insert(enrollment);
 
@@ -362,75 +356,6 @@ public class CourseServiceImpl implements CourseService {
         throw MyException.create(HttpStatus.BAD_REQUEST, "失败");
     }
 
-    @Override
-    @Transactional
-    public void enrollByClassCode(EnrollDTO enrollDTO, String classCode) {
-        // 根据班级码查询班级信息
-        QueryWrapper<Class> classWrapper = new QueryWrapper<>();
-        classWrapper.eq("class_code", classCode);
-        Class targetClass = classMapper.selectOne(classWrapper);
-
-        if (targetClass == null) {
-            throw MyException.create(HttpStatus.BAD_REQUEST, "班级码不存在");
-        }
-
-        Long courseId = targetClass.getCourseId();
-        Long classId = targetClass.getClassId();
-
-        // 检查学生是否已经加入了该课程下的其他班级
-        QueryWrapper<ClassStudent> csWrapper = new QueryWrapper<>();
-        csWrapper.eq("student_id", enrollDTO.getStudentId());
-        csWrapper.inSql("class_id", "SELECT class_id FROM class WHERE course_id = " + courseId);
-        ClassStudent existingClassStudent = classStudentMapper.selectOne(csWrapper);
-
-        if (existingClassStudent != null) {
-            throw MyException.create(HttpStatus.BAD_REQUEST, "学生已经加入了该课程下的一个班级");
-        }
-
-        // 检查学生是否已经选过该课程
-        QueryWrapper<CourseStudent> courseStudentWrapper = new QueryWrapper<>();
-        courseStudentWrapper.eq("student_id", enrollDTO.getStudentId());
-        courseStudentWrapper.eq("course_id", courseId);
-        CourseStudent existingCourseStudent = courseStudentMapper.selectOne(courseStudentWrapper);
-
-        if (existingCourseStudent == null) {
-            // 创建新的选课记录
-            Enrollment enrollment = new Enrollment();
-            enrollment.setStudentId(enrollDTO.getStudentId());
-            enrollment.setCourseId(courseId);
-            enrollment.setEnrollTime(new Date());
-            enrollment.setEnrollCode(classCode);
-
-            int status = courseStudentMapper.insert(enrollment);
-            if (status == 0) {
-                log.error("选课失败,数据库插入错误!");
-                throw new MyException(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()+":"+"选课错误");
-            }
-        }
-
-        // 将学生加入班级
-        ClassStudent classStudent = new ClassStudent();
-        classStudent.setStudentId(enrollDTO.getStudentId());
-        classStudent.setClassId(classId);
-        classStudent.setState(1); // 已加入状态
-
-        // 获取学生信息
-        User student = userMapper.selectById(enrollDTO.getStudentId());
-        if (student != null) {
-            classStudent.setOfficialNumber(student.getOfficialNumber());
-            classStudent.setStuName(student.getName());
-        }
-
-        int csStatus = classStudentMapper.insert(classStudent);
-        if (csStatus == 0) {
-            log.error("加入班级失败,数据库插入错误!");
-            throw new MyException(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()+":"+"加入班级错误");
-        }
-
-        // 更新班级人数
-        classMapper.increaseStuNumber(classId, 1);
-    }
-
 
     /**
      * 获取某课程的所有选课学生信息
@@ -521,6 +446,86 @@ public class CourseServiceImpl implements CourseService {
         return course;
     }
 
+    /**
+     * 通过班级码选课
+     * @param enrollDTO 包含学生ID和课程ID
+     */
+    @Override
+    @Transactional
+    public void enrollByClassCode(EnrollDTO enrollDTO) {
+        // 获取班级码
+        String classCode = enrollDTO.getClassCode();
+        Long studentId = enrollDTO.getStudentId();
+        Long courseId = enrollDTO.getCourseId();
+
+        // 根据班级码查询班级信息
+        QueryWrapper<Class> classWrapper = new QueryWrapper<>();
+        classWrapper.eq("class_code", classCode);
+        Class targetClass = classMapper.selectOne(classWrapper);
+
+        if (targetClass == null) {
+            throw MyException.create(HttpStatus.BAD_REQUEST, "班级码不存在");
+        }
+
+        // 验证班级是否属于指定课程
+        if (!targetClass.getCourseId().equals(courseId)) {
+            throw MyException.create(HttpStatus.BAD_REQUEST, "班级码与课程不匹配");
+        }
+
+        Long classId = targetClass.getClassId();
+
+        // 检查学生是否已经加入了该课程下的其他班级
+        QueryWrapper<ClassStudent> csWrapper = new QueryWrapper<>();
+        csWrapper.eq("student_id", studentId);
+        csWrapper.inSql("class_id", "SELECT class_id FROM class WHERE course_id = " + courseId);
+        ClassStudent existingClassStudent = classStudentMapper.selectOne(csWrapper);
+
+        if (existingClassStudent != null) {
+            throw MyException.create(HttpStatus.BAD_REQUEST, "学生已经加入了该课程下的一个班级");
+        }
+
+        // 检查学生是否已经选过该课程
+        QueryWrapper<Enrollment> enrollmentWrapper = new QueryWrapper<>();
+        enrollmentWrapper.eq("student_id", studentId);
+        enrollmentWrapper.eq("course_id", courseId);
+        Enrollment existingEnrollment = courseStudentMapper.selectOne(enrollmentWrapper);
+
+        if (existingEnrollment == null) {
+            // 创建新的选课记录
+            Enrollment enrollment = new Enrollment();
+            enrollment.setStudentId(studentId);
+            enrollment.setCourseId(courseId);
+
+            int status = courseStudentMapper.insert(enrollment);
+            if (status == 0) {
+                log.error("选课失败,数据库插入错误!");
+                throw new MyException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "选课错误");
+            }
+        }
+
+        // 将学生加入班级
+        ClassStudent classStudent = new ClassStudent();
+        classStudent.setStudentId(studentId);
+        classStudent.setClassId(classId);
+        classStudent.setState(ClassStudentState.JOINED); // 已加入状态
+
+        // 获取学生信息
+        User student = userMapper.selectById(studentId);
+        if (student != null) {
+            classStudent.setOfficialNumber(student.getOfficialNumber());
+            classStudent.setStuName(student.getName());
+        }
+
+        int csStatus = classStudentMapper.insert(classStudent);
+        if (csStatus == 0) {
+            log.error("加入班级失败,数据库插入错误!");
+            throw new MyException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "加入班级错误");
+        }
+
+        // 更新班级人数
+        classMapper.increaseStuNumber(classId, 1);
+    }
+
     /**
      * 将PO转换成VO
      * @param course

+ 0 - 48
src/main/java/com/njuzr/eaibackend/util/DatabaseMigrationUtil.java

@@ -1,48 +0,0 @@
-package com.njuzr.eaibackend.util;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.jdbc.core.JdbcTemplate;
-import org.springframework.stereotype.Component;
-import org.springframework.util.FileCopyUtils;
-
-import javax.annotation.PostConstruct;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-
-@Component
-public class DatabaseMigrationUtil {
-
-    @Autowired
-    private JdbcTemplate jdbcTemplate;
-
-    /**
-     * 执行数据库迁移脚本
-     */
-    @PostConstruct
-    public void migrate() {
-        try {
-            // 读取SQL脚本
-            String sql = readSqlScript("add_class_code_column.sql");
-
-            // 执行SQL脚本
-            jdbcTemplate.execute(sql);
-            System.out.println("数据库迁移成功:添加class_code字段");
-        } catch (Exception e) {
-            System.err.println("数据库迁移失败:" + e.getMessage());
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * 读取SQL脚本文件
-     */
-    private String readSqlScript(String fileName) throws IOException {
-        ClassPathResource resource = new ClassPathResource(fileName);
-        try (InputStream inputStream = resource.getInputStream()) {
-            byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
-            return new String(bytes, StandardCharsets.UTF_8);
-        }
-    }
-}