Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
邬吉朋
practical_train
Commits
226897b4
Commit
226897b4
authored
Aug 17, 2026
by
wujipeng
Browse files
管理员-教务管理-考试管理
parent
fe3a8781
Changes
19
Hide whitespace changes
Inline
Side-by-side
practical-api/practical-business-api/src/main/java/com/platform/business/model/dto/ExamAdminSaveDTO.java
0 → 100644
View file @
226897b4
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
;
}
practical-api/practical-business-api/src/main/java/com/platform/business/model/dto/ExamAdminUpdateDTO.java
0 → 100644
View file @
226897b4
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
;
}
practical-api/practical-business-api/src/main/java/com/platform/business/model/entity/ExamEntity.java
View file @
226897b4
...
...
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.annotation.JsonFormat;
import
io.swagger.annotations.ApiModelProperty
;
import
lombok.Data
;
import
java.math.BigDecimal
;
import
java.util.Date
;
@Data
...
...
@@ -61,6 +62,30 @@ public class ExamEntity {
@ApiModelProperty
(
value
=
"考试地点"
)
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
=
"考试状态"
)
@TableField
(
exist
=
false
)
private
Boolean
status
;
...
...
practical-api/practical-business-api/src/main/java/com/platform/business/model/vo/ExamAdminClassVO.java
0 → 100644
View file @
226897b4
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
;
}
practical-api/practical-business-api/src/main/java/com/platform/business/model/vo/ExamAdminDetailVO.java
0 → 100644
View file @
226897b4
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
;
}
practical-api/practical-business-api/src/main/java/com/platform/business/model/vo/ExamAdminOptionsVO.java
0 → 100644
View file @
226897b4
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
;
}
practical-api/practical-business-api/src/main/java/com/platform/business/model/vo/ExamAdminStudentOptionVO.java
0 → 100644
View file @
226897b4
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
;
}
practical-business/src/main/java/com/platform/business/constant/ExamAdminConstants.java
0 → 100644
View file @
226897b4
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
()
{
}
}
practical-business/src/main/java/com/platform/business/controller/ExamAdminController.java
0 → 100644
View file @
226897b4
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
;
}
}
practical-business/src/main/java/com/platform/business/mapper/ExamMapper.java
View file @
226897b4
...
...
@@ -3,6 +3,10 @@ package com.platform.business.mapper;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
import
com.platform.business.model.dto.ExamDTO
;
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.ExamVO
;
import
com.platform.business.model.vo.TheoreticalPaperStudentDetailVO
;
...
...
@@ -10,6 +14,7 @@ import org.apache.ibatis.annotations.Mapper;
import
org.apache.ibatis.annotations.Param
;
import
java.util.List
;
import
java.util.Date
;
@Mapper
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
);
/* ==================== 管理员端考试管理 ==================== */
/** 锁定班级行,使同一班级并发创建、编辑考试时串行完成冲突校验。 */
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
);
}
practical-business/src/main/java/com/platform/business/service/ExamAdminService.java
0 → 100644
View file @
226897b4
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
);
}
practical-business/src/main/java/com/platform/business/service/impl/ExamAdminServiceImpl.java
0 → 100644
View file @
226897b4
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.ClassAdminOptionVO
;
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.model.vo.ExamAdminStudentOptionVO
;
import
com.platform.business.service.ClassAdminService
;
import
com.platform.business.service.ExamAdminService
;
import
com.platform.business.service.ExamStudentService
;
import
com.platform.business.service.TheoreticalPaperService
;
import
com.platform.exception.BusinessException
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
javax.annotation.Resource
;
import
java.math.BigDecimal
;
import
java.math.RoundingMode
;
import
java.time.Instant
;
import
java.time.LocalDate
;
import
java.time.ZonedDateTime
;
import
java.util.ArrayList
;
import
java.util.Arrays
;
import
java.util.Collections
;
import
java.util.Date
;
import
java.util.LinkedHashSet
;
import
java.util.List
;
import
java.util.Set
;
import
java.util.TreeSet
;
/**
* 管理员端考试计划核心实现。
*
* <p>本实现不复用旧版 {@link ExamServiceImpl#saveOrUpdateExam},原因是旧入口缺少管理员鉴权、
* 计划锁定、时间冲突和严格关系校验。独立服务既保留旧接口兼容性,也确保管理端写入的数据
* 能安全地被学生考试与教师阅卷模块继续使用。</p>
*/
@Service
public
class
ExamAdminServiceImpl
implements
ExamAdminService
{
@Resource
private
ExamMapper
examMapper
;
@Resource
private
ClassAdminService
classAdminService
;
@Resource
private
TheoreticalPaperService
theoreticalPaperService
;
@Resource
private
ExamStudentService
examStudentService
;
@Override
public
List
<
ClassAdminTreeVO
>
tree
(
String
keyword
)
{
return
classAdminService
.
tree
(
keyword
);
}
@Override
@Transactional
(
readOnly
=
true
)
public
ExamAdminClassVO
classPlans
(
Integer
classId
)
{
requirePositiveId
(
classId
,
"班级ID"
);
ExamAdminClassVO
result
=
requireManagedClass
(
classId
);
result
.
setTermName
(
buildTermName
(
result
));
Date
now
=
businessNow
();
List
<
ExamAdminDetailVO
>
exams
=
examMapper
.
selectAdminExamPlans
(
classId
,
now
);
if
(
exams
==
null
)
{
exams
=
Collections
.
emptyList
();
}
for
(
ExamAdminDetailVO
exam
:
exams
)
{
applyStatus
(
exam
,
now
);
}
result
.
setExams
(
exams
);
result
.
setPlannedCount
(
exams
.
size
());
return
result
;
}
@Override
@Transactional
(
readOnly
=
true
)
public
ExamAdminOptionsVO
options
(
Integer
classId
)
{
requirePositiveId
(
classId
,
"班级ID"
);
ExamAdminClassVO
managedClass
=
requireManagedClass
(
classId
);
if
(
trimToNull
(
managedClass
.
getLevelName
())
==
null
)
{
throw
new
BusinessException
(
"班级职业等级尚未配置,无法筛选试卷"
);
}
ExamAdminOptionsVO
result
=
new
ExamAdminOptionsVO
();
List
<
ClassAdminOptionVO
>
teachers
=
examMapper
.
selectAdminExamTeacherOptions
();
List
<
ClassAdminOptionVO
>
papers
=
examMapper
.
selectAdminExamPaperOptions
(
managedClass
.
getLevelName
());
List
<
ExamAdminStudentOptionVO
>
students
=
examMapper
.
selectAdminExamStudentOptions
(
classId
);
result
.
setTeachers
(
teachers
==
null
?
Collections
.
emptyList
()
:
teachers
);
result
.
setPapers
(
papers
==
null
?
Collections
.
emptyList
()
:
papers
);
result
.
setStudents
(
students
==
null
?
Collections
.
emptyList
()
:
students
);
return
result
;
}
@Override
@Transactional
(
readOnly
=
true
)
public
ExamAdminDetailVO
detail
(
Integer
examId
)
{
requirePositiveId
(
examId
,
"考试ID"
);
ExamAdminDetailVO
detail
=
examMapper
.
selectAdminExamDetail
(
examId
);
if
(
detail
==
null
)
{
throw
new
BusinessException
(
"考试计划不存在或已删除"
);
}
List
<
String
>
studentIds
=
examMapper
.
selectAdminExamStudentIds
(
examId
);
detail
.
setStudentIds
(
studentIds
==
null
?
Collections
.
emptyList
()
:
studentIds
);
applyStatus
(
detail
,
businessNow
());
return
detail
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
ExamAdminDetailVO
create
(
ExamAdminSaveDTO
request
)
{
if
(
request
==
null
)
{
throw
new
BusinessException
(
"考试信息不能为空"
);
}
requirePositiveId
(
request
.
getClassId
(),
"班级ID"
);
// 先锁班级,再锁教师和班级成员;相同资源始终按固定顺序加锁,降低并发死锁概率。
if
(
examMapper
.
lockAdminExamClass
(
request
.
getClassId
())
==
null
)
{
throw
new
BusinessException
(
"班级不存在或已删除"
);
}
ExamAdminClassVO
managedClass
=
requireManagedClass
(
request
.
getClassId
());
List
<
String
>
studentIds
=
normalizeStudentIds
(
request
.
getStudentIds
());
PreparedExam
prepared
=
prepareCreate
(
request
,
managedClass
,
studentIds
);
lockAndValidateRelationships
(
request
.
getClassId
(),
prepared
.
chiefId
,
prepared
.
invigilatorId
,
studentIds
);
validateDuplicateName
(
request
.
getClassId
(),
prepared
.
name
,
null
);
validateConflicts
(
request
.
getClassId
(),
prepared
.
name
,
prepared
.
examTime
,
prepared
.
duration
,
prepared
.
chiefId
,
prepared
.
invigilatorId
,
studentIds
,
null
);
ExamEntity
entity
=
new
ExamEntity
();
entity
.
setClassId
(
request
.
getClassId
());
entity
.
setName
(
prepared
.
name
);
entity
.
setType
(
prepared
.
type
);
entity
.
setExamTime
(
prepared
.
examTime
);
entity
.
setDuration
(
prepared
.
duration
);
entity
.
setForbid
(
prepared
.
forbid
);
entity
.
setChiefId
(
prepared
.
chiefId
);
entity
.
setInvigilationId
(
prepared
.
invigilatorId
);
entity
.
setPaperId
(
prepared
.
paper
.
getId
());
entity
.
setLocation
(
prepared
.
location
);
entity
.
setTotalScore
(
prepared
.
totalScore
);
entity
.
setPassScore
(
prepared
.
passScore
);
entity
.
setMarkFlag
(
false
);
Date
now
=
businessNow
();
entity
.
setCreateTime
(
now
);
entity
.
setUpdateTime
(
now
);
if
(
examMapper
.
insert
(
entity
)
!=
1
||
entity
.
getId
()
<=
0
)
{
throw
new
BusinessException
(
"考试计划创建失败,请稍后重试"
);
}
List
<
ExamStudentEntity
>
candidates
=
new
ArrayList
<>(
studentIds
.
size
());
for
(
String
studentId
:
studentIds
)
{
candidates
.
add
(
ExamStudentEntity
.
builder
()
.
classId
(
request
.
getClassId
())
.
examId
(
entity
.
getId
())
.
studentId
(
studentId
)
.
submit
(
false
)
.
markFlag
(
false
)
.
build
());
}
if
(!
examStudentService
.
saveBatch
(
candidates
))
{
throw
new
BusinessException
(
"应考学员保存失败,请稍后重试"
);
}
return
detail
(
entity
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
ExamAdminDetailVO
update
(
Integer
examId
,
ExamAdminUpdateDTO
request
)
{
requirePositiveId
(
examId
,
"考试ID"
);
if
(
request
==
null
)
{
throw
new
BusinessException
(
"考试信息不能为空"
);
}
ExamEntity
existing
=
lockMutableExam
(
examId
);
if
(
examMapper
.
lockAdminExamClass
(
existing
.
getClassId
())
==
null
)
{
throw
new
BusinessException
(
"考试所属班级不存在或已删除"
);
}
ExamAdminClassVO
managedClass
=
requireManagedClass
(
existing
.
getClassId
());
List
<
String
>
studentIds
=
examMapper
.
selectAdminExamStudentIds
(
examId
);
if
(
studentIds
==
null
||
studentIds
.
isEmpty
())
{
throw
new
BusinessException
(
"考试没有应考学员,无法编辑"
);
}
PreparedUpdate
prepared
=
prepareUpdate
(
request
,
existing
,
managedClass
);
lockAndValidateRelationships
(
existing
.
getClassId
(),
prepared
.
chiefId
,
existing
.
getInvigilationId
(),
studentIds
);
validateDuplicateName
(
existing
.
getClassId
(),
prepared
.
name
,
examId
);
validateConflicts
(
existing
.
getClassId
(),
prepared
.
name
,
prepared
.
examTime
,
prepared
.
duration
,
prepared
.
chiefId
,
existing
.
getInvigilationId
(),
studentIds
,
examId
);
ExamEntity
update
=
new
ExamEntity
();
update
.
setId
(
examId
);
update
.
setName
(
prepared
.
name
);
update
.
setType
(
prepared
.
type
);
update
.
setExamTime
(
prepared
.
examTime
);
update
.
setDuration
(
prepared
.
duration
);
update
.
setChiefId
(
prepared
.
chiefId
);
update
.
setLocation
(
prepared
.
location
);
update
.
setPassScore
(
prepared
.
passScore
);
update
.
setUpdateTime
(
businessNow
());
if
(
examMapper
.
updateAdminExam
(
update
)
!=
1
)
{
throw
new
BusinessException
(
"考试计划已发生变化,请刷新后重试"
);
}
return
detail
(
examId
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
delete
(
Integer
examId
)
{
requirePositiveId
(
examId
,
"考试ID"
);
ExamEntity
existing
=
lockMutableExam
(
examId
);
// 先删除尚未作答的应考关系,再删除主记录,避免没有数据库外键的旧环境遗留孤儿数据。
examMapper
.
deleteAdminExamStudents
(
examId
);
if
(
examMapper
.
deleteById
(
existing
.
getId
())
!=
1
)
{
throw
new
BusinessException
(
"考试计划已发生变化,请刷新后重试"
);
}
return
true
;
}
/** 新增时校验试卷并生成不可变总分快照。 */
private
PreparedExam
prepareCreate
(
ExamAdminSaveDTO
request
,
ExamAdminClassVO
managedClass
,
List
<
String
>
studentIds
)
{
PreparedExam
prepared
=
new
PreparedExam
();
prepared
.
name
=
normalizeName
(
request
.
getName
());
prepared
.
type
=
normalizeType
(
request
.
getType
());
prepared
.
examTime
=
requireFutureExamTime
(
request
.
getExamTime
(),
managedClass
);
prepared
.
duration
=
validateDuration
(
request
.
getDuration
());
prepared
.
forbid
=
validateForbid
(
request
.
getForbid
(),
prepared
.
duration
);
prepared
.
chiefId
=
requireText
(
request
.
getChiefExaminerId
(),
"首席考评员ID"
,
64
);
prepared
.
invigilatorId
=
requireText
(
request
.
getInvigilatorId
(),
"监考教师ID"
,
64
);
prepared
.
location
=
optionalText
(
request
.
getLocation
(),
"考场"
,
ExamAdminConstants
.
MAX_LOCATION_LENGTH
);
String
paperId
=
requireText
(
request
.
getPaperId
(),
"试卷ID"
,
64
);
TheoreticalPaperEntity
paper
=
theoreticalPaperService
.
getById
(
paperId
);
if
(
paper
==
null
)
{
throw
new
BusinessException
(
"所选试卷不存在或已删除"
);
}
if
(
trimToNull
(
managedClass
.
getLevelName
())
==
null
||
!
managedClass
.
getLevelName
().
equals
(
trimToNull
(
paper
.
getLev
())))
{
throw
new
BusinessException
(
"所选试卷等级与班级职业等级不匹配"
);
}
if
(
paper
.
getSum
()
==
null
||
!
Double
.
isFinite
(
paper
.
getSum
())
||
paper
.
getSum
()
<=
0
)
{
throw
new
BusinessException
(
"所选试卷总分无效"
);
}
prepared
.
paper
=
paper
;
prepared
.
totalScore
=
BigDecimal
.
valueOf
(
paper
.
getSum
()).
setScale
(
2
,
RoundingMode
.
HALF_UP
);
prepared
.
passScore
=
normalizePassScore
(
request
.
getPassScore
(),
prepared
.
totalScore
,
true
);
if
(
studentIds
.
size
()
>
ExamAdminConstants
.
MAX_STUDENT_COUNT
)
{
throw
new
BusinessException
(
"单场考试应考学员不能超过"
+
ExamAdminConstants
.
MAX_STUDENT_COUNT
+
"人"
);
}
return
prepared
;
}
/** 编辑不改变试卷及总分快照,合格分为空时保留旧值。 */
private
PreparedUpdate
prepareUpdate
(
ExamAdminUpdateDTO
request
,
ExamEntity
existing
,
ExamAdminClassVO
managedClass
)
{
PreparedUpdate
prepared
=
new
PreparedUpdate
();
prepared
.
name
=
normalizeName
(
request
.
getName
());
prepared
.
type
=
normalizeType
(
request
.
getType
());
prepared
.
examTime
=
requireFutureExamTime
(
request
.
getExamTime
(),
managedClass
);
prepared
.
duration
=
validateDuration
(
request
.
getDuration
());
prepared
.
chiefId
=
requireText
(
request
.
getChiefExaminerId
(),
"首席考评员ID"
,
64
);
prepared
.
location
=
optionalText
(
request
.
getLocation
(),
"考场"
,
ExamAdminConstants
.
MAX_LOCATION_LENGTH
);
if
(
existing
.
getTotalScore
()
==
null
||
existing
.
getTotalScore
().
compareTo
(
BigDecimal
.
ZERO
)
<=
0
)
{
throw
new
BusinessException
(
"考试总分快照缺失,请先执行考试管理数据库迁移脚本"
);
}
BigDecimal
requestedPass
=
request
.
getPassScore
()
==
null
?
existing
.
getPassScore
()
:
request
.
getPassScore
();
prepared
.
passScore
=
normalizePassScore
(
requestedPass
,
existing
.
getTotalScore
(),
false
);
return
prepared
;
}
/**
* 锁定并校验教师与班级成员。返回数量必须与请求完全一致,不能静默忽略跨班学员。
*/
private
void
lockAndValidateRelationships
(
Integer
classId
,
String
chiefId
,
String
invigilatorId
,
List
<
String
>
studentIds
)
{
Set
<
String
>
teacherIds
=
new
TreeSet
<>(
Arrays
.
asList
(
chiefId
,
invigilatorId
));
Set
<
String
>
allUserIds
=
new
TreeSet
<>(
teacherIds
);
allUserIds
.
addAll
(
studentIds
);
List
<
String
>
lockedUsers
=
examMapper
.
lockAdminExamUsers
(
new
ArrayList
<>(
allUserIds
));
if
(
lockedUsers
==
null
||
new
LinkedHashSet
<>(
lockedUsers
).
size
()
!=
allUserIds
.
size
())
{
throw
new
BusinessException
(
"所选教师或应考学员不存在"
);
}
if
(
examMapper
.
countAdminExamActiveTeacher
(
chiefId
)
!=
1
)
{
throw
new
BusinessException
(
"所选首席考评员不存在、已停用或不具有教师角色"
);
}
if
(
examMapper
.
countAdminExamActiveTeacher
(
invigilatorId
)
!=
1
)
{
throw
new
BusinessException
(
"所选监考教师不存在、已停用或不具有教师角色"
);
}
List
<
String
>
lockedStudents
=
examMapper
.
lockAdminExamStudents
(
classId
,
studentIds
);
Set
<
String
>
actualIds
=
lockedStudents
==
null
?
Collections
.
emptySet
()
:
new
LinkedHashSet
<>(
lockedStudents
);
if
(
actualIds
.
size
()
!=
studentIds
.
size
()
||
!
actualIds
.
containsAll
(
studentIds
))
{
throw
new
BusinessException
(
"应考学员中存在不属于当前班级或已移除的学员"
);
}
}
private
void
validateDuplicateName
(
Integer
classId
,
String
name
,
Integer
excludeId
)
{
if
(
examMapper
.
countAdminExamDuplicateName
(
classId
,
name
,
excludeId
)
>
0
)
{
throw
new
BusinessException
(
"同一班级内考试名称不能重复"
);
}
}
/** 将数据库返回的冲突场次转换为页面可直接展示的明确错误。 */
private
void
validateConflicts
(
Integer
classId
,
String
name
,
Date
startTime
,
Integer
duration
,
String
chiefId
,
String
invigilatorId
,
List
<
String
>
studentIds
,
Integer
excludeId
)
{
List
<
ExamAdminDetailVO
>
conflicts
=
examMapper
.
selectAdminExamConflicts
(
startTime
,
duration
,
classId
,
chiefId
,
invigilatorId
,
studentIds
,
excludeId
);
if
(
conflicts
==
null
||
conflicts
.
isEmpty
())
{
return
;
}
ExamAdminDetailVO
conflict
=
conflicts
.
get
(
0
);
String
conflictName
=
trimToNull
(
conflict
.
getName
())
==
null
?
"未命名考试"
:
conflict
.
getName
();
if
(
classId
.
equals
(
conflict
.
getClassId
()))
{
throw
new
BusinessException
(
"与本班考试“"
+
conflictName
+
"”时间冲突"
);
}
if
(
teacherMatches
(
conflict
,
chiefId
))
{
throw
new
BusinessException
(
"首席考评员与考试“"
+
conflictName
+
"”时间冲突"
);
}
if
(
teacherMatches
(
conflict
,
invigilatorId
))
{
throw
new
BusinessException
(
"监考教师与考试“"
+
conflictName
+
"”时间冲突"
);
}
throw
new
BusinessException
(
"应考学员与考试“"
+
conflictName
+
"”时间冲突"
);
}
private
boolean
teacherMatches
(
ExamAdminDetailVO
conflict
,
String
teacherId
)
{
if
(
teacherId
.
equals
(
conflict
.
getChiefExaminerId
()))
{
return
true
;
}
String
stored
=
trimToNull
(
conflict
.
getInvigilatorId
());
if
(
stored
==
null
)
{
return
false
;
}
for
(
String
value
:
stored
.
split
(
","
))
{
if
(
teacherId
.
equals
(
value
.
trim
()))
{
return
true
;
}
}
return
false
;
}
/** 锁定考试并统一执行“未开考且无人作答”的写操作前置条件。 */
private
ExamEntity
lockMutableExam
(
Integer
examId
)
{
ExamEntity
existing
=
examMapper
.
selectAdminExamForUpdate
(
examId
);
if
(
existing
==
null
)
{
throw
new
BusinessException
(
"考试计划不存在或已删除"
);
}
if
(
existing
.
getExamTime
()
==
null
||
!
existing
.
getExamTime
().
after
(
businessNow
()))
{
throw
new
BusinessException
(
"考试已经开始,不能编辑或删除"
);
}
// 与学生开始考试事务使用同一exam_student行锁,避免临近开考时删除正在启动的考试。
examMapper
.
lockAdminExamCandidates
(
examId
);
if
(
examMapper
.
countAdminExamAttempts
(
examId
)
>
0
)
{
throw
new
BusinessException
(
"已有学员开始考试或产生作答数据,不能编辑或删除"
);
}
return
existing
;
}
private
ExamAdminClassVO
requireManagedClass
(
Integer
classId
)
{
ExamAdminClassVO
managedClass
=
examMapper
.
selectAdminExamClass
(
classId
);
if
(
managedClass
==
null
)
{
throw
new
BusinessException
(
"班级不存在或已删除"
);
}
return
managedClass
;
}
private
Date
requireFutureExamTime
(
Date
examTime
,
ExamAdminClassVO
managedClass
)
{
if
(
examTime
==
null
)
{
throw
new
BusinessException
(
"考试开始时间不能为空"
);
}
if
(!
examTime
.
after
(
businessNow
()))
{
throw
new
BusinessException
(
"考试开始时间必须晚于当前时间"
);
}
if
(
managedClass
.
getStartDate
()
==
null
||
managedClass
.
getEndDate
()
==
null
)
{
throw
new
BusinessException
(
"班级培训日期尚未配置,无法安排考试"
);
}
LocalDate
examDate
=
toBusinessDate
(
examTime
);
LocalDate
classStart
=
toBusinessDate
(
managedClass
.
getStartDate
());
LocalDate
classEnd
=
toBusinessDate
(
managedClass
.
getEndDate
());
if
(
examDate
.
isBefore
(
classStart
)
||
examDate
.
isAfter
(
classEnd
))
{
throw
new
BusinessException
(
"考试日期必须位于班级培训起止日期内"
);
}
return
examTime
;
}
private
List
<
String
>
normalizeStudentIds
(
List
<
String
>
values
)
{
if
(
values
==
null
||
values
.
isEmpty
())
{
throw
new
BusinessException
(
"请至少选择1名应考学员"
);
}
List
<
String
>
normalized
=
new
ArrayList
<>(
values
.
size
());
Set
<
String
>
unique
=
new
LinkedHashSet
<>();
for
(
String
value
:
values
)
{
String
id
=
requireText
(
value
,
"学员ID"
,
64
);
if
(!
unique
.
add
(
id
))
{
throw
new
BusinessException
(
"应考学员不能重复选择"
);
}
normalized
.
add
(
id
);
}
return
normalized
;
}
private
String
normalizeName
(
String
value
)
{
return
requireText
(
value
,
"考试名称"
,
ExamAdminConstants
.
MAX_NAME_LENGTH
);
}
private
String
normalizeType
(
String
value
)
{
String
type
=
requireText
(
value
,
"考试类型"
,
8
);
if
(!
ExamAdminConstants
.
EXAM_TYPES
.
contains
(
type
))
{
throw
new
BusinessException
(
"考试类型只支持理论或实训"
);
}
return
type
;
}
private
int
validateDuration
(
Integer
duration
)
{
if
(
duration
==
null
||
duration
<
ExamAdminConstants
.
MIN_DURATION_MINUTES
||
duration
>
ExamAdminConstants
.
MAX_DURATION_MINUTES
)
{
throw
new
BusinessException
(
"考试时长必须在15到600分钟之间"
);
}
return
duration
;
}
private
int
validateForbid
(
Integer
forbid
,
int
duration
)
{
if
(
forbid
==
null
||
forbid
<
0
||
forbid
>
duration
)
{
throw
new
BusinessException
(
"禁止交卷时间必须在0到考试时长之间"
);
}
return
forbid
;
}
private
BigDecimal
normalizePassScore
(
BigDecimal
requested
,
BigDecimal
totalScore
,
boolean
useDefault
)
{
BigDecimal
passScore
=
requested
;
if
(
passScore
==
null
&&
useDefault
)
{
passScore
=
totalScore
.
multiply
(
ExamAdminConstants
.
DEFAULT_PASS_RATE
);
}
if
(
passScore
==
null
)
{
throw
new
BusinessException
(
"合格分不能为空"
);
}
passScore
=
passScore
.
setScale
(
2
,
RoundingMode
.
HALF_UP
);
if
(
passScore
.
compareTo
(
BigDecimal
.
ZERO
)
<
0
||
passScore
.
compareTo
(
totalScore
)
>
0
)
{
throw
new
BusinessException
(
"合格分必须在0到考试总分之间"
);
}
return
passScore
;
}
/** 根据当前时刻派生状态和按钮权限,状态本身不写入数据库。 */
void
applyStatus
(
ExamAdminDetailVO
exam
,
Date
now
)
{
if
(
exam
.
getExamTime
()
==
null
)
{
exam
.
setStatus
(
ExamAdminConstants
.
STATUS_ENDED
);
exam
.
setStatusName
(
"已结束"
);
exam
.
setEditable
(
false
);
exam
.
setDeletable
(
false
);
return
;
}
long
durationMillis
=
(
exam
.
getDuration
()
==
null
?
0L
:
exam
.
getDuration
().
longValue
())
*
60_000L
;
long
endMillis
=
exam
.
getExamTime
().
getTime
()
+
durationMillis
;
if
(
now
.
before
(
exam
.
getExamTime
()))
{
exam
.
setStatus
(
ExamAdminConstants
.
STATUS_UPCOMING
);
exam
.
setStatusName
(
"未开始"
);
boolean
mutable
=
exam
.
getAttemptCount
()
==
null
||
exam
.
getAttemptCount
()
==
0
;
exam
.
setEditable
(
mutable
);
exam
.
setDeletable
(
mutable
);
}
else
if
(
now
.
getTime
()
<
endMillis
)
{
exam
.
setStatus
(
ExamAdminConstants
.
STATUS_ONGOING
);
exam
.
setStatusName
(
"进行中"
);
exam
.
setEditable
(
false
);
exam
.
setDeletable
(
false
);
}
else
{
exam
.
setStatus
(
ExamAdminConstants
.
STATUS_ENDED
);
exam
.
setStatusName
(
"已结束"
);
exam
.
setEditable
(
false
);
exam
.
setDeletable
(
false
);
}
}
private
String
buildTermName
(
ExamAdminClassVO
managedClass
)
{
if
(
managedClass
.
getStartDate
()
==
null
)
{
return
managedClass
.
getTrainingYear
()
==
null
?
null
:
managedClass
.
getTrainingYear
()
+
" 学年"
;
}
LocalDate
start
=
toBusinessDate
(
managedClass
.
getStartDate
());
return
start
.
getYear
()
+
(
start
.
getMonthValue
()
<=
6
?
" 春"
:
" 秋"
);
}
private
LocalDate
toBusinessDate
(
Date
date
)
{
if
(
date
instanceof
java
.
sql
.
Date
)
{
return
((
java
.
sql
.
Date
)
date
).
toLocalDate
();
}
return
Instant
.
ofEpochMilli
(
date
.
getTime
())
.
atZone
(
ExamAdminConstants
.
BUSINESS_ZONE
).
toLocalDate
();
}
/** 单独封装当前时间,便于测试状态边界且集中维护业务时区约定。 */
Date
businessNow
()
{
ZonedDateTime
now
=
ZonedDateTime
.
now
(
ExamAdminConstants
.
BUSINESS_ZONE
);
return
Date
.
from
(
now
.
toInstant
());
}
private
void
requirePositiveId
(
Integer
value
,
String
fieldName
)
{
if
(
value
==
null
||
value
<=
0
)
{
throw
new
BusinessException
(
fieldName
+
"无效"
);
}
}
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
final
class
PreparedExam
{
private
String
name
;
private
String
type
;
private
Date
examTime
;
private
int
duration
;
private
int
forbid
;
private
String
chiefId
;
private
String
invigilatorId
;
private
String
location
;
private
TheoreticalPaperEntity
paper
;
private
BigDecimal
totalScore
;
private
BigDecimal
passScore
;
}
/** 编辑请求完成规范化后的工作数据。 */
private
static
final
class
PreparedUpdate
{
private
String
name
;
private
String
type
;
private
Date
examTime
;
private
int
duration
;
private
String
chiefId
;
private
String
location
;
private
BigDecimal
passScore
;
}
}
practical-business/src/main/java/com/platform/business/service/impl/ExamServiceImpl.java
View file @
226897b4
...
...
@@ -132,7 +132,13 @@ public class ExamServiceImpl extends ServiceImpl<ExamMapper, ExamEntity> impleme
}
//检查是否已经开始考试
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
()))
{
return
Result
.
fail
(
"考试已开始"
);
}
...
...
practical-business/src/main/resources/com/platform/business/mapper/ExamMapper.xml
View file @
226897b4
...
...
@@ -252,4 +252,257 @@
AND score IS NOT NULL
GROUP BY type;
</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)
>
#{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
<>
#{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
<
timestampadd(minute, #{duration}, #{startTime})
and timestampadd(minute, coalesce(e.duration, 0), e.exam_time)
>
#{startTime}
<if
test=
"excludeId != null"
>
and e.id
<>
#{excludeId}
</if>
and (
e.class_id = #{classId}
or e.chief_id in (#{chiefId}, #{invigilatorId})
or find_in_set(#{chiefId}, replace(coalesce(e.invigilation_id, ''), ' ', ''))
>
0
or find_in_set(#{invigilatorId}, replace(coalesce(e.invigilation_id, ''), ' ', ''))
>
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>
practical-business/src/main/resources/exam-management-api.md
0 → 100644
View file @
226897b4
# 管理员端考试管理接口
接口统一使用
`/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`
主记录;历史成绩和进行中考试不会被删除。
practical-business/src/main/resources/sql/exam_management.sql
0 → 100644
View file @
226897b4
-- 管理员端“教务管理-考试管理”增量数据库脚本(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
;
practical-business/src/test/java/com/platform/business/controller/ExamAdminControllerTest.java
0 → 100644
View file @
226897b4
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
));
}
}
practical-business/src/test/java/com/platform/business/mapper/ExamMapperXmlTest.java
0 → 100644
View file @
226897b4
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"
));
}
}
practical-business/src/test/java/com/platform/business/service/impl/ExamAdminServiceImplTest.java
0 → 100644
View file @
226897b4
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
(
100
D
);
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
(
100
D
);
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
;
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment