Commit eca651ce authored by wujipeng's avatar wujipeng
Browse files

学员-考试中心/我的成绩-拆分

parent ffe84393
package com.platform.business.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.platform.business.constant.ExamAdminConstants;
import com.platform.business.mapper.StudentExamCenterMapper;
import com.platform.business.model.dto.StudentExamAnswerDTO;
import com.platform.business.model.dto.StudentExamCenterQueryDTO;
import com.platform.business.model.entity.TheoreticalPaperDetailEntity;
import com.platform.business.model.entity.TheoreticalPaperEntity;
import com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.StudentExamCenterVO;
import com.platform.business.service.StudentExamCenterService;
import com.platform.business.service.TheoreticalPaperDetailService;
import com.platform.business.service.TheoreticalPaperService;
import com.platform.business.service.TheoreticalPaperStudentDetailService;
import com.platform.business.service.UserService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* 学员端考试中心实现。
*
* <p>开考、保存答案和交卷都会先校验“应考记录ID + JWT学员ID”,并在需要改变状态时锁定
* 应考记录,保证重复点击和并发请求不会生成重复试卷或重复交卷。</p>
*/
@Service
public class StudentExamCenterServiceImpl implements StudentExamCenterService {
private static final int MAX_KEYWORD_LENGTH = 40;
private static final int MAX_ANSWER_LENGTH = 2000;
private static final DateTimeFormatter ANSWER_TIME_FORMATTER =
DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss");
private static final List<String> EXAM_NOTICES = Collections.unmodifiableList(Arrays.asList(
"考试开始后计时不可暂停,请确保有充足的作答时间",
"考试时长结束将自动停止作答,请合理安排答题进度",
"可使用答题卡快速跳转至任意题目",
"需要复查的题目可在前端临时标记",
"答题过程中请勿关闭或刷新浏览器页面"
));
@Resource
private StudentExamCenterMapper studentExamCenterMapper;
@Resource
private TheoreticalPaperService theoreticalPaperService;
@Resource
private TheoreticalPaperDetailService theoreticalPaperDetailService;
@Resource
private TheoreticalPaperStudentDetailService theoreticalPaperStudentDetailService;
@Resource
private UserService userService;
@Override
public List<StudentExamCenterVO.ListItem> page(StudentExamCenterQueryDTO query,
String studentId) {
normalizeQuery(query);
List<StudentExamCenterVO.ListItem> rows = studentExamCenterMapper.selectPage(query, studentId);
if (rows == null) {
return Collections.emptyList();
}
long now = System.currentTimeMillis();
for (StudentExamCenterVO.ListItem row : rows) {
fillWorkflow(row, now);
}
return rows;
}
@Override
public StudentExamCenterVO.Instructions instructions(Integer examStudentId, String studentId) {
StudentExamCenterVO.Attempt attempt = requireAttempt(examStudentId, studentId, false);
StudentExamCenterVO.Instructions result = new StudentExamCenterVO.Instructions();
result.setExamStudentId(attempt.getId());
result.setExamId(attempt.getExamId());
result.setExamName(attempt.getExamName());
result.setType(attempt.getExamType());
result.setExamTime(attempt.getExamTime());
result.setDuration(attempt.getExamDuration());
result.setForbidMinutes(attempt.getForbidMinutes());
result.setLocation(attempt.getLocation());
result.setTotalScore(attempt.getTotalScore());
result.setPassScore(attempt.getPassScore());
result.setNotices(EXAM_NOTICES);
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Integer start(Integer examStudentId, String studentId) {
StudentExamCenterVO.Attempt attempt = requireAttempt(examStudentId, studentId, true);
requireTheory(attempt);
if (Boolean.TRUE.equals(attempt.getSubmit())) {
throw new BusinessException("本场考试已经交卷,不能再次开始");
}
if (attempt.getExamTime() == null) {
throw new BusinessException("考试时间尚未配置");
}
long now = System.currentTimeMillis();
if (now < attempt.getExamTime().getTime()) {
throw new BusinessException("考试尚未开始");
}
if (attempt.getExamDuration() == null || attempt.getExamDuration() <= 0) {
throw new BusinessException("考试时长配置无效");
}
long scheduledEnd = attempt.getExamTime().getTime()
+ TimeUnit.MINUTES.toMillis(attempt.getExamDuration());
if (attempt.getStartTime() == null && now > scheduledEnd) {
// 首次开考必须处于统一考试时段内;已经开考的学员仍走上方幂等恢复逻辑。
throw new BusinessException("本场考试已结束,不能再开始考试");
}
int generated = studentExamCenterMapper.countGeneratedQuestions(
attempt.getExamId(), studentId);
if (attempt.getStartTime() != null && generated > 0) {
// 已经开考时返回原应考记录ID,前端可直接恢复,不再把重复点击当作异常。
markUserExamState(studentId, attempt.getId());
return attempt.getId();
}
if (generated == 0) {
generatePersonalPaper(attempt, studentId);
}
if (attempt.getStartTime() == null) {
long endTime = now + TimeUnit.MINUTES.toMillis(attempt.getExamDuration());
int updated = studentExamCenterMapper.updateAttemptStarted(
attempt.getId(), now, endTime, formatTime(now));
if (updated != 1) {
throw new BusinessException("考试状态已变化,请刷新后重试");
}
}
markUserExamState(studentId, attempt.getId());
return attempt.getId();
}
@Override
public StudentExamCenterVO.Paper paper(Integer examStudentId, String studentId) {
StudentExamCenterVO.Attempt attempt = requireAttempt(examStudentId, studentId, false);
requireTheory(attempt);
if (attempt.getStartTime() == null) {
throw new BusinessException("请先开始考试");
}
if (Boolean.TRUE.equals(attempt.getSubmit())) {
throw new BusinessException("考试已经交卷,请前往我的成绩查看正式结果");
}
List<StudentExamCenterVO.Question> questions = studentExamCenterMapper.selectPaperQuestions(
attempt.getExamId(), studentId);
if (questions == null || questions.isEmpty()) {
throw new BusinessException("个人试卷尚未生成,请重新开始考试");
}
int answered = (int) questions.stream()
.filter(question -> hasText(question.getActualChoice())).count();
StudentExamCenterVO.Paper result = new StudentExamCenterVO.Paper();
result.setExamStudentId(attempt.getId());
result.setExamId(attempt.getExamId());
result.setExamName(attempt.getExamName());
result.setStartTime(attempt.getStartTime());
result.setEndTime(attempt.getEndTime());
result.setTotalCount(questions.size());
result.setAnsweredCount(answered);
result.setQuestions(questions);
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean saveAnswer(Integer examStudentId, String questionId,
StudentExamAnswerDTO answer, String studentId) {
if (!hasText(questionId)) {
throw new BusinessException("题目ID不能为空");
}
if (answer == null) {
throw new BusinessException("答案请求不能为空");
}
String actualChoice = trimToNull(answer.getActualChoice());
if (actualChoice != null && actualChoice.length() > MAX_ANSWER_LENGTH) {
throw new BusinessException("答案内容不能超过2000个字符");
}
// 先锁应考记录再锁题目,所有写操作使用相同顺序,降低并发死锁概率。
StudentExamCenterVO.Attempt attempt = requireAttempt(examStudentId, studentId, true);
requireTheory(attempt);
requireAnswerable(attempt);
TheoreticalPaperStudentDetailEntity question =
studentExamCenterMapper.selectQuestionForUpdate(
questionId, attempt.getExamId(), studentId);
if (question == null) {
throw new BusinessException("题目不存在或不属于当前学员");
}
if (studentExamCenterMapper.updateAnswer(questionId, actualChoice) != 1) {
throw new BusinessException("答案保存失败,请稍后重试");
}
return true;
}
@Override
public StudentExamCenterVO.SubmitCheck submitCheck(Integer examStudentId, String studentId) {
StudentExamCenterVO.Attempt attempt = requireAttempt(examStudentId, studentId, false);
requireTheory(attempt);
List<TheoreticalPaperStudentDetailEntity> questions =
studentExamCenterMapper.selectQuestionsForSubmit(attempt.getExamId(), studentId);
return buildSubmitCheck(attempt, questions, System.currentTimeMillis());
}
@Override
@Transactional(rollbackFor = Exception.class)
public StudentExamCenterVO.SubmitResult submit(Integer examStudentId, String studentId) {
StudentExamCenterVO.Attempt attempt = requireAttempt(examStudentId, studentId, true);
requireTheory(attempt);
if (attempt.getStartTime() == null) {
throw new BusinessException("考试尚未开始");
}
List<TheoreticalPaperStudentDetailEntity> questions =
studentExamCenterMapper.selectQuestionsForSubmit(attempt.getExamId(), studentId);
long now = System.currentTimeMillis();
StudentExamCenterVO.SubmitCheck check = buildSubmitCheck(attempt, questions, now);
if (Boolean.TRUE.equals(attempt.getSubmit())) {
// 幂等返回不包含成绩,避免网络重试被误判为重复业务操作。
return buildSubmitResult(attempt, check, attempt.getDuration());
}
if (questions == null || questions.isEmpty()) {
// 正常开考后个人试卷必须包含题目;禁止把异常空试卷按0分提交,便于事务整体回滚并及时暴露组卷问题。
throw new BusinessException("个人试卷没有可提交题目,请联系考试管理员");
}
if (!Boolean.TRUE.equals(check.getSubmitAllowed())) {
throw new BusinessException(check.getMessage());
}
double totalScore = 0D;
for (TheoreticalPaperStudentDetailEntity question : questions) {
if (isSubjective(question.getType())) {
// 主观题由教师阅卷;若已有暂存分数则纳入总分,否则保持0分且不伪造判定结果。
if (question.getActualScore() != null) {
totalScore += question.getActualScore();
}
continue;
}
boolean correct = answersEqual(
question.getActualChoice(), question.getAnswer(), question.getType());
double actualScore = correct && question.getScore() != null ? question.getScore() : 0D;
studentExamCenterMapper.updateQuestionResult(question.getId(), correct, actualScore);
totalScore += actualScore;
}
long effectiveEnd = attempt.getEndTime() == null ? now : Math.min(now, attempt.getEndTime());
long elapsed = Math.max(0L, effectiveEnd - attempt.getStartTime());
String duration = formatDuration(elapsed);
String answerTime = formatTime(attempt.getStartTime()) + "-" + formatTime(effectiveEnd);
int updated = studentExamCenterMapper.updateAttemptSubmitted(
attempt.getId(), totalScore, duration, answerTime);
if (updated != 1) {
throw new BusinessException("考试状态已变化,请勿重复交卷");
}
userService.closeExam(studentId);
attempt.setSubmit(true);
attempt.setDuration(duration);
return buildSubmitResult(attempt, check, duration);
}
private void normalizeQuery(StudentExamCenterQueryDTO query) {
String keyword = trimToNull(query.getKeyword());
if (keyword != null && keyword.length() > MAX_KEYWORD_LENGTH) {
throw new BusinessException("考试名称关键字不能超过40个字符");
}
query.setKeyword(keyword);
String status = trimToNull(query.getStatus());
status = status == null ? "ALL" : status.toUpperCase(Locale.ROOT);
if (!Arrays.asList("ALL", "PENDING", "COMPLETED").contains(status)) {
throw new BusinessException("考试状态只支持ALL、PENDING或COMPLETED");
}
query.setStatus(status);
}
private void fillWorkflow(StudentExamCenterVO.ListItem row, long now) {
boolean published = Boolean.TRUE.equals(row.getSubmit())
&& Boolean.TRUE.equals(row.getStudentMarkFlag())
&& Boolean.TRUE.equals(row.getExamMarkFlag())
&& row.getScore() != null;
if (published) {
row.setWorkflowStatus("PUBLISHED");
row.setAction("VIEW_SCORE");
} else if (Boolean.TRUE.equals(row.getSubmit())) {
row.setWorkflowStatus("SUBMITTED");
row.setAction("WAIT");
} else if (row.getStartTime() != null) {
row.setWorkflowStatus("IN_PROGRESS");
row.setAction(isTheory(row.getType()) ? "RESUME" : "VIEW_INSTRUCTIONS");
} else {
row.setWorkflowStatus("WAITING");
if (!isTheory(row.getType())) {
row.setAction("VIEW_INSTRUCTIONS");
} else if (row.getExamTime() != null && now >= row.getExamTime().getTime()) {
row.setAction("START");
} else {
row.setAction("WAIT");
}
}
if (!published) {
// Mapper已做一次保护,Service再次清空可避免未来SQL调整时意外泄露未发布分数。
row.setScore(null);
}
}
private StudentExamCenterVO.Attempt requireAttempt(Integer examStudentId, String studentId,
boolean lock) {
if (examStudentId == null || examStudentId <= 0) {
throw new BusinessException("应考记录ID必须为正整数");
}
StudentExamCenterVO.Attempt attempt = lock
? studentExamCenterMapper.selectAttemptForUpdate(examStudentId, studentId)
: studentExamCenterMapper.selectAttempt(examStudentId, studentId);
if (attempt == null) {
throw new BusinessException("考试记录不存在或不属于当前学员");
}
return attempt;
}
private void requireTheory(StudentExamCenterVO.Attempt attempt) {
if (!isTheory(attempt.getExamType())) {
throw new BusinessException("实训考试由仿真系统执行,当前接口只支持在线理论考试");
}
}
private void requireAnswerable(StudentExamCenterVO.Attempt attempt) {
if (attempt.getStartTime() == null) {
throw new BusinessException("考试尚未开始");
}
if (Boolean.TRUE.equals(attempt.getSubmit())) {
throw new BusinessException("考试已经交卷,答案不能继续修改");
}
if (attempt.getEndTime() != null && System.currentTimeMillis() > attempt.getEndTime()) {
throw new BusinessException("考试时间已结束,请立即交卷");
}
}
private void generatePersonalPaper(StudentExamCenterVO.Attempt attempt, String studentId) {
if (!hasText(attempt.getPaperId())) {
throw new BusinessException("考试尚未配置理论试卷");
}
TheoreticalPaperEntity paper = theoreticalPaperService.getById(attempt.getPaperId());
if (paper == null) {
throw new BusinessException("考试关联的理论试卷不存在");
}
List<TheoreticalPaperDetailEntity> source;
if ("乱序".equals(paper.getSequence())) {
source = theoreticalPaperDetailService.selectDisorderly(attempt.getPaperId());
} else {
source = theoreticalPaperDetailService.lambdaQuery()
.eq(TheoreticalPaperDetailEntity::getPaperId, attempt.getPaperId())
.orderByAsc(TheoreticalPaperDetailEntity::getSequence)
.list();
}
if (source == null || source.isEmpty()) {
throw new BusinessException("考试试卷没有可用题目");
}
List<TheoreticalPaperStudentDetailEntity> personal = new ArrayList<>(source.size());
for (TheoreticalPaperDetailEntity item : source) {
TheoreticalPaperStudentDetailEntity target = BeanUtil.copyProperties(
item, TheoreticalPaperStudentDetailEntity.class);
target.setId(null);
// 必须使用JWT学员ID;旧实现误用应考记录ID检查重复,可能生成多份个人试卷。
target.setStudentId(studentId);
target.setExamId(attempt.getExamId());
target.setActualChoice(null);
target.setActualScore(null);
target.setResult(null);
personal.add(target);
}
if (!theoreticalPaperStudentDetailService.saveBatch(personal)) {
throw new BusinessException("个人试卷生成失败,请稍后重试");
}
}
private void markUserExamState(String studentId, Integer examStudentId) {
UserEntity update = new UserEntity();
update.setId(studentId);
update.setExamFlag(true);
update.setExamOneselfId(examStudentId);
if (!userService.updateById(update)) {
throw new BusinessException("学员考试状态更新失败");
}
}
private StudentExamCenterVO.SubmitCheck buildSubmitCheck(
StudentExamCenterVO.Attempt attempt,
List<TheoreticalPaperStudentDetailEntity> questions, long now) {
List<TheoreticalPaperStudentDetailEntity> safeQuestions =
questions == null ? Collections.emptyList() : questions;
int answered = (int) safeQuestions.stream()
.filter(question -> hasText(question.getActualChoice())).count();
int forbidMinutes = attempt.getForbidMinutes() == null ? 0 : attempt.getForbidMinutes();
long allowedAt = attempt.getStartTime() == null ? Long.MAX_VALUE
: attempt.getStartTime() + TimeUnit.MINUTES.toMillis(Math.max(0, forbidMinutes));
StudentExamCenterVO.SubmitCheck result = new StudentExamCenterVO.SubmitCheck();
result.setTotalCount(safeQuestions.size());
result.setAnsweredCount(answered);
result.setUnansweredCount(safeQuestions.size() - answered);
result.setAllowedAt(allowedAt == Long.MAX_VALUE ? null : allowedAt);
if (Boolean.TRUE.equals(attempt.getSubmit())) {
result.setSubmitAllowed(false);
result.setMessage("本场考试已经交卷");
} else if (attempt.getStartTime() == null) {
result.setSubmitAllowed(false);
result.setMessage("考试尚未开始");
} else if (now < allowedAt) {
result.setSubmitAllowed(false);
result.setMessage("开考后" + Math.max(0, forbidMinutes) + "分钟内禁止交卷");
} else {
result.setSubmitAllowed(true);
result.setMessage(result.getUnansweredCount() > 0
? "还有" + result.getUnansweredCount() + "道题未作答,交卷后无法修改"
: "已完成全部题目,交卷后无法修改");
}
return result;
}
private StudentExamCenterVO.SubmitResult buildSubmitResult(
StudentExamCenterVO.Attempt attempt, StudentExamCenterVO.SubmitCheck check,
String duration) {
StudentExamCenterVO.SubmitResult result = new StudentExamCenterVO.SubmitResult();
result.setExamStudentId(attempt.getId());
result.setStatus("SUBMITTED");
result.setTotalCount(check.getTotalCount());
result.setAnsweredCount(check.getAnsweredCount());
result.setUnansweredCount(check.getUnansweredCount());
result.setDuration(duration);
return result;
}
private boolean answersEqual(String actual, String expected, String type) {
if (!hasText(actual) || !hasText(expected)) {
return false;
}
if (type != null && type.contains("多选")) {
return normalizeMultiAnswer(actual).equals(normalizeMultiAnswer(expected));
}
return actual.trim().equalsIgnoreCase(expected.trim());
}
private List<String> normalizeMultiAnswer(String value) {
return Arrays.stream(value.split("[,,、;;\\s]+"))
.map(String::trim)
.filter(this::hasText)
.map(item -> item.toUpperCase(Locale.ROOT))
.distinct()
.sorted(Comparator.naturalOrder())
.collect(Collectors.toList());
}
private boolean isTheory(String type) {
return ExamAdminConstants.TYPE_THEORY.equals(type)
|| "THEORY".equalsIgnoreCase(type == null ? "" : type.trim());
}
private boolean isSubjective(String type) {
return type != null && (type.contains("主观") || type.contains("简答")
|| type.contains("案例"));
}
private String formatTime(long timestamp) {
LocalDateTime time = LocalDateTime.ofInstant(
Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
return time.format(ANSWER_TIME_FORMATTER);
}
private String formatDuration(long milliseconds) {
long totalSeconds = TimeUnit.MILLISECONDS.toSeconds(Math.max(0L, milliseconds));
return String.format("%02d:%02d:%02d", totalSeconds / 3600,
(totalSeconds % 3600) / 60, totalSeconds % 60);
}
private String trimToNull(String value) {
return hasText(value) ? value.trim() : null;
}
private boolean hasText(String value) {
return value != null && !value.trim().isEmpty();
}
}
package com.platform.business.service.impl;
import com.platform.business.constant.ExamAdminConstants;
import com.platform.business.mapper.StudentScoreMapper;
import com.platform.business.model.dto.StudentScoreQueryDTO;
import com.platform.business.model.vo.StudentScoreVO;
import com.platform.business.service.StudentScoreService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* 学员端“我的成绩”聚合服务。
*
* <p>所有入口只读取双重发布标记成立的正式成绩。理论与实训在同一详情接口聚合,但明细
* 来源严格分支:理论读取个人理论试卷,实训只读取fz_grades最新题号记录。</p>
*/
@Service
public class StudentScoreServiceImpl implements StudentScoreService {
private static final int MAX_KEYWORD_LENGTH = 40;
@Resource
private StudentScoreMapper studentScoreMapper;
@Override
public StudentScoreVO.Overview overview(String studentId) {
StudentScoreVO.Overview result = studentScoreMapper.selectOverview(studentId);
if (result == null) {
result = new StudentScoreVO.Overview();
}
result.setExamCount(result.getExamCount() == null ? 0 : result.getExamCount());
Integer classId = studentScoreMapper.selectCurrentClassId(studentId, new Date());
result.setClassId(classId);
if (classId != null && result.getExamCount() > 0) {
result.setClassRank(studentScoreMapper.selectClassRank(classId, studentId));
}
return result;
}
@Override
public List<StudentScoreVO.ListItem> page(StudentScoreQueryDTO query, String studentId) {
normalizeQuery(query);
List<StudentScoreVO.ListItem> rows = studentScoreMapper.selectPage(query, studentId);
return rows == null ? Collections.emptyList() : rows;
}
@Override
public StudentScoreVO.Detail detail(Integer examStudentId, String studentId) {
if (examStudentId == null || examStudentId <= 0) {
throw new BusinessException("应考记录ID必须为正整数");
}
StudentScoreVO.Detail result = studentScoreMapper.selectDetail(examStudentId, studentId);
if (result == null) {
throw new BusinessException("正式成绩不存在、尚未发布或不属于当前学员");
}
fillCommonStatistics(result);
if (isTheory(result.getType())) {
fillTheoryDetail(result, studentId);
} else if (isPractice(result.getType())) {
fillPracticeDetail(result, studentId);
} else {
// 未知历史类型不猜测明细来源,只返回已经确认的公共成绩字段。
result.setTheoryQuestions(Collections.emptyList());
result.setTypeAnalysis(Collections.emptyList());
result.setPracticeItems(Collections.emptyList());
}
return result;
}
@Override
public void export(Integer examStudentId, String studentId, HttpServletResponse response) {
StudentScoreVO.Detail detail = detail(examStudentId, studentId);
String safeName = detail.getExamName() == null ? "考试成绩"
: detail.getExamName().replaceAll("[\\r\\n\\\\/:*?\"<>|]", "_");
String fileName = safeName + "-成绩.csv";
try {
String encoded = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())
.replace("+", "%20");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType("text/csv;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encoded);
ServletOutputStream output = response.getOutputStream();
// UTF-8 BOM确保Windows Excel直接打开中文CSV时不会乱码。
output.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
output.write(buildCsv(detail).getBytes(StandardCharsets.UTF_8));
output.flush();
} catch (IOException e) {
throw new BusinessException("成绩导出失败:" + e.getMessage());
}
}
private void normalizeQuery(StudentScoreQueryDTO query) {
String keyword = trimToNull(query.getKeyword());
if (keyword != null && keyword.length() > MAX_KEYWORD_LENGTH) {
throw new BusinessException("考试名称关键字不能超过40个字符");
}
query.setKeyword(keyword);
String type = trimToNull(query.getType());
if (type == null || "ALL".equalsIgnoreCase(type)) {
query.setType("ALL");
} else if (isTheory(type)) {
query.setType(ExamAdminConstants.TYPE_THEORY);
} else if (isPractice(type)) {
query.setType(ExamAdminConstants.TYPE_PRACTICE);
} else {
throw new BusinessException("考试类型只支持ALL、THEORY或PRACTICE");
}
}
private void fillCommonStatistics(StudentScoreVO.Detail detail) {
double score = detail.getScore() == null ? 0D : detail.getScore();
BigDecimal total = detail.getTotalScore();
BigDecimal pass = detail.getPassScore();
if (pass == null && total != null) {
pass = total.multiply(ExamAdminConstants.DEFAULT_PASS_RATE)
.setScale(2, RoundingMode.HALF_UP);
detail.setPassScore(pass);
}
detail.setPassed(pass != null && BigDecimal.valueOf(score).compareTo(pass) >= 0);
detail.setGrade(grade(score, total, pass));
if (detail.getClassAverageScore() != null) {
detail.setScoreDifference(round(score - detail.getClassAverageScore()));
}
}
private void fillTheoryDetail(StudentScoreVO.Detail detail, String studentId) {
List<StudentScoreVO.TheoryQuestion> questions = studentScoreMapper.selectTheoryQuestions(
detail.getExamId(), studentId);
questions = questions == null ? new ArrayList<>() : questions;
int right = 0;
int wrong = 0;
int partial = 0;
for (StudentScoreVO.TheoryQuestion question : questions) {
if (Boolean.TRUE.equals(question.getPartiallyRight())) {
partial++;
question.setResultDescription("部分对");
} else if (Boolean.TRUE.equals(question.getResult())) {
right++;
question.setResultDescription("答对");
} else if (Boolean.FALSE.equals(question.getResult())) {
wrong++;
question.setResultDescription("答错");
} else {
question.setResultDescription("待阅卷");
}
}
detail.setTheoryQuestions(questions);
detail.setTotalQuestionCount(questions.size());
detail.setRightCount(right);
detail.setWrongCount(wrong);
detail.setPartiallyRightCount(partial);
detail.setCorrectRate(questions.isEmpty() ? 0D
: round(100D * right / questions.size()));
detail.setTypeAnalysis(mergeAnalysis(
studentScoreMapper.selectTheoryPersonalAnalysis(detail.getExamId(), studentId),
studentScoreMapper.selectTheoryClassAnalysis(
detail.getExamId(), detail.getClassId())));
}
private void fillPracticeDetail(StudentScoreVO.Detail detail, String studentId) {
List<StudentScoreVO.PracticeItem> items = studentScoreMapper.selectPracticeItems(
detail.getExamId(), studentId);
items = items == null ? new ArrayList<>() : items;
int passed = 0;
int partial = 0;
int failed = 0;
for (StudentScoreVO.PracticeItem item : items) {
String status = normalizePracticeStatus(item.getResult());
item.setNormalizedStatus(status);
if ("PASS".equals(status)) {
passed++;
} else if ("PARTIAL".equals(status)) {
partial++;
} else {
failed++;
}
}
StudentScoreVO.PracticeSummary summary = new StudentScoreVO.PracticeSummary();
summary.setTotalCount(items.size());
summary.setPassedCount(passed);
summary.setPartiallyPassedCount(partial);
summary.setFailedCount(failed);
summary.setWeightedPassRate(items.isEmpty() ? 0D
: round(100D * (passed + partial * 0.5D) / items.size()));
detail.setPracticeItems(items);
detail.setPracticeSummary(summary);
}
private List<StudentScoreVO.TypeAnalysis> mergeAnalysis(
List<StudentScoreVO.TypeAnalysis> personal,
List<StudentScoreVO.TypeAnalysis> classAverage) {
Map<String, StudentScoreVO.TypeAnalysis> merged = new LinkedHashMap<>();
if (personal != null) {
for (StudentScoreVO.TypeAnalysis item : personal) {
merged.put(item.getType(), item);
}
}
if (classAverage != null) {
for (StudentScoreVO.TypeAnalysis item : classAverage) {
StudentScoreVO.TypeAnalysis target = merged.computeIfAbsent(
item.getType(), key -> {
StudentScoreVO.TypeAnalysis created = new StudentScoreVO.TypeAnalysis();
created.setType(key);
return created;
});
target.setClassAverageRate(item.getClassAverageRate());
}
}
return new ArrayList<>(merged.values());
}
private String grade(double score, BigDecimal total, BigDecimal pass) {
double rate = total != null && total.compareTo(BigDecimal.ZERO) > 0
? score / total.doubleValue() : score / 100D;
if (rate >= 0.90D) {
return "优秀";
}
if (rate >= 0.80D) {
return "良好";
}
if (pass != null && BigDecimal.valueOf(score).compareTo(pass) >= 0) {
return "合格";
}
return "不合格";
}
private String normalizePracticeStatus(String result) {
if (result == null || result.trim().isEmpty()) {
return "FAIL";
}
String normalized = result.trim().toUpperCase(Locale.ROOT);
if (normalized.contains("部分") || normalized.contains("PARTIAL")) {
return "PARTIAL";
}
// “未通过/不通过”包含“通过”字样,必须先识别否定结果,避免被误判为PASS。
if (normalized.contains("未通过") || normalized.contains("不通过")
|| normalized.contains("失败") || normalized.contains("FAIL")) {
return "FAIL";
}
if (normalized.contains("通过") || normalized.contains("合格")
|| normalized.contains("成功") || normalized.contains("PASS")) {
return "PASS";
}
return "FAIL";
}
private String buildCsv(StudentScoreVO.Detail detail) {
StringBuilder csv = new StringBuilder();
csv.append("考试名称,考试类型,考试时间,班级,本人得分,班级均分,班级排名,考试结果\r\n");
csv.append(csv(detail.getExamName())).append(',')
.append(csv(detail.getType())).append(',')
.append(csv(String.valueOf(detail.getExamTime()))).append(',')
.append(csv(detail.getClassName())).append(',')
.append(value(detail.getScore())).append(',')
.append(value(detail.getClassAverageScore())).append(',')
.append(value(detail.getRank())).append(',')
.append(csv(detail.getGrade())).append("\r\n\r\n");
if (isTheory(detail.getType())) {
csv.append("序号,题型,题目,考生答案,正确答案,得分,满分,结果\r\n");
for (StudentScoreVO.TheoryQuestion item : detail.getTheoryQuestions()) {
csv.append(csv(item.getSequence())).append(',')
.append(csv(item.getType())).append(',')
.append(csv(item.getProblem())).append(',')
.append(csv(item.getActualChoice())).append(',')
.append(csv(item.getAnswer())).append(',')
.append(value(item.getActualScore())).append(',')
.append(value(item.getScore())).append(',')
.append(csv(item.getResultDescription())).append("\r\n");
}
} else {
csv.append("步骤编号,标题,题型,作答文本,判定结果,得分,附件\r\n");
for (StudentScoreVO.PracticeItem item : detail.getPracticeItems()) {
csv.append(csv(item.getCode())).append(',')
.append(csv(item.getTitle())).append(',')
.append(csv(item.getType())).append(',')
.append(csv(item.getText())).append(',')
.append(csv(item.getResult())).append(',')
.append(value(item.getScore())).append(',')
.append(csv(item.getFile())).append("\r\n");
}
}
return csv.toString();
}
private String csv(String value) {
String safe = value == null ? "" : value;
return '"' + safe.replace("\"", "\"\"") + '"';
}
private String value(Object value) {
return value == null ? "" : String.valueOf(value);
}
private boolean isTheory(String type) {
return ExamAdminConstants.TYPE_THEORY.equals(type)
|| "THEORY".equalsIgnoreCase(type == null ? "" : type.trim());
}
private boolean isPractice(String type) {
return ExamAdminConstants.TYPE_PRACTICE.equals(type)
|| "PRACTICE".equalsIgnoreCase(type == null ? "" : type.trim());
}
private double round(double value) {
return BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP).doubleValue();
}
private String trimToNull(String value) {
return value == null || value.trim().isEmpty() ? null : value.trim();
}
}
...@@ -111,148 +111,6 @@ ...@@ -111,148 +111,6 @@
from exam e from exam e
where e.class_id = #{classId} where e.class_id = #{classId}
</select> </select>
<select id="unfinished" resultType="com.platform.business.model.vo.ExamVO">
select
e.id,
e.name,
e.type,
e.exam_time,
e.duration,
e.location,
es.submit as status,
es.score
from
exam e
left join
exam_student es
on
e.id = es.exam_id
<where>
<if test="userId != null and userId != ''">
es.student_id = #{userId}
</if>
<if test="status != null and status != ''">
and es.submit = #{status}
</if>
<if test="name != null and name != ''">
and e.name like concat('%',#{name},'%')
</if>
</where>
</select>
<select id="paperOverview" resultType="com.platform.business.model.vo.TheoreticalPaperStudentDetailVO">
SELECT
id,
IF(actual_choice IS NULL, FALSE, TRUE) AS isAnswer,
result
FROM
theoretical_paper_student_detail
WHERE
student_id = #{studentId}
AND
exam_id = #{examId}
and
type = #{type}
</select>
<select id="numberAndScore" resultType="com.platform.business.model.vo.TheoreticalPaperStudentDetailVO">
select
type,
score,
count(*) as num
from
theoretical_paper_student_detail
where
exam_id = #{examId}
and
student_id = #{studentId}
group by
type, score
</select>
<select id="gradesDetail" resultType="com.platform.business.model.vo.ExamStudentVO">
select
u.nick_name as studentName,
c.name as className,
tp.lev,
e.exam_time as examTime,
es.answer_time as answerTime,
es.duration,
es.score
from
exam_student es
left join user u on es.student_id = u.id
left join class c on es.class_id = c.id
left join exam e on es.exam_id = e.id
left join theoretical_paper tp on e.paper_id = tp.id
where es.id = #{id}
</select>
<select id="same" resultType="com.platform.business.model.vo.TheoreticalPaperStudentDetailVO">
select
count(*) as sameRightNum,
ifnull(sum(score), 0) as sameScore
from
theoretical_paper_student_detail
where
student_id = #{studentId}
and exam_id = #{examId}
and type = #{type}
and result = true
</select>
<select id="gradesSummary" resultType="com.platform.business.model.vo.ExamStudentVO">
SELECT
e.name AS exam_name,
e.type AS exam_type,
e.exam_time,
c.name AS class_name,
es.score,
es.exam_id,
rank_table.score_rank AS rank,
es.student_id AS studentId
FROM
exam_student es
LEFT JOIN
exam e
ON
es.exam_id = e.id
LEFT JOIN
class c
ON
es.class_id = c.id
LEFT JOIN (SELECT exam_id,
student_id,
DENSE_RANK() OVER (PARTITION BY exam_id ORDER BY score DESC NULLS LAST) AS score_rank
FROM exam_student) rank_table
ON es.exam_id = rank_table.exam_id AND es.student_id = rank_table.student_id
WHERE es.student_id = #{id}
</select>
<select id="gradesStatistics" resultType="com.platform.business.model.vo.ExamStudentVO">
select
answer_time,
score,
tp.sum
from
exam_student es
left join
exam e
on
es.exam_id = e.id
left join
theoretical_paper tp
on
e.paper_id = tp.id
where
es.id = #{id}
</select>
<select id="gradesAnalysis" resultType="com.platform.business.model.vo.ExamStudentVO">
SELECT
type,
(SUM(IF(result = 1, score, 0)) / SUM(score)) * 100 AS scoreRate
FROM theoretical_paper_student_detail
WHERE type IS NOT NULL
AND exam_id = #{examId}
AND student_id = #{studentId}
AND score IS NOT NULL
GROUP BY type;
</select>
<!-- ==================== 管理员端考试管理 ==================== --> <!-- ==================== 管理员端考试管理 ==================== -->
<select id="lockAdminExamClass" resultType="java.lang.Integer"> <select id="lockAdminExamClass" resultType="java.lang.Integer">
......
...@@ -46,39 +46,6 @@ ...@@ -46,39 +46,6 @@
and es.mark_flag = 0 and es.mark_flag = 0
</select> </select>
<select id="page" resultType="com.platform.business.model.vo.ExamStudentVO">
SELECT
es.id,
e.name AS examName,
es.score,
e.exam_time AS examTime,
AVG(es.score) OVER (PARTITION BY es.exam_id) AS avgScore,
RANK() OVER (PARTITION BY es.exam_id ORDER BY es.score DESC) AS rank
FROM
exam_student es
LEFT JOIN
exam e ON es.exam_id = e.id
WHERE
es.student_id = #{studentId}
ORDER BY
e.exam_time DESC;
</select>
<select id="paperDetail" resultType="com.platform.business.model.vo.ExamStudentVO">
select es.id,
es.class_id,
es.exam_id,
es.student_id,
u.nick_name as studentName,
es.end_time
from
exam_student es
left join
user u
on
es.student_id = u.id
where
es.id = #{id}
</select>
<select id="queryOneself" resultType="com.platform.business.model.vo.ExamStudentVO"> <select id="queryOneself" resultType="com.platform.business.model.vo.ExamStudentVO">
select select
e.name as examName, e.name as examName,
...@@ -103,53 +70,4 @@ ...@@ -103,53 +70,4 @@
e.chief_id = #{userId} or e.invigilation_id like concat('%',#{userId},'%') e.chief_id = #{userId} or e.invigilation_id like concat('%',#{userId},'%')
); );
</select> </select>
<select id="summary" resultType="java.util.Map">
SELECT
-- 所有考试的平均分:该学生的所有考试分数的平均值
ROUND(AVG(es.score), 1) AS overallAvgScore,
-- 班级排名:按班级分组,计算每个学生的总平均分,然后按总平均分降序排名
RANK() OVER (PARTITION BY es.class_id ORDER BY AVG(es.score) DESC) AS classRank,
-- 最高分:该学生所有考试中的最高得分
MAX(es.score) AS highestScore,
-- 考试次数:该学生参加的考试总次数
COUNT(es.id) AS examCount
FROM
exam_student es
LEFT JOIN
exam e
ON
es.exam_id = e.id
WHERE
es.student_id = #{studentId}
-- 建议加上分数非空判断,避免拉低平均分或影响排名准确性
AND
es.score IS NOT NULL
GROUP BY
es.class_id;
</select>
<select id="recent" resultType="com.platform.business.model.vo.ExamStudentVO">
select u.level as lev,
e.type,
e.name as examName,
es.start_time as startTime,
es.duration,
e.forbid,
e.chief_id as chiefId,
e.invigilation_id as invigilationId,
es.exam_id as examId,
c.name as className
from exam_student es
left join exam e on es.exam_id = e.id
left join user u on es.student_id = u.id
left join class c on e.class_id = c.id
where u.id = #{studentId}
order by es.start_time desc
limit 1
</select>
<select id="theSameEvent" resultType="com.platform.business.model.vo.ExamStudentVO">
select es.student_id as studentId, u.nick_name as studentName
from exam_student es
left join user u on es.student_id = u.id
where es.exam_id = #{examId}
</select>
</mapper> </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.StudentExamCenterMapper">
<!-- 考试中心可展示全部个人应考关系,但只有双重发布标记均成立时才返回分数。 -->
<select id="selectPage" resultType="com.platform.business.model.vo.StudentExamCenterVO$ListItem">
SELECT
es.id AS examStudentId,
e.id AS examId,
e.name AS examName,
e.type,
e.exam_time AS examTime,
e.duration,
e.location,
e.total_score AS totalScore,
e.pass_score AS passScore,
es.start_time AS startTime,
es.end_time AS endTime,
es.submit,
es.mark_flag AS studentMarkFlag,
e.mark_flag AS examMarkFlag,
CASE
WHEN COALESCE(e.mark_flag, 0) = 1
AND COALESCE(es.mark_flag, 0) = 1
AND es.score IS NOT NULL THEN es.score
ELSE NULL
END AS score
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id
WHERE es.student_id = #{studentId}
<if test="query.keyword != null and query.keyword != ''">
AND e.name LIKE CONCAT('%', #{query.keyword}, '%')
</if>
<if test="query.status == 'PENDING'">
AND COALESCE(es.submit, 0) = 0
</if>
<if test="query.status == 'COMPLETED'">
AND COALESCE(es.submit, 0) = 1
</if>
ORDER BY e.exam_time DESC, e.id DESC
</select>
<sql id="attemptColumns">
es.id,
es.class_id AS classId,
es.exam_id AS examId,
es.student_id AS studentId,
es.score,
es.start_time AS startTime,
es.end_time AS endTime,
es.answer_time AS answerTime,
es.submit,
es.mark_flag AS markFlag,
es.duration,
e.name AS examName,
e.type AS examType,
e.exam_time AS examTime,
e.duration AS examDuration,
e.forbid AS forbidMinutes,
e.location,
e.paper_id AS paperId,
e.total_score AS totalScore,
e.pass_score AS passScore,
e.mark_flag AS examMarkFlag
</sql>
<!-- 详情必须同时匹配应考记录主键和JWT学员ID,防止顺序ID越权。 -->
<select id="selectAttempt" resultType="com.platform.business.model.vo.StudentExamCenterVO$Attempt">
SELECT <include refid="attemptColumns"/>
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id
WHERE es.id = #{examStudentId}
AND es.student_id = #{studentId}
</select>
<!-- 开考和交卷共享同一应考行锁,串行化重复点击及管理员并发变更。 -->
<select id="selectAttemptForUpdate"
resultType="com.platform.business.model.vo.StudentExamCenterVO$Attempt">
SELECT <include refid="attemptColumns"/>
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id
WHERE es.id = #{examStudentId}
AND es.student_id = #{studentId}
FOR UPDATE
</select>
<select id="countGeneratedQuestions" resultType="java.lang.Integer">
SELECT COUNT(*)
FROM theoretical_paper_student_detail
WHERE exam_id = #{examId}
AND student_id = #{studentId}
</select>
<update id="updateAttemptStarted">
UPDATE exam_student
SET start_time = #{startTime},
end_time = #{endTime},
answer_time = #{answerTime}
WHERE id = #{examStudentId}
AND start_time IS NULL
AND COALESCE(submit, 0) = 0
</update>
<!-- 在线试卷明确不查询answer/result/actual_score,防止作答期间泄题。 -->
<select id="selectPaperQuestions"
resultType="com.platform.business.model.vo.StudentExamCenterVO$Question">
SELECT
id,
sequence,
type,
problem,
option_a AS optionA,
option_b AS optionB,
option_c AS optionC,
option_d AS optionD,
option_e AS optionE,
score,
actual_choice AS actualChoice
FROM theoretical_paper_student_detail
WHERE exam_id = #{examId}
AND student_id = #{studentId}
AND COALESCE(is_problem, 1) = 1
ORDER BY CAST(sequence AS UNSIGNED), sequence, id
</select>
<select id="selectQuestionForUpdate"
resultType="com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity">
SELECT *
FROM theoretical_paper_student_detail
WHERE id = #{questionId}
AND exam_id = #{examId}
AND student_id = #{studentId}
AND COALESCE(is_problem, 1) = 1
FOR UPDATE
</select>
<update id="updateAnswer">
UPDATE theoretical_paper_student_detail
SET actual_choice = #{actualChoice}
WHERE id = #{questionId}
</update>
<select id="selectQuestionsForSubmit"
resultType="com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity">
SELECT *
FROM theoretical_paper_student_detail
WHERE exam_id = #{examId}
AND student_id = #{studentId}
AND COALESCE(is_problem, 1) = 1
ORDER BY CAST(sequence AS UNSIGNED), sequence, id
</select>
<update id="updateQuestionResult">
UPDATE theoretical_paper_student_detail
SET result = #{result},
actual_score = #{actualScore}
WHERE id = #{id}
</update>
<update id="updateAttemptSubmitted">
UPDATE exam_student
SET score = #{score},
submit = 1,
duration = #{duration},
answer_time = #{answerTime}
WHERE id = #{examStudentId}
AND COALESCE(submit, 0) = 0
</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.StudentScoreMapper">
<!-- 个人统计只使用已经交卷、考试和个人均已发布且分数非空的正式成绩。 -->
<select id="selectOverview" resultType="com.platform.business.model.vo.StudentScoreVO$Overview">
SELECT
ROUND(AVG(es.score), 2) AS averageScore,
MAX(es.score) AS highestScore,
COUNT(*) AS examCount
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id
WHERE es.student_id = #{studentId}
AND COALESCE(es.submit, 0) = 1
AND COALESCE(es.mark_flag, 0) = 1
AND COALESCE(e.mark_flag, 0) = 1
AND es.score IS NOT NULL
</select>
<!-- 当前班级优先级与学员首页保持一致:在读、未来、最近历史班级。 -->
<select id="selectCurrentClassId" resultType="java.lang.Integer">
SELECT c.id
FROM class_student cs
INNER JOIN `class` c ON c.id = cs.class_id
WHERE cs.user_id = #{studentId}
AND COALESCE(c.archived_flag, 0) = 0
ORDER BY
CASE
WHEN (c.start_date IS NULL OR c.start_date &lt;= #{today})
AND (c.end_date IS NULL OR c.end_date &gt;= #{today}) THEN 0
WHEN c.end_date IS NULL OR c.end_date &gt;= #{today} THEN 1
ELSE 2
END,
c.start_date DESC,
c.id DESC
LIMIT 1
</select>
<!--
MySQL 5.7没有窗口函数:先按学员聚合正式平均分,再统计平均分高于当前学员的人数。
相同平均分得到相同名次。
-->
<select id="selectClassRank" resultType="java.lang.Integer">
SELECT CASE
WHEN own_average.avg_score IS NULL THEN NULL
ELSE 1 + COUNT(higher_students.student_id)
END
FROM (
SELECT (
SELECT AVG(mine.score)
FROM exam_student mine
INNER JOIN exam mine_exam ON mine_exam.id = mine.exam_id
WHERE mine.class_id = #{classId}
AND mine.student_id = #{studentId}
AND COALESCE(mine.submit, 0) = 1
AND COALESCE(mine.mark_flag, 0) = 1
AND COALESCE(mine_exam.mark_flag, 0) = 1
AND mine.score IS NOT NULL
) AS avg_score
) own_average
LEFT JOIN (
SELECT ranked.student_id, AVG(ranked.score) AS avg_score
FROM exam_student ranked
INNER JOIN exam ranked_exam ON ranked_exam.id = ranked.exam_id
WHERE ranked.class_id = #{classId}
AND COALESCE(ranked.submit, 0) = 1
AND COALESCE(ranked.mark_flag, 0) = 1
AND COALESCE(ranked_exam.mark_flag, 0) = 1
AND ranked.score IS NOT NULL
GROUP BY ranked.student_id
) higher_students ON higher_students.avg_score &gt; own_average.avg_score
GROUP BY own_average.avg_score
</select>
<select id="selectPage" resultType="com.platform.business.model.vo.StudentScoreVO$ListItem">
SELECT
es.id AS examStudentId,
es.exam_id AS examId,
e.name AS examName,
e.type,
es.score,
ROUND((
SELECT AVG(peer.score)
FROM exam_student peer
INNER JOIN exam peer_exam ON peer_exam.id = peer.exam_id
WHERE peer.exam_id = es.exam_id
AND peer.class_id = es.class_id
AND COALESCE(peer.submit, 0) = 1
AND COALESCE(peer.mark_flag, 0) = 1
AND COALESCE(peer_exam.mark_flag, 0) = 1
AND peer.score IS NOT NULL
), 2) AS averageScore,
1 + (
SELECT COUNT(*)
FROM exam_student peer
WHERE peer.exam_id = es.exam_id
AND peer.class_id = es.class_id
AND COALESCE(peer.submit, 0) = 1
AND COALESCE(peer.mark_flag, 0) = 1
AND peer.score IS NOT NULL
AND peer.score &gt; es.score
) AS rank,
(
SELECT COUNT(*)
FROM exam_student peer
WHERE peer.exam_id = es.exam_id
AND peer.class_id = es.class_id
AND COALESCE(peer.submit, 0) = 1
AND COALESCE(peer.mark_flag, 0) = 1
AND peer.score IS NOT NULL
) AS classCount,
e.exam_time AS examTime
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id
WHERE es.student_id = #{studentId}
AND COALESCE(es.submit, 0) = 1
AND COALESCE(es.mark_flag, 0) = 1
AND COALESCE(e.mark_flag, 0) = 1
AND es.score IS NOT NULL
<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 query.type != 'ALL'">
AND e.type = #{query.type}
</if>
ORDER BY e.exam_time DESC, e.id DESC
</select>
<!-- 聚合详情入口同时验证记录归属和正式发布状态。 -->
<select id="selectDetail" resultType="com.platform.business.model.vo.StudentScoreVO$Detail">
SELECT
es.id AS examStudentId,
es.exam_id AS examId,
es.class_id AS classId,
e.name AS examName,
e.type,
c.name AS className,
e.exam_time AS examTime,
es.score,
e.total_score AS totalScore,
e.pass_score AS passScore,
es.duration,
ROUND((
SELECT AVG(peer.score)
FROM exam_student peer
WHERE peer.exam_id = es.exam_id
AND peer.class_id = es.class_id
AND COALESCE(peer.submit, 0) = 1
AND COALESCE(peer.mark_flag, 0) = 1
AND peer.score IS NOT NULL
), 2) AS classAverageScore,
1 + (
SELECT COUNT(*)
FROM exam_student peer
WHERE peer.exam_id = es.exam_id
AND peer.class_id = es.class_id
AND COALESCE(peer.submit, 0) = 1
AND COALESCE(peer.mark_flag, 0) = 1
AND peer.score IS NOT NULL
AND peer.score &gt; es.score
) AS rank,
(
SELECT COUNT(*)
FROM exam_student peer
WHERE peer.exam_id = es.exam_id
AND peer.class_id = es.class_id
AND COALESCE(peer.submit, 0) = 1
AND COALESCE(peer.mark_flag, 0) = 1
AND peer.score IS NOT NULL
) AS classCount
FROM exam_student es
INNER JOIN exam e ON e.id = es.exam_id
LEFT JOIN `class` c ON c.id = es.class_id
WHERE es.id = #{examStudentId}
AND es.student_id = #{studentId}
AND COALESCE(es.submit, 0) = 1
AND COALESCE(es.mark_flag, 0) = 1
AND COALESCE(e.mark_flag, 0) = 1
AND es.score IS NOT NULL
</select>
<select id="selectTheoryQuestions"
resultType="com.platform.business.model.vo.StudentScoreVO$TheoryQuestion">
SELECT
id,
sequence,
type,
problem,
option_a AS optionA,
option_b AS optionB,
option_c AS optionC,
option_d AS optionD,
option_e AS optionE,
actual_choice AS actualChoice,
answer,
score,
actual_score AS actualScore,
result,
is_partially_right AS partiallyRight
FROM theoretical_paper_student_detail
WHERE exam_id = #{examId}
AND student_id = #{studentId}
AND COALESCE(is_problem, 1) = 1
ORDER BY CAST(sequence AS UNSIGNED), sequence, id
</select>
<select id="selectTheoryPersonalAnalysis"
resultType="com.platform.business.model.vo.StudentScoreVO$TypeAnalysis">
SELECT
type,
ROUND(100 * SUM(COALESCE(actual_score, 0)) / NULLIF(SUM(score), 0), 2)
AS personalRate
FROM theoretical_paper_student_detail
WHERE exam_id = #{examId}
AND student_id = #{studentId}
AND COALESCE(is_problem, 1) = 1
AND type IS NOT NULL
GROUP BY type
ORDER BY type
</select>
<select id="selectTheoryClassAnalysis"
resultType="com.platform.business.model.vo.StudentScoreVO$TypeAnalysis">
SELECT
detail.type,
ROUND(100 * SUM(COALESCE(detail.actual_score, 0)) / NULLIF(SUM(detail.score), 0), 2)
AS classAverageRate
FROM theoretical_paper_student_detail detail
INNER JOIN exam_student published
ON published.exam_id = detail.exam_id
AND published.student_id = detail.student_id
AND published.class_id = #{classId}
AND COALESCE(published.submit, 0) = 1
AND COALESCE(published.mark_flag, 0) = 1
AND published.score IS NOT NULL
WHERE detail.exam_id = #{examId}
AND COALESCE(detail.is_problem, 1) = 1
AND detail.type IS NOT NULL
GROUP BY detail.type
ORDER BY detail.type
</select>
<!-- fz_grades可能存在历史重复题号,按雪花ID最大的记录作为该步骤最新结果。 -->
<select id="selectPracticeItems"
resultType="com.platform.business.model.vo.StudentScoreVO$PracticeItem">
SELECT
grade.id,
grade.code,
grade.lev AS level,
grade.title,
grade.type,
grade.options,
grade.text,
grade.result,
grade.file,
grade.score,
grade.start_time AS startTime,
grade.submission_time AS submissionTime
FROM fz_grades grade
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 = grade.id
ORDER BY grade.code, grade.id
</select>
</mapper>
-- 学员端“考试中心/我的成绩”查询与一致性迁移脚本(MySQL 5.7+/8.0)。
--
-- 执行顺序:exam_management.sql -> exam_review.sql -> student_score_management.sql
-- -> student_exam_score.sql
-- 本脚本不新增业务字段,也不会自动删除历史重复应考关系。
delimiter $$
drop procedure if exists migrate_student_exam_score$$
create procedure migrate_student_exam_score()
begin
declare duplicate_pair_count int default 0;
-- 同一考试、同一学员只能存在一条应考关系。发现历史重复时中止迁移,避免静默删数据。
select count(*) into duplicate_pair_count
from (
select exam_id, student_id
from exam_student
group by exam_id, student_id
having count(*) > 1
) duplicate_pairs;
if duplicate_pair_count > 0 then
signal sqlstate '45000'
set message_text = 'exam_student存在重复的exam_id + student_id,请先人工合并后重新执行迁移';
end if;
if not exists (
select 1
from (
select non_unique,
group_concat(column_name order by seq_in_index separator ',') as indexed_columns
from information_schema.statistics
where table_schema = database() and table_name = 'exam_student'
group by index_name, non_unique
) existing_indexes
where existing_indexes.non_unique = 0
and existing_indexes.indexed_columns = 'exam_id,student_id'
) then
alter table exam_student
add unique index uk_exam_student_exam_user (exam_id, student_id);
end if;
-- 班级综合排名、单场均分和排名均按正式发布状态过滤。
if not exists (
select 1
from (
select group_concat(column_name order by seq_in_index separator ',') as indexed_columns
from information_schema.statistics
where table_schema = database() and table_name = 'exam_student'
group by index_name
) existing_indexes
where existing_indexes.indexed_columns =
'class_id,submit,mark_flag,student_id,score,exam_id'
) then
alter table exam_student
add index idx_exam_student_class_publish_score
(class_id, submit, mark_flag, student_id, score, exam_id);
end if;
-- 在线试卷恢复、交卷判分及理论成绩分析都按考试、学员、题型读取。
if not exists (
select 1
from (
select group_concat(column_name order by seq_in_index separator ',') as indexed_columns
from information_schema.statistics
where table_schema = database()
and table_name = 'theoretical_paper_student_detail'
group by index_name
) existing_indexes
where existing_indexes.indexed_columns = 'exam_id,student_id,type,id'
) then
alter table theoretical_paper_student_detail
add index idx_tpsd_exam_student_type (exam_id, student_id, type, id);
end if;
end$$
call migrate_student_exam_score()$$
drop procedure if exists migrate_student_exam_score$$
delimiter ;
-- 若迁移因重复应考关系中止,可先使用此查询定位;脚本不替业务方决定保留哪条记录。
select exam_id, student_id, count(*) as duplicate_count,
group_concat(id order by id) as exam_student_ids
from exam_student
group by exam_id, student_id
having count(*) > 1;
# 学员端考试中心接口
统一前缀:`/exam/student/center`。所有请求必须携带 `Authorization`,服务端只使用JWT解析出的
当前学员ID,不接受 `studentId/userId`。旧 `/exam/student/list`、`/exam/start`、
`/exam/paper/**`、`/exam/question/**` 和 `/exam/submit/**` 已移除。
## 考试列表
`POST /exam/student/center/page`
```json
{"pageNum":1,"pageSize":10,"keyword":"理论","status":"ALL"}
```
`status` 支持 `ALL/PENDING/COMPLETED`。返回行中的 `workflowStatus` 为:
- `WAITING`:尚未开考;
- `IN_PROGRESS`:已经开始且尚未交卷;
- `SUBMITTED`:已经交卷但成绩尚未正式发布;
- `PUBLISHED`:正式成绩可见。
未发布场次的 `score` 固定为 `null`。`action` 支持 `WAIT/START/RESUME/VIEW_INSTRUCTIONS/VIEW_SCORE`。
## 在线考试流程
- `GET /{examStudentId}/instructions`:考试信息与考试须知;实训考试只提供说明。
- `POST /{examStudentId}/start`:开始或恢复理论考试,重复调用返回同一应考记录ID。
- `GET /attempts/{examStudentId}/paper`:返回个人试卷和已保存答案,不返回正确答案。
- `PUT /attempts/{examStudentId}/questions/{questionId}/answer`:请求体 `{ "actualChoice": "A" }`;
传 `null` 或空白表示清空本题答案。
- `GET /attempts/{examStudentId}/submit-check`:返回已答/未答数量和禁交状态。
- `POST /attempts/{examStudentId}/submit`:确认交卷;重复网络请求幂等返回,响应不包含未发布分数。
所有应考、试卷和题目查询都同时校验 `examStudentId/questionId + JWT学员ID`。
# 学员端“我的成绩”接口
统一前缀:`/exam/student/scores`。旧 `/exam/student/page`、`/exam/student/summary/**`、
`/exam/grades/**` 和 `/score/detail` 已移除。
正式成绩必须同时满足:已经交卷、`exam.mark_flag=1`、`exam_student.mark_flag=1` 且分数非空。
班级均分、排名和个人统计均只使用这一口径,未发布数据不会出现在本模块。
## 页面接口
- `GET /overview`:平均分、最高分、考试次数和当前/最近班级综合排名。
- `POST /page`:正式成绩分页;请求体支持 `pageNum/pageSize/keyword/type`,`type` 为
`ALL/THEORY/PRACTICE`。
- `GET /{examStudentId}`:单场聚合详情,一次返回公共摘要以及理论或实训分支。
- `GET /{examStudentId}/export`:导出当前学员单场正式成绩CSV。
## 聚合详情口径
- 理论考试从 `theoretical_paper_student_detail` 返回题目、作答、正确答案、实际得分、判定结果,
并按题型计算个人得分率和班级平均得分率。
- 实训考试只读取 `fz_grades`,同一 `exam_id + user_id + code` 按最大雪花ID取最新记录。
- 实训现有协议没有步骤满分、扣分维度和教师评语,因此接口不会构造这些字段;仅根据 `result`
文本归一化 `PASS/PARTIAL/FAIL` 并计算步骤数量及加权通过率。
- 详情和导出均使用 `examStudentId + JWT学员ID` 查询,不能访问其他学员成绩。
package com.platform.business.controller;
import com.platform.business.model.dto.StudentExamAnswerDTO;
import com.platform.business.model.dto.StudentExamCenterQueryDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.StudentExamCenterService;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 考试中心Controller的JWT身份、角色校验、分页边界和参数转发测试。 */
@ExtendWith(MockitoExtension.class)
class StudentExamCenterControllerTest {
@Mock
private StudentExamCenterService service;
@Mock
private AuthenticatedUserService authenticatedUserService;
private StudentExamCenterController controller;
@BeforeEach
void setUp() {
controller = new StudentExamCenterController();
ReflectionTestUtils.setField(controller, "studentExamCenterService", service);
ReflectionTestUtils.setField(controller, "authenticatedUserService", authenticatedUserService);
}
@Test
void allEndpointsShouldUseJwtStudentAndNormalizePage() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity student = new UserEntity();
student.setId("student-1");
when(authenticatedUserService.current(request)).thenReturn(student);
when(service.page(any(StudentExamCenterQueryDTO.class), eq("student-1")))
.thenReturn(Collections.emptyList());
StudentExamCenterQueryDTO query = new StudentExamCenterQueryDTO();
query.setPageNum(0);
query.setPageSize(1000);
StudentExamAnswerDTO answer = new StudentExamAnswerDTO();
answer.setActualChoice("A");
controller.page(query, request);
controller.instructions(1, request);
controller.start(1, request);
controller.paper(1, request);
controller.saveAnswer(1, "q-1", answer, request);
controller.submitCheck(1, request);
controller.submit(1, request);
verify(authenticatedUserService, times(7)).requireStudent(student);
verify(service).saveAnswer(1, "q-1", answer, "student-1");
assertEquals(1, query.getPageNum());
assertEquals(100, query.getPageSize());
}
@Test
void roleFailureShouldStopBeforeExamService() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity teacher = new UserEntity();
teacher.setId("teacher-1");
when(authenticatedUserService.current(request)).thenReturn(teacher);
doThrow(new BusinessException("只有学员可以访问学员端接口"))
.when(authenticatedUserService).requireStudent(teacher);
assertThrows(BusinessException.class, () -> controller.start(1, request));
}
}
package com.platform.business.controller;
import org.junit.jupiter.api.Test;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** 确保考试中心与我的成绩保持独立根路径,防止学生功能再次混入通用ExamController。 */
class StudentLearningControllerSeparationTest {
@Test
void studentExamAndScoreControllersShouldUseIndependentRoots() {
assertRoot(StudentExamCenterController.class, "/exam/student/center");
assertRoot(StudentScoreController.class, "/exam/student/scores");
assertRoot(ExamController.class, "/exam");
}
private static void assertRoot(Class<?> controller, String expected) {
RequestMapping mapping = controller.getAnnotation(RequestMapping.class);
assertNotNull(mapping);
assertArrayEquals(new String[]{expected}, mapping.value());
}
}
package com.platform.business.controller;
import com.platform.business.model.dto.StudentScoreQueryDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.StudentScoreService;
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 java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 我的成绩Controller的JWT身份、角色校验、分页边界和导出转发测试。 */
@ExtendWith(MockitoExtension.class)
class StudentScoreControllerTest {
@Mock
private StudentScoreService service;
@Mock
private AuthenticatedUserService authenticatedUserService;
private StudentScoreController controller;
@BeforeEach
void setUp() {
controller = new StudentScoreController();
ReflectionTestUtils.setField(controller, "studentScoreService", service);
ReflectionTestUtils.setField(controller, "authenticatedUserService", authenticatedUserService);
}
@Test
void allEndpointsShouldUseJwtStudentAndNormalizePage() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
UserEntity student = new UserEntity();
student.setId("student-1");
when(authenticatedUserService.current(request)).thenReturn(student);
when(service.page(any(StudentScoreQueryDTO.class), eq("student-1")))
.thenReturn(Collections.emptyList());
StudentScoreQueryDTO query = new StudentScoreQueryDTO();
query.setPageNum(-1);
query.setPageSize(0);
controller.overview(request);
controller.page(query, request);
controller.detail(7, request);
controller.export(7, request, response);
verify(authenticatedUserService, times(4)).requireStudent(student);
verify(service).detail(7, "student-1");
verify(service).export(7, "student-1", response);
assertEquals(1, query.getPageNum());
assertEquals(10, query.getPageSize());
}
@Test
void roleFailureShouldStopBeforeScoreService() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity admin = new UserEntity();
when(authenticatedUserService.current(request)).thenReturn(admin);
doThrow(new BusinessException("只有学员可以访问学员端接口"))
.when(authenticatedUserService).requireStudent(admin);
assertThrows(BusinessException.class, () -> controller.overview(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.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 解析两个学生专用Mapper,并约束成绩SQL兼容MySQL 5.7。 */
class StudentLearningMapperXmlTest {
@Test
void studentExamMapperShouldRegisterOnlineExamStatements() throws Exception {
Configuration configuration = parse("com/platform/business/mapper/StudentExamCenterMapper.xml");
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.StudentExamCenterMapper.selectPage"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.StudentExamCenterMapper.selectAttemptForUpdate"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.StudentExamCenterMapper.updateAttemptSubmitted"));
}
@Test
void studentScoreMapperShouldRegisterAggregationAndAvoidWindowFunctions() throws Exception {
String resource = "com/platform/business/mapper/StudentScoreMapper.xml";
Configuration configuration = parse(resource);
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.StudentScoreMapper.selectOverview"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.StudentScoreMapper.selectDetail"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.StudentScoreMapper.selectPracticeItems"));
String xml = resource(resource).toLowerCase();
assertFalse(xml.contains(" over ("));
assertFalse(xml.contains("dense_rank("));
assertFalse(xml.contains("rank()"));
}
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;
}
private String resource(String path) throws Exception {
try (InputStream input = Resources.getResourceAsStream(path)) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = input.read(buffer)) >= 0) {
output.write(buffer, 0, length);
}
return new String(output.toByteArray(), StandardCharsets.UTF_8);
}
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.StudentExamCenterMapper;
import com.platform.business.model.dto.StudentExamAnswerDTO;
import com.platform.business.model.dto.StudentExamCenterQueryDTO;
import com.platform.business.model.entity.TheoreticalPaperDetailEntity;
import com.platform.business.model.entity.TheoreticalPaperEntity;
import com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity;
import com.platform.business.model.vo.StudentExamCenterVO;
import com.platform.business.service.TheoreticalPaperDetailService;
import com.platform.business.service.TheoreticalPaperService;
import com.platform.business.service.TheoreticalPaperStudentDetailService;
import com.platform.business.service.UserService;
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.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
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.anyCollection;
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 StudentExamCenterServiceImplTest {
@Mock
private StudentExamCenterMapper mapper;
@Mock
private TheoreticalPaperService paperService;
@Mock
private TheoreticalPaperDetailService paperDetailService;
@Mock
private TheoreticalPaperStudentDetailService studentDetailService;
@Mock
private UserService userService;
private StudentExamCenterServiceImpl service;
@BeforeEach
void setUp() {
service = new StudentExamCenterServiceImpl();
ReflectionTestUtils.setField(service, "studentExamCenterMapper", mapper);
ReflectionTestUtils.setField(service, "theoreticalPaperService", paperService);
ReflectionTestUtils.setField(service, "theoreticalPaperDetailService", paperDetailService);
ReflectionTestUtils.setField(service, "theoreticalPaperStudentDetailService", studentDetailService);
ReflectionTestUtils.setField(service, "userService", userService);
}
@Test
void pageShouldNormalizeStatusAndNeverExposeUnpublishedScore() {
StudentExamCenterQueryDTO query = new StudentExamCenterQueryDTO();
query.setStatus(null);
StudentExamCenterVO.ListItem waiting = new StudentExamCenterVO.ListItem();
waiting.setType("理论");
waiting.setExamTime(new Date(System.currentTimeMillis() - 1000));
waiting.setScore(95D);
when(mapper.selectPage(query, "student-1")).thenReturn(Collections.singletonList(waiting));
List<StudentExamCenterVO.ListItem> rows = service.page(query, "student-1");
assertEquals("ALL", query.getStatus());
assertEquals("WAITING", rows.get(0).getWorkflowStatus());
assertEquals("START", rows.get(0).getAction());
assertNull(rows.get(0).getScore());
}
@Test
void startShouldRejectRecordNotOwnedByCurrentStudent() {
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(null);
assertThrows(BusinessException.class, () -> service.start(1, "student-1"));
}
@Test
void startShouldRejectBeforeScheduledTime() {
StudentExamCenterVO.Attempt attempt = attempt(false);
attempt.setExamTime(new Date(System.currentTimeMillis() + 60000));
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(attempt);
assertThrows(BusinessException.class, () -> service.start(1, "student-1"));
verify(mapper, never()).countGeneratedQuestions(any(), any());
}
@Test
void repeatedStartShouldResumeExistingPaperWithoutRegeneration() {
StudentExamCenterVO.Attempt attempt = attempt(false);
attempt.setStartTime(System.currentTimeMillis() - 1000);
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(attempt);
when(mapper.countGeneratedQuestions(10, "student-1")).thenReturn(20);
when(userService.updateById(any())).thenReturn(true);
assertEquals(1, service.start(1, "student-1"));
verify(studentDetailService, never()).saveBatch(anyCollection());
verify(mapper, never()).updateAttemptStarted(any(), any(), any(), any());
}
@Test
void firstStartShouldGeneratePaperWithJwtStudentIdAndMarkAttemptStarted() {
StudentExamCenterVO.Attempt attempt = attempt(false);
attempt.setPaperId("paper-1");
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(attempt);
when(mapper.countGeneratedQuestions(10, "student-1")).thenReturn(0);
TheoreticalPaperEntity paper = new TheoreticalPaperEntity();
paper.setSequence("乱序");
when(paperService.getById("paper-1")).thenReturn(paper);
TheoreticalPaperDetailEntity source = new TheoreticalPaperDetailEntity();
source.setId("source-question");
source.setProblem("题目");
when(paperDetailService.selectDisorderly("paper-1"))
.thenReturn(Collections.singletonList(source));
when(studentDetailService.saveBatch(anyCollection())).thenReturn(true);
when(mapper.updateAttemptStarted(eq(1), any(), any(), any())).thenReturn(1);
when(userService.updateById(any())).thenReturn(true);
service.start(1, "student-1");
@SuppressWarnings("unchecked")
ArgumentCaptor<java.util.Collection<TheoreticalPaperStudentDetailEntity>> captor =
ArgumentCaptor.forClass(java.util.Collection.class);
verify(studentDetailService).saveBatch(captor.capture());
TheoreticalPaperStudentDetailEntity generated = captor.getValue().iterator().next();
assertEquals("student-1", generated.getStudentId());
assertEquals(10, generated.getExamId());
assertNull(generated.getId());
}
@Test
void practicalExamShouldNotEnterTheoryStartFlow() {
StudentExamCenterVO.Attempt attempt = attempt(false);
attempt.setExamType("实训");
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(attempt);
assertThrows(BusinessException.class, () -> service.start(1, "student-1"));
}
@Test
void saveAnswerShouldRequireQuestionOwnership() {
StudentExamCenterVO.Attempt attempt = attempt(false);
attempt.setStartTime(System.currentTimeMillis() - 1000);
attempt.setEndTime(System.currentTimeMillis() + 60000);
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(attempt);
when(mapper.selectQuestionForUpdate("q-1", 10, "student-1")).thenReturn(null);
StudentExamAnswerDTO answer = new StudentExamAnswerDTO();
answer.setActualChoice("A");
assertThrows(BusinessException.class,
() -> service.saveAnswer(1, "q-1", answer, "student-1"));
}
@Test
void submitShouldScoreObjectiveQuestionsAndHideScoreFromResponse() {
StudentExamCenterVO.Attempt attempt = attempt(false);
attempt.setStartTime(System.currentTimeMillis() - 60000);
attempt.setEndTime(System.currentTimeMillis() + 60000);
attempt.setForbidMinutes(0);
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(attempt);
TheoreticalPaperStudentDetailEntity right = question("q-1", "单选题", "A", "A", 5D);
TheoreticalPaperStudentDetailEntity wrong = question("q-2", "单选题", "B", "A", 5D);
when(mapper.selectQuestionsForSubmit(10, "student-1"))
.thenReturn(Arrays.asList(right, wrong));
when(mapper.updateAttemptSubmitted(eq(1), eq(5D), any(), any())).thenReturn(1);
StudentExamCenterVO.SubmitResult result = service.submit(1, "student-1");
assertEquals("SUBMITTED", result.getStatus());
assertEquals(2, result.getAnsweredCount());
verify(mapper).updateQuestionResult("q-1", true, 5D);
verify(mapper).updateQuestionResult("q-2", false, 0D);
verify(userService).closeExam("student-1");
}
@Test
void submittedAttemptShouldReturnIdempotentResultWithoutUpdatingAgain() {
StudentExamCenterVO.Attempt attempt = attempt(true);
attempt.setStartTime(System.currentTimeMillis() - 60000);
attempt.setDuration("00:01:00");
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(attempt);
when(mapper.selectQuestionsForSubmit(10, "student-1"))
.thenReturn(Collections.singletonList(question("q-1", "单选题", "A", "A", 5D)));
StudentExamCenterVO.SubmitResult result = service.submit(1, "student-1");
assertTrue("SUBMITTED".equals(result.getStatus()));
verify(mapper, never()).updateAttemptSubmitted(any(), any(), any(), any());
}
@Test
void submitShouldRespectConfiguredForbidMinutes() {
StudentExamCenterVO.Attempt attempt = attempt(false);
attempt.setStartTime(System.currentTimeMillis() - 60000);
attempt.setForbidMinutes(10);
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(attempt);
when(mapper.selectQuestionsForSubmit(10, "student-1"))
.thenReturn(Collections.singletonList(question("q-1", "单选题", "A", "A", 5D)));
assertThrows(BusinessException.class, () -> service.submit(1, "student-1"));
verify(mapper, never()).updateAttemptSubmitted(any(), any(), any(), any());
}
@Test
void submitShouldRejectAbnormalEmptyPaperInsteadOfSavingZeroScore() {
StudentExamCenterVO.Attempt attempt = attempt(false);
attempt.setStartTime(System.currentTimeMillis() - 60000);
attempt.setForbidMinutes(0);
when(mapper.selectAttemptForUpdate(1, "student-1")).thenReturn(attempt);
when(mapper.selectQuestionsForSubmit(10, "student-1"))
.thenReturn(Collections.emptyList());
assertThrows(BusinessException.class, () -> service.submit(1, "student-1"));
verify(mapper, never()).updateAttemptSubmitted(any(), any(), any(), any());
}
private StudentExamCenterVO.Attempt attempt(boolean submitted) {
StudentExamCenterVO.Attempt attempt = new StudentExamCenterVO.Attempt();
attempt.setId(1);
attempt.setExamId(10);
attempt.setStudentId("student-1");
attempt.setExamType("理论");
attempt.setExamTime(new Date(System.currentTimeMillis() - 1000));
attempt.setExamDuration(90);
attempt.setSubmit(submitted);
return attempt;
}
private TheoreticalPaperStudentDetailEntity question(String id, String type,
String actual, String answer,
Double score) {
TheoreticalPaperStudentDetailEntity question = new TheoreticalPaperStudentDetailEntity();
question.setId(id);
question.setType(type);
question.setActualChoice(actual);
question.setAnswer(answer);
question.setScore(score);
return question;
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.StudentScoreMapper;
import com.platform.business.model.vo.StudentScoreVO;
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.MockHttpServletResponse;
import org.springframework.test.util.ReflectionTestUtils;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
/** 正式成绩口径、理论/实训聚合、空数据和越权保护测试。 */
@ExtendWith(MockitoExtension.class)
class StudentScoreServiceImplTest {
@Mock
private StudentScoreMapper mapper;
private StudentScoreServiceImpl service;
@BeforeEach
void setUp() {
service = new StudentScoreServiceImpl();
ReflectionTestUtils.setField(service, "studentScoreMapper", mapper);
}
@Test
void emptyOverviewShouldReturnZeroCountWithoutDivisionErrors() {
when(mapper.selectOverview("student-1")).thenReturn(null);
when(mapper.selectCurrentClassId(org.mockito.ArgumentMatchers.eq("student-1"),
org.mockito.ArgumentMatchers.any())).thenReturn(null);
StudentScoreVO.Overview overview = service.overview("student-1");
assertEquals(0, overview.getExamCount());
}
@Test
void missingOrUnpublishedDetailShouldBeRejectedWithoutRevealingOwnership() {
when(mapper.selectDetail(1, "student-1")).thenReturn(null);
assertThrows(BusinessException.class, () -> service.detail(1, "student-1"));
}
@Test
void theoryDetailShouldAggregateQuestionCountsAndMergeClassAnalysis() {
StudentScoreVO.Detail detail = detail("理论");
when(mapper.selectDetail(1, "student-1")).thenReturn(detail);
StudentScoreVO.TheoryQuestion right = theoryQuestion(true, false);
StudentScoreVO.TheoryQuestion partial = theoryQuestion(false, true);
when(mapper.selectTheoryQuestions(10, "student-1"))
.thenReturn(Arrays.asList(right, partial));
StudentScoreVO.TypeAnalysis personal = new StudentScoreVO.TypeAnalysis();
personal.setType("单选题");
personal.setPersonalRate(80D);
StudentScoreVO.TypeAnalysis classAverage = new StudentScoreVO.TypeAnalysis();
classAverage.setType("单选题");
classAverage.setClassAverageRate(70D);
when(mapper.selectTheoryPersonalAnalysis(10, "student-1"))
.thenReturn(Collections.singletonList(personal));
when(mapper.selectTheoryClassAnalysis(10, 7))
.thenReturn(Collections.singletonList(classAverage));
StudentScoreVO.Detail result = service.detail(1, "student-1");
assertEquals("良好", result.getGrade());
assertTrue(result.getPassed());
assertEquals(1, result.getRightCount());
assertEquals(1, result.getPartiallyRightCount());
assertEquals(50D, result.getCorrectRate());
assertEquals(70D, result.getTypeAnalysis().get(0).getClassAverageRate());
}
@Test
void practiceDetailShouldUseExistingResultTextWithoutInventingMaxScores() {
StudentScoreVO.Detail detail = detail("实训");
when(mapper.selectDetail(1, "student-1")).thenReturn(detail);
StudentScoreVO.PracticeItem pass = new StudentScoreVO.PracticeItem();
pass.setResult("通过");
StudentScoreVO.PracticeItem partial = new StudentScoreVO.PracticeItem();
partial.setResult("部分通过");
StudentScoreVO.PracticeItem fail = new StudentScoreVO.PracticeItem();
fail.setResult("未通过");
when(mapper.selectPracticeItems(10, "student-1"))
.thenReturn(Arrays.asList(pass, partial, fail));
StudentScoreVO.Detail result = service.detail(1, "student-1");
assertEquals("PASS", pass.getNormalizedStatus());
assertEquals("PARTIAL", partial.getNormalizedStatus());
assertEquals("FAIL", fail.getNormalizedStatus());
assertEquals(50D, result.getPracticeSummary().getWeightedPassRate());
}
@Test
void exportShouldReturnUtf8CsvForOwnedPublishedScore() throws Exception {
StudentScoreVO.Detail detail = detail("实训");
detail.setExamName("水质检测");
when(mapper.selectDetail(1, "student-1")).thenReturn(detail);
when(mapper.selectPracticeItems(10, "student-1")).thenReturn(Collections.emptyList());
MockHttpServletResponse response = new MockHttpServletResponse();
service.export(1, "student-1", response);
assertEquals("text/csv;charset=UTF-8", response.getContentType());
assertNotNull(response.getHeader("Content-Disposition"));
byte[] bytes = response.getContentAsByteArray();
assertTrue(bytes.length > 3);
assertEquals((byte) 0xEF, bytes[0]);
}
private StudentScoreVO.Detail detail(String type) {
StudentScoreVO.Detail detail = new StudentScoreVO.Detail();
detail.setExamStudentId(1);
detail.setExamId(10);
detail.setClassId(7);
detail.setType(type);
detail.setScore(85D);
detail.setTotalScore(new BigDecimal("100"));
detail.setPassScore(new BigDecimal("60"));
detail.setClassAverageScore(75D);
return detail;
}
private StudentScoreVO.TheoryQuestion theoryQuestion(boolean result, boolean partial) {
StudentScoreVO.TheoryQuestion question = new StudentScoreVO.TheoryQuestion();
question.setResult(result);
question.setPartiallyRight(partial);
return question;
}
}
package com.platform.business.sql;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 验证学生考试成绩迁移脚本包含重复数据保护和幂等索引检查。 */
class StudentExamScoreMigrationSqlTest {
@Test
void migrationShouldProtectDuplicatesAndCreateRequiredIndexes() throws Exception {
String sql = resource("sql/student_exam_score.sql").toLowerCase();
assertTrue(sql.contains("signal sqlstate '45000'"));
assertTrue(sql.contains("indexed_columns = 'exam_id,student_id'"));
assertTrue(sql.contains("uk_exam_student_exam_user"));
assertTrue(sql.contains("idx_exam_student_class_publish_score"));
assertTrue(sql.contains("idx_tpsd_exam_student_type"));
assertFalse(sql.contains("delete from exam_student"));
}
private String resource(String path) throws Exception {
try (InputStream input = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(path)) {
assertTrue(input != null, "迁移SQL资源必须存在:" + path);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = input.read(buffer)) >= 0) {
output.write(buffer, 0, length);
}
return new String(output.toByteArray(), StandardCharsets.UTF_8);
}
}
}
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