Commit 226897b4 authored by wujipeng's avatar wujipeng
Browse files

管理员-教务管理-考试管理

parent fe3a8781
package com.platform.business.model.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/** 管理员新增考试计划请求。总分由服务端从试卷复制,不接受客户端直接指定。 */
@Data
public class ExamAdminSaveDTO {
private Integer classId;
private String name;
/** 仅支持“理论”或“实训”。 */
private String type;
@ApiModelProperty("考试准确开始时间,格式:yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examTime;
/** 考试时长,单位为分钟。 */
private Integer duration;
/** 开考后多少分钟内禁止交卷。 */
private Integer forbid;
private String chiefExaminerId;
private String invigilatorId;
private String paperId;
private String location;
/** 可不传;不传时按试卷总分的60%生成。 */
private BigDecimal passScore;
private List<String> studentIds;
}
package com.platform.business.model.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/**
* 管理员编辑考试计划请求。
*
* <p>试卷、监考教师、禁止交卷时间和应考学员不在原型编辑弹窗中,因此本请求有意不暴露
* 这些字段,防止普通编辑意外重建已经确定的考试关系。</p>
*/
@Data
public class ExamAdminUpdateDTO {
private String name;
private String type;
@ApiModelProperty("考试准确开始时间,格式:yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examTime;
private Integer duration;
private String chiefExaminerId;
private String location;
private BigDecimal passScore;
}
...@@ -8,6 +8,7 @@ import com.fasterxml.jackson.annotation.JsonFormat; ...@@ -8,6 +8,7 @@ import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
@Data @Data
...@@ -61,6 +62,30 @@ public class ExamEntity { ...@@ -61,6 +62,30 @@ public class ExamEntity {
@ApiModelProperty(value = "考试地点") @ApiModelProperty(value = "考试地点")
private String location; private String location;
/**
* 创建考试时从试卷复制的总分快照。
*
* <p>试卷后续被修改时,已经安排的考试仍应保持原总分,因此不能在查询时实时读取
* theoretical_paper.sum。</p>
*/
@ApiModelProperty(value = "考试总分快照")
@TableField("total_score")
private BigDecimal totalScore;
@ApiModelProperty(value = "合格分")
@TableField("pass_score")
private BigDecimal passScore;
@ApiModelProperty(value = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField("create_time")
private Date createTime;
@ApiModelProperty(value = "更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField("update_time")
private Date updateTime;
@ApiModelProperty(value = "考试状态") @ApiModelProperty(value = "考试状态")
@TableField(exist = false) @TableField(exist = false)
private Boolean status; private Boolean status;
......
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
import java.util.List;
/** 考试管理页面右侧的班级摘要与未结束考试计划。 */
@Data
public class ExamAdminClassVO {
private Integer classId;
private String className;
private String occupation;
private Integer trainingYear;
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 String termName;
private Integer studentCount;
private Integer plannedCount;
private List<ExamAdminDetailVO> exams;
}
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 ExamAdminDetailVO {
private Integer id;
private Integer classId;
private String className;
private String name;
private String type;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examTime;
private Integer duration;
private Integer forbid;
private BigDecimal totalScore;
private BigDecimal passScore;
private String chiefExaminerId;
private String chiefExaminerName;
private String invigilatorId;
private String invigilatorName;
private String paperId;
private String paperName;
private String location;
/** UPCOMING、ONGOING或ENDED,由服务端实时派生。 */
private String status;
private String statusName;
/** 页面根据服务端判断控制按钮,不能仅靠本地时间自行推断。 */
private Boolean editable;
private Boolean deletable;
/** Mapper用于批量判断按钮权限的内部统计字段,不向前端暴露。 */
@JsonIgnore
private Integer attemptCount;
/** 详情接口返回;班级计划列表中可为空以缩小响应。 */
private List<String> studentIds;
}
package com.platform.business.model.vo;
import lombok.Data;
import java.util.List;
/** 管理员考试表单需要的教师、试卷和学员选项集合。 */
@Data
public class ExamAdminOptionsVO {
/** 首席考评员和监考教师共用同一份有效教师列表。 */
private List<ClassAdminOptionVO> teachers;
/** 仅返回与当前班级职业等级一致的试卷。 */
private List<ClassAdminOptionVO> papers;
private List<ExamAdminStudentOptionVO> students;
}
package com.platform.business.model.vo;
import lombok.Data;
import java.math.BigDecimal;
/** 新增考试弹窗中的班级学员选项及真实出勤统计。 */
@Data
public class ExamAdminStudentOptionVO {
private String userId;
private String name;
private String idCard;
private String sex;
private String phone;
private String factory;
/** NORMAL和LATE占全部有效出勤记录的百分比;没有记录时为空。 */
private BigDecimal attendanceRate;
}
package com.platform.business.constant;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* 管理员端考试管理使用的稳定业务常量。
*
* <p>考试类型沿用项目已有的中文业务值,避免新接口写入的数据在旧版学生端、阅卷端中
* 出现无法识别的英文枚举。状态不落库,而是根据开始时间和时长实时计算。</p>
*/
public final class ExamAdminConstants {
public static final String TYPE_THEORY = "理论";
public static final String TYPE_PRACTICE = "实训";
public static final Set<String> EXAM_TYPES = Collections.unmodifiableSet(
new LinkedHashSet<>(Arrays.asList(TYPE_THEORY, TYPE_PRACTICE)));
public static final String STATUS_UPCOMING = "UPCOMING";
public static final String STATUS_ONGOING = "ONGOING";
public static final String STATUS_ENDED = "ENDED";
public static final int MIN_DURATION_MINUTES = 15;
public static final int MAX_DURATION_MINUTES = 600;
public static final int MAX_NAME_LENGTH = 40;
public static final int MAX_LOCATION_LENGTH = 30;
public static final int MAX_STUDENT_COUNT = 500;
/** 合格分未填写时按试卷总分的60%生成,并保留两位小数。 */
public static final BigDecimal DEFAULT_PASS_RATE = new BigDecimal("0.60");
/** 所有考试时间判断都使用业务约定的中国标准时间,避免服务器部署时区影响状态。 */
public static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
private ExamAdminConstants() {
}
}
package com.platform.business.controller;
import com.platform.business.model.dto.ExamAdminSaveDTO;
import com.platform.business.model.dto.ExamAdminUpdateDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.ClassAdminTreeVO;
import com.platform.business.model.vo.ExamAdminClassVO;
import com.platform.business.model.vo.ExamAdminDetailVO;
import com.platform.business.model.vo.ExamAdminOptionsVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.ExamAdminService;
import com.platform.model.resp.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 java.util.List;
/**
* 管理员端“教务管理-考试管理”接口。
*
* <p>所有入口都从Authorization令牌解析当前用户并校验管理员角色,不接收客户端传入的
* 管理员ID。独立路径不会改变旧版学生考试、成绩和教师阅卷接口。</p>
*/
@Api(tags = "管理员端-考试管理")
@RestController
@RequestMapping("/exam/admin")
public class ExamAdminController {
@Resource
private ExamAdminService examAdminService;
@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(examAdminService.tree(keyword));
}
@ApiOperation("班级未结束考试计划")
@GetMapping("/classes/{classId}")
public Result<ExamAdminClassVO> classPlans(@PathVariable("classId") Integer classId,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(examAdminService.classPlans(classId));
}
@ApiOperation("考试表单选项")
@GetMapping("/classes/{classId}/options")
public Result<ExamAdminOptionsVO> options(@PathVariable("classId") Integer classId,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(examAdminService.options(classId));
}
@ApiOperation("考试计划详情")
@GetMapping("/{examId}")
public Result<ExamAdminDetailVO> detail(@PathVariable("examId") Integer examId,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(examAdminService.detail(examId));
}
@ApiOperation("新增考试计划")
@PostMapping
public Result<ExamAdminDetailVO> create(@RequestBody ExamAdminSaveDTO body,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(examAdminService.create(body));
}
@ApiOperation("编辑考试计划")
@PutMapping("/{examId}")
public Result<ExamAdminDetailVO> update(@PathVariable("examId") Integer examId,
@RequestBody ExamAdminUpdateDTO body,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(examAdminService.update(examId, body));
}
@ApiOperation("删除未开考计划")
@DeleteMapping("/{examId}")
public Result<Boolean> delete(@PathVariable("examId") Integer examId,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(examAdminService.delete(examId));
}
/** 统一执行管理员鉴权,确保后续新增入口不会遗漏权限保护。 */
private UserEntity requireAdmin(HttpServletRequest request) {
UserEntity administrator = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(administrator);
return administrator;
}
}
...@@ -3,6 +3,10 @@ package com.platform.business.mapper; ...@@ -3,6 +3,10 @@ package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.dto.ExamDTO; import com.platform.business.model.dto.ExamDTO;
import com.platform.business.model.entity.ExamEntity; import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.vo.ClassAdminOptionVO;
import com.platform.business.model.vo.ExamAdminClassVO;
import com.platform.business.model.vo.ExamAdminDetailVO;
import com.platform.business.model.vo.ExamAdminStudentOptionVO;
import com.platform.business.model.vo.ExamStudentVO; import com.platform.business.model.vo.ExamStudentVO;
import com.platform.business.model.vo.ExamVO; import com.platform.business.model.vo.ExamVO;
import com.platform.business.model.vo.TheoreticalPaperStudentDetailVO; import com.platform.business.model.vo.TheoreticalPaperStudentDetailVO;
...@@ -10,6 +14,7 @@ import org.apache.ibatis.annotations.Mapper; ...@@ -10,6 +14,7 @@ import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
import java.util.Date;
@Mapper @Mapper
public interface ExamMapper extends BaseMapper<ExamEntity> { public interface ExamMapper extends BaseMapper<ExamEntity> {
...@@ -38,4 +43,66 @@ public interface ExamMapper extends BaseMapper<ExamEntity> { ...@@ -38,4 +43,66 @@ public interface ExamMapper extends BaseMapper<ExamEntity> {
List<ExamStudentVO> gradesAnalysis(@Param("examId") int examId, @Param("studentId") String studentId); List<ExamStudentVO> gradesAnalysis(@Param("examId") int examId, @Param("studentId") String studentId);
/* ==================== 管理员端考试管理 ==================== */
/** 锁定班级行,使同一班级并发创建、编辑考试时串行完成冲突校验。 */
Integer lockAdminExamClass(@Param("classId") Integer classId);
/**
* 按固定顺序锁定教师与应考学员的用户行,避免跨班并发安排同一人员到重叠场次。
*/
List<String> lockAdminExamUsers(@Param("userIds") List<String> userIds);
/** 锁定所选班级成员关系,并返回真正属于该班级的学员ID。 */
List<String> lockAdminExamStudents(@Param("classId") Integer classId,
@Param("studentIds") List<String> studentIds);
/** 查询考试管理页面所需的班级基础信息。 */
ExamAdminClassVO selectAdminExamClass(@Param("classId") Integer classId);
/** 查询尚未结束的考试计划;历史考试由成绩管理模块负责。 */
List<ExamAdminDetailVO> selectAdminExamPlans(@Param("classId") Integer classId,
@Param("now") Date now);
ExamAdminDetailVO selectAdminExamDetail(@Param("examId") Integer examId);
List<String> selectAdminExamStudentIds(@Param("examId") Integer examId);
List<ClassAdminOptionVO> selectAdminExamTeacherOptions();
List<ClassAdminOptionVO> selectAdminExamPaperOptions(@Param("levelName") String levelName);
List<ExamAdminStudentOptionVO> selectAdminExamStudentOptions(@Param("classId") Integer classId);
int countAdminExamActiveTeacher(@Param("teacherId") String teacherId);
int countAdminExamDuplicateName(@Param("classId") Integer classId,
@Param("name") String name,
@Param("excludeId") Integer excludeId);
/**
* 查询与新时间段发生冲突的场次。冲突主体可以是班级、考评教师、监考教师或应考学员。
*/
List<ExamAdminDetailVO> selectAdminExamConflicts(@Param("startTime") Date startTime,
@Param("duration") Integer duration,
@Param("classId") Integer classId,
@Param("chiefId") String chiefId,
@Param("invigilatorId") String invigilatorId,
@Param("studentIds") List<String> studentIds,
@Param("excludeId") Integer excludeId);
/** 锁定考试主记录;返回空表示记录已被其他请求删除。 */
ExamEntity selectAdminExamForUpdate(@Param("examId") Integer examId);
/** 锁定本场全部应考关系,防止管理员写操作与学生点击开始考试并发穿透。 */
List<Integer> lockAdminExamCandidates(@Param("examId") Integer examId);
/** 任一考生已经开始、交卷或产生分数后,考试计划即不可再修改。 */
int countAdminExamAttempts(@Param("examId") Integer examId);
/** 只更新管理员编辑弹窗允许维护的字段。 */
int updateAdminExam(ExamEntity entity);
int deleteAdminExamStudents(@Param("examId") Integer examId);
} }
package com.platform.business.service;
import com.platform.business.model.dto.ExamAdminSaveDTO;
import com.platform.business.model.dto.ExamAdminUpdateDTO;
import com.platform.business.model.vo.ClassAdminTreeVO;
import com.platform.business.model.vo.ExamAdminClassVO;
import com.platform.business.model.vo.ExamAdminDetailVO;
import com.platform.business.model.vo.ExamAdminOptionsVO;
import java.util.List;
/** 管理员端考试计划业务接口,与既有学生考试和教师阅卷能力相互隔离。 */
public interface ExamAdminService {
List<ClassAdminTreeVO> tree(String keyword);
ExamAdminClassVO classPlans(Integer classId);
ExamAdminOptionsVO options(Integer classId);
ExamAdminDetailVO detail(Integer examId);
ExamAdminDetailVO create(ExamAdminSaveDTO request);
ExamAdminDetailVO update(Integer examId, ExamAdminUpdateDTO request);
boolean delete(Integer examId);
}
...@@ -132,7 +132,13 @@ public class ExamServiceImpl extends ServiceImpl<ExamMapper, ExamEntity> impleme ...@@ -132,7 +132,13 @@ public class ExamServiceImpl extends ServiceImpl<ExamMapper, ExamEntity> impleme
} }
//检查是否已经开始考试 //检查是否已经开始考试
ExamStudentEntity examStudent = examStudentService.getOne(new LambdaQueryWrapper<ExamStudentEntity>() ExamStudentEntity examStudent = examStudentService.getOne(new LambdaQueryWrapper<ExamStudentEntity>()
.eq(ExamStudentEntity::getExamId, examDTO.getId()).eq(ExamStudentEntity::getStudentId, examDTO.getUserId())); .eq(ExamStudentEntity::getExamId, examDTO.getId())
.eq(ExamStudentEntity::getStudentId, examDTO.getUserId())
// 与管理员考试编辑/删除使用同一行锁,避免临近开考时应考关系被并发移除。
.last("for update"));
if (ObjectUtils.isEmpty(examStudent)) {
return Result.fail("您不在本场考试名单中,或考试计划已取消");
}
if (!ObjectUtils.isEmpty(examStudent.getEndTime())) { if (!ObjectUtils.isEmpty(examStudent.getEndTime())) {
return Result.fail("考试已开始"); return Result.fail("考试已开始");
} }
......
...@@ -252,4 +252,257 @@ ...@@ -252,4 +252,257 @@
AND score IS NOT NULL AND score IS NOT NULL
GROUP BY type; GROUP BY type;
</select> </select>
<!-- ==================== 管理员端考试管理 ==================== -->
<select id="lockAdminExamClass" resultType="java.lang.Integer">
select id from `class` where id = #{classId} for update
</select>
<select id="lockAdminExamUsers" resultType="java.lang.String">
select id
from user
where id in
<foreach collection="userIds" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
order by id
for update
</select>
<select id="lockAdminExamStudents" resultType="java.lang.String">
select member.user_id
from class_student member
inner join user student on student.id = member.user_id
where member.class_id = #{classId}
and coalesce(student.del_flag, 0) = 0
and member.user_id in
<foreach collection="studentIds" item="studentId" open="(" separator="," close=")">
#{studentId}
</foreach>
order by member.user_id
for update
</select>
<select id="selectAdminExamClass" resultType="com.platform.business.model.vo.ExamAdminClassVO">
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,
(select count(*) from class_student member where member.class_id = c.id) as studentCount
from `class` c
left join sys_level level_info on cast(level_info.id as char) = c.level
where c.id = #{classId}
</select>
<sql id="adminExamDetailColumns">
e.id,
e.class_id as classId,
c.name as className,
e.name,
e.type,
e.exam_time as examTime,
e.duration,
e.forbid,
e.total_score as totalScore,
e.pass_score as passScore,
e.chief_id as chiefExaminerId,
coalesce(nullif(chief_user.nick_name, ''), chief_user.username) as chiefExaminerName,
e.invigilation_id as invigilatorId,
coalesce(nullif(invigilator.nick_name, ''), invigilator.username) as invigilatorName,
e.paper_id as paperId,
paper.name as paperName,
e.location,
(select count(*)
from exam_student attempt
where attempt.exam_id = e.id
and (attempt.start_time is not null
or attempt.end_time is not null
or coalesce(attempt.submit, 0) = 1
or attempt.score is not null)) as attemptCount
</sql>
<select id="selectAdminExamPlans" resultType="com.platform.business.model.vo.ExamAdminDetailVO">
select <include refid="adminExamDetailColumns"/>
from exam e
inner join `class` c on c.id = e.class_id
left join user chief_user on chief_user.id = e.chief_id
left join user invigilator on invigilator.id = e.invigilation_id
left join theoretical_paper paper on paper.id = e.paper_id
where e.class_id = #{classId}
and timestampadd(minute, coalesce(e.duration, 0), e.exam_time) &gt; #{now}
order by e.exam_time asc, e.id asc
</select>
<select id="selectAdminExamDetail" resultType="com.platform.business.model.vo.ExamAdminDetailVO">
select <include refid="adminExamDetailColumns"/>
from exam e
inner join `class` c on c.id = e.class_id
left join user chief_user on chief_user.id = e.chief_id
left join user invigilator on invigilator.id = e.invigilation_id
left join theoretical_paper paper on paper.id = e.paper_id
where e.id = #{examId}
</select>
<select id="selectAdminExamStudentIds" resultType="java.lang.String">
select student_id
from exam_student
where exam_id = #{examId}
order by id asc
</select>
<select id="selectAdminExamTeacherOptions"
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.id asc
</select>
<select id="selectAdminExamPaperOptions"
resultType="com.platform.business.model.vo.ClassAdminOptionVO">
select
paper.id as value,
paper.name as label,
paper.lev as parentValue,
concat(coalesce(paper.num, 0), '题 · ', coalesce(paper.sum, 0), '分') as extra
from theoretical_paper paper
where paper.lev = #{levelName}
order by paper.create_time desc, paper.id desc
</select>
<select id="selectAdminExamStudentOptions"
resultType="com.platform.business.model.vo.ExamAdminStudentOptionVO">
select
member.user_id as userId,
coalesce(nullif(student.nick_name, ''), student.username) as name,
student.id_card as idCard,
student.sex,
student.phone_number as phone,
student.factory,
attendance.attendanceRate
from class_student member
inner join user student on student.id = member.user_id
left join (
select
record.user_id,
round(sum(case when record.status in ('NORMAL', 'LATE') then 1 else 0 end)
* 100.0 / count(record.id), 2) as attendanceRate
from class_subject_attendance record
inner join class_subject subject on subject.id = record.subject_id
where subject.class_id = #{classId}
and record.status in ('NORMAL', 'LATE', 'ABSENT', 'LEAVE')
group by record.user_id
) attendance on attendance.user_id = member.user_id
where member.class_id = #{classId}
and coalesce(student.del_flag, 0) = 0
order by name asc, student.phone_number asc, member.id asc
</select>
<select id="countAdminExamActiveTeacher" resultType="java.lang.Integer">
select count(distinct teacher.id)
from user teacher
inner join phone_role role_info
on role_info.phone = teacher.phone_number and role_info.role_name = '教师'
where teacher.id = #{teacherId}
and coalesce(teacher.del_flag, 0) = 0
</select>
<select id="countAdminExamDuplicateName" resultType="java.lang.Integer">
select count(*)
from exam
where class_id = #{classId}
and name = #{name}
<if test="excludeId != null">
and id &lt;&gt; #{excludeId}
</if>
</select>
<select id="selectAdminExamConflicts"
resultType="com.platform.business.model.vo.ExamAdminDetailVO">
select distinct <include refid="adminExamDetailColumns"/>
from exam e
inner join `class` c on c.id = e.class_id
left join user chief_user on chief_user.id = e.chief_id
left join user invigilator on invigilator.id = e.invigilation_id
left join theoretical_paper paper on paper.id = e.paper_id
where e.exam_time &lt; timestampadd(minute, #{duration}, #{startTime})
and timestampadd(minute, coalesce(e.duration, 0), e.exam_time) &gt; #{startTime}
<if test="excludeId != null">
and e.id &lt;&gt; #{excludeId}
</if>
and (
e.class_id = #{classId}
or e.chief_id in (#{chiefId}, #{invigilatorId})
or find_in_set(#{chiefId}, replace(coalesce(e.invigilation_id, ''), ' ', '')) &gt; 0
or find_in_set(#{invigilatorId}, replace(coalesce(e.invigilation_id, ''), ' ', '')) &gt; 0
or exists (
select 1
from exam_student conflict_student
where conflict_student.exam_id = e.id
and conflict_student.student_id in
<foreach collection="studentIds" item="studentId" open="(" separator="," close=")">
#{studentId}
</foreach>
)
)
order by e.exam_time asc, e.id asc
</select>
<select id="selectAdminExamForUpdate"
resultType="com.platform.business.model.entity.ExamEntity">
select
id, class_id, name, exam_time, type, duration, forbid, chief_id,
invigilation_id, paper_id, location, total_score, pass_score,
create_time, update_time, mark_flag
from exam
where id = #{examId}
for update
</select>
<select id="countAdminExamAttempts" resultType="java.lang.Integer">
select count(*)
from exam_student
where exam_id = #{examId}
and (start_time is not null
or end_time is not null
or coalesce(submit, 0) = 1
or score is not null)
</select>
<select id="lockAdminExamCandidates" resultType="java.lang.Integer">
select id
from exam_student
where exam_id = #{examId}
order by id
for update
</select>
<update id="updateAdminExam">
update exam
set name = #{name},
type = #{type},
exam_time = #{examTime},
duration = #{duration},
chief_id = #{chiefId},
location = #{location,jdbcType=VARCHAR},
pass_score = #{passScore},
update_time = #{updateTime}
where id = #{id}
</update>
<delete id="deleteAdminExamStudents">
delete from exam_student where exam_id = #{examId}
</delete>
</mapper> </mapper>
# 管理员端考试管理接口
接口统一使用 `/exam/admin` 前缀。所有请求必须携带 `Authorization`,服务端从JWT解析
当前用户并校验 `phone_role.role_name=管理员`,不接受客户端提交管理员用户ID。
部署前依次执行:
1. `src/main/resources/sql/class_management.sql`
2. `src/main/resources/sql/exam_management.sql`
考试状态不写入数据库:开始前为 `UPCOMING`,开始后至“开始时间+时长”为 `ONGOING`,
之后为 `ENDED`。考试计划页只返回尚未结束的场次,历史成绩继续由成绩管理模块查询。
## 1. 班级导航树
`GET /exam/admin/tree?keyword=污水`
返回 `OCCUPATION → YEAR → LEVEL → CLASS` 四层节点,结构与班级管理接口一致。班级叶节点
的 `classId` 用于后续计划、选项和新增请求。
## 2. 班级考试计划
`GET /exam/admin/classes/{classId}`
返回班级名称、工种、年度、等级、培训日期、学期、学员人数和未结束考试数组。每场考试包括
开始时间、时长、总分/合格分、考评员、监考教师、试卷、考场、状态以及服务端计算的
`editable/deletable`,页面不能仅按本地时间决定是否允许操作。
## 3. 表单选项
`GET /exam/admin/classes/{classId}/options`
- `teachers`:未删除且具有教师角色的用户,首席考评员和监考教师共用。
- `papers`:`theoretical_paper.lev` 与班级等级名称完全一致的试卷;理论、实训考试共用。
- `students`:当前班级有效学员,包含身份证号、性别、手机号、单位和个人出勤率。
出勤率按 `NORMAL/LATE` 占 `NORMAL/LATE/ABSENT/LEAVE` 的百分比计算;没有有效记录时为
`null`,由页面展示为“—”。
## 4. 考试详情
`GET /exam/admin/{examId}`
返回列表字段以及 `studentIds`。总分是创建时从试卷复制的快照,只读,不因试卷后续修改而
变化。
## 5. 新增考试
`POST /exam/admin`
```json
{
"classId": 10,
"name": "污水一级·2026秋·第一次理论考试",
"type": "理论",
"examTime": "2026-09-18 09:00:00",
"duration": 90,
"forbid": 30,
"chiefExaminerId": "1900000000000000001",
"invigilatorId": "1900000000000000002",
"paperId": "1900000000000000100",
"location": "教学楼A-301",
"passScore": 60,
"studentIds": ["1900000000000000201", "1900000000000000202"]
}
```
- 类型只支持“理论”“实训”;考试日期必须位于班级培训起止日期内。
- 时长为15~600分钟;`forbid` 为0~考试时长。
- 试卷必须与班级等级一致,总分从试卷复制;`passScore` 不传时默认为总分的60%。
- 至少选择1名、最多500名班级学员,ID不得重复。
- 同班级、首席考评员、监考教师或任一应考学员的考试时间不能重叠。
- 同一班级内考试名称不能重复。
成功后返回完整考试详情。考试与应考关系在同一事务内保存,任一步失败都会回滚。
## 6. 编辑考试
`PUT /exam/admin/{examId}`
```json
{
"name": "污水一级·2026秋·理论考试(一)",
"type": "理论",
"examTime": "2026-09-18 09:30:00",
"duration": 90,
"chiefExaminerId": "1900000000000000001",
"location": "教学楼A-302",
"passScore": 60
}
```
编辑不改变试卷、总分快照、监考教师、禁止交卷时间或应考学员。考试已到开始时间,或任一
考生已开始、交卷、产生分数后禁止编辑。新的时间和教师安排仍会执行完整冲突校验。
## 7. 删除考试
`DELETE /exam/admin/{examId}`
仅允许删除未到开始时间且无人开始/交卷/产生分数的考试。服务端在事务中先删除
`exam_student` 应考关系,再删除 `exam` 主记录;历史成绩和进行中考试不会被删除。
-- 管理员端“教务管理-考试管理”增量数据库脚本(MySQL 5.7+/8.0)。
--
-- 执行顺序:先执行class_management.sql,确保班级工种、年度和培训日期可用于考试校验。
-- 设计说明:
-- 1. 项目已经存在exam和exam_student表,本脚本只补充分数快照、审计字段及常用索引。
-- 2. 所有变更都通过information_schema判断,可在不同环境重复执行。
-- 3. 沿用项目现有的服务层关系校验方式,不新增外键,避免历史孤儿数据阻断部署。
delimiter $$
drop procedure if exists migrate_exam_management$$
create procedure migrate_exam_management()
begin
if not exists (
select 1 from information_schema.columns
where table_schema = database() and table_name = 'exam' and column_name = 'total_score'
) then
alter table exam
add column total_score decimal(8,2) null comment '创建考试时复制的试卷总分快照' after location;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema = database() and table_name = 'exam' and column_name = 'pass_score'
) then
alter table exam
add column pass_score decimal(8,2) null comment '考试合格分' after total_score;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema = database() and table_name = 'exam' and column_name = 'create_time'
) then
alter table exam
add column create_time datetime null comment '创建时间' after pass_score;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema = database() and table_name = 'exam' and column_name = 'update_time'
) then
alter table exam
add column update_time datetime null comment '更新时间' after create_time;
end if;
-- 班级计划页和班级时间冲突校验均按class_id、exam_time缩小范围。
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'exam' and index_name = 'idx_exam_class_time'
) then
alter table exam add index idx_exam_class_time (class_id, exam_time, id);
end if;
-- 全局计划状态与教师时间冲突查询使用以下索引;invigilation_id仍兼容旧版逗号分隔值。
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'exam' and index_name = 'idx_exam_time'
) then
alter table exam add index idx_exam_time (exam_time, id);
end if;
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'exam' and index_name = 'idx_exam_chief_time'
) then
alter table exam add index idx_exam_chief_time (chief_id, exam_time, id);
end if;
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'exam_student'
and index_name = 'idx_exam_student_exam_user'
) then
alter table exam_student add index idx_exam_student_exam_user (exam_id, student_id);
end if;
end$$
call migrate_exam_management()$$
drop procedure if exists migrate_exam_management$$
delimiter ;
-- 旧考试尽可能从关联试卷回填总分;没有有效试卷的数据保持NULL,避免伪造业务分值。
update exam e
left join theoretical_paper paper on paper.id = e.paper_id
set e.total_score = coalesce(e.total_score, paper.sum),
e.pass_score = coalesce(
e.pass_score,
round(coalesce(e.total_score, paper.sum) * 0.60, 2)
),
e.update_time = coalesce(e.update_time, now())
where e.total_score is null
or e.pass_score is null
or e.update_time is null;
-- 执行后可用该只读查询定位无法从旧试卷关系补齐的考试。
select e.id, e.name, e.paper_id, e.total_score, e.pass_score
from exam e
where e.total_score is null or e.pass_score is null;
package com.platform.business.controller;
import com.platform.business.model.dto.ExamAdminSaveDTO;
import com.platform.business.model.dto.ExamAdminUpdateDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.ExamAdminService;
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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 管理员考试控制器鉴权与路由参数转发测试。 */
@ExtendWith(MockitoExtension.class)
class ExamAdminControllerTest {
@Mock
private ExamAdminService examAdminService;
@Mock
private AuthenticatedUserService authenticatedUserService;
private ExamAdminController controller;
@BeforeEach
void setUp() {
controller = new ExamAdminController();
ReflectionTestUtils.setField(controller, "examAdminService", examAdminService);
ReflectionTestUtils.setField(controller, "authenticatedUserService", authenticatedUserService);
}
@Test
void everyEndpointShouldRequireAdminAndForwardParameters() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity administrator = new UserEntity();
when(authenticatedUserService.current(request)).thenReturn(administrator);
ExamAdminSaveDTO createBody = new ExamAdminSaveDTO();
ExamAdminUpdateDTO updateBody = new ExamAdminUpdateDTO();
controller.tree("污水", request);
controller.classPlans(10, request);
controller.options(10, request);
controller.detail(20, request);
controller.create(createBody, request);
controller.update(20, updateBody, request);
controller.delete(20, request);
verify(authenticatedUserService, times(7)).requireAdmin(administrator);
verify(examAdminService).tree("污水");
verify(examAdminService).classPlans(10);
verify(examAdminService).options(10);
verify(examAdminService).detail(20);
verify(examAdminService).create(createBody);
verify(examAdminService).update(20, updateBody);
verify(examAdminService).delete(20);
}
@Test
void endpointShouldStopBeforeServiceWhenUserIsNotAdmin() {
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.classPlans(10, request));
}
}
package com.platform.business.mapper;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 确保管理员考试新增的动态SQL在应用启动前即可被MyBatis完整解析。 */
class ExamMapperXmlTest {
@Test
void mapperXmlShouldParseAndRegisterAdminStatements() throws Exception {
String resource = "com/platform/business/mapper/ExamMapper.xml";
Configuration configuration = new Configuration();
try (InputStream input = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder builder = new XMLMapperBuilder(
input, configuration, resource, configuration.getSqlFragments());
builder.parse();
}
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.ExamMapper.selectAdminExamPlans"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.ExamMapper.selectAdminExamConflicts"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.ExamMapper.updateAdminExam"));
}
}
package com.platform.business.service.impl;
import com.platform.business.constant.ExamAdminConstants;
import com.platform.business.mapper.ExamMapper;
import com.platform.business.model.dto.ExamAdminSaveDTO;
import com.platform.business.model.dto.ExamAdminUpdateDTO;
import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.entity.ExamStudentEntity;
import com.platform.business.model.entity.TheoreticalPaperEntity;
import com.platform.business.model.vo.ExamAdminClassVO;
import com.platform.business.model.vo.ExamAdminDetailVO;
import com.platform.business.service.ClassAdminService;
import com.platform.business.service.ExamStudentService;
import com.platform.business.service.TheoreticalPaperService;
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.Timestamp;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
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 ExamAdminServiceImplTest {
@Mock
private ExamMapper examMapper;
@Mock
private ClassAdminService classAdminService;
@Mock
private TheoreticalPaperService theoreticalPaperService;
@Mock
private ExamStudentService examStudentService;
@InjectMocks
private ExamAdminServiceImpl service;
@Test
void createShouldSnapshotPaperScoreAndSaveAllCandidates() {
ExamAdminSaveDTO request = validCreateRequest();
mockWritableClass();
mockValidPaper();
mockValidRelationships();
when(examMapper.countAdminExamDuplicateName(1, "测试考试", null)).thenReturn(0);
when(examMapper.selectAdminExamConflicts(any(), eq(90), eq(1),
eq("teacher-1"), eq("teacher-2"), anyList(), eq(null)))
.thenReturn(Collections.emptyList());
when(examMapper.insert(any(ExamEntity.class))).thenAnswer(invocation -> {
ExamEntity entity = invocation.getArgument(0);
entity.setId(99);
return 1;
});
when(examStudentService.saveBatch(anyList())).thenReturn(true);
ExamAdminDetailVO savedDetail = new ExamAdminDetailVO();
savedDetail.setId(99);
savedDetail.setExamTime(request.getExamTime());
savedDetail.setDuration(90);
when(examMapper.selectAdminExamDetail(99)).thenReturn(savedDetail);
when(examMapper.selectAdminExamStudentIds(99)).thenReturn(request.getStudentIds());
ExamAdminDetailVO result = service.create(request);
ArgumentCaptor<ExamEntity> examCaptor = ArgumentCaptor.forClass(ExamEntity.class);
verify(examMapper).insert(examCaptor.capture());
assertEquals(new BigDecimal("100.00"), examCaptor.getValue().getTotalScore());
assertEquals(new BigDecimal("60.00"), examCaptor.getValue().getPassScore());
assertEquals("teacher-2", examCaptor.getValue().getInvigilationId());
assertEquals(99, result.getId());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<ExamStudentEntity>> studentsCaptor =
ArgumentCaptor.forClass((Class) List.class);
verify(examStudentService).saveBatch(studentsCaptor.capture());
assertEquals(2, studentsCaptor.getValue().size());
assertFalse(studentsCaptor.getValue().get(0).getSubmit());
}
@Test
void createShouldRejectPaperFromAnotherLevel() {
ExamAdminSaveDTO request = validCreateRequest();
mockWritableClass();
TheoreticalPaperEntity paper = new TheoreticalPaperEntity();
paper.setId("paper-1");
paper.setLev("污水二级");
paper.setSum(100D);
when(theoreticalPaperService.getById("paper-1")).thenReturn(paper);
BusinessException error = assertThrows(BusinessException.class,
() -> service.create(request));
assertEquals("所选试卷等级与班级职业等级不匹配", error.getMessage());
verify(examMapper, never()).insert(any(ExamEntity.class));
}
@Test
void createShouldRejectDuplicateCandidateIdsBeforeWritingExam() {
ExamAdminSaveDTO request = validCreateRequest();
request.setStudentIds(Arrays.asList("student-1", "student-1"));
mockWritableClass();
BusinessException error = assertThrows(BusinessException.class,
() -> service.create(request));
assertEquals("应考学员不能重复选择", error.getMessage());
verify(examMapper, never()).insert(any(ExamEntity.class));
}
@Test
void createShouldRejectStudentOutsideClass() {
ExamAdminSaveDTO request = validCreateRequest();
mockWritableClass();
mockValidPaper();
when(examMapper.lockAdminExamUsers(anyList()))
.thenReturn(Arrays.asList("student-1", "student-2", "teacher-1", "teacher-2"));
when(examMapper.countAdminExamActiveTeacher("teacher-1")).thenReturn(1);
when(examMapper.countAdminExamActiveTeacher("teacher-2")).thenReturn(1);
when(examMapper.lockAdminExamStudents(1, request.getStudentIds()))
.thenReturn(Collections.singletonList("student-1"));
BusinessException error = assertThrows(BusinessException.class,
() -> service.create(request));
assertEquals("应考学员中存在不属于当前班级或已移除的学员", error.getMessage());
verify(examMapper, never()).insert(any(ExamEntity.class));
}
@Test
void createShouldReturnSpecificClassConflict() {
ExamAdminSaveDTO request = validCreateRequest();
mockWritableClass();
mockValidPaper();
mockValidRelationships();
when(examMapper.countAdminExamDuplicateName(1, "测试考试", null)).thenReturn(0);
ExamAdminDetailVO conflict = new ExamAdminDetailVO();
conflict.setId(8);
conflict.setClassId(1);
conflict.setName("已有考试");
when(examMapper.selectAdminExamConflicts(any(), eq(90), eq(1),
eq("teacher-1"), eq("teacher-2"), anyList(), eq(null)))
.thenReturn(Collections.singletonList(conflict));
BusinessException error = assertThrows(BusinessException.class,
() -> service.create(request));
assertEquals("与本班考试“已有考试”时间冲突", error.getMessage());
verify(examMapper, never()).insert(any(ExamEntity.class));
}
@Test
void updateShouldRejectExamThatHasStarted() {
ExamEntity existing = new ExamEntity();
existing.setId(7);
existing.setExamTime(Timestamp.valueOf("2020-01-01 09:00:00"));
when(examMapper.selectAdminExamForUpdate(7)).thenReturn(existing);
BusinessException error = assertThrows(BusinessException.class,
() -> service.update(7, new ExamAdminUpdateDTO()));
assertEquals("考试已经开始,不能编辑或删除", error.getMessage());
verify(examMapper, never()).updateAdminExam(any(ExamEntity.class));
}
@Test
void updateShouldChangeOnlyEditableFieldsAndKeepScoreSnapshot() {
ExamEntity existing = new ExamEntity();
existing.setId(7);
existing.setClassId(1);
existing.setExamTime(Timestamp.valueOf("2099-09-18 09:00:00"));
existing.setInvigilationId("teacher-2");
existing.setPaperId("paper-1");
existing.setTotalScore(new BigDecimal("100.00"));
existing.setPassScore(new BigDecimal("60.00"));
when(examMapper.selectAdminExamForUpdate(7)).thenReturn(existing);
when(examMapper.countAdminExamAttempts(7)).thenReturn(0);
when(examMapper.lockAdminExamClass(1)).thenReturn(1);
when(examMapper.selectAdminExamClass(1)).thenReturn(managedClass());
when(examMapper.selectAdminExamStudentIds(7))
.thenReturn(Arrays.asList("student-1", "student-2"));
mockValidRelationships();
when(examMapper.countAdminExamDuplicateName(1, "修改后考试", 7)).thenReturn(0);
when(examMapper.selectAdminExamConflicts(any(), eq(120), eq(1),
eq("teacher-1"), eq("teacher-2"), anyList(), eq(7)))
.thenReturn(Collections.emptyList());
when(examMapper.updateAdminExam(any(ExamEntity.class))).thenReturn(1);
ExamAdminDetailVO detail = new ExamAdminDetailVO();
detail.setId(7);
detail.setExamTime(Timestamp.valueOf("2099-09-19 10:00:00"));
detail.setDuration(120);
when(examMapper.selectAdminExamDetail(7)).thenReturn(detail);
ExamAdminUpdateDTO request = new ExamAdminUpdateDTO();
request.setName("修改后考试");
request.setType("实训");
request.setExamTime(Timestamp.valueOf("2099-09-19 10:00:00"));
request.setDuration(120);
request.setChiefExaminerId("teacher-1");
request.setLocation("B-102");
request.setPassScore(new BigDecimal("70"));
service.update(7, request);
ArgumentCaptor<ExamEntity> captor = ArgumentCaptor.forClass(ExamEntity.class);
verify(examMapper).updateAdminExam(captor.capture());
assertEquals(new BigDecimal("70.00"), captor.getValue().getPassScore());
// SQL更新语句不包含以下字段;实体保持null可防止后续误改试卷、监考和总分快照。
assertEquals(null, captor.getValue().getPaperId());
assertEquals(null, captor.getValue().getInvigilationId());
assertEquals(null, captor.getValue().getTotalScore());
}
@Test
void createShouldPropagateCandidateFailureForTransactionRollback() {
ExamAdminSaveDTO request = validCreateRequest();
mockWritableClass();
mockValidPaper();
mockValidRelationships();
when(examMapper.countAdminExamDuplicateName(1, "测试考试", null)).thenReturn(0);
when(examMapper.selectAdminExamConflicts(any(), eq(90), eq(1),
eq("teacher-1"), eq("teacher-2"), anyList(), eq(null)))
.thenReturn(Collections.emptyList());
when(examMapper.insert(any(ExamEntity.class))).thenAnswer(invocation -> {
ExamEntity entity = invocation.getArgument(0);
entity.setId(99);
return 1;
});
when(examStudentService.saveBatch(anyList())).thenReturn(false);
BusinessException error = assertThrows(BusinessException.class,
() -> service.create(request));
assertEquals("应考学员保存失败,请稍后重试", error.getMessage());
// create方法标记rollbackFor=Exception,异常会让已经插入的exam主记录随事务回滚。
verify(examMapper).insert(any(ExamEntity.class));
}
@Test
void deleteShouldRejectExamWithAttempts() {
ExamEntity existing = new ExamEntity();
existing.setId(7);
existing.setClassId(1);
existing.setExamTime(Timestamp.valueOf("2099-09-18 09:00:00"));
when(examMapper.selectAdminExamForUpdate(7)).thenReturn(existing);
when(examMapper.countAdminExamAttempts(7)).thenReturn(1);
BusinessException error = assertThrows(BusinessException.class,
() -> service.delete(7));
assertEquals("已有学员开始考试或产生作答数据,不能编辑或删除", error.getMessage());
verify(examMapper, never()).deleteAdminExamStudents(7);
}
@Test
void deleteShouldRemoveCandidatesBeforeExam() {
ExamEntity existing = new ExamEntity();
existing.setId(7);
existing.setClassId(1);
existing.setExamTime(Timestamp.valueOf("2099-09-18 09:00:00"));
when(examMapper.selectAdminExamForUpdate(7)).thenReturn(existing);
when(examMapper.countAdminExamAttempts(7)).thenReturn(0);
when(examMapper.deleteById(7)).thenReturn(1);
assertTrue(service.delete(7));
verify(examMapper).deleteAdminExamStudents(7);
verify(examMapper).deleteById(7);
}
@Test
void applyStatusShouldExposeOnlyUpcomingExamAsMutable() {
Date now = Timestamp.valueOf("2026-09-18 09:00:00");
ExamAdminDetailVO upcoming = new ExamAdminDetailVO();
upcoming.setExamTime(Timestamp.valueOf("2026-09-18 10:00:00"));
upcoming.setDuration(90);
upcoming.setAttemptCount(0);
ExamAdminDetailVO ongoing = new ExamAdminDetailVO();
ongoing.setExamTime(Timestamp.valueOf("2026-09-18 08:30:00"));
ongoing.setDuration(90);
service.applyStatus(upcoming, now);
service.applyStatus(ongoing, now);
assertEquals(ExamAdminConstants.STATUS_UPCOMING, upcoming.getStatus());
assertTrue(upcoming.getEditable());
assertEquals(ExamAdminConstants.STATUS_ONGOING, ongoing.getStatus());
assertFalse(ongoing.getEditable());
}
private void mockWritableClass() {
when(examMapper.lockAdminExamClass(1)).thenReturn(1);
when(examMapper.selectAdminExamClass(1)).thenReturn(managedClass());
}
private void mockValidPaper() {
TheoreticalPaperEntity paper = new TheoreticalPaperEntity();
paper.setId("paper-1");
paper.setLev("污水一级");
paper.setSum(100D);
when(theoreticalPaperService.getById("paper-1")).thenReturn(paper);
}
private void mockValidRelationships() {
when(examMapper.lockAdminExamUsers(anyList()))
.thenReturn(Arrays.asList("student-1", "student-2", "teacher-1", "teacher-2"));
when(examMapper.countAdminExamActiveTeacher("teacher-1")).thenReturn(1);
when(examMapper.countAdminExamActiveTeacher("teacher-2")).thenReturn(1);
when(examMapper.lockAdminExamStudents(eq(1), anyList()))
.thenReturn(Arrays.asList("student-1", "student-2"));
}
private ExamAdminClassVO managedClass() {
ExamAdminClassVO managedClass = new ExamAdminClassVO();
managedClass.setClassId(1);
managedClass.setClassName("测试班级");
managedClass.setLevelId("1");
managedClass.setLevelName("污水一级");
managedClass.setStartDate(java.sql.Date.valueOf("2099-09-01"));
managedClass.setEndDate(java.sql.Date.valueOf("2099-12-31"));
return managedClass;
}
private ExamAdminSaveDTO validCreateRequest() {
ExamAdminSaveDTO request = new ExamAdminSaveDTO();
request.setClassId(1);
request.setName(" 测试考试 ");
request.setType("理论");
request.setExamTime(Timestamp.valueOf("2099-09-18 09:00:00"));
request.setDuration(90);
request.setForbid(30);
request.setChiefExaminerId("teacher-1");
request.setInvigilatorId("teacher-2");
request.setPaperId("paper-1");
request.setLocation("A-301");
request.setStudentIds(Arrays.asList("student-1", "student-2"));
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