"...git@gitlab.ruzhoukj.com:wujipeng/practical_train.git" did not exist on "091a5b1ef686ac4f1a0baf18f2dece4b1fe86349"
Commit fe3a8781 authored by wujipeng's avatar wujipeng
Browse files

管理员-教务管理-课程管理

parent 2fea7e12
package com.platform.business.model.dto;
import lombok.Data;
import java.util.List;
/** 管理员一次为同一班级新增多节课程的请求。 */
@Data
public class CourseAdminBatchSaveDTO {
/** 所属班级ID。 */
private Integer classId;
/** 待新增课程,单次最多100节。 */
private List<CourseAdminSaveDTO> courses;
}
package com.platform.business.model.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* 管理员新增或编辑单节课程的请求。
*
* <p>所属班级由批量新增请求或编辑目标记录决定,故本对象不接收classId,防止编辑时
* 通过篡改请求体把课程移动到未经校验的班级。</p>
*/
@Data
public class CourseAdminSaveDTO {
/** 课程日期,格式为yyyy-MM-dd。 */
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date date;
/** 课次/节次数量,允许1到40。 */
private Integer subjectTimes;
/**
* 当天的一个或多个上课时段,格式为HH:mm-HH:mm。
* 接口同时兼容原型中的“~”“—”“–”分隔符,并统一保存为短横线。
*/
private List<String> timeFrames;
/** 课时数,允许0.5到16并以0.5递增。 */
private BigDecimal subjectHour;
/** 课程名称。 */
private String subjectName;
/** 授课教师用户ID,不能提交教师姓名。 */
private String teacherId;
/** 上课地点,选填。 */
private String location;
/** 课程类型:理论、实训或考核。 */
private String type;
/** 课程备注,选填。 */
private String remark;
}
package com.platform.business.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/**
* 班级排课实体。
*
* <p>一条记录表示某个班级的一节课程,可以包含多个不重叠的上课时段。历史表使用
* {@code time_frame} 以逗号拼接时段;管理端接口会把它转换为字符串数组,避免前端
* 直接处理数据库存储格式。</p>
*/
@Data
@TableName("class_subject")
public class ClassSubjectEntity {
......@@ -15,17 +25,28 @@ public class ClassSubjectEntity {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** 课程日期,只保存日期部分。 */
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date date;
/** 所属班级ID。 */
private int classId;
/** 服务端根据课程日期生成的中文星期,例如“周一”。 */
private String week;
/** 课次/节次数量,由课程管理页面填写。 */
private int subjectTimes;
/** 多个时段使用英文逗号分隔,例如“09:00-10:20,10:40-12:00”。 */
private String timeFrame;
private Integer subjectHour;
/**
* 课时数支持0.5课时粒度。
*
* <p>使用BigDecimal而不是double,避免课程汇总时出现二进制浮点误差。</p>
*/
private BigDecimal subjectHour;
private String subjectName;
......@@ -36,6 +57,16 @@ public class ClassSubjectEntity {
@ApiModelProperty(value = "课程地点")
private String location;
@ApiModelProperty(value = "课程类型:理论/实操")
@ApiModelProperty(value = "课程类型:理论/实训/考核")
private String type;
/** 记录创建时间,由管理端新增接口维护。 */
@TableField("create_time")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
/** 最近更新时间,由管理端编辑接口维护。 */
@TableField("update_time")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
}
......@@ -3,6 +3,7 @@ package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/** 班级详情中的逻辑课程汇总项。 */
......@@ -13,7 +14,8 @@ public class ClassAdminCourseVO {
private String type;
private Integer totalHours;
/** 聚合课时,支持0.5课时粒度。 */
private BigDecimal totalHours;
private String teacherId;
......
......@@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
......@@ -17,7 +18,8 @@ public class ClassVO extends ClassEntity {
private Integer studentNum;
private Integer subjectHour;
/** 课程总课时,支持0.5课时粒度。 */
private BigDecimal subjectHour;
private List<ClassStudentVO> classStudentList;
......
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* 课程管理页面右侧完整数据。
*
* <p>班级摘要和课程表一次返回,切换左侧班级节点时无需再拼接多个基础信息接口。</p>
*/
@Data
public class CourseAdminDetailVO {
private Integer classId;
private String className;
private String occupation;
private Integer trainingYear;
/** 根据培训年度和开班月份生成的页面展示值,例如“2026 春”。 */
private String termName;
private String levelId;
private String levelName;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date startDate;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date endDate;
private Integer studentCount;
private Integer courseCount;
private BigDecimal totalHours;
private List<CourseAdminScheduleVO> courses;
}
package com.platform.business.model.vo;
import lombok.Data;
import java.util.List;
/** 新增/编辑课程弹窗需要的稳定选项。 */
@Data
public class CourseAdminOptionsVO {
/** 当前有效且拥有教师角色的用户。 */
private List<ClassAdminOptionVO> teachers;
/** 服务端允许的课程类型。 */
private List<String> courseTypes;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/** 管理员课程表中的单节课程。 */
@Data
public class CourseAdminScheduleVO {
private Integer id;
private Integer classId;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date date;
private String week;
private Integer subjectTimes;
/**
* Mapper接收数据库的逗号拼接值时使用,接口序列化时隐藏。
* 页面只需要读取结构化的timeFrames字段。
*/
@JsonIgnore
private String timeFrame;
private List<String> timeFrames;
private BigDecimal subjectHour;
private String subjectName;
private String teacherId;
private String teacherName;
private String location;
private String type;
private String remark;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
}
......@@ -3,9 +3,12 @@ package com.platform.business.model.vo;
import lombok.Builder;
import lombok.Data;
import java.math.BigDecimal;
@Data
@Builder
public class SysTeacherCountVO {
private Integer remainClassHour;
/** 剩余课时,支持0.5课时粒度。 */
private BigDecimal remainClassHour;
private Integer remainMarkCount;
}
package com.platform.business.constant;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
/** 管理员端课程管理的输入边界和固定选项。 */
public final class CourseAdminConstants {
private CourseAdminConstants() {
}
public static final int MAX_BATCH_SIZE = 100;
public static final int MAX_SUBJECT_TIMES = 40;
public static final int MAX_TIME_FRAMES = 8;
public static final int MAX_SUBJECT_NAME_LENGTH = 100;
public static final int MAX_LOCATION_LENGTH = 255;
public static final int MAX_REMARK_LENGTH = 1000;
/** 数据库存储和接口返回时统一采用补零后的24小时制。 */
public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
/** LinkedHashSet用于保证选项接口返回“理论、实训、考核”的固定展示顺序。 */
public static final Set<String> COURSE_TYPES = Collections.unmodifiableSet(
new LinkedHashSet<>(Arrays.asList("理论", "实训", "考核")));
}
package com.platform.business.controller;
import com.platform.business.model.dto.CourseAdminBatchSaveDTO;
import com.platform.business.model.dto.CourseAdminSaveDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.ClassAdminTreeVO;
import com.platform.business.model.vo.CourseAdminDetailVO;
import com.platform.business.model.vo.CourseAdminOptionsVO;
import com.platform.business.model.vo.CourseAdminScheduleVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.CourseAdminService;
import com.platform.model.resp.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* 管理员端“教务管理-课程管理”接口。
*
* <p>本控制器使用独立的admin前缀,不改变历史的saveOrUpdate、detail和教师端接口。
* 每个入口都从JWT解析真实登录用户并校验管理员角色,不信任客户端提交的用户ID。</p>
*/
@Api(tags = "管理员端-课程管理")
@RestController
@RequestMapping("/class/subject/admin")
public class CourseAdminController {
@Resource
private CourseAdminService courseAdminService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation("课程管理班级导航树")
@GetMapping("/tree")
public Result<List<ClassAdminTreeVO>> tree(
@RequestParam(value = "keyword", required = false) String keyword,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(courseAdminService.tree(keyword));
}
@ApiOperation("课程类型和授课教师选项")
@GetMapping("/options")
public Result<CourseAdminOptionsVO> options(HttpServletRequest request) {
requireAdmin(request);
return Result.data(courseAdminService.options());
}
@ApiOperation("按班级查询课程表")
@GetMapping("/classes/{classId}")
public Result<CourseAdminDetailVO> detail(
@PathVariable("classId") Integer classId,
@RequestParam(value = "startDate", required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(courseAdminService.detail(classId, startDate, endDate));
}
@ApiOperation("为同一班级批量新增课程")
@PostMapping("/batch")
public Result<CourseAdminDetailVO> createBatch(@RequestBody CourseAdminBatchSaveDTO body,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(courseAdminService.createBatch(body));
}
@ApiOperation("编辑单节课程")
@PutMapping("/{courseId}")
public Result<CourseAdminScheduleVO> update(@PathVariable("courseId") Integer courseId,
@RequestBody CourseAdminSaveDTO body,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(courseAdminService.update(courseId, body));
}
@ApiOperation("删除未产生业务数据的课程")
@DeleteMapping("/{courseId}")
public Result<Boolean> delete(@PathVariable("courseId") Integer courseId,
HttpServletRequest request) {
requireAdmin(request);
courseAdminService.delete(courseId);
return Result.data(Boolean.TRUE);
}
@ApiOperation("导出班级课程CSV")
@GetMapping("/classes/{classId}/export")
public void export(
@PathVariable("classId") Integer classId,
@RequestParam(value = "startDate", required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
@RequestParam(value = "endDate", required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 必须在写响应流前完成鉴权,避免鉴权失败时返回半截CSV文件。
requireAdmin(request);
courseAdminService.export(classId, startDate, endDate, response);
}
/** 统一执行JWT解析和管理员角色校验,防止新增入口遗漏权限保护。 */
private UserEntity requireAdmin(HttpServletRequest request) {
UserEntity administrator = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(administrator);
return administrator;
}
}
......@@ -3,8 +3,11 @@ package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.dto.ClassSubjectDTO;
import com.platform.business.model.entity.ClassSubjectEntity;
import com.platform.business.model.vo.ClassAdminOptionVO;
import com.platform.business.model.vo.CalendarVO;
import com.platform.business.model.vo.ClassSubjectVO;
import com.platform.business.model.vo.CourseAdminDetailVO;
import com.platform.business.model.vo.CourseAdminScheduleVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
......@@ -34,5 +37,41 @@ public interface ClassSubjectMapper extends BaseMapper<ClassSubjectEntity> {
List<ClassSubjectVO> queryTeacherCourse(@Param("userId") String userId, @Param("startDate") Date startDate, @Param("endDate") Date endDate);
/** 锁定班级行,使同一班级的并发排课按事务串行执行。 */
Integer lockAdminCourseClass(@Param("classId") Integer classId);
/**
* 按固定ID顺序锁定教师行,防止两个班级同时为同一教师创建重叠课程。
*/
List<String> lockAdminCourseTeachers(@Param("teacherIds") List<String> teacherIds);
/** 查询课程管理页面所需的班级摘要。 */
CourseAdminDetailVO selectAdminCourseClass(@Param("classId") Integer classId);
/** 按班级和可选日期范围查询课程表。 */
List<CourseAdminScheduleVO> selectAdminCourseList(@Param("classId") Integer classId,
@Param("startDate") Date startDate,
@Param("endDate") Date endDate);
/** 查询单节课程并补充教师姓名。 */
CourseAdminScheduleVO selectAdminCourseById(@Param("courseId") Integer courseId);
/** 查询同日、同班级或同教师的候选记录,具体时段重叠由Java精确判断。 */
List<ClassSubjectEntity> selectAdminConflictCandidates(@Param("date") Date date,
@Param("classId") Integer classId,
@Param("teacherId") String teacherId,
@Param("excludeId") Integer excludeId);
/** 教师必须是未删除且在phone_role中具有教师角色的用户。 */
int countAdminActiveTeacher(@Param("teacherId") String teacherId);
/** 课程新增/编辑弹窗的教师选项。 */
List<ClassAdminOptionVO> selectAdminCourseTeacherOptions();
/** 已被签到、请假或评价使用的课程不能直接编辑或删除。 */
int countAdminCourseDependencies(@Param("courseId") Integer courseId);
/** 仅更新管理员课程表单允许修改的列。 */
int updateAdminCourse(ClassSubjectEntity entity);
}
package com.platform.business.service;
import com.platform.business.model.dto.CourseAdminBatchSaveDTO;
import com.platform.business.model.dto.CourseAdminSaveDTO;
import com.platform.business.model.vo.ClassAdminTreeVO;
import com.platform.business.model.vo.CourseAdminDetailVO;
import com.platform.business.model.vo.CourseAdminOptionsVO;
import com.platform.business.model.vo.CourseAdminScheduleVO;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/** 管理员端“教务管理-课程管理”业务接口。 */
public interface CourseAdminService {
List<ClassAdminTreeVO> tree(String keyword);
CourseAdminOptionsVO options();
CourseAdminDetailVO detail(Integer classId, Date startDate, Date endDate);
CourseAdminDetailVO createBatch(CourseAdminBatchSaveDTO request);
CourseAdminScheduleVO update(Integer courseId, CourseAdminSaveDTO request);
void delete(Integer courseId);
void export(Integer classId, Date startDate, Date endDate,
HttpServletResponse response) throws IOException;
}
......@@ -22,6 +22,7 @@ import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
......@@ -67,10 +68,11 @@ public class ClassSubjectServiceImpl extends ServiceImpl<ClassSubjectMapper, Cla
List<ClassSubjectVO> classSubjectVOList = baseMapper.queryByClassAndMonth(classSubjectDTO);
classVO.setClassSubjectList(classSubjectVOList);
//计算总课时
int subjectHour = 0;
// 课程管理允许0.5课时,使用BigDecimal累加避免小数课时被截断。
BigDecimal subjectHour = BigDecimal.ZERO;
for (ClassSubjectVO classSubjectVO : classSubjectVOList) {
if (!ObjectUtils.isEmpty(classSubjectVO.getSubjectHour())) {
subjectHour += classSubjectVO.getSubjectHour();
subjectHour = subjectHour.add(classSubjectVO.getSubjectHour());
}
}
classVO.setSubjectHour(subjectHour);
......@@ -211,7 +213,7 @@ public class ClassSubjectServiceImpl extends ServiceImpl<ClassSubjectMapper, Cla
public SysTeacherCountVO queryByTeacherUserName(String userName) {
UserVO userVO = userService.queryByUserName(userName);
String teacherId = userVO.getId();
Integer count1 = 0;//记录当月剩余课时
BigDecimal count1 = BigDecimal.ZERO;//记录当月剩余课时
int count2 = 0;//记录待评分试卷
// 获取当前日期和时间
LocalDateTime now = LocalDateTime.now();
......@@ -236,8 +238,10 @@ public class ClassSubjectServiceImpl extends ServiceImpl<ClassSubjectMapper, Cla
Set<Integer> classId = new HashSet<>();
for (ClassSubjectVO classSubjectVO : classSubjectList) {
//课时
Integer subjectHour = classSubjectVO.getSubjectHour();
count1 += subjectHour;
BigDecimal subjectHour = classSubjectVO.getSubjectHour();
if (subjectHour != null) {
count1 = count1.add(subjectHour);
}
classId.add(classSubjectVO.getClassId());
}
for (Integer classId1 : classId) {
......
package com.platform.business.service.impl;
import com.platform.business.constant.ClassAdminConstants;
import com.platform.business.constant.CourseAdminConstants;
import com.platform.business.mapper.ClassMapper;
import com.platform.business.mapper.ClassSubjectMapper;
import com.platform.business.model.dto.CourseAdminBatchSaveDTO;
import com.platform.business.model.dto.CourseAdminSaveDTO;
import com.platform.business.model.entity.ClassEntity;
import com.platform.business.model.entity.ClassSubjectEntity;
import com.platform.business.model.vo.ClassAdminOptionVO;
import com.platform.business.model.vo.ClassAdminTreeVO;
import com.platform.business.model.vo.CourseAdminDetailVO;
import com.platform.business.model.vo.CourseAdminOptionsVO;
import com.platform.business.model.vo.CourseAdminScheduleVO;
import com.platform.business.service.ClassAdminService;
import com.platform.business.service.CourseAdminService;
import com.platform.exception.BusinessException;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* 管理员端课程管理实现。
*
* <p>历史{@link ClassSubjectServiceImpl}保留按天覆盖排课的旧行为;本实现为新管理页面
* 提供独立的强校验接口,避免旧接口“先删后存”误删已产生签到、请假或评价数据的课程。</p>
*/
@Service
public class CourseAdminServiceImpl implements CourseAdminService {
/** 兼容前端输入不补零的时间,例如9:00。 */
private static final DateTimeFormatter FLEXIBLE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("H:mm");
private static final String[] CHINESE_WEEKDAYS = {
"", "周一", "周二", "周三", "周四", "周五", "周六", "周日"
};
@Resource
private ClassSubjectMapper classSubjectMapper;
@Resource
private ClassMapper classMapper;
@Resource
private ClassAdminService classAdminService;
@Override
public List<ClassAdminTreeVO> tree(String keyword) {
// 班级管理和课程管理展示同一棵树,复用构造逻辑可保证分组数量与筛选口径一致。
return classAdminService.tree(keyword);
}
@Override
public CourseAdminOptionsVO options() {
CourseAdminOptionsVO result = new CourseAdminOptionsVO();
List<ClassAdminOptionVO> teachers = classSubjectMapper.selectAdminCourseTeacherOptions();
result.setTeachers(teachers == null ? Collections.emptyList() : teachers);
result.setCourseTypes(new ArrayList<>(CourseAdminConstants.COURSE_TYPES));
return result;
}
@Override
@Transactional(readOnly = true)
public CourseAdminDetailVO detail(Integer classId, Date startDate, Date endDate) {
requireClassId(classId);
validateQueryDateRange(startDate, endDate);
CourseAdminDetailVO result = classSubjectMapper.selectAdminCourseClass(classId);
if (result == null) {
throw new BusinessException("班级不存在或已删除");
}
result.setTermName(resolveTermName(result.getTrainingYear(), result.getStartDate()));
List<CourseAdminScheduleVO> courses = classSubjectMapper.selectAdminCourseList(
classId, startDate, endDate);
if (courses == null) {
courses = Collections.emptyList();
}
BigDecimal totalHours = BigDecimal.ZERO;
for (CourseAdminScheduleVO course : courses) {
// 数据库存储格式只在服务内部存在,接口始终返回结构化的时段数组。
course.setTimeFrames(splitStoredFrames(course.getTimeFrame()));
if (course.getSubjectHour() != null) {
totalHours = totalHours.add(course.getSubjectHour());
}
}
result.setCourses(courses);
result.setCourseCount(courses.size());
result.setTotalHours(totalHours);
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public CourseAdminDetailVO createBatch(CourseAdminBatchSaveDTO request) {
if (request == null) {
throw new BusinessException("课程信息不能为空");
}
requireClassId(request.getClassId());
if (request.getCourses() == null || request.getCourses().isEmpty()) {
throw new BusinessException("请至少添加一节课程");
}
if (request.getCourses().size() > CourseAdminConstants.MAX_BATCH_SIZE) {
throw new BusinessException("单次最多新增100节课程");
}
ClassEntity managedClass = lockAndLoadClass(request.getClassId());
lockTeachers(collectTeacherIds(request.getCourses()));
Date now = new Date();
for (int index = 0; index < request.getCourses().size(); index++) {
CourseAdminSaveDTO item = request.getCourses().get(index);
try {
PreparedCourse prepared = prepareCourse(item, request.getClassId(), managedClass);
ensureNoConflict(prepared.entity, prepared.timeRanges, null);
prepared.entity.setCreateTime(now);
prepared.entity.setUpdateTime(now);
if (classSubjectMapper.insert(prepared.entity) != 1) {
throw new BusinessException("课程新增失败,请稍后重试");
}
} catch (BusinessException e) {
// 批量请求指出具体行号,页面可直接定位到错误行。
throw new BusinessException("第" + (index + 1) + "节课程:" + e.getMessage());
}
}
// 返回刷新后的完整班级课表,前端无需再根据临时行逐条合并ID。
return detail(request.getClassId(), null, null);
}
@Override
@Transactional(rollbackFor = Exception.class)
public CourseAdminScheduleVO update(Integer courseId, CourseAdminSaveDTO request) {
requireCourseId(courseId);
ClassSubjectEntity snapshot = classSubjectMapper.selectById(courseId);
if (snapshot == null) {
throw new BusinessException("课程不存在或已删除");
}
ClassEntity managedClass = lockAndLoadClass(snapshot.getClassId());
// 班级锁取得后重新读取,避免等待锁期间课程已被另一个事务删除或修改。
ClassSubjectEntity existing = classSubjectMapper.selectById(courseId);
if (existing == null) {
throw new BusinessException("课程不存在或已删除");
}
if (existing.getClassId() != snapshot.getClassId()) {
throw new BusinessException("课程所属班级已发生变化,请刷新后重试");
}
lockTeachers(collectTeacherIds(existing.getTeacherId(),
request == null ? null : request.getTeacherId()));
rejectIfCourseHasDependencies(courseId, "课程已产生签到、请假或评价数据,不能直接编辑");
PreparedCourse prepared = prepareCourse(request, existing.getClassId(), managedClass);
prepared.entity.setId(courseId);
prepared.entity.setUpdateTime(new Date());
ensureNoConflict(prepared.entity, prepared.timeRanges, courseId);
if (classSubjectMapper.updateAdminCourse(prepared.entity) != 1) {
throw new BusinessException("课程信息已发生变化,请刷新后重试");
}
CourseAdminScheduleVO result = classSubjectMapper.selectAdminCourseById(courseId);
if (result == null) {
throw new BusinessException("课程更新成功但读取失败,请刷新后重试");
}
result.setTimeFrames(splitStoredFrames(result.getTimeFrame()));
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Integer courseId) {
requireCourseId(courseId);
ClassSubjectEntity snapshot = classSubjectMapper.selectById(courseId);
if (snapshot == null) {
throw new BusinessException("课程不存在或已删除");
}
lockAndLoadClass(snapshot.getClassId());
ClassSubjectEntity existing = classSubjectMapper.selectById(courseId);
if (existing == null) {
throw new BusinessException("课程不存在或已删除");
}
if (existing.getClassId() != snapshot.getClassId()) {
throw new BusinessException("课程所属班级已发生变化,请刷新后重试");
}
rejectIfCourseHasDependencies(courseId, "课程已产生签到、请假或评价数据,不能删除");
if (classSubjectMapper.deleteById(courseId) != 1) {
throw new BusinessException("课程信息已发生变化,请刷新后重试");
}
}
@Override
@Transactional(readOnly = true)
public void export(Integer classId, Date startDate, Date endDate,
HttpServletResponse response) throws IOException {
CourseAdminDetailVO detail = detail(classId, startDate, endDate);
String fileName = "课程表_" + detail.getClassName() + ".csv";
String encodedName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())
.replace("+", "%20");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType("text/csv;charset=UTF-8");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename*=UTF-8''" + encodedName);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(
response.getOutputStream(), StandardCharsets.UTF_8));
// Excel识别UTF-8 CSV依赖BOM,否则中文可能按本地ANSI编码打开并出现乱码。
writer.write('\ufeff');
writeCsvRow(writer, "序号", "日期", "星期", "课次", "时段", "课时",
"课程名称", "课程类型", "授课教师", "上课地点", "备注");
int sequence = 1;
for (CourseAdminScheduleVO course : detail.getCourses()) {
writeCsvRow(writer,
String.valueOf(sequence++),
formatDate(course.getDate()),
course.getWeek(),
valueOf(course.getSubjectTimes()),
String.join(" / ", course.getTimeFrames()),
valueOf(course.getSubjectHour()),
course.getSubjectName(),
course.getType(),
course.getTeacherName(),
course.getLocation(),
course.getRemark());
}
// 不关闭Servlet容器管理的输出流,只刷新本次响应写入的数据。
writer.flush();
}
/**
* 校验表单、规范字符串和时段,并构建只包含可写字段的实体。
*/
private PreparedCourse prepareCourse(CourseAdminSaveDTO request, Integer classId,
ClassEntity managedClass) {
if (request == null) {
throw new BusinessException("课程信息不能为空");
}
if (request.getDate() == null) {
throw new BusinessException("课程日期不能为空");
}
validateCourseDate(request.getDate(), managedClass);
if (request.getSubjectTimes() == null
|| request.getSubjectTimes() < 1
|| request.getSubjectTimes() > CourseAdminConstants.MAX_SUBJECT_TIMES) {
throw new BusinessException("课次必须在1到40之间");
}
BigDecimal hours = request.getSubjectHour();
if (hours == null || hours.compareTo(new BigDecimal("0.5")) < 0
|| hours.compareTo(new BigDecimal("16")) > 0
|| hours.multiply(new BigDecimal("2")).stripTrailingZeros().scale() > 0) {
throw new BusinessException("课时必须在0.5到16之间并以0.5递增");
}
String subjectName = requireText(request.getSubjectName(), "课程名称",
CourseAdminConstants.MAX_SUBJECT_NAME_LENGTH);
String teacherId = requireText(request.getTeacherId(), "授课教师ID", 64);
if (classSubjectMapper.countAdminActiveTeacher(teacherId) != 1) {
throw new BusinessException("所选授课教师不存在、已停用或不具有教师角色");
}
String type = requireText(request.getType(), "课程类型", 16);
if (!CourseAdminConstants.COURSE_TYPES.contains(type)) {
throw new BusinessException("课程类型只支持理论、实训或考核");
}
String location = optionalText(request.getLocation(), "上课地点",
CourseAdminConstants.MAX_LOCATION_LENGTH);
String remark = optionalText(request.getRemark(), "课程备注",
CourseAdminConstants.MAX_REMARK_LENGTH);
List<TimeRange> ranges = normalizeTimeFrames(request.getTimeFrames());
ClassSubjectEntity entity = new ClassSubjectEntity();
entity.setClassId(classId);
entity.setDate(request.getDate());
entity.setWeek(chineseWeekday(request.getDate()));
entity.setSubjectTimes(request.getSubjectTimes());
entity.setTimeFrame(ranges.stream().map(TimeRange::asText)
.collect(Collectors.joining(",")));
entity.setSubjectHour(hours.setScale(1));
entity.setSubjectName(subjectName);
entity.setTeacherId(teacherId);
entity.setLocation(location);
entity.setType(type);
entity.setRemark(remark);
return new PreparedCourse(entity, ranges);
}
/**
* 精确检查新课程是否与同班级或同教师的已有课程重叠。
* 相邻时段(例如10:00结束、10:00开始)允许保存。
*/
private void ensureNoConflict(ClassSubjectEntity subject, List<TimeRange> newRanges,
Integer excludeId) {
List<ClassSubjectEntity> candidates = classSubjectMapper.selectAdminConflictCandidates(
subject.getDate(), subject.getClassId(), subject.getTeacherId(), excludeId);
if (candidates == null) {
return;
}
for (ClassSubjectEntity candidate : candidates) {
List<TimeRange> existingRanges;
try {
existingRanges = normalizeStoredTimeFrames(candidate.getTimeFrame());
} catch (BusinessException e) {
throw new BusinessException("已有课程“" + candidate.getSubjectName()
+ "”的时段格式异常,请先修复该课程");
}
if (!overlaps(newRanges, existingRanges)) {
continue;
}
if (candidate.getClassId() == subject.getClassId()) {
throw new BusinessException("与本班课程“" + candidate.getSubjectName() + "”时间冲突");
}
if (subject.getTeacherId().equals(candidate.getTeacherId())) {
throw new BusinessException("授课教师与课程“" + candidate.getSubjectName() + "”时间冲突");
}
}
}
/** 将前端提交的时段校验、排序并规范为不可重叠的时间范围。 */
private List<TimeRange> normalizeTimeFrames(List<String> frames) {
if (frames == null || frames.isEmpty()) {
throw new BusinessException("至少需要一个上课时段");
}
if (frames.size() > CourseAdminConstants.MAX_TIME_FRAMES) {
throw new BusinessException("一节课程最多配置8个上课时段");
}
List<TimeRange> ranges = new ArrayList<>();
for (String frame : frames) {
ranges.add(parseTimeRange(frame));
}
ranges.sort(Comparator.comparing(TimeRange::getStart));
for (int index = 1; index < ranges.size(); index++) {
if (ranges.get(index).start.isBefore(ranges.get(index - 1).end)) {
throw new BusinessException("同一课程内的上课时段不能重叠");
}
}
return ranges;
}
/** 解析数据库中的历史逗号拼接时段,供冲突检查使用。 */
private List<TimeRange> normalizeStoredTimeFrames(String stored) {
if (stored == null || stored.trim().isEmpty()) {
throw new BusinessException("课程时段未配置");
}
List<String> frames = new ArrayList<>();
Collections.addAll(frames, stored.split(","));
return normalizeTimeFrames(frames);
}
private TimeRange parseTimeRange(String value) {
String normalized = trimToNull(value);
if (normalized == null) {
throw new BusinessException("上课时段不能为空");
}
normalized = normalized.replace('~', '-').replace('—', '-')
.replace('–', '-').replace('→', '-');
String[] times = normalized.split("\\s*-\\s*", -1);
if (times.length != 2) {
throw new BusinessException("上课时段格式应为HH:mm-HH:mm");
}
try {
LocalTime start = LocalTime.parse(times[0].trim(), FLEXIBLE_TIME_FORMATTER);
LocalTime end = LocalTime.parse(times[1].trim(), FLEXIBLE_TIME_FORMATTER);
if (!end.isAfter(start)) {
throw new BusinessException("上课结束时间必须晚于开始时间");
}
return new TimeRange(start, end);
} catch (DateTimeParseException e) {
throw new BusinessException("上课时段格式应为HH:mm-HH:mm");
}
}
private boolean overlaps(List<TimeRange> left, List<TimeRange> right) {
for (TimeRange first : left) {
for (TimeRange second : right) {
if (first.start.isBefore(second.end) && second.start.isBefore(first.end)) {
return true;
}
}
}
return false;
}
private ClassEntity lockAndLoadClass(Integer classId) {
if (classSubjectMapper.lockAdminCourseClass(classId) == null) {
throw new BusinessException("班级不存在或已删除");
}
ClassEntity managedClass = classMapper.selectById(classId);
if (managedClass == null) {
throw new BusinessException("班级不存在或已删除");
}
return managedClass;
}
private void lockTeachers(List<String> teacherIds) {
if (!teacherIds.isEmpty()) {
classSubjectMapper.lockAdminCourseTeachers(teacherIds);
}
}
private List<String> collectTeacherIds(List<CourseAdminSaveDTO> requests) {
Set<String> teacherIds = new TreeSet<>();
for (CourseAdminSaveDTO request : requests) {
if (request != null && trimToNull(request.getTeacherId()) != null) {
teacherIds.add(request.getTeacherId().trim());
}
}
return new ArrayList<>(teacherIds);
}
private List<String> collectTeacherIds(String first, String second) {
Set<String> teacherIds = new TreeSet<>();
if (trimToNull(first) != null) teacherIds.add(first.trim());
if (trimToNull(second) != null) teacherIds.add(second.trim());
return new ArrayList<>(teacherIds);
}
private void validateCourseDate(Date courseDate, ClassEntity managedClass) {
LocalDate course = toLocalDate(courseDate);
if (managedClass.getStartDate() != null
&& course.isBefore(toLocalDate(managedClass.getStartDate()))) {
throw new BusinessException("课程日期不能早于班级培训开始日期");
}
if (managedClass.getEndDate() != null
&& course.isAfter(toLocalDate(managedClass.getEndDate()))) {
throw new BusinessException("课程日期不能晚于班级培训结束日期");
}
}
private void validateQueryDateRange(Date startDate, Date endDate) {
if (startDate != null && endDate != null
&& toLocalDate(startDate).isAfter(toLocalDate(endDate))) {
throw new BusinessException("查询结束日期不能早于开始日期");
}
}
private void rejectIfCourseHasDependencies(Integer courseId, String message) {
if (classSubjectMapper.countAdminCourseDependencies(courseId) > 0) {
throw new BusinessException(message);
}
}
private String chineseWeekday(Date date) {
DayOfWeek day = toLocalDate(date).getDayOfWeek();
return CHINESE_WEEKDAYS[day.getValue()];
}
/**
* 原型只展示春/秋学期而班级表未单独保存学期,因此按开班月份生成展示值:
* 1月至6月为春季,7月至12月为秋季。原始年度或日期缺失时不伪造数据。
*/
private String resolveTermName(Integer trainingYear, Date startDate) {
if (startDate == null) {
return null;
}
LocalDate start = toLocalDate(startDate);
int year = trainingYear == null ? start.getYear() : trainingYear;
return year + (start.getMonthValue() <= 6 ? " 春" : " 秋");
}
/** 列表读取历史数据时做宽松拆分,避免单条旧数据异常导致整个课程表无法打开。 */
private List<String> splitStoredFrames(String stored) {
if (stored == null || stored.trim().isEmpty()) {
return Collections.emptyList();
}
List<String> result = new ArrayList<>();
for (String frame : stored.split(",")) {
if (trimToNull(frame) != null) {
result.add(frame.trim());
}
}
return result;
}
private void writeCsvRow(PrintWriter writer, String... values) {
for (int index = 0; index < values.length; index++) {
if (index > 0) writer.write(',');
String value = values[index] == null ? "" : values[index];
writer.write('"');
writer.write(value.replace("\"", "\"\""));
writer.write('"');
}
writer.write("\r\n");
}
private String formatDate(Date value) {
return value == null ? "" : toLocalDate(value).toString();
}
private String valueOf(Object value) {
return value == null ? "" : String.valueOf(value);
}
private void requireClassId(Integer classId) {
if (classId == null || classId <= 0) {
throw new BusinessException("班级ID无效");
}
}
private void requireCourseId(Integer courseId) {
if (courseId == null || courseId <= 0) {
throw new BusinessException("课程ID无效");
}
}
private String requireText(String value, String fieldName, int maxLength) {
String normalized = trimToNull(value);
if (normalized == null) {
throw new BusinessException(fieldName + "不能为空");
}
if (normalized.length() > maxLength) {
throw new BusinessException(fieldName + "不能超过" + maxLength + "个字符");
}
return normalized;
}
private String optionalText(String value, String fieldName, int maxLength) {
String normalized = trimToNull(value);
if (normalized != null && normalized.length() > maxLength) {
throw new BusinessException(fieldName + "不能超过" + maxLength + "个字符");
}
return normalized;
}
private String trimToNull(String value) {
if (value == null) return null;
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
private static LocalDate toLocalDate(Date date) {
// JDBC的DATE没有时区语义,直接取toLocalDate可避免服务器默认时区导致前后偏移一天。
if (date instanceof java.sql.Date) {
return ((java.sql.Date) date).toLocalDate();
}
return Instant.ofEpochMilli(date.getTime())
.atZone(ClassAdminConstants.BUSINESS_ZONE).toLocalDate();
}
/** 经过规范化的课程实体及其时段,避免冲突检查重复解析请求。 */
private static final class PreparedCourse {
private final ClassSubjectEntity entity;
private final List<TimeRange> timeRanges;
private PreparedCourse(ClassSubjectEntity entity, List<TimeRange> timeRanges) {
this.entity = entity;
this.timeRanges = timeRanges;
}
}
/** 单个半开时间区间[start, end),相邻课程因此不会被误判为冲突。 */
private static final class TimeRange {
private final LocalTime start;
private final LocalTime end;
private TimeRange(LocalTime start, LocalTime end) {
this.start = start;
this.end = end;
}
private LocalTime getStart() {
return start;
}
private String asText() {
return start.format(CourseAdminConstants.TIME_FORMATTER) + "-"
+ end.format(CourseAdminConstants.TIME_FORMATTER);
}
}
}
......@@ -203,4 +203,172 @@
cs.teacher_id = #{teacherId}
</select>
<!--
同一班级的排课写操作先锁定班级主记录。返回值只用于判断班级是否存在,
真正目的在于让并发新增、编辑和删除进入一致的事务顺序。
-->
<select id="lockAdminCourseClass" resultType="java.lang.Integer">
select id
from `class`
where id = #{classId}
for update
</select>
<!-- 教师ID由服务层排序后传入,固定加锁顺序可以降低批量排课时的死锁概率。 -->
<select id="lockAdminCourseTeachers" resultType="java.lang.String">
select id
from user
where id in
<foreach collection="teacherIds" item="teacherId" open="(" close=")" separator=",">
#{teacherId}
</foreach>
order by id
for update
</select>
<!-- 左侧班级被选中后,右侧标题区需要的班级摘要。 -->
<select id="selectAdminCourseClass" resultType="com.platform.business.model.vo.CourseAdminDetailVO">
select
c.id as classId,
c.name as className,
c.occupation,
c.training_year as trainingYear,
c.level as levelId,
level_info.name as levelName,
c.start_date as startDate,
c.end_date as endDate,
coalesce(members.student_count, 0) as studentCount
from `class` c
left join sys_level level_info
on cast(level_info.id as char) = c.level
left join (
select class_id, count(*) as student_count
from class_student
group by class_id
) members on members.class_id = c.id
where c.id = #{classId}
</select>
<!-- 课程按日期、首个开始时段和ID稳定排序,保证页面刷新后序号不会随机变化。 -->
<select id="selectAdminCourseList" resultType="com.platform.business.model.vo.CourseAdminScheduleVO">
select
subject.id,
subject.class_id as classId,
subject.date,
subject.week,
subject.subject_times as subjectTimes,
subject.time_frame as timeFrame,
subject.subject_hour as subjectHour,
subject.subject_name as subjectName,
subject.teacher_id as teacherId,
coalesce(nullif(teacher.nick_name, ''), teacher.username) as teacherName,
subject.location,
subject.type,
subject.remark,
subject.create_time as createTime,
subject.update_time as updateTime
from class_subject subject
left join user teacher on teacher.id = subject.teacher_id
where subject.class_id = #{classId}
<if test="startDate != null">
and subject.date &gt;= #{startDate}
</if>
<if test="endDate != null">
and subject.date &lt;= #{endDate}
</if>
order by subject.date asc, subject.time_frame asc, subject.id asc
</select>
<select id="selectAdminCourseById" resultType="com.platform.business.model.vo.CourseAdminScheduleVO">
select
subject.id,
subject.class_id as classId,
subject.date,
subject.week,
subject.subject_times as subjectTimes,
subject.time_frame as timeFrame,
subject.subject_hour as subjectHour,
subject.subject_name as subjectName,
subject.teacher_id as teacherId,
coalesce(nullif(teacher.nick_name, ''), teacher.username) as teacherName,
subject.location,
subject.type,
subject.remark,
subject.create_time as createTime,
subject.update_time as updateTime
from class_subject subject
left join user teacher on teacher.id = subject.teacher_id
where subject.id = #{courseId}
</select>
<!-- SQL先按日期和资源范围缩小候选集合,时段文本的精确重叠判断交给服务层。 -->
<select id="selectAdminConflictCandidates"
resultType="com.platform.business.model.entity.ClassSubjectEntity">
select
id, class_id, date, subject_name, teacher_id, time_frame
from class_subject
where date = #{date}
and (class_id = #{classId} or teacher_id = #{teacherId})
<if test="excludeId != null">
and id != #{excludeId}
</if>
order by id
</select>
<select id="countAdminActiveTeacher" resultType="java.lang.Integer">
select count(*)
from user teacher
where teacher.id = #{teacherId}
and coalesce(teacher.del_flag, 0) = 0
and exists (
select 1
from phone_role role_info
where role_info.phone = teacher.phone_number
and role_info.role_name = '教师'
)
</select>
<select id="selectAdminCourseTeacherOptions"
resultType="com.platform.business.model.vo.ClassAdminOptionVO">
select distinct
teacher.id as value,
coalesce(nullif(teacher.nick_name, ''), teacher.username) as label,
null as parentValue,
teacher.phone_number as extra
from user teacher
inner join phone_role role_info
on role_info.phone = teacher.phone_number and role_info.role_name = '教师'
where coalesce(teacher.del_flag, 0) = 0
order by label asc, teacher.phone_number asc
</select>
<!--
四类业务关系中任意一类已存在,都说明课程已经进入后续流程。
此时不允许管理员直接改删排课,以免签到、请假或评价数据失去业务语义。
-->
<select id="countAdminCourseDependencies" resultType="java.lang.Integer">
select
(select count(*) from class_subject_attendance where subject_id = #{courseId})
+ (select count(*) from class_subject_attendance_session where subject_id = #{courseId})
+ (select count(*) from student_leave_subject where subject_id = #{courseId})
+ (select count(*) from evaluation_task where subject_id = #{courseId})
</select>
<!-- 明确列出可编辑字段,禁止请求意外覆盖班级ID、主键和创建时间。 -->
<update id="updateAdminCourse">
update class_subject
set date = #{date},
week = #{week},
subject_times = #{subjectTimes},
time_frame = #{timeFrame},
subject_hour = #{subjectHour},
subject_name = #{subjectName},
teacher_id = #{teacherId},
location = #{location,jdbcType=VARCHAR},
type = #{type},
remark = #{remark,jdbcType=VARCHAR},
update_time = #{updateTime}
where id = #{id}
</update>
</mapper>
# 管理员端课程管理接口
接口统一使用 `/class/subject/admin` 前缀,所有请求都必须携带 `Authorization`。服务端从
JWT解析当前用户,并校验 `phone_role.role_name=管理员`,不接受客户端提交管理员用户ID。
部署前依次执行:
1. `src/main/resources/sql/class_management.sql`
2. `src/main/resources/sql/course_management.sql`
第二个脚本将 `class_subject.subject_hour` 调整为 `decimal(5,1)`,补充创建/更新时间和班级、
教师日期索引。两个脚本都可重复执行。
## 1. 班级导航树
`GET /class/subject/admin/tree?keyword=污水`
返回 `OCCUPATION → YEAR → LEVEL → CLASS` 四层节点,结构与班级管理树一致。班级叶节点的
`classId` 用于后续课程查询和新增请求。
## 2. 表单选项
`GET /class/subject/admin/options`
返回有效授课教师和固定课程类型:`理论`、`实训`、`考核`。教师选项的 `value` 是用户ID,
`label` 是姓名,`extra` 是手机号;保存时必须提交ID,不能提交教师姓名。
## 3. 查询班级课程表
`GET /class/subject/admin/classes/{classId}`
可选参数:`startDate=2026-09-01&endDate=2026-09-30`。返回班级名称、工种、年度、等级、
培训起止日期、学期展示值 `termName`、学员人数、课程数量、总课时和课程数组。`termName`
按开班月份生成(1~6月为春季、7~12月为秋季)。每节课程示例:
```json
{
"id": 1001,
"classId": 10,
"date": "2026-09-08",
"week": "周二",
"subjectTimes": 2,
"timeFrames": ["09:00-10:20", "10:40-12:00"],
"subjectHour": 2.0,
"subjectName": "水污染知识",
"teacherId": "1900000000000000001",
"teacherName": "王建国",
"location": "A栋302",
"type": "理论",
"remark": null
}
```
## 4. 批量新增课程
`POST /class/subject/admin/batch`
```json
{
"classId": 10,
"courses": [
{
"date": "2026-09-08",
"subjectTimes": 2,
"timeFrames": ["09:00-10:20", "10:40-12:00"],
"subjectHour": 2.0,
"subjectName": "水污染知识",
"teacherId": "1900000000000000001",
"location": "A栋302",
"type": "理论",
"remark": "第一章"
}
]
}
```
- 单次至少1节、最多100节。
- 课程日期必须位于班级培训起止日期内;星期由服务端根据日期生成。
- 课次为1~40;课时为0.5~16并以0.5递增。
- 每节课程允许1~8个时段,格式为 `HH:mm-HH:mm`;同时兼容原型中的 `~`、`—`、`–`。
- 课程名称最多100字,地点最多255字,备注最多1000字。
- 同一班级或同一教师的课程时段不能重叠;首尾相接的时段不算冲突。
- 批量保存使用事务,任意一行失败都会整体回滚。错误消息带“第N节课程”行号。
成功后返回该班级刷新后的完整课程表。
## 5. 编辑课程
`PUT /class/subject/admin/{courseId}`
请求体为批量新增中 `courses` 数组的单个元素,不接收 `classId`。编辑后返回该节课程。
课程一旦产生签到记录/签到场次、关联请假或评价任务,就禁止直接修改,以防业务数据与排课
信息不一致。
## 6. 删除课程
`DELETE /class/subject/admin/{courseId}`
仅允许删除尚未产生签到、请假或评价数据的课程,成功返回 `true`。
## 7. 导出课程表
`GET /class/subject/admin/classes/{classId}/export`
支持与列表相同的 `startDate`、`endDate` 参数,返回带UTF-8 BOM的CSV文件,可直接使用Excel
打开。导出内容使用服务端实时查询结果,不信任客户端拼装的数据。
-- 管理员端“教务管理-课程管理”增量数据库脚本(MySQL 5.7+/8.0)。
--
-- 执行顺序:先执行class_management.sql补齐班级培训日期等字段,再执行本脚本。
-- 设计说明:
-- 1. 项目已存在class_subject表,本脚本只调整课时精度、补充审计列和常用索引。
-- 2. 旧数据允许审计时间为空;新增/编辑接口会自动维护create_time和update_time。
-- 3. 项目历史表主要由服务层维护关系完整性,本脚本不额外引入外键,避免阻断旧数据迁移。
delimiter $$
drop procedure if exists migrate_course_management$$
create procedure migrate_course_management()
begin
-- 页面允许0.5课时,原int列会截断小数,因此统一调整为一位小数。
if exists (
select 1 from information_schema.columns
where table_schema = database()
and table_name = 'class_subject'
and column_name = 'subject_hour'
) then
alter table class_subject
modify column subject_hour decimal(5,1) null comment '课时数,支持0.5课时粒度';
end if;
if not exists (
select 1 from information_schema.columns
where table_schema = database()
and table_name = 'class_subject'
and column_name = 'create_time'
) then
alter table class_subject
add column create_time datetime null comment '创建时间' after type;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema = database()
and table_name = 'class_subject'
and column_name = 'update_time'
) then
alter table class_subject
add column update_time datetime null comment '更新时间' after create_time;
end if;
-- 班级课程表按class_id和date过滤、排序,该索引同时服务课程导出和日期范围查询。
if not exists (
select 1 from information_schema.statistics
where table_schema = database()
and table_name = 'class_subject'
and index_name = 'idx_subject_class_date'
) then
alter table class_subject
add index idx_subject_class_date (class_id, date, id);
end if;
-- 教师冲突校验和教师日历按teacher_id、date缩小候选集合。
if not exists (
select 1 from information_schema.statistics
where table_schema = database()
and table_name = 'class_subject'
and index_name = 'idx_subject_teacher_date'
) then
alter table class_subject
add index idx_subject_teacher_date (teacher_id, date, id);
end if;
end$$
call migrate_course_management()$$
drop procedure if exists migrate_course_management$$
delimiter ;
-- 旧记录没有可靠的原始创建时间,使用当前时间仅回填update_time,create_time保持NULL表示未知。
update class_subject
set update_time = coalesce(update_time, now())
where update_time is null;
package com.platform.business.controller;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.CourseAdminOptionsVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.CourseAdminService;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 课程管理控制器的管理员鉴权测试。 */
@ExtendWith(MockitoExtension.class)
class CourseAdminControllerTest {
@Mock
private CourseAdminService courseAdminService;
@Mock
private AuthenticatedUserService authenticatedUserService;
private CourseAdminController controller;
@BeforeEach
void setUp() {
controller = new CourseAdminController();
ReflectionTestUtils.setField(controller, "courseAdminService", courseAdminService);
ReflectionTestUtils.setField(controller, "authenticatedUserService", authenticatedUserService);
}
@Test
void optionsShouldRequireAdminBeforeCallingService() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity administrator = new UserEntity();
when(authenticatedUserService.current(request)).thenReturn(administrator);
when(courseAdminService.options()).thenReturn(new CourseAdminOptionsVO());
controller.options(request);
verify(authenticatedUserService).requireAdmin(administrator);
verify(courseAdminService).options();
}
@Test
void optionsShouldStopWhenUserIsNotAdmin() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity teacher = new UserEntity();
when(authenticatedUserService.current(request)).thenReturn(teacher);
doThrow(new BusinessException("只有管理员可以访问管理端接口"))
.when(authenticatedUserService).requireAdmin(teacher);
assertThrows(BusinessException.class, () -> controller.options(request));
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.ClassMapper;
import com.platform.business.mapper.ClassSubjectMapper;
import com.platform.business.model.dto.CourseAdminBatchSaveDTO;
import com.platform.business.model.dto.CourseAdminSaveDTO;
import com.platform.business.model.entity.ClassEntity;
import com.platform.business.model.entity.ClassSubjectEntity;
import com.platform.business.model.vo.CourseAdminDetailVO;
import com.platform.business.model.vo.CourseAdminScheduleVO;
import com.platform.business.service.ClassAdminService;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 管理员端课程管理的规范化、冲突保护和数据聚合测试。 */
@ExtendWith(MockitoExtension.class)
class CourseAdminServiceImplTest {
@Mock
private ClassSubjectMapper classSubjectMapper;
@Mock
private ClassMapper classMapper;
@Mock
private ClassAdminService classAdminService;
@InjectMocks
private CourseAdminServiceImpl service;
@Test
void createBatchShouldNormalizeTimeWeekAndDecimalHours() {
mockWritableClass();
when(classSubjectMapper.countAdminActiveTeacher("teacher-1")).thenReturn(1);
when(classSubjectMapper.selectAdminConflictCandidates(any(), eq(1),
eq("teacher-1"), eq(null))).thenReturn(Collections.emptyList());
when(classSubjectMapper.insert(any(ClassSubjectEntity.class))).thenAnswer(invocation -> {
ClassSubjectEntity entity = invocation.getArgument(0);
entity.setId(99);
return 1;
});
mockEmptyDetail();
CourseAdminSaveDTO item = validCourse();
item.setTimeFrames(Arrays.asList("13:00~14:20", "9:00—10:20"));
item.setSubjectHour(new BigDecimal("1.5"));
CourseAdminBatchSaveDTO request = new CourseAdminBatchSaveDTO();
request.setClassId(1);
request.setCourses(Collections.singletonList(item));
service.createBatch(request);
ArgumentCaptor<ClassSubjectEntity> captor =
ArgumentCaptor.forClass(ClassSubjectEntity.class);
verify(classSubjectMapper).insert(captor.capture());
assertEquals("09:00-10:20,13:00-14:20", captor.getValue().getTimeFrame());
assertEquals("周二", captor.getValue().getWeek());
assertEquals(new BigDecimal("1.5"), captor.getValue().getSubjectHour());
assertEquals("测试课程", captor.getValue().getSubjectName());
}
@Test
void createBatchShouldRejectClassAndTeacherTimeConflicts() {
mockWritableClass();
when(classSubjectMapper.countAdminActiveTeacher("teacher-1")).thenReturn(1);
ClassSubjectEntity existing = new ClassSubjectEntity();
existing.setId(8);
existing.setClassId(1);
existing.setTeacherId("teacher-2");
existing.setSubjectName("已有课程");
existing.setTimeFrame("09:30-11:00");
when(classSubjectMapper.selectAdminConflictCandidates(any(), eq(1),
eq("teacher-1"), eq(null))).thenReturn(Collections.singletonList(existing));
CourseAdminBatchSaveDTO request = new CourseAdminBatchSaveDTO();
request.setClassId(1);
request.setCourses(Collections.singletonList(validCourse()));
BusinessException error = assertThrows(BusinessException.class,
() -> service.createBatch(request));
// 批量错误既包含行号,也保留具体冲突课程名称,便于页面定位。
assertEquals("第1节课程:与本班课程“已有课程”时间冲突", error.getMessage());
verify(classSubjectMapper, never()).insert(any(ClassSubjectEntity.class));
}
@Test
void createBatchShouldRejectQuarterHourValues() {
mockWritableClass();
CourseAdminSaveDTO item = validCourse();
item.setSubjectHour(new BigDecimal("1.25"));
CourseAdminBatchSaveDTO request = new CourseAdminBatchSaveDTO();
request.setClassId(1);
request.setCourses(Collections.singletonList(item));
assertThrows(BusinessException.class, () -> service.createBatch(request));
verify(classSubjectMapper, never()).insert(any(ClassSubjectEntity.class));
}
@Test
void updateShouldRejectCourseWithDownstreamBusinessData() {
ClassSubjectEntity existing = new ClassSubjectEntity();
existing.setId(7);
existing.setClassId(1);
existing.setTeacherId("teacher-1");
when(classSubjectMapper.selectById(7)).thenReturn(existing);
mockWritableClass();
when(classSubjectMapper.countAdminCourseDependencies(7)).thenReturn(1);
assertThrows(BusinessException.class, () -> service.update(7, validCourse()));
verify(classSubjectMapper, never()).updateAdminCourse(any(ClassSubjectEntity.class));
}
@Test
void detailShouldReturnStructuredFramesAndExactTotalHours() {
CourseAdminDetailVO detail = new CourseAdminDetailVO();
detail.setClassId(1);
detail.setClassName("测试班级");
when(classSubjectMapper.selectAdminCourseClass(1)).thenReturn(detail);
CourseAdminScheduleVO first = new CourseAdminScheduleVO();
first.setTimeFrame("09:00-10:20,10:40-12:00");
first.setSubjectHour(new BigDecimal("1.5"));
CourseAdminScheduleVO second = new CourseAdminScheduleVO();
second.setTimeFrame("13:00-14:20");
second.setSubjectHour(new BigDecimal("2.0"));
when(classSubjectMapper.selectAdminCourseList(1, null, null))
.thenReturn(Arrays.asList(first, second));
CourseAdminDetailVO result = service.detail(1, null, null);
assertEquals(2, result.getCourseCount());
assertEquals(new BigDecimal("3.5"), result.getTotalHours());
assertEquals(Arrays.asList("09:00-10:20", "10:40-12:00"),
result.getCourses().get(0).getTimeFrames());
}
private void mockWritableClass() {
when(classSubjectMapper.lockAdminCourseClass(1)).thenReturn(1);
ClassEntity managedClass = new ClassEntity();
managedClass.setId(1);
managedClass.setStartDate(Date.valueOf("2026-09-01"));
managedClass.setEndDate(Date.valueOf("2026-12-31"));
when(classMapper.selectById(1)).thenReturn(managedClass);
}
private void mockEmptyDetail() {
CourseAdminDetailVO detail = new CourseAdminDetailVO();
detail.setClassId(1);
detail.setClassName("测试班级");
when(classSubjectMapper.selectAdminCourseClass(1)).thenReturn(detail);
when(classSubjectMapper.selectAdminCourseList(1, null, null))
.thenReturn(Collections.emptyList());
}
private CourseAdminSaveDTO validCourse() {
CourseAdminSaveDTO request = new CourseAdminSaveDTO();
request.setDate(Date.valueOf("2026-09-08"));
request.setSubjectTimes(2);
request.setTimeFrames(Collections.singletonList("09:00-10:20"));
request.setSubjectHour(new BigDecimal("1.0"));
request.setSubjectName(" 测试课程 ");
request.setTeacherId("teacher-1");
request.setType("理论");
return request;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment