Commit 98e0a708 authored by wujipeng's avatar wujipeng
Browse files

教师端-教学管理-阅卷管理

parent 8f8b9d12
package com.platform.business.service.impl;
import com.platform.business.constant.ExamReviewConstants;
import com.platform.business.mapper.ExamReviewMapper;
import com.platform.business.mapper.ExamReviewScoreLogMapper;
import com.platform.business.model.dto.ExamReviewSaveDTO;
import com.platform.business.model.dto.ExamReviewScoreItemDTO;
import com.platform.business.model.dto.ExamReviewStudentQueryDTO;
import com.platform.business.model.dto.ExamReviewTaskQueryDTO;
import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.entity.ExamReviewScoreLogEntity;
import com.platform.business.model.entity.ExamStudentEntity;
import com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity;
import com.platform.business.model.vo.ExamReviewPaperVO;
import com.platform.business.model.vo.ExamReviewQuestionVO;
import com.platform.business.model.vo.ExamReviewRecordVO;
import com.platform.business.model.vo.ExamReviewScoreSummaryVO;
import com.platform.business.model.vo.ExamReviewStudentVO;
import com.platform.business.model.vo.ExamReviewTaskVO;
import com.platform.business.service.ExamReviewService;
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.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* 教师端阅卷管理核心实现。
*
* <p>关键状态流转如下:考生交卷后进入待阅卷;教师保存主观题分数时只更新答题明细并
* 写审计日志,不改变发布标记;发布时在同一事务内锁定考试及全部已交卷考生、校验评分
* 完整性、重算总分,最后统一设置考生和考试的 mark_flag。</p>
*/
@Service
public class ExamReviewServiceImpl implements ExamReviewService {
@Resource
private ExamReviewMapper examReviewMapper;
@Resource
private ExamReviewScoreLogMapper scoreLogMapper;
@Override
public List<ExamReviewTaskVO> queryTasks(ExamReviewTaskQueryDTO query, String teacherId) {
ExamReviewTaskQueryDTO safeQuery = query == null ? new ExamReviewTaskQueryDTO() : query;
safeQuery.setKeyword(trimToNull(safeQuery.getKeyword()));
safeQuery.setStatus(normalizeStatus(safeQuery.getStatus()));
List<ExamReviewTaskVO> tasks = examReviewMapper.queryTasks(teacherId, safeQuery);
tasks.forEach(this::fillDeadline);
return tasks;
}
@Override
public List<ExamReviewStudentVO> queryStudents(ExamReviewStudentQueryDTO query, String teacherId) {
if (query == null || query.getExamId() == null || query.getClassId() == null) {
throw new BusinessException("考试ID和班级ID不能为空");
}
ExamReviewTaskVO task = requireTask(query.getExamId(), teacherId);
// 班级ID由任务列表带入并在服务端复核,防止拼接其他班级ID读取无关考生。
if (!query.getClassId().equals(task.getClassId())) {
throw new BusinessException("考试与班级不匹配");
}
query.setKeyword(trimToNull(query.getKeyword()));
return examReviewMapper.queryStudents(teacherId, query);
}
@Override
public ExamReviewPaperVO paper(Integer examStudentId, String teacherId) {
ExamReviewStudentVO student = requireStudent(examStudentId, teacherId);
ExamReviewTaskVO task = requireTask(student.getExamId(), teacherId);
List<ExamReviewQuestionVO> questions = examReviewMapper.queryQuestions(
student.getExamId(), student.getStudentId());
if (questions == null || questions.isEmpty()) {
throw new BusinessException("该考生尚未生成可阅卷的试卷明细");
}
return assemblePaper(task, student, questions);
}
@Override
@Transactional
public ExamReviewPaperVO saveScores(Integer examStudentId, ExamReviewSaveDTO request,
String teacherId) {
validateSaveRequest(request);
// 先锁考生记录:发布事务也会锁同一行,因此保存和发布不会交叉覆盖。
ExamStudentEntity student = examReviewMapper.lockStudent(examStudentId, teacherId);
if (student == null) {
throw new BusinessException("已交试卷不存在或当前教师无权阅卷");
}
if (Boolean.TRUE.equals(student.getMarkFlag())) {
throw new BusinessException("成绩已经发布,不能继续修改评分");
}
Map<String, ExamReviewScoreItemDTO> requestByQuestionId = new LinkedHashMap<>();
List<String> questionIds = new ArrayList<>();
for (ExamReviewScoreItemDTO item : request.getScores()) {
String questionId = trimToNull(item.getQuestionId());
if (questionId == null) {
throw new BusinessException("答题明细ID不能为空");
}
if (requestByQuestionId.put(questionId, item) != null) {
throw new BusinessException("同一道题不能重复提交评分");
}
questionIds.add(questionId);
}
List<TheoreticalPaperStudentDetailEntity> lockedQuestions = examReviewMapper.lockQuestions(
questionIds, student.getExamId(), student.getStudentId());
if (lockedQuestions.size() != questionIds.size()) {
throw new BusinessException("评分题目不属于当前考生,或题目不存在");
}
Date now = new Date();
for (TheoreticalPaperStudentDetailEntity question : lockedQuestions) {
ExamReviewScoreItemDTO item = requestByQuestionId.get(question.getId());
validateQuestionScore(question, item);
BigDecimal maxScore = BigDecimal.valueOf(question.getScore());
BigDecimal newScore = item.getScore();
boolean fullScore = newScore.compareTo(maxScore) == 0;
boolean partiallyRight = newScore.compareTo(BigDecimal.ZERO) > 0 && !fullScore;
int updated = examReviewMapper.updateQuestionScore(question.getId(),
newScore.doubleValue(), fullScore, partiallyRight);
if (updated != 1) {
throw new BusinessException("题目评分保存失败,请刷新后重试");
}
BigDecimal previousScore = toBigDecimal(question.getActualScore());
String reviewComment = trimToNull(item.getComment());
// 分数未变化且没有评分说明时不制造重复审计数据。
if (!sameScore(previousScore, newScore) || reviewComment != null) {
insertLog(student.getExamId(), student.getId(), question.getId(), teacherId,
previousScore, newScore, ExamReviewConstants.ACTION_SAVE, reviewComment, now);
}
}
// 返回最新工作台数据,前端无需再额外发起一次刷新请求。
return paper(examStudentId, teacherId);
}
@Override
@Transactional
public boolean publish(Integer examId, String teacherId) {
if (examId == null) {
throw new BusinessException("考试ID不能为空");
}
// 考试主记录行锁用于串行化同一场考试的发布请求。
ExamEntity exam = examReviewMapper.lockTask(examId, teacherId);
if (exam == null) {
throw new BusinessException("阅卷任务不存在或当前教师无权发布");
}
List<ExamStudentEntity> students = examReviewMapper.lockSubmittedStudents(examId);
if (students == null || students.isEmpty()) {
throw new BusinessException("本场考试暂无已交试卷,不能发布成绩");
}
List<ExamStudentEntity> pendingStudents = new ArrayList<>();
for (ExamStudentEntity student : students) {
if (!Boolean.TRUE.equals(student.getMarkFlag())) {
pendingStudents.add(student);
}
}
// 若所有考生都已发布:主标记也为 true 时属于重复操作;仅主标记缺失时在锁内修复。
if (pendingStudents.isEmpty()) {
if (Boolean.TRUE.equals(exam.getMarkFlag())) {
throw new BusinessException("本场考试成绩已经发布,请勿重复操作");
}
if (examReviewMapper.publishTask(examId) != 1) {
throw new BusinessException("阅卷任务状态修复失败,请稍后重试");
}
return true;
}
// 即使考试主标记因历史发布已经为 true,只要出现新的未发布交卷,仍允许补充发布;
// 任务列表同样以考生 mark_flag 聚合,因此不会发生列表显示待阅卷却无法进入发布的问题。
if (examReviewMapper.countSubmittedWithoutPaper(examId) > 0) {
throw new BusinessException("存在尚未生成试卷明细的已交考生,暂不能发布");
}
int unscoredCount = examReviewMapper.countUnscoredSubjective(examId);
if (unscoredCount > 0) {
throw new BusinessException("还有" + unscoredCount + "道主观题未评分,完成后才能发布");
}
Date now = new Date();
for (ExamStudentEntity student : pendingStudents) {
Double finalScore = examReviewMapper.calculateStudentScore(examId, student.getStudentId());
if (finalScore == null) {
finalScore = 0D;
}
int updated = examReviewMapper.publishStudent(student.getId(), finalScore);
if (updated != 1) {
throw new BusinessException("考生成绩发布状态已变化,请刷新后重试");
}
insertLog(examId, student.getId(), null, teacherId,
toBigDecimal(student.getScore()), toBigDecimal(finalScore),
ExamReviewConstants.ACTION_PUBLISH, "发布最终成绩", now);
}
if (examReviewMapper.publishTask(examId) != 1) {
throw new BusinessException("阅卷任务发布失败,请稍后重试");
}
return true;
}
@Override
public List<ExamReviewRecordVO> history(Integer examStudentId, String teacherId) {
// 先做带教师ID的关联校验,避免仅凭考生考试记录ID读取其他教师的评分历史。
requireStudent(examStudentId, teacherId);
return examReviewMapper.queryHistory(examStudentId);
}
private ExamReviewPaperVO assemblePaper(ExamReviewTaskVO task, ExamReviewStudentVO student,
List<ExamReviewQuestionVO> questions) {
Map<String, ExamReviewScoreSummaryVO> summaryMap = new LinkedHashMap<>();
double currentTotal = 0D;
double calculatedPaperTotal = 0D;
boolean scoringCompleted = true;
for (ExamReviewQuestionVO question : questions) {
String type = trimToNull(question.getType());
if (type == null) {
type = "其他";
}
ExamReviewScoreSummaryVO summary = summaryMap.get(type);
if (summary == null) {
summary = new ExamReviewScoreSummaryVO();
summary.setType(type);
summary.setQuestionCount(0);
summary.setReviewedCount(0);
summary.setMaxScore(0D);
summary.setActualScore(0D);
summaryMap.put(type, summary);
}
double maxScore = question.getMaxScore() == null ? 0D : question.getMaxScore();
double actualScore = question.getActualScore() == null ? 0D : question.getActualScore();
summary.setQuestionCount(summary.getQuestionCount() + 1);
summary.setMaxScore(summary.getMaxScore() + maxScore);
summary.setActualScore(summary.getActualScore() + actualScore);
if (Boolean.TRUE.equals(question.getReviewed())) {
summary.setReviewedCount(summary.getReviewedCount() + 1);
}
if (Boolean.TRUE.equals(question.getManualScoreRequired())
&& !Boolean.TRUE.equals(question.getReviewed())) {
scoringCompleted = false;
}
currentTotal += actualScore;
calculatedPaperTotal += maxScore;
}
for (ExamReviewScoreSummaryVO summary : summaryMap.values()) {
summary.setCompleted(summary.getQuestionCount().equals(summary.getReviewedCount()));
}
ExamReviewPaperVO paper = new ExamReviewPaperVO();
paper.setExamId(task.getExamId());
paper.setClassId(task.getClassId());
paper.setExamName(task.getExamName());
paper.setClassName(task.getClassName());
paper.setPaperId(task.getPaperId());
paper.setPaperName(task.getPaperName());
paper.setPaperTotal(task.getPaperTotal() == null ? calculatedPaperTotal : task.getPaperTotal());
paper.setDuration(task.getDuration());
paper.setStudent(student);
paper.setScoreSummaries(new ArrayList<>(summaryMap.values()));
paper.setQuestions(questions);
paper.setCurrentTotalScore(currentTotal);
paper.setScoringCompleted(scoringCompleted);
paper.setPublished(Boolean.TRUE.equals(student.getPublished()));
return paper;
}
private ExamReviewTaskVO requireTask(Integer examId, String teacherId) {
if (examId == null) {
throw new BusinessException("考试ID不能为空");
}
ExamReviewTaskVO task = examReviewMapper.findTask(examId, teacherId);
if (task == null) {
throw new BusinessException("阅卷任务不存在或当前教师无权访问");
}
fillDeadline(task);
return task;
}
private ExamReviewStudentVO requireStudent(Integer examStudentId, String teacherId) {
if (examStudentId == null) {
throw new BusinessException("考生考试记录ID不能为空");
}
ExamReviewStudentVO student = examReviewMapper.findStudent(examStudentId, teacherId);
if (student == null) {
throw new BusinessException("已交试卷不存在或当前教师无权访问");
}
return student;
}
private void validateSaveRequest(ExamReviewSaveDTO request) {
if (request == null || request.getScores() == null || request.getScores().isEmpty()) {
throw new BusinessException("至少需要提交一道题的评分");
}
if (request.getScores().size() > ExamReviewConstants.MAX_SCORE_BATCH_SIZE) {
throw new BusinessException("单次最多保存" + ExamReviewConstants.MAX_SCORE_BATCH_SIZE + "道题的评分");
}
for (ExamReviewScoreItemDTO item : request.getScores()) {
if (item == null) {
throw new BusinessException("评分列表不能包含空项");
}
if (item.getScore() == null) {
throw new BusinessException("题目得分不能为空");
}
if (item.getComment() != null && item.getComment().trim().length() > 1000) {
throw new BusinessException("单题评分说明不能超过1000个字符");
}
}
}
private void validateQuestionScore(TheoreticalPaperStudentDetailEntity question,
ExamReviewScoreItemDTO item) {
if (!ExamReviewConstants.SUBJECTIVE_TYPE.equals(question.getType())) {
throw new BusinessException("客观题由系统自动判分,不能手动修改");
}
if (question.getScore() == null || question.getScore() < 0D) {
throw new BusinessException("题目满分配置异常,无法保存评分");
}
BigDecimal score = item.getScore();
BigDecimal maxScore = BigDecimal.valueOf(question.getScore());
if (score.compareTo(BigDecimal.ZERO) < 0 || score.compareTo(maxScore) > 0) {
throw new BusinessException("题目得分必须在0至" + maxScore.stripTrailingZeros().toPlainString() + "之间");
}
}
private String normalizeStatus(String status) {
String normalized = trimToNull(status);
if (normalized == null) {
return ExamReviewConstants.STATUS_ALL;
}
normalized = normalized.toUpperCase(Locale.ROOT);
Set<String> supported = new HashSet<>();
supported.add(ExamReviewConstants.STATUS_ALL);
supported.add(ExamReviewConstants.STATUS_PENDING);
supported.add(ExamReviewConstants.STATUS_COMPLETED);
if (!supported.contains(normalized)) {
throw new BusinessException("阅卷状态只能是 ALL、PENDING 或 COMPLETED");
}
return normalized;
}
private void fillDeadline(ExamReviewTaskVO task) {
if (task.getExamTime() == null) {
return;
}
int duration = task.getDuration() == null ? 0 : Math.max(task.getDuration(), 0);
task.setDeadline(new Date(task.getExamTime().getTime() + duration * 60_000L));
}
private void insertLog(Integer examId, Integer examStudentId, String questionId,
String reviewerId, BigDecimal previousScore, BigDecimal newScore,
String action, String reviewComment, Date createdAt) {
ExamReviewScoreLogEntity log = new ExamReviewScoreLogEntity();
log.setExamId(examId);
log.setExamStudentId(examStudentId);
log.setQuestionId(questionId);
log.setReviewerId(reviewerId);
log.setPreviousScore(previousScore);
log.setNewScore(newScore);
log.setAction(action);
log.setReviewComment(reviewComment);
log.setCreatedAt(createdAt);
if (scoreLogMapper.insert(log) != 1) {
throw new BusinessException("评分审计记录保存失败");
}
}
private static BigDecimal toBigDecimal(Double value) {
return value == null ? null : BigDecimal.valueOf(value);
}
private static boolean sameScore(BigDecimal left, BigDecimal right) {
return left == null ? right == null : right != null && left.compareTo(right) == 0;
}
private static String trimToNull(String value) {
if (value == null) {
return null;
}
String trimmed = value.trim();
return trimmed.isEmpty() ? null : trimmed;
}
}
<?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.ExamReviewMapper">
<!--
教师只能看到本人作为首席考评员的考试。任务状态按已交卷考生的 mark_flag 聚合:
任意一份已交试卷尚未发布即为 PENDING,全部发布后才是 COMPLETED。
-->
<select id="queryTasks" resultType="com.platform.business.model.vo.ExamReviewTaskVO">
SELECT
e.id AS examId,
e.class_id AS classId,
e.name AS examName,
c.name AS className,
e.type AS examType,
e.paper_id AS paperId,
tp.name AS paperName,
tp.sum AS paperTotal,
e.exam_time AS examTime,
e.duration,
COUNT(es.id) AS totalCount,
SUM(CASE WHEN es.submit = 1 THEN 1 ELSE 0 END) AS submittedCount,
SUM(CASE WHEN es.submit = 1 AND IFNULL(es.mark_flag, 0) = 1 THEN 1 ELSE 0 END) AS reviewedCount,
SUM(CASE WHEN es.submit = 1 AND IFNULL(es.mark_flag, 0) = 0 THEN 1 ELSE 0 END) AS pendingCount,
CASE
WHEN SUM(CASE WHEN es.submit = 1 AND IFNULL(es.mark_flag, 0) = 0 THEN 1 ELSE 0 END) &gt; 0
THEN 'PENDING'
ELSE 'COMPLETED'
END AS reviewStatus
FROM exam e
INNER JOIN exam_student es ON es.exam_id = e.id
LEFT JOIN class c ON c.id = e.class_id
LEFT JOIN theoretical_paper tp ON tp.id = e.paper_id
WHERE e.chief_id = #{teacherId}
<if test="query.keyword != null and query.keyword != ''">
AND e.name LIKE CONCAT('%', #{query.keyword}, '%')
</if>
GROUP BY e.id, e.class_id, e.name, c.name, e.type, e.paper_id, tp.name, tp.sum,
e.exam_time, e.duration
HAVING SUM(CASE WHEN es.submit = 1 THEN 1 ELSE 0 END) &gt; 0
<if test="query.status == 'PENDING'">
AND SUM(CASE WHEN es.submit = 1 AND IFNULL(es.mark_flag, 0) = 0 THEN 1 ELSE 0 END) &gt; 0
</if>
<if test="query.status == 'COMPLETED'">
AND SUM(CASE WHEN es.submit = 1 AND IFNULL(es.mark_flag, 0) = 0 THEN 1 ELSE 0 END) = 0
</if>
ORDER BY e.exam_time DESC, e.id DESC
</select>
<!-- 查询任务详情时仍带教师条件,用于所有工作台读写接口的越权校验。 -->
<select id="findTask" resultType="com.platform.business.model.vo.ExamReviewTaskVO">
SELECT
e.id AS examId,
e.class_id AS classId,
e.name AS examName,
c.name AS className,
e.type AS examType,
e.paper_id AS paperId,
tp.name AS paperName,
tp.sum AS paperTotal,
e.exam_time AS examTime,
e.duration,
COUNT(es.id) AS totalCount,
SUM(CASE WHEN es.submit = 1 THEN 1 ELSE 0 END) AS submittedCount,
SUM(CASE WHEN es.submit = 1 AND IFNULL(es.mark_flag, 0) = 1 THEN 1 ELSE 0 END) AS reviewedCount,
SUM(CASE WHEN es.submit = 1 AND IFNULL(es.mark_flag, 0) = 0 THEN 1 ELSE 0 END) AS pendingCount,
CASE
WHEN SUM(CASE WHEN es.submit = 1 AND IFNULL(es.mark_flag, 0) = 0 THEN 1 ELSE 0 END) &gt; 0
THEN 'PENDING'
ELSE 'COMPLETED'
END AS reviewStatus
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 theoretical_paper tp ON tp.id = e.paper_id
WHERE e.id = #{examId}
AND e.chief_id = #{teacherId}
GROUP BY e.id, e.class_id, e.name, c.name, e.type, e.paper_id, tp.name, tp.sum,
e.exam_time, e.duration
</select>
<!-- 发布事务开始时锁定考试主记录,串行化同一考试的重复发布请求。 -->
<select id="lockTask" resultType="com.platform.business.model.entity.ExamEntity">
SELECT e.*
FROM exam e
WHERE e.id = #{examId}
AND e.chief_id = #{teacherId}
FOR UPDATE
</select>
<select id="queryStudents" resultType="com.platform.business.model.vo.ExamReviewStudentVO">
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,
u.factory AS department,
c.name AS className,
es.answer_time AS answerTime,
es.score,
(SELECT COUNT(*)
FROM theoretical_paper_student_detail d
WHERE d.exam_id = es.exam_id
AND d.student_id = es.student_id
AND d.is_problem = 1
AND d.type = '主观题') AS subjectiveCount,
(SELECT COUNT(*)
FROM theoretical_paper_student_detail d
WHERE d.exam_id = es.exam_id
AND d.student_id = es.student_id
AND d.is_problem = 1
AND d.type = '主观题'
AND d.actual_score IS NOT NULL) AS scoredSubjectiveCount,
CASE WHEN 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 AND e.chief_id = #{teacherId}
LEFT JOIN user u ON u.id = es.student_id
LEFT JOIN class c ON c.id = es.class_id
WHERE es.exam_id = #{query.examId}
AND es.class_id = #{query.classId}
AND es.submit = 1
<if test="query.keyword != null and query.keyword != ''">
AND (
u.nick_name LIKE CONCAT('%', #{query.keyword}, '%')
OR u.id_card LIKE CONCAT('%', #{query.keyword}, '%')
OR u.factory LIKE CONCAT('%', #{query.keyword}, '%')
)
</if>
ORDER BY IFNULL(es.mark_flag, 0), u.nick_name, es.id
</select>
<select id="findStudent" resultType="com.platform.business.model.vo.ExamReviewStudentVO">
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,
u.factory AS department,
c.name AS className,
es.answer_time AS answerTime,
es.score,
(SELECT COUNT(*)
FROM theoretical_paper_student_detail d
WHERE d.exam_id = es.exam_id
AND d.student_id = es.student_id
AND d.is_problem = 1
AND d.type = '主观题') AS subjectiveCount,
(SELECT COUNT(*)
FROM theoretical_paper_student_detail d
WHERE d.exam_id = es.exam_id
AND d.student_id = es.student_id
AND d.is_problem = 1
AND d.type = '主观题'
AND d.actual_score IS NOT NULL) AS scoredSubjectiveCount,
CASE WHEN 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 AND e.chief_id = #{teacherId}
LEFT JOIN user u ON u.id = es.student_id
LEFT JOIN class c ON c.id = es.class_id
WHERE es.id = #{examStudentId}
AND es.submit = 1
</select>
<!-- 保存评分前锁定考生记录,防止保存与发布同时执行。 -->
<select id="lockStudent" resultType="com.platform.business.model.entity.ExamStudentEntity">
SELECT es.*
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id AND e.chief_id = #{teacherId}
WHERE es.id = #{examStudentId}
AND es.submit = 1
FOR UPDATE
</select>
<!--
客观题得分根据交卷时的判题结果实时换算;主观题读取教师暂存的 actual_score。
因此保存阶段无需改写考生正式总分,只有发布事务才落最终总分。
-->
<select id="queryQuestions" 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,
CASE
WHEN d.type = '主观题' THEN d.actual_score IS NOT NULL
ELSE TRUE
END AS reviewed
FROM theoretical_paper_student_detail d
WHERE d.exam_id = #{examId}
AND d.student_id = #{studentId}
AND d.is_problem = 1
ORDER BY FIELD(d.type, '判断题', '单选题', '多选题', '主观题'), d.sequence, d.id
</select>
<!-- 题目ID、考试ID和考生ID必须同时匹配,锁定后才允许更新。 -->
<select id="lockQuestions" resultType="com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity">
SELECT d.*
FROM theoretical_paper_student_detail d
WHERE d.exam_id = #{examId}
AND d.student_id = #{studentId}
AND d.is_problem = 1
AND d.id IN
<foreach collection="questionIds" item="questionId" open="(" separator="," close=")">
#{questionId}
</foreach>
FOR UPDATE
</select>
<update id="updateQuestionScore">
UPDATE theoretical_paper_student_detail
SET actual_score = #{actualScore},
result = #{result},
is_partially_right = #{partiallyRight}
WHERE id = #{questionId}
AND type = '主观题'
</update>
<!-- 发布时锁定全部已交卷考生,保证总分计算和发布标记原子完成。 -->
<select id="lockSubmittedStudents" resultType="com.platform.business.model.entity.ExamStudentEntity">
SELECT es.*
FROM exam_student es
WHERE es.exam_id = #{examId}
AND es.submit = 1
ORDER BY es.id
FOR UPDATE
</select>
<select id="countSubmittedWithoutPaper" resultType="int">
SELECT COUNT(*)
FROM exam_student es
WHERE es.exam_id = #{examId}
AND es.submit = 1
AND IFNULL(es.mark_flag, 0) = 0
AND NOT EXISTS (
SELECT 1
FROM theoretical_paper_student_detail d
WHERE d.exam_id = es.exam_id
AND d.student_id = es.student_id
AND d.is_problem = 1
)
</select>
<select id="countUnscoredSubjective" resultType="int">
SELECT COUNT(*)
FROM exam_student es
INNER JOIN theoretical_paper_student_detail d
ON d.exam_id = es.exam_id AND d.student_id = es.student_id
WHERE es.exam_id = #{examId}
AND es.submit = 1
AND IFNULL(es.mark_flag, 0) = 0
AND d.is_problem = 1
AND d.type = '主观题'
AND d.actual_score IS NULL
</select>
<select id="calculateStudentScore" resultType="double">
SELECT IFNULL(SUM(
CASE
WHEN d.type = '主观题' THEN IFNULL(d.actual_score, 0)
WHEN d.result = 1 THEN IFNULL(d.score, 0)
ELSE 0
END
), 0)
FROM theoretical_paper_student_detail d
WHERE d.exam_id = #{examId}
AND d.student_id = #{studentId}
AND d.is_problem = 1
</select>
<update id="publishStudent">
UPDATE exam_student
SET score = #{score},
mark_flag = 1
WHERE id = #{examStudentId}
AND submit = 1
AND IFNULL(mark_flag, 0) = 0
</update>
<update id="publishTask">
UPDATE exam
SET mark_flag = 1
WHERE id = #{examId}
</update>
<select id="queryHistory" resultType="com.platform.business.model.vo.ExamReviewRecordVO">
SELECT
l.id,
l.question_id AS questionId,
d.sequence AS questionSequence,
d.type AS questionType,
l.reviewer_id AS reviewerId,
u.nick_name AS reviewerName,
l.previous_score AS previousScore,
l.new_score AS newScore,
l.action,
l.review_comment AS reviewComment,
l.created_at AS createdAt
FROM exam_review_score_log l
LEFT JOIN theoretical_paper_student_detail d ON d.id = l.question_id
LEFT JOIN user u ON u.id = l.reviewer_id
WHERE l.exam_student_id = #{examStudentId}
ORDER BY l.created_at DESC, l.id DESC
</select>
</mapper>
# 教师端阅卷管理接口
所有接口统一使用前缀 `/exam/review`,并从请求头 `Authorization` 中解析当前登录教师。
客户端不能指定 `teacherId`;服务端仅允许考试字段 `chief_id` 为当前教师的任务被查询、评分或发布。
部署前请先执行 `src/main/resources/sql/exam_review.sql` 创建评分审计表。现有数据库还需包含项目原查询已经使用的
`exam.mark_flag` 与 `exam_student.mark_flag` 字段,其中 `0/null` 表示未发布,`1` 表示已发布。
## 1. 阅卷任务列表
`POST /exam/review/tasks/page`
```json
{
"pageNum": 1,
"pageSize": 10,
"keyword": "期末考试",
"status": "PENDING"
}
```
`status` 支持 `ALL`、`PENDING`、`COMPLETED`。列表返回考试与班级 ID、考试名称、班级、已交卷份数、
已发布份数、截止时间及阅卷状态。只有至少一名考生已经交卷的考试会成为阅卷任务。
## 2. 阅卷工作台考生列表
`POST /exam/review/students/page`
```json
{
"pageNum": 1,
"pageSize": 20,
"examId": 1001,
"classId": 20,
"keyword": "张三"
}
```
`examId` 和 `classId` 都来自任务列表。服务端会校验二者关系;关键字可匹配姓名、身份证号或所属单位。
列表只返回已经交卷的考生。
## 3. 获取考生试卷
`GET /exam/review/students/{examStudentId}/paper`
返回考生信息、试卷元数据、各题型评分汇总和完整题目列表。客观题分数根据系统判题结果计算;
主观题的 `manualScoreRequired` 为 `true`,未评分时 `actualScore` 为 `null`。
## 4. 保存阅卷进度
`PUT /exam/review/students/{examStudentId}/scores`
```json
{
"scores": [
{
"questionId": "19876543210001",
"score": 6.5,
"comment": "要点基本完整,缺少异常工况说明"
}
]
}
```
可仅提交本次变化的主观题。服务端校验题目归属、题型以及 `0 <= score <= 题目满分`;保存成功后写入审计日志,
但不会把暂存结果标记为正式发布。已发布的考生成绩不可再次修改。
## 5. 发布成绩
`PUT /exam/review/tasks/{examId}/publish`
发布前会锁定本场考试及全部已交卷考生,并校验每位考生已经生成试卷、所有主观题均已评分。随后服务端重新汇总
客观题与主观题得分,更新 `exam_student.score`,最后统一设置考生和考试的 `mark_flag=1`。任一步失败都会回滚。
## 6. 评分追溯记录
`GET /exam/review/students/{examStudentId}/history`
返回每次分数变化和最终发布操作,包括教师、题号、调整前后分数、评分说明及时间。教师只能查看本人阅卷任务中的记录。
-- 教师端阅卷管理评分追溯表(MySQL 5.7+/8.0)。
--
-- 说明:现有 ExamMapper.xml、ExamStudentMapper.xml 已经使用 exam.mark_flag 和
-- exam_student.mark_flag,因此本功能直接复用这两个既有发布状态字段,不重复执行 ALTER。
-- 部署本功能前只需新增下方审计表。
CREATE TABLE IF NOT EXISTS exam_review_score_log (
id VARCHAR(32) NOT NULL COMMENT '审计记录ID',
exam_id INT NOT NULL COMMENT '考试ID',
exam_student_id INT NOT NULL COMMENT '考生考试记录ID',
question_id VARCHAR(64) NULL COMMENT '答题明细ID;发布记录为空',
reviewer_id VARCHAR(64) NOT NULL COMMENT '阅卷教师ID',
previous_score DECIMAL(10, 2) NULL COMMENT '变更前得分',
new_score DECIMAL(10, 2) NULL COMMENT '变更后得分',
action VARCHAR(16) NOT NULL COMMENT 'SAVE-保存评分,PUBLISH-发布成绩',
review_comment VARCHAR(1000) NULL COMMENT '评分说明',
created_at DATETIME(3) NOT NULL COMMENT '操作时间',
PRIMARY KEY (id),
KEY idx_review_log_student_time (exam_student_id, created_at),
KEY idx_review_log_exam (exam_id),
KEY idx_review_log_question (question_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='阅卷评分审计日志';
package com.platform.business.service.impl;
import com.platform.business.mapper.ExamReviewMapper;
import com.platform.business.mapper.ExamReviewScoreLogMapper;
import com.platform.business.model.dto.ExamReviewSaveDTO;
import com.platform.business.model.dto.ExamReviewScoreItemDTO;
import com.platform.business.model.dto.ExamReviewTaskQueryDTO;
import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.entity.ExamReviewScoreLogEntity;
import com.platform.business.model.entity.ExamStudentEntity;
import com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity;
import com.platform.business.model.vo.ExamReviewTaskVO;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
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.anyDouble;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 阅卷服务核心业务规则单元测试。
*
* <p>测试不连接数据库,重点验证容易造成成绩错误的边界:非法状态、超分保存、
* 未完成主观题时发布,以及成功发布后的总分和审计写入。</p>
*/
@ExtendWith(MockitoExtension.class)
class ExamReviewServiceImplTest {
@Mock
private ExamReviewMapper examReviewMapper;
@Mock
private ExamReviewScoreLogMapper scoreLogMapper;
@InjectMocks
private ExamReviewServiceImpl examReviewService;
@Test
void queryTasksShouldRejectUnsupportedStatus() {
ExamReviewTaskQueryDTO query = new ExamReviewTaskQueryDTO();
query.setStatus("UNKNOWN");
assertThrows(BusinessException.class,
() -> examReviewService.queryTasks(query, "teacher-1"));
verify(examReviewMapper, never()).queryTasks(any(), any());
}
@Test
void queryTasksShouldCalculateDeadlineFromExamDuration() {
Date examTime = new Date(1_000_000L);
ExamReviewTaskVO task = new ExamReviewTaskVO();
task.setExamTime(examTime);
task.setDuration(90);
when(examReviewMapper.queryTasks(any(), any()))
.thenReturn(Collections.singletonList(task));
examReviewService.queryTasks(new ExamReviewTaskQueryDTO(), "teacher-1");
assertEquals(examTime.getTime() + 90L * 60_000L, task.getDeadline().getTime());
}
@Test
void saveScoresShouldRejectScoreAboveQuestionMaximum() {
ExamStudentEntity student = ExamStudentEntity.builder()
.id(10)
.examId(100)
.studentId("student-1")
.submit(true)
.markFlag(false)
.build();
TheoreticalPaperStudentDetailEntity question = new TheoreticalPaperStudentDetailEntity();
question.setId("question-1");
question.setExamId(100);
question.setStudentId("student-1");
question.setIsProblem(true);
question.setType("主观题");
question.setScore(5D);
when(examReviewMapper.lockStudent(10, "teacher-1")).thenReturn(student);
when(examReviewMapper.lockQuestions(any(), anyInt(), any()))
.thenReturn(Collections.singletonList(question));
ExamReviewScoreItemDTO item = new ExamReviewScoreItemDTO();
item.setQuestionId("question-1");
item.setScore(new BigDecimal("5.01"));
ExamReviewSaveDTO request = new ExamReviewSaveDTO();
request.setScores(Collections.singletonList(item));
assertThrows(BusinessException.class,
() -> examReviewService.saveScores(10, request, "teacher-1"));
verify(examReviewMapper, never()).updateQuestionScore(any(), anyDouble(), any(), any());
verify(scoreLogMapper, never()).insert(any());
}
@Test
void publishShouldRejectWhenSubjectiveQuestionsRemainUnscored() {
ExamEntity exam = new ExamEntity();
exam.setId(100);
exam.setMarkFlag(false);
ExamStudentEntity student = ExamStudentEntity.builder()
.id(10)
.examId(100)
.studentId("student-1")
.submit(true)
.markFlag(false)
.build();
when(examReviewMapper.lockTask(100, "teacher-1")).thenReturn(exam);
when(examReviewMapper.lockSubmittedStudents(100))
.thenReturn(Collections.singletonList(student));
when(examReviewMapper.countSubmittedWithoutPaper(100)).thenReturn(0);
when(examReviewMapper.countUnscoredSubjective(100)).thenReturn(2);
assertThrows(BusinessException.class,
() -> examReviewService.publish(100, "teacher-1"));
verify(examReviewMapper, never()).publishStudent(anyInt(), anyDouble());
verify(examReviewMapper, never()).publishTask(anyInt());
}
@Test
void publishShouldRecalculateFinalScoreAndWriteAuditLog() {
ExamEntity exam = new ExamEntity();
exam.setId(100);
exam.setMarkFlag(false);
ExamStudentEntity student = ExamStudentEntity.builder()
.id(10)
.examId(100)
.studentId("student-1")
.score(40D)
.submit(true)
.markFlag(false)
.build();
when(examReviewMapper.lockTask(100, "teacher-1")).thenReturn(exam);
when(examReviewMapper.lockSubmittedStudents(100))
.thenReturn(Collections.singletonList(student));
when(examReviewMapper.countSubmittedWithoutPaper(100)).thenReturn(0);
when(examReviewMapper.countUnscoredSubjective(100)).thenReturn(0);
when(examReviewMapper.calculateStudentScore(100, "student-1")).thenReturn(86.5D);
when(examReviewMapper.publishStudent(10, 86.5D)).thenReturn(1);
when(examReviewMapper.publishTask(100)).thenReturn(1);
when(scoreLogMapper.insert(any(ExamReviewScoreLogEntity.class))).thenReturn(1);
assertTrue(examReviewService.publish(100, "teacher-1"));
verify(examReviewMapper).publishStudent(10, 86.5D);
verify(examReviewMapper).publishTask(100);
verify(scoreLogMapper).insert(any(ExamReviewScoreLogEntity.class));
}
@Test
void publishShouldAllowLatePendingStudentAfterEarlierTaskPublish() {
// 历史任务主标记为已发布,但后来出现新的未发布交卷时,应以考生状态为准继续发布。
ExamEntity exam = new ExamEntity();
exam.setId(100);
exam.setMarkFlag(true);
ExamStudentEntity lateStudent = ExamStudentEntity.builder()
.id(11)
.examId(100)
.studentId("student-late")
.submit(true)
.markFlag(false)
.build();
when(examReviewMapper.lockTask(100, "teacher-1")).thenReturn(exam);
when(examReviewMapper.lockSubmittedStudents(100))
.thenReturn(Collections.singletonList(lateStudent));
when(examReviewMapper.countSubmittedWithoutPaper(100)).thenReturn(0);
when(examReviewMapper.countUnscoredSubjective(100)).thenReturn(0);
when(examReviewMapper.calculateStudentScore(100, "student-late")).thenReturn(70D);
when(examReviewMapper.publishStudent(11, 70D)).thenReturn(1);
when(examReviewMapper.publishTask(100)).thenReturn(1);
when(scoreLogMapper.insert(any(ExamReviewScoreLogEntity.class))).thenReturn(1);
assertTrue(examReviewService.publish(100, "teacher-1"));
verify(examReviewMapper).publishStudent(11, 70D);
}
}
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