Commit 0e26d1b5 authored by wujipeng's avatar wujipeng
Browse files

对接数字仿真-优化

parent 3ad3b803
......@@ -8,7 +8,12 @@ import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/** 管理员新增考试计划请求。总分由服务端从试卷复制,不接受客户端直接指定。 */
/**
* 管理员新增考试计划请求。
*
* <p>理论考试的总分由服务端从理论试卷复制;实训考试不绑定本系统试卷,因此必须由
* 管理员直接填写总分。两个字段由考试类型互斥使用,避免一场考试同时出现两套分值来源。</p>
*/
@Data
public class ExamAdminSaveDTO {
......@@ -35,9 +40,12 @@ public class ExamAdminSaveDTO {
private String paperId;
/** 仅实训考试必填;理论考试不允许提交,由服务端从试卷生成总分快照。 */
private BigDecimal totalScore;
private String location;
/** 可不传;不传时按试卷总分的60%生成。 */
/** 可不传;不传时按本场考试总分的60%生成。 */
private BigDecimal passScore;
private List<String> studentIds;
......
......@@ -8,12 +8,12 @@ import java.util.List;
/**
* 阅卷工作台保存评分请求。
*
* <p>请求按考生维度提交,可只传本次发生变化的题目。服务端会校验每道题确实属于
* 当前考生、当前考试且为主观题,避免通过篡改题目ID修改其他试卷。</p>
* <p>请求按考生维度提交,可只传本次发生变化的题目。理论考试只接受主观题明细ID;
* 实训考试接受fz_grades明细ID。服务端始终同时校验考试、考生和明细归属。</p>
*/
@Data
public class ExamReviewSaveDTO {
@ApiModelProperty(value = "需要保存的主观题评分", required = true)
@ApiModelProperty(value = "需要保存的理论主观题或实训项目评分", required = true)
private List<ExamReviewScoreItemDTO> scores;
}
......@@ -6,15 +6,15 @@ import lombok.Data;
import java.math.BigDecimal;
/**
* 单道主观题的评分内容。
* 单道理论主观题或单个实训项目的评分内容。
*/
@Data
public class ExamReviewScoreItemDTO {
@ApiModelProperty(value = "考生答题明细ID", required = true)
@ApiModelProperty(value = "理论答题明细ID;实训考试为fz_grades.id", required = true)
private String questionId;
@ApiModelProperty(value = "本题得分,必须在0至题目满分之间", required = true)
@ApiModelProperty(value = "本项得分;理论受题目满分限制,实训受考试总分限制", required = true)
private BigDecimal score;
@ApiModelProperty(value = "可选评分说明,最多1000个字符")
......
......@@ -19,6 +19,9 @@ public class ExamReviewPaperVO {
private String className;
@ApiModelProperty("考试类型:理论或实训")
private String examType;
private String paperId;
private String paperName;
......@@ -35,6 +38,9 @@ public class ExamReviewPaperVO {
private List<ExamReviewQuestionVO> questions;
@ApiModelProperty("实训考试逐项明细;理论考试返回空数组")
private List<ExamReviewPracticeItemVO> practiceItems;
@ApiModelProperty("当前已评分总分,未发布时仅供教师预览")
private Double currentTotalScore;
......
package com.platform.business.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/** 教师阅卷工作台中的第三方实训项目明细。 */
@Data
public class ExamReviewPracticeItemVO {
/** fz_grades主键;保存实训评分时作为questionId回传。 */
private String id;
private String code;
private String level;
private String title;
private String type;
private String options;
private Boolean mark;
private String text;
private String result;
private byte[] file;
private String fileFormat;
private Double score;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date startTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date submissionTime;
}
......@@ -14,6 +14,7 @@ public class TeacherScoreExamVO {
private Integer examId;
private Integer classId;
private String examName;
private String examType;
private String className;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
......
......@@ -17,6 +17,7 @@ public class TeacherScoreStudentVO {
private String idCard;
private String className;
private String examName;
private String examType;
private Boolean submitted;
@ApiModelProperty("该学员成绩是否已经正式发布")
......
......@@ -70,7 +70,7 @@ public class ExamReviewController extends BaseController {
return Result.data(examReviewService.paper(examStudentId, teacher.getId()));
}
@ApiOperation("暂存单个考生的主观题评分")
@ApiOperation("暂存单个考生的理论主观题或实训项目评分")
@PutMapping("/students/{examStudentId}/scores")
public Result<ExamReviewPaperVO> saveScores(@PathVariable Integer examStudentId,
@RequestBody ExamReviewSaveDTO body,
......
......@@ -25,10 +25,10 @@ public class FzGradesController {
@Resource
private FzGradesService fzGradesService;
@ApiOperation("仿真考试数据接收")
@ApiOperation("接收单场单学员的完整仿真实训成绩并进入教师待复核")
@PostMapping("/receive")
public Result<Boolean> receive(@RequestBody List<FzGradesDTO> fzGradesList) {
// 业务层统一完成应考关系校验、自然键幂等更新以及submissionTime触发的正式成绩发布。
// 业务层统一完成应考校验、完整快照幂等判断和待复核落账;本入口绝不自动发布正式成绩。
return Result.data(fzGradesService.receive(fzGradesList));
}
}
......@@ -4,8 +4,10 @@ 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.ExamStudentEntity;
import com.platform.business.model.entity.FzGradesEntity;
import com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity;
import com.platform.business.model.vo.ExamReviewQuestionVO;
import com.platform.business.model.vo.ExamReviewPracticeItemVO;
import com.platform.business.model.vo.ExamReviewRecordVO;
import com.platform.business.model.vo.ExamReviewStudentVO;
import com.platform.business.model.vo.ExamReviewTaskVO;
......@@ -44,6 +46,9 @@ public interface ExamReviewMapper {
List<ExamReviewQuestionVO> queryQuestions(@Param("examId") Integer examId,
@Param("studentId") String studentId);
List<ExamReviewPracticeItemVO> queryPracticeItems(@Param("examId") Integer examId,
@Param("studentId") String studentId);
List<TheoreticalPaperStudentDetailEntity> lockQuestions(
@Param("questionIds") List<String> questionIds,
@Param("examId") Integer examId,
......@@ -54,15 +59,31 @@ public interface ExamReviewMapper {
@Param("result") Boolean result,
@Param("partiallyRight") Boolean partiallyRight);
List<FzGradesEntity> lockPracticeItems(@Param("questionIds") List<String> questionIds,
@Param("examId") Integer examId,
@Param("studentId") String studentId);
int updatePracticeScore(@Param("questionId") String questionId,
@Param("score") Double score);
/** 教师暂存后同步待复核总分,正式可见性仍由mark_flag控制。 */
int updatePendingPracticeTotal(@Param("examStudentId") Integer examStudentId,
@Param("score") Double score);
List<ExamStudentEntity> lockSubmittedStudents(@Param("examId") Integer examId);
int countSubmittedWithoutPaper(@Param("examId") Integer examId);
int countSubmittedWithoutPracticeItems(@Param("examId") Integer examId);
int countUnscoredSubjective(@Param("examId") Integer examId);
Double calculateStudentScore(@Param("examId") Integer examId,
@Param("studentId") String studentId);
Double calculatePracticeScore(@Param("examId") Integer examId,
@Param("studentId") String studentId);
int publishStudent(@Param("examStudentId") Integer examStudentId,
@Param("score") Double score);
......
......@@ -2,23 +2,26 @@ package com.platform.business.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.platform.business.model.entity.FzGradesEntity;
import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.entity.ExamStudentEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/**
* @Author: wujipeng
* @Description: 仿真实训逐题成绩持久化与正式成绩发布
* @Description: 仿真实训完整成绩持久化与待教师复核落账
* @Date: 2026/8/13 16:05
* @Version: 1.0
*/
@Mapper
public interface FzGradesMapper extends BaseMapper<FzGradesEntity> {
/** 锁定应考记录,串行化同一学员同一考试的增量上报。 */
/** 发布和第三方接收都先锁考试主记录,保证两条事务使用相同锁顺序。 */
ExamEntity lockPracticeExam(@Param("examId") Integer examId);
/** 锁定应考记录,串行化同一学员同一考试的完整成绩上报。 */
ExamStudentEntity lockExamStudent(@Param("examId") Integer examId,
@Param("studentId") String studentId);
......@@ -26,18 +29,14 @@ public interface FzGradesMapper extends BaseMapper<FzGradesEntity> {
List<FzGradesEntity> selectLatestItems(@Param("examId") Integer examId,
@Param("studentId") String studentId);
/** 同步更新自然键相同的全部历史重复行,避免旧重复数据继续产生不同版本。 */
int updateByBusinessKey(FzGradesEntity entity);
Double sumLatestScores(@Param("examId") Integer examId,
@Param("studentId") String studentId);
int publishPracticeStudent(@Param("examStudentId") Integer examStudentId,
/** 首次完整上报只形成待复核成绩,不设置个人或考试发布标记。 */
int submitPracticeStudent(@Param("examStudentId") Integer examStudentId,
@Param("score") Double score,
@Param("startTime") Long startTime,
@Param("endTime") Long endTime,
@Param("answerTime") String answerTime,
@Param("duration") String duration);
int publishPracticeExam(@Param("examId") Integer examId, @Param("updateTime") Date updateTime);
}
......@@ -14,5 +14,6 @@ import java.util.List;
*/
public interface FzGradesService extends IService<FzGradesEntity> {
/** 接收同一考试、同一学员的完整实训成绩快照,并形成待教师复核记录。 */
Boolean receive(List<FzGradesDTO> fzGradesList);
}
......@@ -146,7 +146,8 @@ public class ExamAdminServiceImpl implements ExamAdminService {
entity.setForbid(prepared.forbid);
entity.setChiefId(prepared.chiefId);
entity.setInvigilationId(prepared.invigilatorId);
entity.setPaperId(prepared.paper.getId());
// 实训考试的试卷完全由第三方系统负责,本系统必须显式保存空paper_id。
entity.setPaperId(prepared.paper == null ? null : prepared.paper.getId());
entity.setLocation(prepared.location);
entity.setTotalScore(prepared.totalScore);
entity.setPassScore(prepared.passScore);
......@@ -227,7 +228,10 @@ public class ExamAdminServiceImpl implements ExamAdminService {
return true;
}
/** 新增时校验试卷并生成不可变总分快照。 */
/**
* 新增时按考试类型确定唯一分值来源并生成不可变总分快照。
* 理论考试只信任已发布到本系统的试卷总分;实训考试只信任管理员填写的总分。
*/
private PreparedExam prepareCreate(ExamAdminSaveDTO request, ExamAdminClassVO managedClass,
List<String> studentIds) {
PreparedExam prepared = new PreparedExam();
......@@ -240,6 +244,10 @@ public class ExamAdminServiceImpl implements ExamAdminService {
prepared.invigilatorId = requireText(request.getInvigilatorId(), "监考教师ID", 64);
prepared.location = optionalText(request.getLocation(), "考场", ExamAdminConstants.MAX_LOCATION_LENGTH);
if (ExamAdminConstants.TYPE_THEORY.equals(prepared.type)) {
if (request.getTotalScore() != null) {
throw new BusinessException("理论考试总分由试卷确定,不能手动填写");
}
String paperId = requireText(request.getPaperId(), "试卷ID", 64);
TheoreticalPaperEntity paper = theoreticalPaperService.getById(paperId);
if (paper == null) {
......@@ -253,7 +261,15 @@ public class ExamAdminServiceImpl implements ExamAdminService {
throw new BusinessException("所选试卷总分无效");
}
prepared.paper = paper;
prepared.totalScore = BigDecimal.valueOf(paper.getSum()).setScale(2, RoundingMode.HALF_UP);
prepared.totalScore = normalizeTotalScore(
BigDecimal.valueOf(paper.getSum()), "所选试卷总分");
} else {
if (trimToNull(request.getPaperId()) != null) {
throw new BusinessException("实训考试由第三方创建试卷,不能选择本系统试卷");
}
prepared.paper = null;
prepared.totalScore = normalizeTotalScore(request.getTotalScore(), "实训考试总分");
}
prepared.passScore = normalizePassScore(request.getPassScore(), prepared.totalScore, true);
if (studentIds.size() > ExamAdminConstants.MAX_STUDENT_COUNT) {
throw new BusinessException("单场考试应考学员不能超过" + ExamAdminConstants.MAX_STUDENT_COUNT + "人");
......@@ -267,6 +283,10 @@ public class ExamAdminServiceImpl implements ExamAdminService {
PreparedUpdate prepared = new PreparedUpdate();
prepared.name = normalizeName(request.getName());
prepared.type = normalizeType(request.getType());
// 试卷来源和总分快照在创建后已经固定,编辑时切换类型会使历史关系失去语义。
if (!prepared.type.equals(existing.getType())) {
throw new BusinessException("考试类型创建后不能修改");
}
prepared.examTime = requireFutureExamTime(request.getExamTime(), managedClass);
prepared.duration = validateDuration(request.getDuration());
prepared.chiefId = requireText(request.getChiefExaminerId(), "首席考评员ID", 64);
......@@ -455,6 +475,19 @@ public class ExamAdminServiceImpl implements ExamAdminService {
return passScore;
}
/** 将数据库decimal(8,2)能够安全保存的正数规范为两位小数。 */
private BigDecimal normalizeTotalScore(BigDecimal requested, String fieldName) {
if (requested == null) {
throw new BusinessException(fieldName + "不能为空");
}
BigDecimal totalScore = requested.setScale(2, RoundingMode.HALF_UP);
if (totalScore.compareTo(BigDecimal.ZERO) <= 0
|| totalScore.compareTo(new BigDecimal("999999.99")) > 0) {
throw new BusinessException(fieldName + "必须大于0且不超过999999.99");
}
return totalScore;
}
/** 根据当前时刻派生状态和按钮权限,状态本身不写入数据库。 */
void applyStatus(ExamAdminDetailVO exam, Date now) {
if (exam.getExamTime() == null) {
......
package com.platform.business.service.impl;
import com.platform.business.constant.ExamReviewConstants;
import com.platform.business.constant.ExamAdminConstants;
import com.platform.business.mapper.ExamReviewMapper;
import com.platform.business.mapper.ExamReviewScoreLogMapper;
import com.platform.business.model.dto.ExamReviewSaveDTO;
......@@ -10,8 +11,10 @@ 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.FzGradesEntity;
import com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity;
import com.platform.business.model.vo.ExamReviewPaperVO;
import com.platform.business.model.vo.ExamReviewPracticeItemVO;
import com.platform.business.model.vo.ExamReviewQuestionVO;
import com.platform.business.model.vo.ExamReviewRecordVO;
import com.platform.business.model.vo.ExamReviewScoreSummaryVO;
......@@ -25,6 +28,7 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
......@@ -77,6 +81,14 @@ public class ExamReviewServiceImpl implements ExamReviewService {
public ExamReviewPaperVO paper(Integer examStudentId, String teacherId) {
ExamReviewStudentVO student = requireStudent(examStudentId, teacherId);
ExamReviewTaskVO task = requireTask(student.getExamId(), teacherId);
if (isPractice(task.getExamType())) {
List<ExamReviewPracticeItemVO> items = examReviewMapper.queryPracticeItems(
student.getExamId(), student.getStudentId());
if (items == null || items.isEmpty()) {
throw new BusinessException("该考生尚未生成可复核的实训成绩明细");
}
return assemblePracticePaper(task, student, items);
}
List<ExamReviewQuestionVO> questions = examReviewMapper.queryQuestions(
student.getExamId(), student.getStudentId());
if (questions == null || questions.isEmpty()) {
......@@ -100,6 +112,11 @@ public class ExamReviewServiceImpl implements ExamReviewService {
throw new BusinessException("成绩已经发布,不能继续修改评分");
}
ExamReviewTaskVO task = requireTask(student.getExamId(), teacherId);
if (isPractice(task.getExamType())) {
return savePracticeScores(student, task, request, teacherId);
}
Map<String, ExamReviewScoreItemDTO> requestByQuestionId = new LinkedHashMap<>();
List<String> questionIds = new ArrayList<>();
for (ExamReviewScoreItemDTO item : request.getScores()) {
......@@ -184,6 +201,12 @@ public class ExamReviewServiceImpl implements ExamReviewService {
}
// 即使考试主标记因历史发布已经为 true,只要出现新的未发布交卷,仍允许补充发布;
// 任务列表同样以考生 mark_flag 聚合,因此不会发生列表显示待阅卷却无法进入发布的问题。
boolean practiceExam = isPractice(exam.getType());
if (practiceExam) {
if (examReviewMapper.countSubmittedWithoutPracticeItems(examId) > 0) {
throw new BusinessException("存在缺少实训明细的已交考生,暂不能发布");
}
} else {
if (examReviewMapper.countSubmittedWithoutPaper(examId) > 0) {
throw new BusinessException("存在尚未生成试卷明细的已交考生,暂不能发布");
}
......@@ -191,13 +214,20 @@ public class ExamReviewServiceImpl implements ExamReviewService {
if (unscoredCount > 0) {
throw new BusinessException("还有" + unscoredCount + "道主观题未评分,完成后才能发布");
}
}
Date now = new Date();
for (ExamStudentEntity student : pendingStudents) {
Double finalScore = examReviewMapper.calculateStudentScore(examId, student.getStudentId());
Double finalScore = practiceExam
? examReviewMapper.calculatePracticeScore(examId, student.getStudentId())
: examReviewMapper.calculateStudentScore(examId, student.getStudentId());
if (finalScore == null) {
finalScore = 0D;
}
if (practiceExam && exam.getTotalScore() != null
&& BigDecimal.valueOf(finalScore).compareTo(exam.getTotalScore()) > 0) {
throw new BusinessException("学员实训成绩超过考试总分,调整后才能发布");
}
int updated = examReviewMapper.publishStudent(student.getId(), finalScore);
if (updated != 1) {
throw new BusinessException("考生成绩发布状态已变化,请刷新后重试");
......@@ -266,6 +296,7 @@ public class ExamReviewServiceImpl implements ExamReviewService {
paper.setClassId(task.getClassId());
paper.setExamName(task.getExamName());
paper.setClassName(task.getClassName());
paper.setExamType(task.getExamType());
paper.setPaperId(task.getPaperId());
paper.setPaperName(task.getPaperName());
paper.setPaperTotal(task.getPaperTotal() == null ? calculatedPaperTotal : task.getPaperTotal());
......@@ -273,12 +304,109 @@ public class ExamReviewServiceImpl implements ExamReviewService {
paper.setStudent(student);
paper.setScoreSummaries(new ArrayList<>(summaryMap.values()));
paper.setQuestions(questions);
paper.setPracticeItems(Collections.emptyList());
paper.setCurrentTotalScore(currentTotal);
paper.setScoringCompleted(scoringCompleted);
paper.setPublished(Boolean.TRUE.equals(student.getPublished()));
return paper;
}
/**
* 实训评分直接更新第三方明细的当前有效分值,但不提前修改正式发布标记。
* 因第三方协议没有单项满分,只能校验单项非负以及调整后总和不超过考试总分。
*/
private ExamReviewPaperVO savePracticeScores(ExamStudentEntity student,
ExamReviewTaskVO task,
ExamReviewSaveDTO request,
String teacherId) {
Map<String, ExamReviewScoreItemDTO> requestById = new LinkedHashMap<>();
List<String> itemIds = new ArrayList<>();
for (ExamReviewScoreItemDTO item : request.getScores()) {
String itemId = trimToNull(item.getQuestionId());
if (itemId == null) {
throw new BusinessException("实训明细ID不能为空");
}
if (item.getScore().compareTo(BigDecimal.ZERO) < 0) {
throw new BusinessException("实训项目得分不能小于0");
}
if (requestById.put(itemId, item) != null) {
throw new BusinessException("同一实训项目不能重复提交评分");
}
itemIds.add(itemId);
}
List<FzGradesEntity> lockedItems = examReviewMapper.lockPracticeItems(
itemIds, student.getExamId(), student.getStudentId());
if (lockedItems == null || lockedItems.size() != itemIds.size()) {
throw new BusinessException("实训明细不属于当前考生,或明细不存在");
}
BigDecimal projectedTotal = toBigDecimal(examReviewMapper.calculatePracticeScore(
student.getExamId(), student.getStudentId()));
projectedTotal = projectedTotal == null ? BigDecimal.ZERO : projectedTotal;
for (FzGradesEntity locked : lockedItems) {
ExamReviewScoreItemDTO requested = requestById.get(locked.getId());
BigDecimal oldScore = toBigDecimal(locked.getScore());
projectedTotal = projectedTotal.subtract(oldScore == null ? BigDecimal.ZERO : oldScore)
.add(requested.getScore());
}
BigDecimal examTotal = toBigDecimal(task.getPaperTotal());
if (examTotal == null || examTotal.compareTo(BigDecimal.ZERO) <= 0) {
throw new BusinessException("实训考试总分配置异常,不能保存评分");
}
if (projectedTotal.compareTo(examTotal) > 0) {
throw new BusinessException("调整后的实训总分不能超过考试总分");
}
Date now = new Date();
for (FzGradesEntity locked : lockedItems) {
ExamReviewScoreItemDTO requested = requestById.get(locked.getId());
BigDecimal previous = toBigDecimal(locked.getScore());
if (examReviewMapper.updatePracticeScore(
locked.getId(), requested.getScore().doubleValue()) != 1) {
throw new BusinessException("实训项目评分保存失败,请刷新后重试");
}
String comment = trimToNull(requested.getComment());
if (!sameScore(previous, requested.getScore()) || comment != null) {
insertLog(student.getExamId(), student.getId(), locked.getId(), teacherId,
previous, requested.getScore(), ExamReviewConstants.ACTION_SAVE, comment, now);
}
}
if (examReviewMapper.updatePendingPracticeTotal(
student.getId(), projectedTotal.doubleValue()) != 1) {
throw new BusinessException("实训待复核总分状态已变化,请刷新后重试");
}
return paper(student.getId(), teacherId);
}
/** 实训工作台不伪造题目满分或理论题型汇总,只返回第三方可稳定提供的字段。 */
private ExamReviewPaperVO assemblePracticePaper(ExamReviewTaskVO task,
ExamReviewStudentVO student,
List<ExamReviewPracticeItemVO> items) {
double currentTotal = 0D;
for (ExamReviewPracticeItemVO item : items) {
currentTotal += item.getScore() == null ? 0D : item.getScore();
}
ExamReviewPaperVO paper = new ExamReviewPaperVO();
paper.setExamId(task.getExamId());
paper.setClassId(task.getClassId());
paper.setExamName(task.getExamName());
paper.setClassName(task.getClassName());
paper.setExamType(task.getExamType());
paper.setPaperId(null);
paper.setPaperName(null);
paper.setPaperTotal(task.getPaperTotal());
paper.setDuration(task.getDuration());
paper.setStudent(student);
paper.setScoreSummaries(Collections.emptyList());
paper.setQuestions(Collections.emptyList());
paper.setPracticeItems(items);
paper.setCurrentTotalScore(currentTotal);
paper.setScoringCompleted(true);
paper.setPublished(Boolean.TRUE.equals(student.getPublished()));
return paper;
}
private ExamReviewTaskVO requireTask(Integer examId, String teacherId) {
if (examId == null) {
throw new BusinessException("考试ID不能为空");
......@@ -353,6 +481,11 @@ public class ExamReviewServiceImpl implements ExamReviewService {
return normalized;
}
private boolean isPractice(String type) {
return ExamAdminConstants.TYPE_PRACTICE.equals(type)
|| "PRACTICE".equalsIgnoreCase(type == null ? "" : type.trim());
}
private void fillDeadline(ExamReviewTaskVO task) {
if (task.getExamTime() == null) {
return;
......
......@@ -2,18 +2,31 @@ package com.platform.business.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.business.constant.ExamAdminConstants;
import com.platform.business.mapper.FzGradesMapper;
import com.platform.business.model.dto.FzGradesDTO;
import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.entity.ExamStudentEntity;
import com.platform.business.model.entity.FzGradesEntity;
import com.platform.business.service.FzGradesService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @Author: wujipeng
* @Description: 仿真实训逐题成绩的增量、幂等接收服务
* @Description: 仿真实训完整成绩的校验、幂等接收与待复核落账服务
* @Date: 2026/8/13 16:06
* @Version: 1.0
*/
......@@ -21,9 +34,183 @@ import java.util.List;
@Service
public class FzGradesServiceImpl extends ServiceImpl<FzGradesMapper, FzGradesEntity> implements FzGradesService {
private static final int MAX_ITEM_COUNT = 2000;
@Override
@Transactional
@Transactional(rollbackFor = Exception.class)
public Boolean receive(List<FzGradesDTO> fzGradesList) {
return saveBatch(BeanUtil.copyToList(fzGradesList, FzGradesEntity.class));
List<FzGradesEntity> incoming = normalizeAndValidateBatch(fzGradesList);
FzGradesEntity first = incoming.get(0);
/*
* 锁顺序固定为exam -> exam_student,与教师发布事务保持一致。这样接收请求与发布请求
* 同时到达时,其中一方会完整完成后另一方再判断状态,不会出现一半明细已经插入、
* 另一半却被教师发布的中间状态。
*/
ExamEntity exam = baseMapper.lockPracticeExam(first.getExamId());
if (exam == null) {
throw new BusinessException("考试不存在或已删除");
}
if (!ExamAdminConstants.TYPE_PRACTICE.equals(exam.getType())) {
throw new BusinessException("第三方仿真成绩只能上报到实训考试");
}
if (Boolean.TRUE.equals(exam.getMarkFlag())) {
throw new BusinessException("本场实训考试成绩已经发布,不能继续上报");
}
if (exam.getTotalScore() == null || exam.getTotalScore().compareTo(BigDecimal.ZERO) <= 0) {
throw new BusinessException("实训考试总分未配置,不能接收成绩");
}
ExamStudentEntity candidate = baseMapper.lockExamStudent(first.getExamId(), first.getUserId());
if (candidate == null) {
throw new BusinessException("学员不在本场考试应考名单中");
}
if (Boolean.TRUE.equals(candidate.getMarkFlag())) {
throw new BusinessException("该学员实训成绩已经发布,不能继续上报");
}
BigDecimal total = incoming.stream()
.map(item -> BigDecimal.valueOf(item.getScore()))
.reduce(BigDecimal.ZERO, BigDecimal::add);
if (total.compareTo(exam.getTotalScore()) > 0) {
throw new BusinessException("实训成绩汇总不能超过考试总分");
}
List<FzGradesEntity> persisted = baseMapper.selectLatestItems(
first.getExamId(), first.getUserId());
if (persisted != null && !persisted.isEmpty()) {
// 首次有效上报后数据源即锁定;仅允许完全相同且顺序无关的网络重试幂等成功。
if (sameSnapshot(incoming, persisted)) {
return true;
}
throw new BusinessException("仿真实训成绩已经接收,后续只能由教师复核调整");
}
for (FzGradesEntity entity : incoming) {
// 外部系统不得控制本系统雪花主键,避免恶意覆盖或跨业务主键碰撞。
entity.setId(null);
if (baseMapper.insert(entity) != 1) {
throw new BusinessException("仿真实训成绩保存失败,请稍后重试");
}
}
Date start = incoming.stream().map(FzGradesEntity::getStartTime)
.filter(Objects::nonNull).min(Comparator.naturalOrder()).orElse(null);
Date end = incoming.stream().map(FzGradesEntity::getSubmissionTime)
.filter(Objects::nonNull).max(Comparator.naturalOrder()).orElse(null);
String answerTime = end == null ? null
: new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(end);
String duration = buildDuration(start, end);
if (baseMapper.submitPracticeStudent(candidate.getId(), total.doubleValue(),
toMillis(start), toMillis(end), answerTime, duration) != 1) {
throw new BusinessException("实训应考状态已变化,请刷新后重试");
}
return true;
}
/** 校验List确实只表示同一考试、同一学员的一份完整且可确定顺序的成绩快照。 */
private List<FzGradesEntity> normalizeAndValidateBatch(List<FzGradesDTO> values) {
if (values == null || values.isEmpty()) {
throw new BusinessException("仿真实训成绩明细不能为空");
}
if (values.size() > MAX_ITEM_COUNT) {
throw new BusinessException("单份仿真实训成绩不能超过" + MAX_ITEM_COUNT + "项");
}
Integer examId = null;
String userId = null;
Map<String, FzGradesEntity> byCode = new LinkedHashMap<>();
for (FzGradesDTO value : values) {
if (value == null) {
throw new BusinessException("仿真实训成绩不能包含空项");
}
if (value.getExamId() == null || value.getExamId() <= 0) {
throw new BusinessException("考试ID必须为正整数");
}
String currentUserId = requireText(value.getUserId(), "学员ID", 64);
String code = requireText(value.getCode(), "题目编号", 128);
if (examId == null) {
examId = value.getExamId();
userId = currentUserId;
} else if (!examId.equals(value.getExamId()) || !userId.equals(currentUserId)) {
throw new BusinessException("一次请求只能上报同一考试、同一学员的完整成绩");
}
if (value.getScore() == null || !Double.isFinite(value.getScore()) || value.getScore() < 0D) {
throw new BusinessException("实训项目得分必须是非负有限数值");
}
FzGradesEntity entity = new FzGradesEntity();
BeanUtil.copyProperties(value, entity);
entity.setExamId(examId);
entity.setUserId(userId);
entity.setCode(code);
if (byCode.put(code, entity) != null) {
throw new BusinessException("同一份成绩中题目编号不能重复");
}
}
List<FzGradesEntity> result = new ArrayList<>(byCode.values());
result.sort(Comparator.comparing(FzGradesEntity::getCode));
return result;
}
/** 比较业务字段而非服务端主键,数组顺序变化不影响第三方幂等重试。 */
private boolean sameSnapshot(List<FzGradesEntity> incoming, List<FzGradesEntity> persisted) {
if (incoming.size() != persisted.size()) {
return false;
}
Map<String, FzGradesEntity> persistedByCode = new LinkedHashMap<>();
for (FzGradesEntity item : persisted) {
persistedByCode.put(item.getCode(), item);
}
for (FzGradesEntity item : incoming) {
FzGradesEntity old = persistedByCode.get(item.getCode());
if (old == null || !sameBusinessFields(item, old)) {
return false;
}
}
return true;
}
private boolean sameBusinessFields(FzGradesEntity left, FzGradesEntity right) {
return Objects.equals(left.getExamId(), right.getExamId())
&& Objects.equals(left.getUserId(), right.getUserId())
&& Objects.equals(left.getCode(), right.getCode())
&& Objects.equals(left.getLev(), right.getLev())
&& sameDate(left.getStartTime(), right.getStartTime())
&& sameDate(left.getSubmissionTime(), right.getSubmissionTime())
&& Objects.equals(left.getTitle(), right.getTitle())
&& Objects.equals(left.getType(), right.getType())
&& Objects.equals(left.getOptions(), right.getOptions())
&& Objects.equals(left.getMark(), right.getMark())
&& Objects.equals(left.getText(), right.getText())
&& Objects.equals(left.getResult(), right.getResult())
&& Arrays.equals(left.getFile(), right.getFile())
&& Objects.equals(left.getFileFormat(), right.getFileFormat())
&& Double.compare(left.getScore(), right.getScore()) == 0;
}
private String requireText(String value, String field, int maxLength) {
String normalized = value == null ? null : value.trim();
if (normalized == null || normalized.isEmpty()) {
throw new BusinessException(field + "不能为空");
}
if (normalized.length() > maxLength) {
throw new BusinessException(field + "不能超过" + maxLength + "个字符");
}
return normalized;
}
private boolean sameDate(Date left, Date right) {
return left == null ? right == null : right != null && left.getTime() == right.getTime();
}
private Long toMillis(Date value) {
return value == null ? null : value.getTime();
}
private String buildDuration(Date start, Date end) {
if (start == null || end == null || end.before(start)) {
return null;
}
long minutes = (end.getTime() - start.getTime() + 59_999L) / 60_000L;
return minutes + "分钟";
}
}
......@@ -41,7 +41,7 @@ public class TeacherScoreServiceImpl implements TeacherScoreService {
private static final int MAX_KEYWORD_LENGTH = 100;
private static final String[] EXPORT_HEADERS = {
"序号", "考试名称", "班级", "学员姓名", "身份证号",
"序号", "考试名称", "考试类型", "班级", "学员姓名", "身份证号",
"参考状态", "成绩", "等级", "是否及格", "交卷时间", "答题时长"
};
......@@ -192,25 +192,26 @@ public class TeacherScoreServiceImpl implements TeacherScoreService {
Row row = sheet.createRow(rowIndex);
writeTextCell(row, 0, String.valueOf(rowIndex), bodyStyle);
writeTextCell(row, 1, student.getExamName(), bodyStyle);
writeTextCell(row, 2, student.getClassName(), bodyStyle);
writeTextCell(row, 3, student.getStudentName(), bodyStyle);
writeTextCell(row, 4, student.getIdCard(), bodyStyle);
writeTextCell(row, 5, participationStatus(student), bodyStyle);
writeTextCell(row, 2, student.getExamType(), bodyStyle);
writeTextCell(row, 3, student.getClassName(), bodyStyle);
writeTextCell(row, 4, student.getStudentName(), bodyStyle);
writeTextCell(row, 5, student.getIdCard(), bodyStyle);
writeTextCell(row, 6, participationStatus(student), bodyStyle);
// POI 不创建值即可得到真正的空单元格,前端打开后不会看到0或字符串“null”。
Cell scoreCell = row.createCell(6);
Cell scoreCell = row.createCell(7);
scoreCell.setCellStyle(bodyStyle);
if (student.getScore() != null) {
scoreCell.setCellValue(student.getScore().doubleValue());
}
writeTextCell(row, 7, student.getGrade(), bodyStyle);
writeTextCell(row, 8, passLabel(student), bodyStyle);
writeTextCell(row, 9, student.getAnswerTime(), bodyStyle);
writeTextCell(row, 10, student.getDuration(), bodyStyle);
writeTextCell(row, 8, student.getGrade(), bodyStyle);
writeTextCell(row, 9, passLabel(student), bodyStyle);
writeTextCell(row, 10, student.getAnswerTime(), bodyStyle);
writeTextCell(row, 11, student.getDuration(), bodyStyle);
rowIndex++;
}
int[] widths = {8, 28, 22, 14, 24, 14, 12, 12, 12, 20, 14};
int[] widths = {8, 28, 12, 22, 14, 24, 14, 12, 12, 12, 20, 14};
for (int i = 0; i < widths.length; i++) {
sheet.setColumnWidth(i, widths[i] * 256);
}
......
......@@ -16,7 +16,7 @@
e.type AS examType,
e.paper_id AS paperId,
tp.name AS paperName,
tp.sum AS paperTotal,
e.total_score AS paperTotal,
e.exam_time AS examTime,
e.duration,
COUNT(es.id) AS totalCount,
......@@ -36,8 +36,8 @@
<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
GROUP BY e.id, e.class_id, e.name, c.name, e.type, e.paper_id, tp.name,
e.total_score, 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
......@@ -58,7 +58,7 @@
e.type AS examType,
e.paper_id AS paperId,
tp.name AS paperName,
tp.sum AS paperTotal,
e.total_score AS paperTotal,
e.exam_time AS examTime,
e.duration,
COUNT(es.id) AS totalCount,
......@@ -76,8 +76,8 @@
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
GROUP BY e.id, e.class_id, e.name, c.name, e.type, e.paper_id, tp.name,
e.total_score, e.exam_time, e.duration
</select>
<!-- 发布事务开始时锁定考试主记录,串行化同一考试的重复发布请求。 -->
......@@ -213,6 +213,23 @@
ORDER BY FIELD(d.type, '判断题', '单选题', '多选题', '主观题'), d.sequence, d.id
</select>
<!-- 与其他实训详情保持相同口径:历史重复code只读取雪花ID最大的最新版本。 -->
<select id="queryPracticeItems"
resultType="com.platform.business.model.vo.ExamReviewPracticeItemVO">
SELECT
g.id, g.code, g.lev AS level, g.title, g.type, g.options, g.mark,
g.text, g.result, g.file, g.file_format AS fileFormat, g.score,
g.start_time AS startTime, g.submission_time AS submissionTime
FROM fz_grades g
INNER JOIN (
SELECT MAX(id) AS id
FROM fz_grades
WHERE exam_id = #{examId} AND user_id = #{studentId}
GROUP BY code
) latest ON latest.id = g.id
ORDER BY g.code, g.id
</select>
<!-- 题目ID、考试ID和考生ID必须同时匹配,锁定后才允许更新。 -->
<select id="lockQuestions" resultType="com.platform.business.model.entity.TheoreticalPaperStudentDetailEntity">
SELECT d.*
......@@ -236,6 +253,33 @@
AND type = '主观题'
</update>
<!-- 锁定明确归属于当前考试和学员的实训项目,阻止篡改其他考生明细。 -->
<select id="lockPracticeItems" resultType="com.platform.business.model.entity.FzGradesEntity">
SELECT g.*
FROM fz_grades g
WHERE g.exam_id = #{examId}
AND g.user_id = #{studentId}
AND g.id IN
<foreach collection="questionIds" item="questionId" open="(" separator="," close=")">
#{questionId}
</foreach>
FOR UPDATE
</select>
<update id="updatePracticeScore">
UPDATE fz_grades
SET score = #{score}
WHERE id = #{questionId}
</update>
<update id="updatePendingPracticeTotal">
UPDATE exam_student
SET score = #{score}
WHERE id = #{examStudentId}
AND submit = 1
AND IFNULL(mark_flag, 0) = 0
</update>
<!-- 发布时锁定全部已交卷考生,保证总分计算和发布标记原子完成。 -->
<select id="lockSubmittedStudents" resultType="com.platform.business.model.entity.ExamStudentEntity">
SELECT es.*
......@@ -261,6 +305,19 @@
)
</select>
<select id="countSubmittedWithoutPracticeItems" 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 fz_grades g
WHERE g.exam_id = es.exam_id AND g.user_id = es.student_id
)
</select>
<select id="countUnscoredSubjective" resultType="int">
SELECT COUNT(*)
FROM exam_student es
......@@ -288,6 +345,17 @@
AND d.is_problem = 1
</select>
<select id="calculatePracticeScore" resultType="double">
SELECT IFNULL(SUM(g.score), 0)
FROM fz_grades g
INNER JOIN (
SELECT MAX(id) AS id
FROM fz_grades
WHERE exam_id = #{examId} AND user_id = #{studentId}
GROUP BY code
) latest ON latest.id = g.id
</select>
<update id="publishStudent">
UPDATE exam_student
SET score = #{score},
......@@ -307,8 +375,8 @@
SELECT
l.id,
l.question_id AS questionId,
d.sequence AS questionSequence,
d.type AS questionType,
COALESCE(d.sequence, practice_item.code) AS questionSequence,
COALESCE(d.type, practice_item.type) AS questionType,
l.reviewer_id AS reviewerId,
u.nick_name AS reviewerName,
l.previous_score AS previousScore,
......@@ -318,6 +386,7 @@
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 fz_grades practice_item ON practice_item.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
......
......@@ -2,6 +2,13 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.FzGradesMapper">
<select id="lockPracticeExam" resultType="com.platform.business.model.entity.ExamEntity">
SELECT e.*
FROM exam e
WHERE e.id = #{examId}
FOR UPDATE
</select>
<select id="lockExamStudent" resultType="com.platform.business.model.entity.ExamStudentEntity">
SELECT es.*
FROM exam_student es
......@@ -15,7 +22,8 @@
SELECT
g.id, g.exam_id AS examId, g.user_id AS userId, g.code, g.lev,
g.start_time AS startTime, g.submission_time AS submissionTime,
g.title, g.type, g.options, g.mark, g.text, g.result, g.file, g.score
g.title, g.type, g.options, g.mark, g.text, g.result, g.file,
g.file_format AS fileFormat, g.score
FROM fz_grades g
INNER JOIN (
SELECT MAX(id) AS id
......@@ -26,24 +34,6 @@
ORDER BY g.code, g.id
</select>
<update id="updateByBusinessKey">
UPDATE fz_grades
SET lev = #{lev},
start_time = #{startTime},
submission_time = #{submissionTime},
title = #{title},
type = #{type},
options = #{options},
mark = #{mark},
text = #{text},
result = #{result},
file = #{file},
score = #{score}
WHERE exam_id = #{examId}
AND user_id = #{userId}
AND code = #{code}
</update>
<select id="sumLatestScores" resultType="double">
SELECT IFNULL(SUM(g.score), 0)
FROM fz_grades g
......@@ -55,7 +45,7 @@
) latest ON latest.id = g.id
</select>
<update id="publishPracticeStudent">
<update id="submitPracticeStudent">
UPDATE exam_student
SET score = #{score},
start_time = #{startTime},
......@@ -63,17 +53,9 @@
answer_time = #{answerTime},
duration = #{duration},
submit = 1,
mark_flag = 1
mark_flag = 0
WHERE id = #{examStudentId}
AND IFNULL(mark_flag, 0) = 0
</update>
<!-- 实训成绩由外部评分系统自动形成,首名学员完成后即可开启考试级成绩可见性。 -->
<update id="publishPracticeExam">
UPDATE exam
SET mark_flag = 1,
update_time = #{updateTime}
WHERE id = #{examId}
</update>
</mapper>
......@@ -23,6 +23,7 @@
e.id AS examId,
e.class_id AS classId,
e.name AS examName,
e.type AS examType,
c.name AS className,
e.exam_time AS examTime,
e.duration,
......@@ -75,7 +76,7 @@
</sql>
<sql id="examSummaryGroup">
GROUP BY e.id, e.class_id, e.name, c.name, e.exam_time, e.duration,
GROUP BY e.id, e.class_id, e.name, e.type, c.name, e.exam_time, e.duration,
e.total_score, e.pass_score
</sql>
......@@ -119,6 +120,7 @@
u.id_card AS idCard,
c.name AS className,
e.name AS examName,
e.type AS examType,
CASE WHEN IFNULL(es.submit, 0) = 1 THEN TRUE ELSE FALSE END AS submitted,
CASE
WHEN IFNULL(es.submit, 0) = 1
......
......@@ -31,7 +31,7 @@
`GET /exam/admin/classes/{classId}/options`
- `teachers`:未删除且具有教师角色的用户,首席考评员和监考教师共用。
- `papers`:`theoretical_paper.lev` 与班级等级名称完全一致的试卷;理论、实训考试共用。
- `papers`:`theoretical_paper.lev` 与班级等级名称完全一致的理论试卷;实训考试不使用。
- `students`:当前班级有效学员,包含身份证号、性别、手机号、单位和个人出勤率。
出勤率按 `NORMAL/LATE` 占 `NORMAL/LATE/ABSENT/LEAVE` 的百分比计算;没有有效记录时为
......@@ -67,7 +67,9 @@
- 类型只支持“理论”“实训”;考试日期必须位于班级培训起止日期内。
- 时长为15~600分钟;`forbid` 为0~考试时长。
- 试卷必须与班级等级一致,总分从试卷复制;`passScore` 不传时默认为总分的60%。
- 理论考试必须选择与班级等级一致的试卷,总分从试卷复制,不能提交`totalScore`。
- 实训考试不传`paperId`,必须提交`totalScore`;试卷由第三方仿真系统创建。
- 两类考试的`passScore`不传时均默认为总分的60%。
- 至少选择1名、最多500名班级学员,ID不得重复。
- 同班级、首席考评员、监考教师或任一应考学员的考试时间不能重叠。
- 同一班级内考试名称不能重复。
......@@ -90,7 +92,7 @@
}
```
编辑不改变试卷、总分快照、监考教师、禁止交卷时间或应考学员。考试已到开始时间,或任一
编辑不允许切换考试类型,也不改变试卷、总分快照、监考教师、禁止交卷时间或应考学员。考试已到开始时间,或任一
考生已开始、交卷、产生分数后禁止编辑。新的时间和教师安排仍会执行完整冲突校验。
## 7. 删除考试
......
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