Commit 3ad3b803 authored by wujipeng's avatar wujipeng
Browse files

优化

parent eca651ce
......@@ -66,7 +66,11 @@ public class FzGradesEntity {
private String result;
@ApiModelProperty("附件")
private String file;
private byte[] file;
@ApiModelProperty("附件格式")
@TableField("file_format")
private String fileFormat;
@ApiModelProperty("分数")
private Double score;
......
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.ExamMapper;
import com.platform.business.mapper.FzGradesMapper;
import com.platform.business.model.dto.FzGradesDTO;
import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.entity.ExamStudentEntity;
import com.platform.business.model.entity.FzGradesEntity;
import com.platform.business.service.FzGradesService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
/**
* @Author: wujipeng
......@@ -34,237 +17,13 @@ import java.util.TreeMap;
* @Date: 2026/8/13 16:06
* @Version: 1.0
*/
@Service
public class FzGradesServiceImpl extends ServiceImpl<FzGradesMapper, FzGradesEntity> implements FzGradesService {
private static final int MAX_BATCH_SIZE = 2000;
@Resource
private ExamMapper examMapper;
@Override
@Transactional(rollbackFor = Exception.class)
@Transactional
public Boolean receive(List<FzGradesDTO> fzGradesList) {
if (fzGradesList == null || fzGradesList.isEmpty()) {
throw new BusinessException("仿真实训成绩明细不能为空");
}
if (fzGradesList.size() > MAX_BATCH_SIZE) {
throw new BusinessException("单次最多上报2000条仿真实训成绩明细");
}
/*
* 一个请求允许包含多个学员,但必须先按稳定键排序处理。多个并发请求若同时包含
* 相同的应考记录,固定锁顺序可以显著降低数据库死锁概率。
*/
Map<String, List<FzGradesDTO>> grouped = new TreeMap<>();
for (FzGradesDTO item : fzGradesList) {
validateItem(item);
String groupKey = item.getExamId() + "\u0000" + item.getUserId().trim();
grouped.computeIfAbsent(groupKey, key -> new ArrayList<>()).add(item);
}
for (List<FzGradesDTO> items : grouped.values()) {
processStudent(items);
}
return true;
}
/** 处理同一考试、同一学员的一组增量题目。 */
private void processStudent(List<FzGradesDTO> items) {
FzGradesDTO first = items.get(0);
Integer examId = first.getExamId();
String studentId = first.getUserId().trim();
// 先锁定应考关系:既完成权限归属校验,也串行化“查询后新增”的竞态窗口。
ExamStudentEntity candidate = baseMapper.lockExamStudent(examId, studentId);
if (candidate == null) {
throw new BusinessException("学员不属于本场考试应考名单");
}
ExamEntity exam = examMapper.selectById(examId);
if (exam == null) {
throw new BusinessException("考试不存在或已删除");
}
if (!isPractice(exam.getType())) {
throw new BusinessException("该接口只接收仿真实训考试成绩");
}
Set<String> requestCodes = new HashSet<>();
for (FzGradesDTO item : items) {
if (!Objects.equals(examId, item.getExamId())
|| !studentId.equals(item.getUserId().trim())) {
throw new BusinessException("同一处理分组中的考试或学员信息不一致");
}
item.setUserId(studentId);
item.setCode(item.getCode().trim());
if (!requestCodes.add(item.getCode())) {
throw new BusinessException("同一次请求中题目编号不能重复:" + item.getCode());
}
}
List<FzGradesEntity> stored = baseMapper.selectLatestItems(examId, studentId);
Map<String, FzGradesEntity> storedByCode = indexByCode(stored);
if (Boolean.TRUE.equals(candidate.getMarkFlag())) {
ensurePublishedReplay(items, storedByCode);
return;
}
Date submissionTime = null;
for (FzGradesDTO item : items) {
FzGradesEntity entity = copyForPersistence(item);
if (storedByCode.containsKey(entity.getCode())) {
baseMapper.updateByBusinessKey(entity);
} else if (baseMapper.insert(entity) != 1) {
throw new BusinessException("仿真实训成绩明细保存失败,请稍后重试");
}
if (item.getSubmissionTime() != null
&& (submissionTime == null || item.getSubmissionTime().after(submissionTime))) {
submissionTime = item.getSubmissionTime();
}
}
// submissionTime是当前协议中唯一的完成标志;没有完成标志时绝不改写正式总分。
if (submissionTime != null) {
publishStudent(exam, candidate, studentId, submissionTime);
}
}
/** 汇总每个题号的最新得分,并原子发布学员与考试的正式成绩标记。 */
private void publishStudent(ExamEntity exam, ExamStudentEntity candidate, String studentId,
Date submissionTime) {
Double sum = baseMapper.sumLatestScores(exam.getId(), studentId);
BigDecimal score = BigDecimal.valueOf(sum == null ? 0D : sum).setScale(2, RoundingMode.HALF_UP);
if (exam.getTotalScore() == null) {
throw new BusinessException("考试总分尚未配置,不能发布仿真实训成绩");
}
if (score.compareTo(exam.getTotalScore()) > 0) {
throw new BusinessException("仿真实训累计得分不能超过考试总分" + exam.getTotalScore());
}
List<FzGradesEntity> allItems = baseMapper.selectLatestItems(exam.getId(), studentId);
Date start = allItems.stream().map(FzGradesEntity::getStartTime).filter(Objects::nonNull)
.min(Comparator.naturalOrder()).orElse(null);
long startMillis = start == null
? (candidate.getStartTime() == null ? submissionTime.getTime() : candidate.getStartTime())
: start.getTime();
long endMillis = submissionTime.getTime();
if (endMillis < startMillis) {
throw new BusinessException("交卷时间不能早于仿真实训开始时间");
}
String answerTime = formatTime(startMillis) + "-" + formatTime(endMillis);
String duration = formatDuration(endMillis - startMillis);
int updated = baseMapper.publishPracticeStudent(candidate.getId(), score.doubleValue(),
startMillis, endMillis, answerTime, duration);
if (updated != 1) {
throw new BusinessException("仿真实训成绩发布状态已变化,请勿重复提交");
}
if (baseMapper.publishPracticeExam(exam.getId(), new Date()) != 1) {
throw new BusinessException("仿真实训考试发布失败,请稍后重试");
}
}
/** 正式发布后的接口只接受完全相同的网络重试,不允许静默篡改分数。 */
private void ensurePublishedReplay(List<FzGradesDTO> incoming,
Map<String, FzGradesEntity> storedByCode) {
for (FzGradesDTO item : incoming) {
FzGradesEntity existing = storedByCode.get(item.getCode());
if (existing == null || !sameBusinessContent(existing, item)) {
throw new BusinessException("仿真实训成绩已经发布,不能继续修改");
}
}
}
private boolean sameBusinessContent(FzGradesEntity left, FzGradesEntity right) {
return Objects.equals(left.getExamId(), right.getExamId())
&& Objects.equals(trim(left.getUserId()), trim(right.getUserId()))
&& Objects.equals(trim(left.getCode()), trim(right.getCode()))
&& Objects.equals(left.getLev(), right.getLev())
&& sameSecond(left.getStartTime(), right.getStartTime())
&& sameSecond(left.getSubmissionTime(), right.getSubmissionTime())
&& Objects.equals(left.getTitle(), right.getTitle())
&& Objects.equals(left.getType(), right.getType())
&& Objects.equals(left.getOptions(), right.getOptions())
&& Objects.equals(left.getMark(), right.getMark())
&& Objects.equals(left.getText(), right.getText())
&& Objects.equals(left.getResult(), right.getResult())
&& Objects.equals(left.getFile(), right.getFile())
&& Objects.equals(left.getScore(), right.getScore());
}
private boolean sameSecond(Date left, Date right) {
if (left == null || right == null) {
return left == right;
}
// MySQL DATETIME通常不保留毫秒,按秒比较可确保数据库回读后的合法重试仍然幂等。
return left.getTime() / 1000 == right.getTime() / 1000;
}
private Map<String, FzGradesEntity> indexByCode(List<FzGradesEntity> items) {
Map<String, FzGradesEntity> result = new LinkedHashMap<>();
if (items != null) {
for (FzGradesEntity item : items) {
result.put(item.getCode(), item);
}
}
return result;
}
/** 明确逐字段复制,禁止外部请求控制主键。 */
private FzGradesEntity copyForPersistence(FzGradesDTO source) {
FzGradesEntity target = new FzGradesEntity();
target.setExamId(source.getExamId());
target.setUserId(source.getUserId());
target.setCode(source.getCode());
target.setLev(source.getLev());
target.setStartTime(source.getStartTime());
target.setSubmissionTime(source.getSubmissionTime());
target.setTitle(source.getTitle());
target.setType(source.getType());
target.setOptions(source.getOptions());
target.setMark(source.getMark());
target.setText(source.getText());
target.setResult(source.getResult());
target.setFile(source.getFile());
target.setScore(source.getScore());
return target;
}
private void validateItem(FzGradesDTO item) {
if (item == null) {
throw new BusinessException("仿真实训成绩明细不能包含空项");
}
if (item.getExamId() == null || item.getExamId() <= 0) {
throw new BusinessException("考试ID必须为正整数");
}
if (trim(item.getUserId()) == null) {
throw new BusinessException("学员ID不能为空");
}
if (trim(item.getCode()) == null) {
throw new BusinessException("题目编号不能为空");
}
if (item.getScore() == null || item.getScore().isNaN()
|| item.getScore().isInfinite() || item.getScore() < 0) {
throw new BusinessException("题目得分必须是非负有限数值");
}
}
private boolean isPractice(String type) {
return type != null && (ExamAdminConstants.TYPE_PRACTICE.equals(type.trim())
|| "PRACTICE".equalsIgnoreCase(type.trim()));
}
private String trim(String value) {
return value == null || value.trim().isEmpty() ? null : value.trim();
}
private String formatTime(long millis) {
return new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date(millis));
}
private String formatDuration(long millis) {
long totalSeconds = Math.max(0, millis / 1000);
long hours = totalSeconds / 3600;
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
return saveBatch(BeanUtil.copyToList(fzGradesList, FzGradesEntity.class));
}
}
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