Commit 5fe1aba7 authored by wujipeng's avatar wujipeng
Browse files

管理员-智能考评-理论试卷管理

parent 6bae6649
package com.platform.business.model.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* 管理员端学员成绩管理的历史考试分页条件。
*
* <p>查询对象不继承考试实体,避免客户端通过分页接口意外提交实体中的写入字段。</p>
*/
@Data
public class ScoreAdminExamQueryDTO {
private int pageNum;
private int pageSize;
@ApiModelProperty(value = "班级ID", required = true)
private Integer classId;
@ApiModelProperty("考试名称关键字")
private String keyword;
@ApiModelProperty("考试类型:THEORY/PRACTICE,也兼容理论/实训")
private String type;
@ApiModelProperty("发布状态:ALL/PENDING_REVIEW/PUBLISHED")
private String status;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ApiModelProperty("考试日期起始值(含)")
private Date startDate;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ApiModelProperty("考试日期结束值(含)")
private Date endDate;
}
package com.platform.business.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/** 管理员端单场考试学员成绩分页条件。 */
@Data
public class ScoreAdminStudentQueryDTO {
private int pageNum;
private int pageSize;
@ApiModelProperty("姓名或身份证号关键字")
private String keyword;
@ApiModelProperty("成绩区间:ALL/EXCELLENT/GOOD/PASS/FAIL")
private String scoreBand;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/** 管理员端成绩管理中的考试汇总行,同时用于考试详情顶部统计。 */
@Data
public class ScoreAdminExamVO {
private Integer examId;
private Integer classId;
private String examName;
private String examType;
private String className;
private String occupation;
private Integer trainingYear;
private String levelName;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examTime;
private Integer duration;
private BigDecimal totalScore;
private BigDecimal passScore;
private String chiefExaminerName;
private Integer expectedCount;
private Integer actualCount;
private Integer publishedCount;
private Integer passedCount;
@ApiModelProperty("仅在存在正式发布成绩时返回")
private BigDecimal averageScore;
@ApiModelProperty("合格人数/已发布实考人数,仅在存在正式发布成绩时返回")
private BigDecimal passRate;
@ApiModelProperty("PENDING_REVIEW/PUBLISHED")
private String reviewStatus;
private Boolean published;
}
package com.platform.business.model.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
/** 单场考试按题目的聚合统计。 */
@Data
public class ScoreAdminQuestionStatisticsVO {
private String questionCode;
private String sequence;
private String questionType;
private String title;
private BigDecimal maxScore;
private BigDecimal averageScore;
private BigDecimal scoreRate;
private Integer correctCount;
private Integer participantCount;
private Integer successResultCount;
private Integer failureResultCount;
@ApiModelProperty("EASY/MEDIUM/HARD;实训题因缺少每题满分而返回null")
private String difficulty;
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.platform.business.model.entity.FzGradesEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/** 管理员查看单个学员正式成绩及答题详情的统一响应。 */
@Data
public class ScoreAdminStudentDetailVO {
private Integer examStudentId;
private Integer examId;
private Integer classId;
private String studentId;
private String studentName;
private String idCard;
private String className;
private String examName;
private String examType;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examTime;
private BigDecimal totalScore;
private BigDecimal passScore;
private BigDecimal score;
private BigDecimal classAverageScore;
private Integer rank;
private Boolean passed;
private String grade;
private String answerTime;
private String duration;
private Boolean submitted;
private Boolean published;
@ApiModelProperty("理论考试答题详情;实训考试返回空数组")
private List<ExamReviewQuestionVO> theoryQuestions = Collections.emptyList();
@ApiModelProperty("仿真实训明细;理论考试返回空数组")
private List<FzGradesEntity> practiceItems = Collections.emptyList();
}
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/** 管理员端成绩明细表中的单个应考学员。 */
@Data
public class ScoreAdminStudentVO {
private Integer examStudentId;
private Integer examId;
private Integer classId;
private String studentId;
private String studentName;
private String idCard;
private String className;
private String examName;
private String examType;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date examTime;
private Boolean submitted;
private Boolean published;
@ApiModelProperty("未发布时固定返回null")
private BigDecimal score;
@ApiModelProperty("优秀/良好/及格/不及格;未发布时返回null")
private String grade;
private Boolean passed;
private String answerTime;
private String duration;
@ApiModelProperty("当前模型没有整场评语来源,保留为可空字段")
private String comment;
}
...@@ -14,7 +14,7 @@ import java.util.List; ...@@ -14,7 +14,7 @@ import java.util.List;
/** /**
* @Author: wujipeng * @Author: wujipeng
* @Description: TODO * @Description: 外部仿真实训系统逐题成绩接收接口
* @Date: 2026/8/13 16:07 * @Date: 2026/8/13 16:07
* @Version: 1.0 * @Version: 1.0
*/ */
...@@ -28,6 +28,7 @@ public class FzGradesController { ...@@ -28,6 +28,7 @@ public class FzGradesController {
@ApiOperation("仿真考试数据接收") @ApiOperation("仿真考试数据接收")
@PostMapping("/receive") @PostMapping("/receive")
public Result<Boolean> receive(@RequestBody List<FzGradesDTO> fzGradesList) { public Result<Boolean> receive(@RequestBody List<FzGradesDTO> fzGradesList) {
// 业务层统一完成应考关系校验、自然键幂等更新以及submissionTime触发的正式成绩发布。
return Result.data(fzGradesService.receive(fzGradesList)); return Result.data(fzGradesService.receive(fzGradesList));
} }
} }
package com.platform.business.controller;
import com.platform.business.model.dto.ScoreAdminExamQueryDTO;
import com.platform.business.model.dto.ScoreAdminStudentQueryDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.ClassAdminTreeVO;
import com.platform.business.model.vo.ScoreAdminExamVO;
import com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO;
import com.platform.business.model.vo.ScoreAdminStudentDetailVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.ScoreAdminService;
import com.platform.controller.BaseController;
import com.platform.model.resp.Result;
import com.platform.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 管理员端学员成绩管理接口。
*
* <p>本控制器只提供只读查询和文件导出;评分、重评分及发布仍由教师阅卷接口负责。</p>
*/
@Api(tags = "管理员端-学员成绩管理")
@RestController
@RequestMapping("/exam/admin/scores")
public class ScoreAdminController extends BaseController {
@Resource
private ScoreAdminService scoreAdminService;
@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(scoreAdminService.tree(keyword));
}
@ApiOperation("历史考试成绩分页列表")
@PostMapping("/exams/page")
public TableDataInfo exams(@RequestBody(required = false) ScoreAdminExamQueryDTO query,
HttpServletRequest request) {
requireAdmin(request);
ScoreAdminExamQueryDTO safeQuery = query == null ? new ScoreAdminExamQueryDTO() : query;
normalizePage(safeQuery);
startPage(safeQuery.getPageNum(), safeQuery.getPageSize());
return getDataTable(scoreAdminService.exams(safeQuery));
}
@ApiOperation("单场考试成绩汇总")
@GetMapping("/exams/{examId}")
public Result<ScoreAdminExamVO> exam(@PathVariable Integer examId,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(scoreAdminService.exam(examId));
}
@ApiOperation("单场考试学员成绩分页列表")
@PostMapping("/exams/{examId}/students/page")
public TableDataInfo students(@PathVariable Integer examId,
@RequestBody(required = false) ScoreAdminStudentQueryDTO query,
HttpServletRequest request) {
requireAdmin(request);
ScoreAdminStudentQueryDTO safeQuery = query == null ? new ScoreAdminStudentQueryDTO() : query;
normalizePage(safeQuery);
startPage(safeQuery.getPageNum(), safeQuery.getPageSize());
return getDataTable(scoreAdminService.students(examId, safeQuery));
}
@ApiOperation("单个学员正式成绩及答题详情")
@GetMapping("/exam-students/{examStudentId}")
public Result<ScoreAdminStudentDetailVO> student(@PathVariable Integer examStudentId,
HttpServletRequest request) {
requireAdmin(request);
return Result.data(scoreAdminService.student(examStudentId));
}
@ApiOperation("单场考试按题目统计")
@GetMapping("/exams/{examId}/questions/statistics")
public Result<List<ScoreAdminQuestionStatisticsVO>> questionStatistics(
@PathVariable Integer examId, HttpServletRequest request) {
requireAdmin(request);
return Result.data(scoreAdminService.questionStatistics(examId));
}
@ApiOperation("导出单场考试正式成绩")
@GetMapping("/exams/{examId}/export")
public void exportExam(@PathVariable Integer examId, HttpServletRequest request,
HttpServletResponse response) {
requireAdmin(request);
scoreAdminService.exportExam(examId, response);
}
@ApiOperation("导出班级全部历史正式成绩")
@GetMapping("/classes/{classId}/export")
public void exportClass(@PathVariable Integer classId, HttpServletRequest request,
HttpServletResponse response) {
requireAdmin(request);
scoreAdminService.exportClass(classId, response);
}
/** 管理端每个入口均执行同一套JWT与角色校验,避免遗漏越权保护。 */
private UserEntity requireAdmin(HttpServletRequest request) {
UserEntity user = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(user);
return user;
}
private void normalizePage(ScoreAdminExamQueryDTO query) {
query.setPageNum(query.getPageNum() <= 0 ? 1 : query.getPageNum());
query.setPageSize(normalizePageSize(query.getPageSize()));
}
private void normalizePage(ScoreAdminStudentQueryDTO query) {
query.setPageNum(query.getPageNum() <= 0 ? 1 : query.getPageNum());
query.setPageSize(normalizePageSize(query.getPageSize()));
}
private int normalizePageSize(int pageSize) {
return pageSize <= 0 ? 10 : Math.min(pageSize, 100);
}
}
...@@ -2,14 +2,42 @@ package com.platform.business.mapper; ...@@ -2,14 +2,42 @@ package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.entity.FzGradesEntity; import com.platform.business.model.entity.FzGradesEntity;
import com.platform.business.model.entity.ExamStudentEntity;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/** /**
* @Author: wujipeng * @Author: wujipeng
* @Description: TODO * @Description: 仿真实训逐题成绩持久化与正式成绩发布
* @Date: 2026/8/13 16:05 * @Date: 2026/8/13 16:05
* @Version: 1.0 * @Version: 1.0
*/ */
@Mapper @Mapper
public interface FzGradesMapper extends BaseMapper<FzGradesEntity> { public interface FzGradesMapper extends BaseMapper<FzGradesEntity> {
/** 锁定应考记录,串行化同一学员同一考试的增量上报。 */
ExamStudentEntity lockExamStudent(@Param("examId") Integer examId,
@Param("studentId") String studentId);
/** 查询每个题号的最新记录;候选行锁已提供主要并发保护。 */
List<FzGradesEntity> selectLatestItems(@Param("examId") Integer examId,
@Param("studentId") String studentId);
/** 同步更新自然键相同的全部历史重复行,避免旧重复数据继续产生不同版本。 */
int updateByBusinessKey(FzGradesEntity entity);
Double sumLatestScores(@Param("examId") Integer examId,
@Param("studentId") String studentId);
int publishPracticeStudent(@Param("examStudentId") Integer examStudentId,
@Param("score") Double score,
@Param("startTime") Long startTime,
@Param("endTime") Long endTime,
@Param("answerTime") String answerTime,
@Param("duration") String duration);
int publishPracticeExam(@Param("examId") Integer examId, @Param("updateTime") Date updateTime);
} }
package com.platform.business.mapper;
import com.platform.business.model.dto.ScoreAdminExamQueryDTO;
import com.platform.business.model.dto.ScoreAdminStudentQueryDTO;
import com.platform.business.model.entity.FzGradesEntity;
import com.platform.business.model.vo.ExamReviewQuestionVO;
import com.platform.business.model.vo.ScoreAdminExamVO;
import com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO;
import com.platform.business.model.vo.ScoreAdminStudentDetailVO;
import com.platform.business.model.vo.ScoreAdminStudentVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/** 管理员端成绩管理专用聚合查询,避免改变旧版成绩接口的返回口径。 */
@Mapper
public interface ScoreAdminMapper {
List<ScoreAdminExamVO> queryExams(@Param("query") ScoreAdminExamQueryDTO query);
ScoreAdminExamVO findExam(@Param("examId") Integer examId);
List<ScoreAdminStudentVO> queryStudents(@Param("examId") Integer examId,
@Param("query") ScoreAdminStudentQueryDTO query);
ScoreAdminStudentDetailVO findStudent(@Param("examStudentId") Integer examStudentId);
List<ExamReviewQuestionVO> queryTheoryQuestions(@Param("examId") Integer examId,
@Param("studentId") String studentId);
List<FzGradesEntity> queryPracticeItems(@Param("examId") Integer examId,
@Param("studentId") String studentId);
List<ScoreAdminQuestionStatisticsVO> queryTheoryStatistics(@Param("examId") Integer examId);
List<ScoreAdminQuestionStatisticsVO> queryPracticeStatistics(@Param("examId") Integer examId);
List<ScoreAdminStudentVO> queryPublishedStudents(@Param("examId") Integer examId);
List<ScoreAdminExamVO> queryClassExams(@Param("classId") Integer classId);
}
package com.platform.business.service;
import com.platform.business.model.dto.ScoreAdminExamQueryDTO;
import com.platform.business.model.dto.ScoreAdminStudentQueryDTO;
import com.platform.business.model.vo.ClassAdminTreeVO;
import com.platform.business.model.vo.ScoreAdminExamVO;
import com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO;
import com.platform.business.model.vo.ScoreAdminStudentDetailVO;
import com.platform.business.model.vo.ScoreAdminStudentVO;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/** 管理员端“智能考评-学员成绩管理”完整业务接口。 */
public interface ScoreAdminService {
List<ClassAdminTreeVO> tree(String keyword);
List<ScoreAdminExamVO> exams(ScoreAdminExamQueryDTO query);
ScoreAdminExamVO exam(Integer examId);
List<ScoreAdminStudentVO> students(Integer examId, ScoreAdminStudentQueryDTO query);
ScoreAdminStudentDetailVO student(Integer examStudentId);
List<ScoreAdminQuestionStatisticsVO> questionStatistics(Integer examId);
void exportExam(Integer examId, HttpServletResponse response);
void exportClass(Integer classId, HttpServletResponse response);
}
package com.platform.business.service.impl; package com.platform.business.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.business.constant.ExamAdminConstants;
import com.platform.business.mapper.ExamMapper;
import com.platform.business.mapper.FzGradesMapper; import com.platform.business.mapper.FzGradesMapper;
import com.platform.business.model.dto.FzGradesDTO; import com.platform.business.model.dto.FzGradesDTO;
import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.entity.ExamStudentEntity;
import com.platform.business.model.entity.FzGradesEntity; import com.platform.business.model.entity.FzGradesEntity;
import com.platform.business.service.FzGradesService; import com.platform.business.service.FzGradesService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
/** /**
* @Author: wujipeng * @Author: wujipeng
* @Description: TODO * @Description: 仿真实训逐题成绩的增量、幂等接收服务
* @Date: 2026/8/13 16:06 * @Date: 2026/8/13 16:06
* @Version: 1.0 * @Version: 1.0
*/ */
@Service @Service
public class FzGradesServiceImpl extends ServiceImpl<FzGradesMapper, FzGradesEntity> implements FzGradesService { public class FzGradesServiceImpl extends ServiceImpl<FzGradesMapper, FzGradesEntity> implements FzGradesService {
private static final int MAX_BATCH_SIZE = 2000;
@Resource
private ExamMapper examMapper;
@Override @Override
@Transactional @Transactional(rollbackFor = Exception.class)
public Boolean receive(List<FzGradesDTO> fzGradesList) { public Boolean receive(List<FzGradesDTO> fzGradesList) {
return saveBatch(BeanUtil.copyToList(fzGradesList, FzGradesEntity.class)); if (fzGradesList == null || fzGradesList.isEmpty()) {
throw new BusinessException("仿真实训成绩明细不能为空");
}
if (fzGradesList.size() > MAX_BATCH_SIZE) {
throw new BusinessException("单次最多上报2000条仿真实训成绩明细");
}
/*
* 一个请求允许包含多个学员,但必须先按稳定键排序处理。多个并发请求若同时包含
* 相同的应考记录,固定锁顺序可以显著降低数据库死锁概率。
*/
Map<String, List<FzGradesDTO>> grouped = new TreeMap<>();
for (FzGradesDTO item : fzGradesList) {
validateItem(item);
String groupKey = item.getExamId() + "\u0000" + item.getUserId().trim();
grouped.computeIfAbsent(groupKey, key -> new ArrayList<>()).add(item);
}
for (List<FzGradesDTO> items : grouped.values()) {
processStudent(items);
}
return true;
}
/** 处理同一考试、同一学员的一组增量题目。 */
private void processStudent(List<FzGradesDTO> items) {
FzGradesDTO first = items.get(0);
Integer examId = first.getExamId();
String studentId = first.getUserId().trim();
// 先锁定应考关系:既完成权限归属校验,也串行化“查询后新增”的竞态窗口。
ExamStudentEntity candidate = baseMapper.lockExamStudent(examId, studentId);
if (candidate == null) {
throw new BusinessException("学员不属于本场考试应考名单");
}
ExamEntity exam = examMapper.selectById(examId);
if (exam == null) {
throw new BusinessException("考试不存在或已删除");
}
if (!isPractice(exam.getType())) {
throw new BusinessException("该接口只接收仿真实训考试成绩");
}
Set<String> requestCodes = new HashSet<>();
for (FzGradesDTO item : items) {
if (!Objects.equals(examId, item.getExamId())
|| !studentId.equals(item.getUserId().trim())) {
throw new BusinessException("同一处理分组中的考试或学员信息不一致");
}
item.setUserId(studentId);
item.setCode(item.getCode().trim());
if (!requestCodes.add(item.getCode())) {
throw new BusinessException("同一次请求中题目编号不能重复:" + item.getCode());
}
}
List<FzGradesEntity> stored = baseMapper.selectLatestItems(examId, studentId);
Map<String, FzGradesEntity> storedByCode = indexByCode(stored);
if (Boolean.TRUE.equals(candidate.getMarkFlag())) {
ensurePublishedReplay(items, storedByCode);
return;
}
Date submissionTime = null;
for (FzGradesDTO item : items) {
FzGradesEntity entity = copyForPersistence(item);
if (storedByCode.containsKey(entity.getCode())) {
baseMapper.updateByBusinessKey(entity);
} else if (baseMapper.insert(entity) != 1) {
throw new BusinessException("仿真实训成绩明细保存失败,请稍后重试");
}
if (item.getSubmissionTime() != null
&& (submissionTime == null || item.getSubmissionTime().after(submissionTime))) {
submissionTime = item.getSubmissionTime();
}
}
// submissionTime是当前协议中唯一的完成标志;没有完成标志时绝不改写正式总分。
if (submissionTime != null) {
publishStudent(exam, candidate, studentId, submissionTime);
}
}
/** 汇总每个题号的最新得分,并原子发布学员与考试的正式成绩标记。 */
private void publishStudent(ExamEntity exam, ExamStudentEntity candidate, String studentId,
Date submissionTime) {
Double sum = baseMapper.sumLatestScores(exam.getId(), studentId);
BigDecimal score = BigDecimal.valueOf(sum == null ? 0D : sum).setScale(2, RoundingMode.HALF_UP);
if (exam.getTotalScore() == null) {
throw new BusinessException("考试总分尚未配置,不能发布仿真实训成绩");
}
if (score.compareTo(exam.getTotalScore()) > 0) {
throw new BusinessException("仿真实训累计得分不能超过考试总分" + exam.getTotalScore());
}
List<FzGradesEntity> allItems = baseMapper.selectLatestItems(exam.getId(), studentId);
Date start = allItems.stream().map(FzGradesEntity::getStartTime).filter(Objects::nonNull)
.min(Comparator.naturalOrder()).orElse(null);
long startMillis = start == null
? (candidate.getStartTime() == null ? submissionTime.getTime() : candidate.getStartTime())
: start.getTime();
long endMillis = submissionTime.getTime();
if (endMillis < startMillis) {
throw new BusinessException("交卷时间不能早于仿真实训开始时间");
}
String answerTime = formatTime(startMillis) + "-" + formatTime(endMillis);
String duration = formatDuration(endMillis - startMillis);
int updated = baseMapper.publishPracticeStudent(candidate.getId(), score.doubleValue(),
startMillis, endMillis, answerTime, duration);
if (updated != 1) {
throw new BusinessException("仿真实训成绩发布状态已变化,请勿重复提交");
}
if (baseMapper.publishPracticeExam(exam.getId(), new Date()) != 1) {
throw new BusinessException("仿真实训考试发布失败,请稍后重试");
}
}
/** 正式发布后的接口只接受完全相同的网络重试,不允许静默篡改分数。 */
private void ensurePublishedReplay(List<FzGradesDTO> incoming,
Map<String, FzGradesEntity> storedByCode) {
for (FzGradesDTO item : incoming) {
FzGradesEntity existing = storedByCode.get(item.getCode());
if (existing == null || !sameBusinessContent(existing, item)) {
throw new BusinessException("仿真实训成绩已经发布,不能继续修改");
}
}
}
private boolean sameBusinessContent(FzGradesEntity left, FzGradesEntity right) {
return Objects.equals(left.getExamId(), right.getExamId())
&& Objects.equals(trim(left.getUserId()), trim(right.getUserId()))
&& Objects.equals(trim(left.getCode()), trim(right.getCode()))
&& Objects.equals(left.getLev(), right.getLev())
&& sameSecond(left.getStartTime(), right.getStartTime())
&& sameSecond(left.getSubmissionTime(), right.getSubmissionTime())
&& Objects.equals(left.getTitle(), right.getTitle())
&& Objects.equals(left.getType(), right.getType())
&& Objects.equals(left.getOptions(), right.getOptions())
&& Objects.equals(left.getMark(), right.getMark())
&& Objects.equals(left.getText(), right.getText())
&& Objects.equals(left.getResult(), right.getResult())
&& Objects.equals(left.getFile(), right.getFile())
&& Objects.equals(left.getScore(), right.getScore());
}
private boolean sameSecond(Date left, Date right) {
if (left == null || right == null) {
return left == right;
}
// MySQL DATETIME通常不保留毫秒,按秒比较可确保数据库回读后的合法重试仍然幂等。
return left.getTime() / 1000 == right.getTime() / 1000;
}
private Map<String, FzGradesEntity> indexByCode(List<FzGradesEntity> items) {
Map<String, FzGradesEntity> result = new LinkedHashMap<>();
if (items != null) {
for (FzGradesEntity item : items) {
result.put(item.getCode(), item);
}
}
return result;
}
/** 明确逐字段复制,禁止外部请求控制主键。 */
private FzGradesEntity copyForPersistence(FzGradesDTO source) {
FzGradesEntity target = new FzGradesEntity();
target.setExamId(source.getExamId());
target.setUserId(source.getUserId());
target.setCode(source.getCode());
target.setLev(source.getLev());
target.setStartTime(source.getStartTime());
target.setSubmissionTime(source.getSubmissionTime());
target.setTitle(source.getTitle());
target.setType(source.getType());
target.setOptions(source.getOptions());
target.setMark(source.getMark());
target.setText(source.getText());
target.setResult(source.getResult());
target.setFile(source.getFile());
target.setScore(source.getScore());
return target;
}
private void validateItem(FzGradesDTO item) {
if (item == null) {
throw new BusinessException("仿真实训成绩明细不能包含空项");
}
if (item.getExamId() == null || item.getExamId() <= 0) {
throw new BusinessException("考试ID必须为正整数");
}
if (trim(item.getUserId()) == null) {
throw new BusinessException("学员ID不能为空");
}
if (trim(item.getCode()) == null) {
throw new BusinessException("题目编号不能为空");
}
if (item.getScore() == null || item.getScore().isNaN()
|| item.getScore().isInfinite() || item.getScore() < 0) {
throw new BusinessException("题目得分必须是非负有限数值");
}
}
private boolean isPractice(String type) {
return type != null && (ExamAdminConstants.TYPE_PRACTICE.equals(type.trim())
|| "PRACTICE".equalsIgnoreCase(type.trim()));
}
private String trim(String value) {
return value == null || value.trim().isEmpty() ? null : value.trim();
}
private String formatTime(long millis) {
return new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date(millis));
}
private String formatDuration(long millis) {
long totalSeconds = Math.max(0, millis / 1000);
long hours = totalSeconds / 3600;
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
} }
} }
package com.platform.business.service.impl;
import com.platform.business.constant.ExamAdminConstants;
import com.platform.business.mapper.ScoreAdminMapper;
import com.platform.business.model.dto.ScoreAdminExamQueryDTO;
import com.platform.business.model.dto.ScoreAdminStudentQueryDTO;
import com.platform.business.model.vo.ClassAdminTreeVO;
import com.platform.business.model.vo.ScoreAdminExamVO;
import com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO;
import com.platform.business.model.vo.ScoreAdminStudentDetailVO;
import com.platform.business.model.vo.ScoreAdminStudentVO;
import com.platform.business.service.ExamAdminService;
import com.platform.business.service.ScoreAdminService;
import com.platform.exception.BusinessException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
/**
* 管理员端学员成绩管理实现。
*
* <p>所有统计均在SQL层限定为正式发布成绩,服务层再负责参数边界、历史考试状态和
* 文件输出,形成双层保护,避免未完成阅卷的暂存分被误当成正式成绩。</p>
*/
@Service
public class ScoreAdminServiceImpl implements ScoreAdminService {
private static final String STATUS_ALL = "ALL";
private static final String STATUS_PENDING = "PENDING_REVIEW";
private static final String STATUS_PUBLISHED = "PUBLISHED";
private static final Set<String> STATUSES = new HashSet<>(
Arrays.asList(STATUS_ALL, STATUS_PENDING, STATUS_PUBLISHED));
private static final String BAND_ALL = "ALL";
private static final Set<String> SCORE_BANDS = new HashSet<>(
Arrays.asList(BAND_ALL, "EXCELLENT", "GOOD", "PASS", "FAIL"));
@Resource
private ScoreAdminMapper scoreAdminMapper;
@Resource
private ExamAdminService examAdminService;
@Override
@Transactional(readOnly = true)
public List<ClassAdminTreeVO> tree(String keyword) {
return examAdminService.tree(keyword);
}
@Override
@Transactional(readOnly = true)
public List<ScoreAdminExamVO> exams(ScoreAdminExamQueryDTO query) {
normalizeExamQuery(query);
List<ScoreAdminExamVO> result = scoreAdminMapper.queryExams(query);
return result == null ? Collections.emptyList() : result;
}
@Override
@Transactional(readOnly = true)
public ScoreAdminExamVO exam(Integer examId) {
ScoreAdminExamVO result = requireExam(examId);
requireEnded(result);
return result;
}
@Override
@Transactional(readOnly = true)
public List<ScoreAdminStudentVO> students(Integer examId, ScoreAdminStudentQueryDTO query) {
ScoreAdminExamVO exam = requireExam(examId);
requireEnded(exam);
normalizeStudentQuery(query);
List<ScoreAdminStudentVO> result = scoreAdminMapper.queryStudents(examId, query);
return result == null ? Collections.emptyList() : result;
}
@Override
@Transactional(readOnly = true)
public ScoreAdminStudentDetailVO student(Integer examStudentId) {
requirePositiveId(examStudentId, "考生考试记录ID");
ScoreAdminStudentDetailVO detail = scoreAdminMapper.findStudent(examStudentId);
if (detail == null) {
throw new BusinessException("考生考试记录不存在或已删除");
}
if (!Boolean.TRUE.equals(detail.getPublished())) {
throw new BusinessException("本名学员成绩尚未正式发布,不能查看答题详情");
}
if (isPractice(detail.getExamType())) {
List<com.platform.business.model.entity.FzGradesEntity> items =
scoreAdminMapper.queryPracticeItems(detail.getExamId(), detail.getStudentId());
detail.setPracticeItems(items == null ? Collections.emptyList() : items);
detail.setTheoryQuestions(Collections.emptyList());
} else {
List<com.platform.business.model.vo.ExamReviewQuestionVO> questions =
scoreAdminMapper.queryTheoryQuestions(detail.getExamId(), detail.getStudentId());
detail.setTheoryQuestions(questions == null ? Collections.emptyList() : questions);
detail.setPracticeItems(Collections.emptyList());
}
return detail;
}
@Override
@Transactional(readOnly = true)
public List<ScoreAdminQuestionStatisticsVO> questionStatistics(Integer examId) {
ScoreAdminExamVO exam = requireExam(examId);
requireEnded(exam);
if (!Boolean.TRUE.equals(exam.getPublished())) {
throw new BusinessException("本场考试成绩尚未正式发布,不能查看题目统计");
}
List<ScoreAdminQuestionStatisticsVO> result = isPractice(exam.getExamType())
? scoreAdminMapper.queryPracticeStatistics(examId)
: scoreAdminMapper.queryTheoryStatistics(examId);
return result == null ? Collections.emptyList() : result;
}
@Override
@Transactional(readOnly = true)
public void exportExam(Integer examId, HttpServletResponse response) {
ScoreAdminExamVO exam = requirePublishedExam(examId);
List<ScoreAdminStudentVO> students = scoreAdminMapper.queryPublishedStudents(examId);
if (students == null || students.isEmpty()) {
throw new BusinessException("本场考试暂无可导出的正式成绩");
}
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
ExcelStyles styles = new ExcelStyles(workbook);
Sheet sheet = workbook.createSheet("成绩明细");
writeStudentSheet(sheet, students, styles);
writeWorkbook(response, workbook, safeFileName(exam.getExamName()) + "_成绩单.xlsx");
} catch (IOException e) {
throw new BusinessException("成绩单导出失败,请稍后重试");
}
}
@Override
@Transactional(readOnly = true)
public void exportClass(Integer classId, HttpServletResponse response) {
requirePositiveId(classId, "班级ID");
List<ScoreAdminExamVO> exams = scoreAdminMapper.queryClassExams(classId);
if (exams == null || exams.isEmpty()) {
throw new BusinessException("当前班级暂无历史考试记录");
}
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
ExcelStyles styles = new ExcelStyles(workbook);
writeExamSummarySheet(workbook.createSheet("考试汇总"), exams, styles);
Sheet studentSheet = workbook.createSheet("学员成绩明细");
int rowIndex = writeStudentHeader(studentSheet, styles);
for (ScoreAdminExamVO exam : exams) {
if (!Boolean.TRUE.equals(exam.getPublished())) {
continue;
}
List<ScoreAdminStudentVO> students = scoreAdminMapper.queryPublishedStudents(exam.getExamId());
if (students != null) {
for (ScoreAdminStudentVO student : students) {
writeStudentRow(studentSheet.createRow(rowIndex++), student, styles.body);
}
}
}
finishStudentSheet(studentSheet);
String className = exams.get(0).getClassName();
writeWorkbook(response, workbook, safeFileName(className) + "_历史成绩.xlsx");
} catch (IOException e) {
throw new BusinessException("班级成绩导出失败,请稍后重试");
}
}
/** 将外部英文类型归一为项目数据库沿用的中文值。 */
void normalizeExamQuery(ScoreAdminExamQueryDTO query) {
if (query == null) {
throw new BusinessException("查询条件不能为空");
}
requirePositiveId(query.getClassId(), "班级ID");
String keyword = trimToNull(query.getKeyword());
if (keyword != null && keyword.length() > 100) {
throw new BusinessException("考试名称关键字不能超过100个字符");
}
query.setKeyword(keyword);
String type = upper(query.getType());
if (type != null) {
if ("THEORY".equals(type) || ExamAdminConstants.TYPE_THEORY.equals(query.getType().trim())) {
query.setType(ExamAdminConstants.TYPE_THEORY);
} else if ("PRACTICE".equals(type) || ExamAdminConstants.TYPE_PRACTICE.equals(query.getType().trim())) {
query.setType(ExamAdminConstants.TYPE_PRACTICE);
} else {
throw new BusinessException("考试类型只支持THEORY/PRACTICE或理论/实训");
}
} else {
query.setType(null);
}
String status = upper(query.getStatus());
status = status == null ? STATUS_ALL : status;
if (!STATUSES.contains(status)) {
throw new BusinessException("成绩发布状态参数无效");
}
query.setStatus(status);
if (query.getStartDate() != null && query.getEndDate() != null
&& query.getStartDate().after(query.getEndDate())) {
throw new BusinessException("考试开始日期不能晚于结束日期");
}
}
void normalizeStudentQuery(ScoreAdminStudentQueryDTO query) {
if (query == null) {
throw new BusinessException("查询条件不能为空");
}
String keyword = trimToNull(query.getKeyword());
if (keyword != null && keyword.length() > 100) {
throw new BusinessException("学员关键字不能超过100个字符");
}
query.setKeyword(keyword);
String band = upper(query.getScoreBand());
band = band == null ? BAND_ALL : band;
if (!SCORE_BANDS.contains(band)) {
throw new BusinessException("成绩区间参数无效");
}
query.setScoreBand(band);
}
private ScoreAdminExamVO requirePublishedExam(Integer examId) {
ScoreAdminExamVO exam = requireExam(examId);
requireEnded(exam);
if (!Boolean.TRUE.equals(exam.getPublished())) {
throw new BusinessException("本场考试成绩尚未正式发布,不能导出");
}
return exam;
}
private ScoreAdminExamVO requireExam(Integer examId) {
requirePositiveId(examId, "考试ID");
ScoreAdminExamVO exam = scoreAdminMapper.findExam(examId);
if (exam == null) {
throw new BusinessException("考试不存在或已删除");
}
return exam;
}
/** 历史成绩接口不允许通过猜测ID读取尚未结束的考试。 */
private void requireEnded(ScoreAdminExamVO exam) {
if (exam.getExamTime() == null) {
throw new BusinessException("考试时间缺失,无法判断历史状态");
}
long durationMillis = Math.max(0, exam.getDuration() == null ? 0 : exam.getDuration()) * 60_000L;
if (exam.getExamTime().getTime() + durationMillis > System.currentTimeMillis()) {
throw new BusinessException("考试尚未结束,不能进入历史成绩管理");
}
}
private void requirePositiveId(Integer id, String field) {
if (id == null || id <= 0) {
throw new BusinessException(field + "必须为正整数");
}
}
private boolean isPractice(String type) {
return type != null && (ExamAdminConstants.TYPE_PRACTICE.equals(type.trim())
|| "PRACTICE".equalsIgnoreCase(type.trim()));
}
private String trimToNull(String value) {
if (value == null || value.trim().isEmpty()) {
return null;
}
return value.trim();
}
private String upper(String value) {
String normalized = trimToNull(value);
return normalized == null ? null : normalized.toUpperCase(Locale.ROOT);
}
private void writeExamSummarySheet(Sheet sheet, List<ScoreAdminExamVO> exams, ExcelStyles styles) {
String[] headers = {"序号", "考试名称", "类型", "考试时间", "实考/应考", "平均分",
"合格率", "主考教师", "批阅状态"};
writeHeader(sheet.createRow(0), headers, styles.header);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < exams.size(); i++) {
ScoreAdminExamVO exam = exams.get(i);
Row row = sheet.createRow(i + 1);
String attendance = value(exam.getActualCount()) + "/" + value(exam.getExpectedCount());
String passRate = exam.getPassRate() == null ? "—" : exam.getPassRate().toPlainString() + "%";
String[] values = {String.valueOf(i + 1), value(exam.getExamName()), value(exam.getExamType()),
exam.getExamTime() == null ? "—" : formatter.format(exam.getExamTime()), attendance,
decimal(exam.getAverageScore()), passRate, value(exam.getChiefExaminerName()),
STATUS_PUBLISHED.equals(exam.getReviewStatus()) ? "已发布" : "待批阅"};
writeCells(row, values, styles.body);
}
sheet.createFreezePane(0, 1);
int[] widths = {8, 34, 12, 22, 14, 12, 12, 18, 14};
setWidths(sheet, widths);
}
private void writeStudentSheet(Sheet sheet, List<ScoreAdminStudentVO> students, ExcelStyles styles) {
int rowIndex = writeStudentHeader(sheet, styles);
for (ScoreAdminStudentVO student : students) {
writeStudentRow(sheet.createRow(rowIndex++), student, styles.body);
}
finishStudentSheet(sheet);
}
private int writeStudentHeader(Sheet sheet, ExcelStyles styles) {
String[] headers = {"序号", "考试名称", "类型", "考试时间", "班级", "学员姓名",
"身份证号", "成绩", "等级", "是否合格", "答题时长", "评语"};
writeHeader(sheet.createRow(0), headers, styles.header);
return 1;
}
private void writeStudentRow(Row row, ScoreAdminStudentVO student, CellStyle style) {
int sequence = row.getRowNum();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String[] values = {String.valueOf(sequence), value(student.getExamName()), value(student.getExamType()),
student.getExamTime() == null ? "—" : formatter.format(student.getExamTime()),
value(student.getClassName()), value(student.getStudentName()), value(student.getIdCard()),
decimal(student.getScore()), value(student.getGrade()),
student.getPassed() == null ? "—" : (student.getPassed() ? "合格" : "不合格"),
value(student.getDuration()), value(student.getComment())};
writeCells(row, values, style);
}
private void finishStudentSheet(Sheet sheet) {
sheet.createFreezePane(0, 1);
int[] widths = {8, 34, 12, 22, 24, 16, 24, 12, 12, 12, 14, 28};
setWidths(sheet, widths);
}
private void writeHeader(Row row, String[] values, CellStyle style) {
writeCells(row, values, style);
row.setHeightInPoints(24);
}
private void writeCells(Row row, String[] values, CellStyle style) {
for (int i = 0; i < values.length; i++) {
Cell cell = row.createCell(i);
cell.setCellValue(values[i]);
cell.setCellStyle(style);
}
}
private void setWidths(Sheet sheet, int[] widths) {
for (int i = 0; i < widths.length; i++) {
sheet.setColumnWidth(i, widths[i] * 256);
}
}
private void writeWorkbook(HttpServletResponse response, XSSFWorkbook workbook, String fileName)
throws IOException {
response.reset();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
String encoded = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replace("+", "%20");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encoded);
try (ServletOutputStream outputStream = response.getOutputStream()) {
workbook.write(outputStream);
outputStream.flush();
}
}
private String safeFileName(String value) {
String name = trimToNull(value);
return name == null ? "成绩" : name.replaceAll("[\\\\/:*?\"<>|]", "_");
}
private String value(Object value) {
return value == null ? "—" : String.valueOf(value);
}
private String decimal(BigDecimal value) {
return value == null ? "—" : value.stripTrailingZeros().toPlainString();
}
/** 工作簿级样式只创建一次,避免逐单元格创建样式触发POI样式数量上限。 */
private static final class ExcelStyles {
private final CellStyle header;
private final CellStyle body;
private ExcelStyles(XSSFWorkbook workbook) {
header = workbook.createCellStyle();
header.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
header.setFillPattern(FillPatternType.SOLID_FOREGROUND);
header.setAlignment(HorizontalAlignment.CENTER);
header.setVerticalAlignment(VerticalAlignment.CENTER);
header.setBorderBottom(BorderStyle.THIN);
Font font = workbook.createFont();
font.setBold(true);
font.setColor(IndexedColors.WHITE.getIndex());
header.setFont(font);
body = workbook.createCellStyle();
body.setVerticalAlignment(VerticalAlignment.CENTER);
body.setBorderBottom(BorderStyle.HAIR);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.FzGradesMapper">
<select id="lockExamStudent" resultType="com.platform.business.model.entity.ExamStudentEntity">
SELECT es.*
FROM exam_student es
WHERE es.exam_id = #{examId}
AND es.student_id = #{studentId}
FOR UPDATE
</select>
<!-- 每个题号只读取雪花ID最大的最新版本,兼容迁移前已经存在的重复数据。 -->
<select id="selectLatestItems" resultType="com.platform.business.model.entity.FzGradesEntity">
SELECT
g.id, g.exam_id AS examId, g.user_id AS userId, g.code, g.lev,
g.start_time AS startTime, g.submission_time AS submissionTime,
g.title, g.type, g.options, g.mark, g.text, g.result, g.file, g.score
FROM fz_grades g
INNER JOIN (
SELECT MAX(id) AS id
FROM fz_grades
WHERE exam_id = #{examId} AND user_id = #{studentId}
GROUP BY code
) latest ON latest.id = g.id
ORDER BY g.code, g.id
</select>
<update id="updateByBusinessKey">
UPDATE fz_grades
SET lev = #{lev},
start_time = #{startTime},
submission_time = #{submissionTime},
title = #{title},
type = #{type},
options = #{options},
mark = #{mark},
text = #{text},
result = #{result},
file = #{file},
score = #{score}
WHERE exam_id = #{examId}
AND user_id = #{userId}
AND code = #{code}
</update>
<select id="sumLatestScores" resultType="double">
SELECT IFNULL(SUM(g.score), 0)
FROM fz_grades g
INNER JOIN (
SELECT MAX(id) AS id
FROM fz_grades
WHERE exam_id = #{examId} AND user_id = #{studentId}
GROUP BY code
) latest ON latest.id = g.id
</select>
<update id="publishPracticeStudent">
UPDATE exam_student
SET score = #{score},
start_time = #{startTime},
end_time = #{endTime},
answer_time = #{answerTime},
duration = #{duration},
submit = 1,
mark_flag = 1
WHERE id = #{examStudentId}
AND IFNULL(mark_flag, 0) = 0
</update>
<!-- 实训成绩由外部评分系统自动形成,首名学员完成后即可开启考试级成绩可见性。 -->
<update id="publishPracticeExam">
UPDATE exam
SET mark_flag = 1,
update_time = #{updateTime}
WHERE id = #{examId}
</update>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.ScoreAdminMapper">
<!--
考试汇总统一只使用 exam.mark_flag 与 exam_student.mark_flag 同时发布的分数。
这样即使教师已经暂存了部分主观题分数,也不会提前泄露为管理员端正式成绩。
-->
<sql id="examSummaryColumns">
e.id AS examId,
e.class_id AS classId,
e.name AS examName,
e.type AS examType,
c.name AS className,
c.occupation,
c.training_year AS trainingYear,
sl.name AS levelName,
e.exam_time AS examTime,
e.duration,
e.total_score AS totalScore,
e.pass_score AS passScore,
chief.nick_name AS chiefExaminerName,
COUNT(es.id) AS expectedCount,
SUM(CASE WHEN IFNULL(es.submit, 0) = 1 THEN 1 ELSE 0 END) AS actualCount,
SUM(CASE
WHEN IFNULL(e.mark_flag, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL THEN 1 ELSE 0
END) AS publishedCount,
SUM(CASE
WHEN IFNULL(e.mark_flag, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL
AND es.score &gt;= IFNULL(e.pass_score, 60) THEN 1 ELSE 0
END) AS passedCount,
CASE
WHEN SUM(CASE
WHEN IFNULL(e.mark_flag, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL THEN 1 ELSE 0
END) = 0 THEN NULL
ELSE ROUND(AVG(CASE
WHEN IFNULL(e.mark_flag, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1 THEN es.score
END), 2)
END AS averageScore,
CASE
WHEN SUM(CASE
WHEN IFNULL(e.mark_flag, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL THEN 1 ELSE 0
END) = 0 THEN NULL
ELSE ROUND(
SUM(CASE
WHEN IFNULL(e.mark_flag, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL
AND es.score &gt;= IFNULL(e.pass_score, 60) THEN 1 ELSE 0
END) * 100.0 /
SUM(CASE
WHEN IFNULL(e.mark_flag, 0) = 1
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL THEN 1 ELSE 0
END), 2)
END AS passRate,
CASE WHEN IFNULL(e.mark_flag, 0) = 1 THEN 'PUBLISHED' ELSE 'PENDING_REVIEW' END AS reviewStatus,
CASE WHEN IFNULL(e.mark_flag, 0) = 1 THEN TRUE ELSE FALSE END AS published
</sql>
<sql id="examSummaryJoins">
FROM exam e
LEFT JOIN exam_student es ON es.exam_id = e.id
LEFT JOIN class c ON c.id = e.class_id
LEFT JOIN sys_level sl ON sl.id = c.level
LEFT JOIN user chief ON chief.id = e.chief_id
</sql>
<sql id="examSummaryGroup">
GROUP BY e.id, e.class_id, e.name, e.type, c.name, c.occupation, c.training_year,
sl.name, e.exam_time, e.duration, e.total_score, e.pass_score,
chief.nick_name, e.mark_flag
</sql>
<select id="queryExams" resultType="com.platform.business.model.vo.ScoreAdminExamVO">
SELECT <include refid="examSummaryColumns"/>
<include refid="examSummaryJoins"/>
WHERE e.class_id = #{query.classId}
AND DATE_ADD(e.exam_time, INTERVAL IFNULL(e.duration, 0) MINUTE) &lt;= NOW()
<if test="query.keyword != null and query.keyword != ''">
AND e.name LIKE CONCAT('%', #{query.keyword}, '%')
</if>
<if test="query.type != null and query.type != ''">
AND e.type = #{query.type}
</if>
<if test="query.startDate != null">
AND e.exam_time &gt;= #{query.startDate}
</if>
<if test="query.endDate != null">
AND e.exam_time &lt; DATE_ADD(#{query.endDate}, INTERVAL 1 DAY)
</if>
<if test="query.status == 'PUBLISHED'">
AND IFNULL(e.mark_flag, 0) = 1
</if>
<if test="query.status == 'PENDING_REVIEW'">
AND IFNULL(e.mark_flag, 0) = 0
</if>
<include refid="examSummaryGroup"/>
ORDER BY e.exam_time DESC, e.id DESC
</select>
<select id="findExam" resultType="com.platform.business.model.vo.ScoreAdminExamVO">
SELECT <include refid="examSummaryColumns"/>
<include refid="examSummaryJoins"/>
WHERE e.id = #{examId}
<include refid="examSummaryGroup"/>
</select>
<!-- 未发布时CASE表达式会主动抹掉分数、等级和合格结果。 -->
<select id="queryStudents" resultType="com.platform.business.model.vo.ScoreAdminStudentVO">
SELECT
es.id AS examStudentId,
es.exam_id AS examId,
es.class_id AS classId,
es.student_id AS studentId,
u.nick_name AS studentName,
u.id_card AS idCard,
c.name AS className,
e.name AS examName,
e.type AS examType,
e.exam_time AS examTime,
CASE WHEN IFNULL(es.submit, 0) = 1 THEN TRUE ELSE FALSE END AS submitted,
CASE
WHEN IFNULL(e.mark_flag, 0) = 1 AND IFNULL(es.mark_flag, 0) = 1
THEN TRUE ELSE FALSE
END AS published,
CASE
WHEN IFNULL(e.mark_flag, 0) = 1 AND IFNULL(es.mark_flag, 0) = 1
THEN es.score ELSE NULL
END AS score,
CASE
WHEN IFNULL(e.mark_flag, 0) = 0 OR IFNULL(es.mark_flag, 0) = 0 OR es.score IS NULL THEN NULL
WHEN es.score &gt;= 90 THEN '优秀'
WHEN es.score &gt;= 80 THEN '良好'
WHEN es.score &gt;= 60 THEN '及格'
ELSE '不及格'
END AS grade,
CASE
WHEN IFNULL(e.mark_flag, 0) = 0 OR IFNULL(es.mark_flag, 0) = 0 OR es.score IS NULL THEN NULL
WHEN es.score &gt;= IFNULL(e.pass_score, 60) THEN TRUE ELSE FALSE
END AS passed,
es.answer_time AS answerTime,
es.duration,
NULL AS comment
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id
LEFT JOIN user u ON u.id = es.student_id
LEFT JOIN class c ON c.id = es.class_id
WHERE es.exam_id = #{examId}
<if test="query.keyword != null and query.keyword != ''">
AND (u.nick_name LIKE CONCAT('%', #{query.keyword}, '%')
OR u.id_card LIKE CONCAT('%', #{query.keyword}, '%'))
</if>
<if test="query.scoreBand == 'EXCELLENT'">
AND IFNULL(e.mark_flag, 0) = 1 AND IFNULL(es.mark_flag, 0) = 1 AND es.score &gt;= 90
</if>
<if test="query.scoreBand == 'GOOD'">
AND IFNULL(e.mark_flag, 0) = 1 AND IFNULL(es.mark_flag, 0) = 1
AND es.score &gt;= 80 AND es.score &lt; 90
</if>
<if test="query.scoreBand == 'PASS'">
AND IFNULL(e.mark_flag, 0) = 1 AND IFNULL(es.mark_flag, 0) = 1
AND es.score &gt;= 60 AND es.score &lt; 80
</if>
<if test="query.scoreBand == 'FAIL'">
AND IFNULL(e.mark_flag, 0) = 1 AND IFNULL(es.mark_flag, 0) = 1 AND es.score &lt; 60
</if>
ORDER BY
CASE WHEN IFNULL(e.mark_flag, 0) = 1 AND IFNULL(es.mark_flag, 0) = 1 THEN 0 ELSE 1 END,
es.score DESC, u.nick_name, es.id
</select>
<select id="findStudent" resultType="com.platform.business.model.vo.ScoreAdminStudentDetailVO">
SELECT
es.id AS examStudentId,
es.exam_id AS examId,
es.class_id AS classId,
es.student_id AS studentId,
u.nick_name AS studentName,
u.id_card AS idCard,
c.name AS className,
e.name AS examName,
e.type AS examType,
e.exam_time AS examTime,
e.total_score AS totalScore,
e.pass_score AS passScore,
es.score,
(SELECT ROUND(AVG(peer.score), 2)
FROM exam_student peer
WHERE peer.exam_id = es.exam_id
AND IFNULL(peer.mark_flag, 0) = 1
AND peer.score IS NOT NULL) AS classAverageScore,
(SELECT COUNT(*) + 1
FROM exam_student peer
WHERE peer.exam_id = es.exam_id
AND IFNULL(peer.mark_flag, 0) = 1
AND peer.score &gt; es.score) AS rank,
CASE WHEN es.score &gt;= IFNULL(e.pass_score, 60) THEN TRUE ELSE FALSE END AS passed,
CASE
WHEN es.score &gt;= 90 THEN '优秀'
WHEN es.score &gt;= 80 THEN '良好'
WHEN es.score &gt;= 60 THEN '及格'
ELSE '不及格'
END AS grade,
es.answer_time AS answerTime,
es.duration,
CASE WHEN IFNULL(es.submit, 0) = 1 THEN TRUE ELSE FALSE END AS submitted,
CASE
WHEN IFNULL(e.mark_flag, 0) = 1 AND IFNULL(es.mark_flag, 0) = 1
THEN TRUE ELSE FALSE
END AS published
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id
LEFT JOIN user u ON u.id = es.student_id
LEFT JOIN class c ON c.id = es.class_id
WHERE es.id = #{examStudentId}
</select>
<select id="queryTheoryQuestions" resultType="com.platform.business.model.vo.ExamReviewQuestionVO">
SELECT
d.id AS questionId,
d.sequence,
d.type,
d.problem,
d.option_a AS optionA,
d.option_b AS optionB,
d.option_c AS optionC,
d.option_d AS optionD,
d.option_e AS optionE,
d.answer,
d.actual_choice AS actualChoice,
d.score AS maxScore,
CASE
WHEN d.type = '主观题' THEN d.actual_score
WHEN d.result = 1 THEN d.score
ELSE 0
END AS actualScore,
d.result,
d.is_partially_right AS partiallyRight,
CASE WHEN d.type = '主观题' THEN TRUE ELSE FALSE END AS manualScoreRequired,
TRUE AS reviewed
FROM theoretical_paper_student_detail d
WHERE d.exam_id = #{examId}
AND d.student_id = #{studentId}
AND IFNULL(d.is_problem, 1) = 1
ORDER BY d.sequence, d.id
</select>
<!-- 历史重复明细按雪花ID最大值视为最新记录,不在查询过程中删除原始数据。 -->
<select id="queryPracticeItems" resultType="com.platform.business.model.entity.FzGradesEntity">
SELECT
g.id, g.exam_id AS examId, g.user_id AS userId, g.code, g.lev,
g.start_time AS startTime, g.submission_time AS submissionTime,
g.title, g.type, g.options, g.mark, g.text, g.result, g.file, g.score
FROM fz_grades g
INNER JOIN (
SELECT MAX(id) AS id
FROM fz_grades
WHERE exam_id = #{examId} AND user_id = #{studentId}
GROUP BY code
) latest ON latest.id = g.id
ORDER BY g.code, g.id
</select>
<select id="queryTheoryStatistics" resultType="com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO">
SELECT
NULL AS questionCode,
d.sequence,
d.type AS questionType,
d.problem AS title,
ROUND(MAX(d.score), 2) AS maxScore,
ROUND(AVG(CASE
WHEN d.type = '主观题' THEN IFNULL(d.actual_score, 0)
WHEN d.result = 1 THEN IFNULL(d.score, 0)
ELSE 0
END), 2) AS averageScore,
ROUND(AVG(CASE
WHEN d.type = '主观题' THEN IFNULL(d.actual_score, 0)
WHEN d.result = 1 THEN IFNULL(d.score, 0)
ELSE 0
END) * 100.0 / NULLIF(MAX(d.score), 0), 2) AS scoreRate,
SUM(CASE WHEN d.result = 1 THEN 1 ELSE 0 END) AS correctCount,
COUNT(DISTINCT d.student_id) AS participantCount,
NULL AS successResultCount,
NULL AS failureResultCount,
CASE
WHEN AVG(CASE
WHEN d.type = '主观题' THEN IFNULL(d.actual_score, 0)
WHEN d.result = 1 THEN IFNULL(d.score, 0)
ELSE 0
END) * 100.0 / NULLIF(MAX(d.score), 0) &gt;= 80 THEN 'EASY'
WHEN AVG(CASE
WHEN d.type = '主观题' THEN IFNULL(d.actual_score, 0)
WHEN d.result = 1 THEN IFNULL(d.score, 0)
ELSE 0
END) * 100.0 / NULLIF(MAX(d.score), 0) &gt;= 60 THEN 'MEDIUM'
ELSE 'HARD'
END AS difficulty
FROM theoretical_paper_student_detail d
INNER JOIN exam_student es
ON es.exam_id = d.exam_id AND es.student_id = d.student_id
AND IFNULL(es.mark_flag, 0) = 1
WHERE d.exam_id = #{examId}
AND IFNULL(d.is_problem, 1) = 1
GROUP BY d.sequence, d.type, d.problem
ORDER BY d.sequence
</select>
<select id="queryPracticeStatistics" resultType="com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO">
SELECT
g.code AS questionCode,
NULL AS sequence,
g.type AS questionType,
MAX(g.title) AS title,
NULL AS maxScore,
ROUND(AVG(g.score), 2) AS averageScore,
NULL AS scoreRate,
NULL AS correctCount,
COUNT(DISTINCT g.user_id) AS participantCount,
SUM(CASE WHEN LOWER(IFNULL(g.result, '')) IN ('1', 'true', '正确', '通过', '合格') THEN 1 ELSE 0 END)
AS successResultCount,
SUM(CASE WHEN LOWER(IFNULL(g.result, '')) IN ('0', 'false', '错误', '未通过', '不合格') THEN 1 ELSE 0 END)
AS failureResultCount,
NULL AS difficulty
FROM fz_grades g
INNER JOIN (
SELECT exam_id, user_id, code, MAX(id) AS id
FROM fz_grades
WHERE exam_id = #{examId}
GROUP BY exam_id, user_id, code
) latest ON latest.id = g.id
INNER JOIN exam_student es
ON es.exam_id = g.exam_id AND es.student_id = g.user_id
AND IFNULL(es.mark_flag, 0) = 1
GROUP BY g.code, g.type
ORDER BY g.code
</select>
<select id="queryPublishedStudents" resultType="com.platform.business.model.vo.ScoreAdminStudentVO">
SELECT
es.id AS examStudentId, es.exam_id AS examId, es.class_id AS classId,
es.student_id AS studentId, u.nick_name AS studentName, u.id_card AS idCard,
c.name AS className, e.name AS examName, e.type AS examType, e.exam_time AS examTime,
TRUE AS submitted, TRUE AS published, es.score,
CASE WHEN es.score &gt;= 90 THEN '优秀' WHEN es.score &gt;= 80 THEN '良好'
WHEN es.score &gt;= 60 THEN '及格' ELSE '不及格' END AS grade,
CASE WHEN es.score &gt;= IFNULL(e.pass_score, 60) THEN TRUE ELSE FALSE END AS passed,
es.answer_time AS answerTime, es.duration, NULL AS comment
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id AND IFNULL(e.mark_flag, 0) = 1
LEFT JOIN user u ON u.id = es.student_id
LEFT JOIN class c ON c.id = es.class_id
WHERE es.exam_id = #{examId}
AND IFNULL(es.mark_flag, 0) = 1
AND es.score IS NOT NULL
ORDER BY es.score DESC, u.nick_name, es.id
</select>
<select id="queryClassExams" resultType="com.platform.business.model.vo.ScoreAdminExamVO">
SELECT <include refid="examSummaryColumns"/>
<include refid="examSummaryJoins"/>
WHERE e.class_id = #{classId}
AND DATE_ADD(e.exam_time, INTERVAL IFNULL(e.duration, 0) MINUTE) &lt;= NOW()
<include refid="examSummaryGroup"/>
ORDER BY e.exam_time DESC, e.id DESC
</select>
</mapper>
-- 管理员端“智能考评-学员成绩管理”与仿真实训成绩增量接收脚本(MySQL 5.7+/8.0)。
--
-- 设计说明:
-- 1. 理论成绩继续复用 exam、exam_student、theoretical_paper_student_detail,不新建重复成绩表。
-- 2. fz_grades 只保存逐题明细;正式总分汇总到 exam_student,统一供学生端和管理端读取。
-- 3. 历史环境可能已经存在重复题号,因此本脚本只增加普通索引,不自动删除或改写历史数据。
-- 4. 应用查询按每个 exam_id + user_id + code 的最大雪花ID归并为最新记录。
CREATE TABLE IF NOT EXISTS fz_grades (
id VARCHAR(64) NOT NULL COMMENT '雪花主键',
exam_id INT NOT NULL COMMENT '考试ID',
user_id VARCHAR(64) NOT NULL COMMENT '系统学员ID',
code VARCHAR(128) NOT NULL COMMENT '题目编号',
lev VARCHAR(64) NULL COMMENT '等级',
start_time DATETIME NULL COMMENT '仿真实训开始时间',
submission_time DATETIME NULL COMMENT '交卷时间;非空表示本场完成',
title VARCHAR(500) NULL COMMENT '题目标题',
type VARCHAR(32) NULL COMMENT '题目类型',
`options` TEXT NULL COMMENT '题目选项',
mark TINYINT(1) NULL COMMENT '0线上/1线下',
`text` LONGTEXT NULL COMMENT '作答文本',
result LONGTEXT NULL COMMENT '判定结果',
file TEXT NULL COMMENT '附件地址或标识',
score DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '本题实际得分',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='仿真实训逐题成绩明细';
delimiter $$
drop procedure if exists migrate_student_score_management$$
create procedure migrate_student_score_management()
begin
-- 增量上报和单个学员详情均先按考试、学员、题号缩小范围。
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'fz_grades'
and index_name = 'idx_fz_grades_exam_user_code'
) then
alter table fz_grades
add index idx_fz_grades_exam_user_code (exam_id, user_id, code);
end if;
-- 考试统计与正式提交排查会按考试、交卷时间、学员读取。
if not exists (
select 1 from information_schema.statistics
where table_schema = database() and table_name = 'fz_grades'
and index_name = 'idx_fz_grades_exam_submit_user'
) then
alter table fz_grades
add index idx_fz_grades_exam_submit_user (exam_id, submission_time, user_id);
end if;
end$$
call migrate_student_score_management()$$
drop procedure if exists migrate_student_score_management$$
delimiter ;
-- 部署后可使用以下只读查询定位历史重复题号;应用会按最大ID读取最新版本,不会丢失原始记录。
select exam_id, user_id, code, count(*) as duplicate_count
from fz_grades
group by exam_id, user_id, code
having count(*) > 1;
# 管理员端学员成绩管理接口
管理端接口统一使用 `/exam/admin/scores` 前缀。每次请求都必须携带 `Authorization`,服务端从
JWT解析当前用户并校验 `phone_role.role_name=管理员`。本模块只提供查询和导出;评分与发布仍由
首席考评教师通过 `/exam/review` 完成。
部署前依次执行已有 `sql/exam_management.sql`、`sql/exam_review.sql`,再执行
`sql/student_score_management.sql`。
## 统一成绩口径
- 历史考试指 `考试开始时间 + 时长 <= 当前时间`。
- 理论成绩必须同时满足 `exam.mark_flag=1`、`exam_student.mark_flag=1` 才是正式成绩。
- 实训成绩在仿真系统提交 `submissionTime` 后自动汇总并设置上述发布标记。
- 待批阅场次可返回应考、实考人数,但平均分、合格率和个人分数为 `null`。
- 合格率分母为已经实考且成绩正式发布的人数,缺考学员不计为不合格。
## 1. 班级导航树
`GET /exam/admin/scores/tree?keyword=污水`
返回 `OCCUPATION → YEAR → LEVEL → CLASS` 四层节点。班级叶节点的 `classId` 用于后续请求。
## 2. 历史考试分页
`POST /exam/admin/scores/exams/page`
```json
{
"pageNum": 1,
"pageSize": 10,
"classId": 10,
"keyword": "期末",
"type": "THEORY",
"status": "PUBLISHED",
"startDate": "2026-01-01",
"endDate": "2026-12-31"
}
```
`type` 支持 `THEORY/PRACTICE`,也兼容数据库中文值“理论/实训”;`status` 支持
`ALL/PENDING_REVIEW/PUBLISHED`。
## 3. 考试汇总与学员分页
- `GET /exam/admin/scores/exams/{examId}`:返回考试与班级信息、应考/实考、已发布人数、
平均分、合格人数和合格率。
- `POST /exam/admin/scores/exams/{examId}/students/page`:请求体支持 `pageNum`、`pageSize`、
`keyword` 和 `scoreBand`。
`scoreBand` 支持:
- `ALL`
- `EXCELLENT`:90分及以上
- `GOOD`:80~89.99分
- `PASS`:60~79.99分
- `FAIL`:60分以下
未发布考试仍返回应考学员和交卷状态,但 `score/grade/passed` 为 `null`。
## 4. 学员详情与题目统计
- `GET /exam/admin/scores/exam-students/{examStudentId}`:只允许读取正式发布成绩。理论考试返回
`theoryQuestions`;实训考试返回 `practiceItems`。
- `GET /exam/admin/scores/exams/{examId}/questions/statistics`:理论题返回满分、平均分、得分率、
答对人数和难度;实训协议没有每题满分,因此 `maxScore/scoreRate/difficulty` 为 `null`。
## 5. Excel导出
- `GET /exam/admin/scores/exams/{examId}/export`:导出单场已发布成绩。
- `GET /exam/admin/scores/classes/{classId}/export`:导出班级历史考试汇总和所有正式学员成绩。
响应类型为 `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,文件名通过
RFC 5987 UTF-8编码。未发布考试禁止导出。
## 6. 仿真实训逐题增量上报
`POST /fz/grades/receive`
```json
[
{
"examId": 1001,
"userId": "1900000000000000201",
"code": "STEP-01",
"lev": "污水一级",
"startTime": "2026-08-17 09:00:00",
"submissionTime": null,
"title": "启动前安全检查",
"type": "3",
"text": "已完成检查",
"result": "通过",
"file": null,
"score": 10
}
]
```
- `examId/userId/code/score` 必填,考试必须为实训,学员必须属于本场应考名单。
- 同一 `examId + userId + code` 再次上报会更新已有记录,不会新增业务重复题目。
- 未传 `submissionTime` 只保存增量明细;任一项传值时汇总该学员所有题目的最新分数并发布。
- 已发布后完全相同的重试返回成功;新增题目或修改任何已发布内容会被拒绝。
package com.platform.business.controller;
import com.platform.business.model.dto.ScoreAdminExamQueryDTO;
import com.platform.business.model.dto.ScoreAdminStudentQueryDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.ScoreAdminService;
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.mock.web.MockHttpServletResponse;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.assertEquals;
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 ScoreAdminControllerTest {
@Mock
private ScoreAdminService scoreAdminService;
@Mock
private AuthenticatedUserService authenticatedUserService;
private ScoreAdminController controller;
@BeforeEach
void setUp() {
controller = new ScoreAdminController();
ReflectionTestUtils.setField(controller, "scoreAdminService", scoreAdminService);
ReflectionTestUtils.setField(controller, "authenticatedUserService", authenticatedUserService);
}
@Test
void endpointsShouldRequireAdminAndNormalizePageSize() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
UserEntity administrator = new UserEntity();
when(authenticatedUserService.current(request)).thenReturn(administrator);
ScoreAdminExamQueryDTO examQuery = new ScoreAdminExamQueryDTO();
examQuery.setPageSize(1000);
ScoreAdminStudentQueryDTO studentQuery = new ScoreAdminStudentQueryDTO();
studentQuery.setPageSize(0);
controller.tree("污水", request);
controller.exams(examQuery, request);
controller.exam(11, request);
controller.students(11, studentQuery, request);
controller.student(22, request);
controller.questionStatistics(11, request);
controller.exportExam(11, request, response);
controller.exportClass(33, request, response);
verify(authenticatedUserService, times(8)).requireAdmin(administrator);
assertEquals(100, examQuery.getPageSize());
assertEquals(10, studentQuery.getPageSize());
verify(scoreAdminService).tree("污水");
verify(scoreAdminService).exam(11);
verify(scoreAdminService).student(22);
verify(scoreAdminService).exportClass(33, response);
}
@Test
void requestShouldStopBeforeServiceWhenRoleCheckFails() {
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.exam(1, 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,防止动态SQL或resultType拼写错误。 */
class ScoreAdminMapperXmlTest {
@Test
void scoreAdminMapperShouldRegisterAllMainQueries() throws Exception {
Configuration configuration = parse("com/platform/business/mapper/ScoreAdminMapper.xml");
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.ScoreAdminMapper.queryExams"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.ScoreAdminMapper.queryStudents"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.ScoreAdminMapper.queryTheoryStatistics"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.ScoreAdminMapper.queryPracticeStatistics"));
}
@Test
void fzGradesMapperShouldRegisterIdempotentReceiveStatements() throws Exception {
Configuration configuration = parse("com/platform/business/mapper/FzGradesMapper.xml");
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.FzGradesMapper.lockExamStudent"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.FzGradesMapper.updateByBusinessKey"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.FzGradesMapper.publishPracticeStudent"));
}
private Configuration parse(String resource) throws Exception {
Configuration configuration = new Configuration();
try (InputStream input = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder builder = new XMLMapperBuilder(
input, configuration, resource, configuration.getSqlFragments());
builder.parse();
}
return configuration;
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.ExamMapper;
import com.platform.business.mapper.FzGradesMapper;
import com.platform.business.model.dto.FzGradesDTO;
import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.entity.ExamStudentEntity;
import com.platform.business.model.entity.FzGradesEntity;
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.test.util.ReflectionTestUtils;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 仿真实训成绩的增量保存、最终发布、幂等重试和越权校验测试。 */
@ExtendWith(MockitoExtension.class)
class FzGradesServiceImplTest {
@Mock
private FzGradesMapper fzGradesMapper;
@Mock
private ExamMapper examMapper;
private FzGradesServiceImpl service;
@BeforeEach
void setUp() {
service = new FzGradesServiceImpl();
ReflectionTestUtils.setField(service, "baseMapper", fzGradesMapper);
ReflectionTestUtils.setField(service, "examMapper", examMapper);
}
@Test
void incrementalItemShouldSaveWithoutPublishing() {
mockCandidate(false);
when(fzGradesMapper.selectLatestItems(1, "student-1")).thenReturn(Collections.emptyList());
when(fzGradesMapper.insert(any(FzGradesEntity.class))).thenReturn(1);
assertTrue(service.receive(Collections.singletonList(item(null, 20D))));
verify(fzGradesMapper).insert(any(FzGradesEntity.class));
verify(fzGradesMapper, never()).publishPracticeStudent(
any(), any(), any(), any(), any(), any());
}
@Test
void submissionTimeShouldAggregateAndPublishOfficialScore() {
mockCandidate(false);
Date start = new Date(System.currentTimeMillis() - 60_000L);
Date end = new Date();
FzGradesEntity persisted = new FzGradesEntity();
persisted.setCode("Q-1");
persisted.setStartTime(start);
when(fzGradesMapper.selectLatestItems(1, "student-1"))
.thenReturn(Collections.emptyList())
.thenReturn(Collections.singletonList(persisted));
when(fzGradesMapper.insert(any(FzGradesEntity.class))).thenReturn(1);
when(fzGradesMapper.sumLatestScores(1, "student-1")).thenReturn(75D);
when(fzGradesMapper.publishPracticeStudent(eq(9), eq(75D), any(), any(), any(), any()))
.thenReturn(1);
when(fzGradesMapper.publishPracticeExam(eq(1), any(Date.class))).thenReturn(1);
assertTrue(service.receive(Collections.singletonList(item(end, 75D))));
verify(fzGradesMapper).publishPracticeExam(eq(1), any(Date.class));
}
@Test
void publishedScoreShouldRejectChangedReplay() {
mockCandidate(true);
FzGradesEntity persisted = new FzGradesEntity();
persisted.setExamId(1);
persisted.setUserId("student-1");
persisted.setCode("Q-1");
persisted.setScore(10D);
when(fzGradesMapper.selectLatestItems(1, "student-1"))
.thenReturn(Collections.singletonList(persisted));
BusinessException error = assertThrows(BusinessException.class,
() -> service.receive(Collections.singletonList(item(null, 20D))));
assertEquals("仿真实训成绩已经发布,不能继续修改", error.getMessage());
}
@Test
void studentOutsideCandidateListShouldBeRejectedBeforeWriting() {
when(fzGradesMapper.lockExamStudent(1, "student-1")).thenReturn(null);
assertThrows(BusinessException.class,
() -> service.receive(Collections.singletonList(item(null, 10D))));
verify(fzGradesMapper, never()).insert(any(FzGradesEntity.class));
}
private void mockCandidate(boolean published) {
ExamStudentEntity candidate = new ExamStudentEntity();
candidate.setId(9);
candidate.setExamId(1);
candidate.setStudentId("student-1");
candidate.setMarkFlag(published);
when(fzGradesMapper.lockExamStudent(1, "student-1")).thenReturn(candidate);
ExamEntity exam = new ExamEntity();
exam.setId(1);
exam.setType("实训");
exam.setTotalScore(new BigDecimal("100"));
when(examMapper.selectById(1)).thenReturn(exam);
}
private FzGradesDTO item(Date submissionTime, Double score) {
FzGradesDTO item = new FzGradesDTO();
item.setExamId(1);
item.setUserId("student-1");
item.setCode("Q-1");
item.setTitle("启动检查");
item.setScore(score);
item.setSubmissionTime(submissionTime);
return item;
}
}
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