"git@gitlab.ruzhoukj.com:wujipeng/ops.git" did not exist on "ecd4e74339b0eff5b7314979db16a26fa8ce3e34"
Commit 6bae6649 authored by wujipeng's avatar wujipeng
Browse files

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

parent 6525db95
package com.platform.business.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 管理员自动组卷请求。
*
* <p>抽题数量和每题分值只读取服务端paper_distribution、paper_rule配置,客户端不能
* 自行扩大抽题范围或修改配分规则。</p>
*/
@Data
public class TheoreticalPaperAutoSaveDTO {
@ApiModelProperty("适用职级,同时用于查找组卷规则")
private String lev;
@ApiModelProperty("试卷名称")
private String name;
@ApiModelProperty("及格分;为空时按总分的60%计算")
private Double passScore;
@ApiModelProperty("顺序/乱序;默认顺序")
private String sequence;
@ApiModelProperty("保存状态:DRAFT/PUBLISHED,默认DRAFT")
private String status;
}
package com.platform.business.model.dto;
import com.platform.business.model.entity.TheoreticalPaperDetailEntity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* 管理员手动组卷或编辑试卷的请求体。
*
* <p>题量和总分不接收客户端计算结果,服务端始终根据questions重新汇总;题目中的id和
* paperId同样会被忽略,防止把其他试卷的明细关系带入当前试卷。</p>
*/
@Data
public class TheoreticalPaperManualSaveDTO {
@ApiModelProperty("适用职级,例如:污水三级")
private String lev;
@ApiModelProperty("试卷名称")
private String name;
@ApiModelProperty("及格分;为空时按总分的60%计算")
private Double passScore;
@ApiModelProperty("顺序/乱序;默认顺序")
private String sequence;
@ApiModelProperty("保存状态:DRAFT/PUBLISHED,默认DRAFT")
private String status;
@ApiModelProperty("试题列表,服务端按数组顺序重新生成题号")
private List<TheoreticalPaperDetailEntity> questions;
}
package com.platform.business.model.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/** 管理员修改试卷状态的最小请求体,避免整对象覆盖造成字段丢失。 */
@Data
public class TheoreticalPaperStatusDTO {
@ApiModelProperty("目标状态:DRAFT/PUBLISHED/ARCHIVED")
private String status;
}
...@@ -35,6 +35,16 @@ public class TheoreticalPaperEntity { ...@@ -35,6 +35,16 @@ public class TheoreticalPaperEntity {
@ApiModelProperty("试卷总分") @ApiModelProperty("试卷总分")
private Double sum; private Double sum;
/**
* 试卷自身的及格分配置。
*
* <p>考试计划创建时会把该值复制到exam.pass_score形成快照,避免试卷后续调整影响
* 已经安排的考试。历史数据由增量SQL按总分的60%回填。</p>
*/
@ApiModelProperty("及格分")
@TableField("pass_score")
private Double passScore;
@ApiModelProperty("创建形式") @ApiModelProperty("创建形式")
@TableField("create_type") @TableField("create_type")
private String createType; private String createType;
...@@ -51,4 +61,13 @@ public class TheoreticalPaperEntity { ...@@ -51,4 +61,13 @@ public class TheoreticalPaperEntity {
@ApiModelProperty("顺序/乱序") @ApiModelProperty("顺序/乱序")
private String sequence; private String sequence;
/** 状态使用稳定代码:DRAFT(草稿)、PUBLISHED(已发布)、ARCHIVED(已归档)。 */
@ApiModelProperty("试卷状态:DRAFT/PUBLISHED/ARCHIVED")
private String status;
@ApiModelProperty("最后更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
@TableField("update_time")
private Date updateTime;
} }
package com.platform.business.model.vo; package com.platform.business.model.vo;
import com.platform.business.model.entity.PaperDistributionEntity;
import com.platform.business.model.entity.PaperRuleEntity;
import com.platform.business.model.entity.TheoreticalPaperDetailEntity; import com.platform.business.model.entity.TheoreticalPaperDetailEntity;
import com.platform.business.model.entity.TheoreticalPaperEntity; import com.platform.business.model.entity.TheoreticalPaperEntity;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
...@@ -20,6 +18,21 @@ import java.util.List; ...@@ -20,6 +18,21 @@ import java.util.List;
@Data @Data
public class TheoreticalPaperVO extends TheoreticalPaperEntity { public class TheoreticalPaperVO extends TheoreticalPaperEntity {
@ApiModelProperty("题型汇总,按判断题/单选题/多选题/主观题顺序展示")
private String questionTypes;
@ApiModelProperty("被考试计划引用的次数")
private Integer usageCount;
@ApiModelProperty("状态中文名称")
private String statusLabel;
@ApiModelProperty("是否允许编辑;已被考试引用的试卷不可直接改题")
private Boolean editable;
@ApiModelProperty("是否允许删除;已发布或已被考试引用的试卷不可删除")
private Boolean deletable;
@ApiModelProperty("试卷详情列表") @ApiModelProperty("试卷详情列表")
private List<TheoreticalPaperDetailEntity> theoreticalPaperDetailList; private List<TheoreticalPaperDetailEntity> theoreticalPaperDetailList;
......
package com.platform.business.constant;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
/** 管理员理论试卷管理使用的状态、题型和容量边界。 */
public final class TheoreticalPaperAdminConstants {
public static final String STATUS_DRAFT = "DRAFT";
public static final String STATUS_PUBLISHED = "PUBLISHED";
public static final String STATUS_ARCHIVED = "ARCHIVED";
public static final String SEQUENCE_ORDERED = "顺序";
public static final String SEQUENCE_RANDOM = "乱序";
/** 单份试卷题量上限,防止错误配置导致一次抽取、复制过多数据。 */
public static final int MAX_QUESTION_COUNT = 500;
public static final Set<String> STATUSES = Collections.unmodifiableSet(
new LinkedHashSet<>(Arrays.asList(
STATUS_DRAFT, STATUS_PUBLISHED, STATUS_ARCHIVED)));
/** 当前考试和阅卷链路能够识别的题型;自动组卷只使用前三类客观题。 */
public static final Set<String> QUESTION_TYPES = Collections.unmodifiableSet(
new LinkedHashSet<>(Arrays.asList("判断题", "单选题", "多选题", "主观题")));
private TheoreticalPaperAdminConstants() {
}
}
package com.platform.business.controller;
import com.github.pagehelper.PageHelper;
import com.platform.business.model.dto.TheoreticalPaperAutoSaveDTO;
import com.platform.business.model.dto.TheoreticalPaperDTO;
import com.platform.business.model.dto.TheoreticalPaperManualSaveDTO;
import com.platform.business.model.dto.TheoreticalPaperStatusDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.CombinationVO;
import com.platform.business.model.vo.TheoreticalPaperVO;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TheoreticalPaperAdminService;
import com.platform.business.service.TheoreticalPaperService;
import com.platform.controller.BaseController;
import com.platform.model.resp.Result;
import com.platform.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 管理员端“智能考评-理论试卷管理”接口。
*
* <p>独立的admin路径保留旧版教师/通用试卷接口兼容性;本控制器的每个入口都先解析JWT
* 并校验管理员角色。创建人由登录态生成,客户端无法冒用其他管理员身份。</p>
*/
@Api(tags = "管理员端-理论试卷管理")
@RestController
@RequestMapping("/theoretical/paper/admin")
public class TheoreticalPaperAdminController extends BaseController {
@Resource
private TheoreticalPaperAdminService paperAdminService;
/** 复用经过多年使用的Word模板导出能力,写操作由新的管理端服务负责。 */
@Resource
private TheoreticalPaperService legacyPaperService;
@Resource
private AuthenticatedUserService authenticatedUserService;
@ApiOperation("试卷库分页,支持名称、职级、组卷方式和状态筛选")
@PostMapping("/page")
public TableDataInfo page(@RequestBody(required = false) TheoreticalPaperDTO query,
HttpServletRequest request) {
currentAdmin(request);
TheoreticalPaperDTO safeQuery = query == null ? new TheoreticalPaperDTO() : query;
normalizePage(safeQuery);
startPage(safeQuery.getPageNum(), safeQuery.getPageSize());
try {
return getDataTable(paperAdminService.page(safeQuery));
} finally {
// 服务层参数校验抛错时也必须清理ThreadLocal,防止容器复用线程后污染下一次请求。
PageHelper.clearPage();
}
}
@ApiOperation("查询自动组卷规则预览")
@GetMapping("/auto-configuration")
public Result<CombinationVO> autoConfiguration(@RequestParam("lev") String level,
HttpServletRequest request) {
currentAdmin(request);
return Result.data(paperAdminService.autoConfiguration(level));
}
@ApiOperation("按数据库组卷规则自动创建试卷")
@PostMapping("/auto")
public Result<TheoreticalPaperVO> createAutomatic(
@RequestBody TheoreticalPaperAutoSaveDTO body,
HttpServletRequest request) {
UserEntity administrator = currentAdmin(request);
return Result.data(paperAdminService.createAutomatic(body, displayName(administrator)));
}
@ApiOperation("手动组卷")
@PostMapping("/manual")
public Result<TheoreticalPaperVO> createManual(
@RequestBody TheoreticalPaperManualSaveDTO body,
HttpServletRequest request) {
UserEntity administrator = currentAdmin(request);
return Result.data(paperAdminService.createManual(body, displayName(administrator)));
}
@ApiOperation("试卷预览/编辑回显详情")
@GetMapping("/{paperId}")
public Result<TheoreticalPaperVO> detail(@PathVariable String paperId,
HttpServletRequest request) {
currentAdmin(request);
return Result.data(paperAdminService.detail(paperId));
}
@ApiOperation("编辑尚未被考试使用的试卷")
@PutMapping("/{paperId}")
public Result<TheoreticalPaperVO> update(@PathVariable String paperId,
@RequestBody TheoreticalPaperManualSaveDTO body,
HttpServletRequest request) {
currentAdmin(request);
return Result.data(paperAdminService.update(paperId, body));
}
@ApiOperation("复制试卷为新草稿")
@PostMapping("/{paperId}/copy")
public Result<TheoreticalPaperVO> copy(@PathVariable String paperId,
HttpServletRequest request) {
UserEntity administrator = currentAdmin(request);
return Result.data(paperAdminService.copy(paperId, displayName(administrator)));
}
@ApiOperation("发布、归档或退回草稿")
@PutMapping("/{paperId}/status")
public Result<TheoreticalPaperVO> changeStatus(@PathVariable String paperId,
@RequestBody TheoreticalPaperStatusDTO body,
HttpServletRequest request) {
currentAdmin(request);
return Result.data(paperAdminService.changeStatus(
paperId, body == null ? null : body.getStatus()));
}
@ApiOperation("删除未发布且未被考试使用的试卷")
@DeleteMapping("/{paperId}")
public Result<Boolean> delete(@PathVariable String paperId,
HttpServletRequest request) {
currentAdmin(request);
return Result.data(paperAdminService.delete(paperId));
}
@ApiOperation("导出无答案Word试卷")
@GetMapping("/{paperId}/export")
public void export(@PathVariable String paperId,
HttpServletRequest request,
HttpServletResponse response) {
currentAdmin(request);
// 先查管理端详情,确保不存在的ID得到统一业务错误,而不是旧导出逻辑空指针。
paperAdminService.detail(paperId);
legacyPaperService.export(paperId, response);
}
@ApiOperation("导出带答案Word试卷")
@GetMapping("/{paperId}/export/answer")
public void exportWithAnswer(@PathVariable String paperId,
HttpServletRequest request,
HttpServletResponse response) {
currentAdmin(request);
paperAdminService.detail(paperId);
legacyPaperService.exportWithAnswer(paperId, response);
}
/** 缺省第1页、每页10条,最大100条,避免管理员页面一次拉取过多题型聚合数据。 */
void normalizePage(TheoreticalPaperDTO query) {
int pageNum = query.getPageNum() == null || query.getPageNum() < 1 ? 1 : query.getPageNum();
int pageSize = query.getPageSize() == null || query.getPageSize() < 1
? 10 : Math.min(query.getPageSize(), 100);
query.setPageNum(pageNum);
query.setPageSize(pageSize);
}
/** 统一管理员鉴权,新增接口时只需复用本入口即可避免漏检。 */
private UserEntity currentAdmin(HttpServletRequest request) {
UserEntity administrator = authenticatedUserService.current(request);
authenticatedUserService.requireAdmin(administrator);
return administrator;
}
/** 创建人保存可读名称快照;旧账号字段不完整时逐级降级,保证永不为空。 */
private String displayName(UserEntity administrator) {
if (StringUtils.hasText(administrator.getNickName())) {
return administrator.getNickName().trim();
}
if (StringUtils.hasText(administrator.getUsername())) {
return administrator.getUsername().trim();
}
if (StringUtils.hasText(administrator.getPhoneNumber())) {
return administrator.getPhoneNumber().trim();
}
return administrator.getId();
}
}
...@@ -5,6 +5,7 @@ import com.platform.business.model.dto.TheoreticalPaperDTO; ...@@ -5,6 +5,7 @@ import com.platform.business.model.dto.TheoreticalPaperDTO;
import com.platform.business.model.entity.TheoreticalPaperEntity; import com.platform.business.model.entity.TheoreticalPaperEntity;
import com.platform.business.model.vo.TheoreticalPaperVO; import com.platform.business.model.vo.TheoreticalPaperVO;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
...@@ -18,4 +19,22 @@ import java.util.List; ...@@ -18,4 +19,22 @@ import java.util.List;
public interface TheoreticalPaperMapper extends BaseMapper<TheoreticalPaperEntity> { public interface TheoreticalPaperMapper extends BaseMapper<TheoreticalPaperEntity> {
List<TheoreticalPaperVO> pageData(TheoreticalPaperDTO theoreticalPaperDTO); List<TheoreticalPaperVO> pageData(TheoreticalPaperDTO theoreticalPaperDTO);
/** 管理端列表额外汇总题型和考试引用次数。 */
List<TheoreticalPaperVO> pageAdmin(TheoreticalPaperDTO query);
/** 查询管理端详情主记录;题目列表由独立查询加载,避免一对多结果重复主对象。 */
TheoreticalPaperVO selectAdminDetail(@Param("paperId") String paperId);
/** 按稳定题型顺序读取试题,复制、编辑和预览共用。 */
List<com.platform.business.model.entity.TheoreticalPaperDetailEntity> selectAdminQuestions(
@Param("paperId") String paperId);
/** 更新、复制、删除前锁定试卷主记录,避免并发操作互相覆盖。 */
TheoreticalPaperEntity lockAdminPaper(@Param("paperId") String paperId);
int countAdminDuplicateName(@Param("name") String name,
@Param("excludeId") String excludeId);
int countAdminUsage(@Param("paperId") String paperId);
} }
package com.platform.business.service;
import com.platform.business.model.dto.TheoreticalPaperAutoSaveDTO;
import com.platform.business.model.dto.TheoreticalPaperDTO;
import com.platform.business.model.dto.TheoreticalPaperManualSaveDTO;
import com.platform.business.model.vo.CombinationVO;
import com.platform.business.model.vo.TheoreticalPaperVO;
import java.util.List;
/** 管理员端“智能考评-理论试卷管理”完整业务接口。 */
public interface TheoreticalPaperAdminService {
List<TheoreticalPaperVO> page(TheoreticalPaperDTO query);
TheoreticalPaperVO detail(String paperId);
CombinationVO autoConfiguration(String level);
TheoreticalPaperVO createAutomatic(TheoreticalPaperAutoSaveDTO request, String creatorName);
TheoreticalPaperVO createManual(TheoreticalPaperManualSaveDTO request, String creatorName);
TheoreticalPaperVO update(String paperId, TheoreticalPaperManualSaveDTO request);
TheoreticalPaperVO copy(String paperId, String creatorName);
TheoreticalPaperVO changeStatus(String paperId, String status);
boolean delete(String paperId);
}
package com.platform.business.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.platform.business.constant.TheoreticalPaperAdminConstants;
import com.platform.business.mapper.TheoreticalPaperMapper;
import com.platform.business.model.dto.TheoreticalPaperAutoSaveDTO;
import com.platform.business.model.dto.TheoreticalPaperDTO;
import com.platform.business.model.dto.TheoreticalPaperManualSaveDTO;
import com.platform.business.model.entity.PaperDistributionEntity;
import com.platform.business.model.entity.PaperRuleEntity;
import com.platform.business.model.entity.TheoreticalPaperDetailEntity;
import com.platform.business.model.entity.TheoreticalPaperEntity;
import com.platform.business.model.vo.CombinationVO;
import com.platform.business.model.vo.TheoreticalPaperVO;
import com.platform.business.service.PaperDistributionService;
import com.platform.business.service.PaperRuleService;
import com.platform.business.service.TheoreticalLibraryService;
import com.platform.business.service.TheoreticalPaperAdminService;
import com.platform.business.service.TheoreticalPaperDetailService;
import com.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* 管理员理论试卷管理实现。
*
* <p>本服务与旧版通用试卷入口隔离:管理端写操作使用JWT中的管理员身份、服务端重新计算
* 题量与总分,并在更新/复制/删除前锁定主记录。这样既不改变学生考试链路,也不会继续
* 信任客户端提交的createUser、num或sum等可伪造字段。</p>
*/
@Service
public class TheoreticalPaperAdminServiceImpl implements TheoreticalPaperAdminService {
@Resource
private TheoreticalPaperMapper paperMapper;
@Resource
private TheoreticalPaperDetailService paperDetailService;
@Resource
private PaperDistributionService paperDistributionService;
@Resource
private PaperRuleService paperRuleService;
@Resource
private TheoreticalLibraryService theoreticalLibraryService;
@Override
@Transactional(readOnly = true)
public List<TheoreticalPaperVO> page(TheoreticalPaperDTO query) {
TheoreticalPaperDTO safeQuery = query == null ? new TheoreticalPaperDTO() : query;
safeQuery.setSearch(trimOptional(safeQuery.getSearch(), 100, "搜索关键字"));
safeQuery.setLev(trimOptional(safeQuery.getLev(), 64, "适用职级"));
safeQuery.setCreateType(trimOptional(safeQuery.getCreateType(), 32, "组卷方式"));
if (StringUtils.hasText(safeQuery.getStatus())) {
safeQuery.setStatus(normalizeStatus(safeQuery.getStatus()));
}
List<TheoreticalPaperVO> rows = paperMapper.pageAdmin(safeQuery);
if (rows == null) {
return Collections.emptyList();
}
for (TheoreticalPaperVO row : rows) {
decorate(row);
}
return rows;
}
@Override
@Transactional(readOnly = true)
public TheoreticalPaperVO detail(String paperId) {
requirePaperId(paperId);
TheoreticalPaperVO result = paperMapper.selectAdminDetail(paperId.trim());
if (result == null) {
throw new BusinessException("试卷不存在或已删除");
}
List<TheoreticalPaperDetailEntity> questions = paperMapper.selectAdminQuestions(paperId.trim());
result.setTheoreticalPaperDetailList(questions == null ? Collections.emptyList() : questions);
decorate(result);
return result;
}
@Override
@Transactional(readOnly = true)
public CombinationVO autoConfiguration(String level) {
String normalizedLevel = requireText(level, 64, "适用职级");
List<PaperDistributionEntity> distributions = paperDistributionService.list(
new LambdaQueryWrapper<PaperDistributionEntity>()
.eq(PaperDistributionEntity::getLev, normalizedLevel)
.orderByAsc(PaperDistributionEntity::getId));
List<PaperRuleEntity> rules = paperRuleService.list(
new LambdaQueryWrapper<PaperRuleEntity>()
.eq(PaperRuleEntity::getLev, normalizedLevel)
.orderByAsc(PaperRuleEntity::getId));
if (distributions == null || distributions.isEmpty()) {
throw new BusinessException("当前职级尚未配置抽题分布");
}
Map<String, Double> scoreRules = buildScoreRules(rules);
int judgmentCount = 0;
int singleCount = 0;
int multipleCount = 0;
BigDecimal totalScore = BigDecimal.ZERO;
for (PaperDistributionEntity distribution : distributions) {
int judgment = requireCount(distribution.getJudgmentCount(), "判断题抽题数量");
int single = requireCount(distribution.getSingleCount(), "单选题抽题数量");
int multiple = requireCount(distribution.getMoreCount(), "多选题抽题数量");
distribution.setSum(judgment + single + multiple);
BigDecimal subtotal = scoreSubtotal(scoreRules, "判断题", judgment)
.add(scoreSubtotal(scoreRules, "单选题", single))
.add(scoreSubtotal(scoreRules, "多选题", multiple));
distribution.setTotal(subtotal.doubleValue());
totalScore = totalScore.add(subtotal);
judgmentCount += judgment;
singleCount += single;
multipleCount += multiple;
}
int totalCount = judgmentCount + singleCount + multipleCount;
if (totalCount < 1 || totalCount > TheoreticalPaperAdminConstants.MAX_QUESTION_COUNT) {
throw new BusinessException("组卷规则题量必须在1到"
+ TheoreticalPaperAdminConstants.MAX_QUESTION_COUNT + "之间");
}
// 把各题型数量和小计写回响应规则,自动组卷确认弹窗可直接展示服务端口径。
for (PaperRuleEntity rule : rules) {
int count = "判断题".equals(rule.getType()) ? judgmentCount
: "单选题".equals(rule.getType()) ? singleCount
: "多选题".equals(rule.getType()) ? multipleCount : 0;
rule.setNum(count);
rule.setTotal(BigDecimal.valueOf(rule.getEachQuestion())
.multiply(BigDecimal.valueOf(count)).doubleValue());
}
CombinationVO result = new CombinationVO();
result.setNum(totalCount);
result.setSum(totalScore.setScale(2, RoundingMode.HALF_UP).doubleValue());
result.setPaperDistributionList(distributions);
result.setPaperRuleList(rules);
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public TheoreticalPaperVO createAutomatic(TheoreticalPaperAutoSaveDTO request,
String creatorName) {
if (request == null) {
throw new BusinessException("自动组卷信息不能为空");
}
String level = requireText(request.getLev(), 64, "适用职级");
String name = requireText(request.getName(), 200, "试卷名称");
String sequence = normalizeSequence(request.getSequence());
String status = normalizeCreateStatus(request.getStatus());
ensureUniqueName(name, null);
// 配置与实际抽题使用同一份数据库规则,避免页面打开后规则变化造成客户端旧数据组卷。
CombinationVO configuration = autoConfiguration(level);
Map<String, Double> scoreRules = buildScoreRules(configuration.getPaperRuleList());
List<TheoreticalPaperDetailEntity> questions = new ArrayList<>();
Set<String> uniqueness = new HashSet<>();
for (PaperDistributionEntity distribution : configuration.getPaperDistributionList()) {
appendRandomQuestions(questions, uniqueness, distribution, level, "判断题",
requireCount(distribution.getJudgmentCount(), "判断题抽题数量"), scoreRules);
appendRandomQuestions(questions, uniqueness, distribution, level, "单选题",
requireCount(distribution.getSingleCount(), "单选题抽题数量"), scoreRules);
appendRandomQuestions(questions, uniqueness, distribution, level, "多选题",
requireCount(distribution.getMoreCount(), "多选题抽题数量"), scoreRules);
}
if (questions.size() != configuration.getNum()) {
throw new BusinessException("题库可用题量不足,未能按组卷规则生成完整试卷");
}
PreparedQuestions prepared = prepareQuestions(questions);
BigDecimal passScore = normalizePassScore(request.getPassScore(), prepared.totalScore);
return createPaper(level, name, passScore, sequence, status, "自动组卷",
creatorName, prepared.questions, prepared.totalScore);
}
@Override
@Transactional(rollbackFor = Exception.class)
public TheoreticalPaperVO createManual(TheoreticalPaperManualSaveDTO request,
String creatorName) {
PreparedPaper prepared = prepareManualRequest(request, false);
ensureUniqueName(prepared.name, null);
return createPaper(prepared.level, prepared.name, prepared.passScore, prepared.sequence,
prepared.status, "手动组卷", creatorName, prepared.questions, prepared.totalScore);
}
@Override
@Transactional(rollbackFor = Exception.class)
public TheoreticalPaperVO update(String paperId, TheoreticalPaperManualSaveDTO request) {
TheoreticalPaperEntity existing = lockPaper(paperId);
if (paperMapper.countAdminUsage(existing.getId()) > 0) {
throw new BusinessException("试卷已被考试使用,请复制后再编辑");
}
PreparedPaper prepared = prepareManualRequest(request, true);
// 编辑表单若没有提交状态,保持原状态;防止只改题目时意外把已发布试卷退回草稿。
if (request == null || !StringUtils.hasText(request.getStatus())) {
prepared.status = existing.getStatus();
}
ensureUniqueName(prepared.name, existing.getId());
List<TheoreticalPaperDetailEntity> oldQuestions = paperMapper.selectAdminQuestions(existing.getId());
if (oldQuestions != null && !oldQuestions.isEmpty()) {
boolean removed = paperDetailService.remove(
new LambdaQueryWrapper<TheoreticalPaperDetailEntity>()
.eq(TheoreticalPaperDetailEntity::getPaperId, existing.getId()));
if (!removed) {
throw new BusinessException("原试题清理失败,请刷新后重试");
}
}
existing.setLev(prepared.level);
existing.setName(prepared.name);
existing.setNum(prepared.questions.size());
existing.setSum(prepared.totalScore.doubleValue());
existing.setPassScore(prepared.passScore.doubleValue());
existing.setSequence(prepared.sequence);
existing.setStatus(prepared.status);
existing.setUpdateTime(new Date());
if (paperMapper.updateById(existing) != 1) {
throw new BusinessException("试卷更新失败,请刷新后重试");
}
saveQuestions(existing.getId(), prepared.questions);
return detail(existing.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public TheoreticalPaperVO copy(String paperId, String creatorName) {
TheoreticalPaperEntity source = lockPaper(paperId);
List<TheoreticalPaperDetailEntity> sourceQuestions = paperMapper.selectAdminQuestions(source.getId());
PreparedQuestions prepared = prepareQuestions(sourceQuestions);
String copyName = nextCopyName(source.getName());
BigDecimal totalScore = prepared.totalScore;
BigDecimal passScore = normalizePassScore(source.getPassScore(), totalScore);
return createPaper(source.getLev(), copyName, passScore,
normalizeSequence(source.getSequence()), TheoreticalPaperAdminConstants.STATUS_DRAFT,
"复制组卷", creatorName, prepared.questions, totalScore);
}
@Override
@Transactional(rollbackFor = Exception.class)
public TheoreticalPaperVO changeStatus(String paperId, String status) {
TheoreticalPaperEntity existing = lockPaper(paperId);
String target = normalizeStatus(status);
if (target.equals(existing.getStatus())) {
return detail(existing.getId());
}
int usageCount = paperMapper.countAdminUsage(existing.getId());
if (TheoreticalPaperAdminConstants.STATUS_DRAFT.equals(target) && usageCount > 0) {
throw new BusinessException("已被考试使用的试卷不能退回草稿");
}
if (TheoreticalPaperAdminConstants.STATUS_PUBLISHED.equals(target)) {
List<TheoreticalPaperDetailEntity> questions = paperMapper.selectAdminQuestions(existing.getId());
if (questions == null || questions.isEmpty()) {
throw new BusinessException("空试卷不能发布");
}
BigDecimal total = questions.stream()
.map(question -> decimal(question.getScore(), "题目分值"))
.reduce(BigDecimal.ZERO, BigDecimal::add);
normalizePassScore(existing.getPassScore(), total);
}
existing.setStatus(target);
existing.setUpdateTime(new Date());
if (paperMapper.updateById(existing) != 1) {
throw new BusinessException("试卷状态更新失败,请刷新后重试");
}
return detail(existing.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean delete(String paperId) {
TheoreticalPaperEntity existing = lockPaper(paperId);
if (paperMapper.countAdminUsage(existing.getId()) > 0) {
throw new BusinessException("试卷已被考试使用,不能删除,可改为已归档");
}
if (TheoreticalPaperAdminConstants.STATUS_PUBLISHED.equals(existing.getStatus())) {
throw new BusinessException("已发布试卷不能直接删除,请先改为草稿或归档");
}
paperDetailService.remove(new LambdaQueryWrapper<TheoreticalPaperDetailEntity>()
.eq(TheoreticalPaperDetailEntity::getPaperId, existing.getId()));
if (paperMapper.deleteById(existing.getId()) != 1) {
throw new BusinessException("试卷删除失败,请刷新后重试");
}
return true;
}
/** 保存主表和题目明细;方法只接收已经过完整校验和重新计算的数据。 */
private TheoreticalPaperVO createPaper(String level, String name, BigDecimal passScore,
String sequence, String status, String createType,
String creatorName,
List<TheoreticalPaperDetailEntity> questions,
BigDecimal totalScore) {
TheoreticalPaperEntity paper = new TheoreticalPaperEntity();
paper.setLev(level);
paper.setName(name);
paper.setNum(questions.size());
paper.setSum(totalScore.setScale(2, RoundingMode.HALF_UP).doubleValue());
paper.setPassScore(passScore.setScale(2, RoundingMode.HALF_UP).doubleValue());
paper.setCreateType(createType);
paper.setCreateUser(requireText(creatorName, 100, "创建人"));
Date now = new Date();
paper.setCreateTime(now);
paper.setUpdateTime(now);
paper.setSequence(sequence);
paper.setStatus(status);
if (paperMapper.insert(paper) != 1 || !StringUtils.hasText(paper.getId())) {
throw new BusinessException("试卷创建失败,请稍后重试");
}
saveQuestions(paper.getId(), questions);
return detail(paper.getId());
}
/** 给明细设置服务端生成的试卷关系;saveBatch失败会触发外层事务整体回滚。 */
private void saveQuestions(String paperId, List<TheoreticalPaperDetailEntity> questions) {
for (TheoreticalPaperDetailEntity question : questions) {
question.setId(null);
question.setPaperId(paperId);
}
if (!paperDetailService.saveBatch(questions)) {
throw new BusinessException("试题明细保存失败,请稍后重试");
}
}
private PreparedPaper prepareManualRequest(TheoreticalPaperManualSaveDTO request,
boolean allowArchived) {
if (request == null) {
throw new BusinessException("试卷信息不能为空");
}
PreparedPaper result = new PreparedPaper();
result.level = requireText(request.getLev(), 64, "适用职级");
result.name = requireText(request.getName(), 200, "试卷名称");
result.sequence = normalizeSequence(request.getSequence());
result.status = allowArchived ? normalizeNullableStatus(request.getStatus())
: normalizeCreateStatus(request.getStatus());
PreparedQuestions preparedQuestions = prepareQuestions(request.getQuestions());
result.questions = preparedQuestions.questions;
result.totalScore = preparedQuestions.totalScore;
result.passScore = normalizePassScore(request.getPassScore(), result.totalScore);
return result;
}
/**
* 复制并校验客户端题目,彻底丢弃客户端id、paperId和题号。
* 这一步同时统一答案格式,保证考试自动判分时不会因中文分隔符产生误判。
*/
private PreparedQuestions prepareQuestions(List<TheoreticalPaperDetailEntity> source) {
if (source == null || source.isEmpty()) {
throw new BusinessException("试卷至少需要一道题");
}
if (source.size() > TheoreticalPaperAdminConstants.MAX_QUESTION_COUNT) {
throw new BusinessException("单份试卷最多"
+ TheoreticalPaperAdminConstants.MAX_QUESTION_COUNT + "道题");
}
List<TheoreticalPaperDetailEntity> result = new ArrayList<>(source.size());
Set<String> duplicateGuard = new HashSet<>();
BigDecimal totalScore = BigDecimal.ZERO;
for (int index = 0; index < source.size(); index++) {
TheoreticalPaperDetailEntity input = source.get(index);
if (input == null) {
throw new BusinessException("第" + (index + 1) + "道题不能为空");
}
String prefix = "第" + (index + 1) + "道题";
String type = requireText(input.getType(), 20, prefix + "题型");
if (!TheoreticalPaperAdminConstants.QUESTION_TYPES.contains(type)) {
throw new BusinessException(prefix + "题型只支持判断题、单选题、多选题或主观题");
}
String problem = requireText(input.getProblem(), 4000, prefix + "题干");
String answer = requireText(input.getAnswer(), 4000, prefix + "答案");
BigDecimal score = decimal(input.getScore(), prefix + "分值");
if (score.compareTo(BigDecimal.ZERO) <= 0 || score.compareTo(new BigDecimal("1000")) > 0) {
throw new BusinessException(prefix + "分值必须大于0且不超过1000");
}
if (!duplicateGuard.add(type + "\u0000" + problem)) {
throw new BusinessException("试卷中存在重复题目:" + problem);
}
TheoreticalPaperDetailEntity question = copyQuestion(input);
question.setType(type);
question.setProblem(problem);
question.setAnswer(normalizeAnswer(type, answer, input, prefix));
question.setScore(score.setScale(2, RoundingMode.HALF_UP).doubleValue());
question.setSequence(String.valueOf(index + 1));
question.setIsProblem(true);
result.add(question);
totalScore = totalScore.add(score);
}
if (totalScore.compareTo(new BigDecimal("100000")) > 0) {
throw new BusinessException("试卷总分不能超过100000分");
}
return new PreparedQuestions(result, totalScore.setScale(2, RoundingMode.HALF_UP));
}
/** 只复制业务字段,不复制任何主键或所属试卷ID。 */
private TheoreticalPaperDetailEntity copyQuestion(TheoreticalPaperDetailEntity source) {
TheoreticalPaperDetailEntity target = new TheoreticalPaperDetailEntity();
target.setScope(trimOptional(source.getScope(), 64, "题目范围"));
target.setLev(source.getLev());
target.setCode(trimOptional(source.getCode(), 100, "题目编号"));
target.setFirstLevelName(trimOptional(source.getFirstLevelName(), 255, "一级知识点"));
target.setSecondLevelName(trimOptional(source.getSecondLevelName(), 255, "二级知识点"));
target.setThirdLevelName(trimOptional(source.getThirdLevelName(), 255, "三级知识点"));
target.setFourthLevelName(trimOptional(source.getFourthLevelName(), 255, "四级知识点"));
target.setOptionA(trimOptional(source.getOptionA(), 2000, "选项A"));
target.setOptionB(trimOptional(source.getOptionB(), 2000, "选项B"));
target.setOptionC(trimOptional(source.getOptionC(), 2000, "选项C"));
target.setOptionD(trimOptional(source.getOptionD(), 2000, "选项D"));
target.setOptionE(trimOptional(source.getOptionE(), 2000, "选项E"));
return target;
}
private String normalizeAnswer(String type, String answer,
TheoreticalPaperDetailEntity question, String prefix) {
if ("单选题".equals(type)) {
String normalized = answer.toUpperCase(Locale.ROOT);
if (normalized.length() != 1 || "ABCDE".indexOf(normalized.charAt(0)) < 0
|| !hasOption(question, normalized.charAt(0))) {
throw new BusinessException(prefix + "答案必须是存在的单个选项字母");
}
requireObjectiveOptions(question, prefix);
return normalized;
}
if ("多选题".equals(type)) {
requireObjectiveOptions(question, prefix);
String normalized = answer.replaceAll("[,,、\\s]", "").toUpperCase(Locale.ROOT);
Set<Character> answers = new HashSet<>();
for (char item : normalized.toCharArray()) {
if ("ABCDE".indexOf(item) < 0 || !hasOption(question, item) || !answers.add(item)) {
throw new BusinessException(prefix + "多选答案必须由不重复的有效选项字母组成");
}
}
if (answers.size() < 2) {
throw new BusinessException(prefix + "多选答案至少包含两个选项");
}
StringBuilder ordered = new StringBuilder();
for (char item : "ABCDE".toCharArray()) {
if (answers.contains(item)) {
ordered.append(item);
}
}
return ordered.toString();
}
return answer;
}
private void requireObjectiveOptions(TheoreticalPaperDetailEntity question, String prefix) {
if (!StringUtils.hasText(question.getOptionA()) || !StringUtils.hasText(question.getOptionB())
|| !StringUtils.hasText(question.getOptionC())
|| !StringUtils.hasText(question.getOptionD())) {
throw new BusinessException(prefix + "必须完整填写A、B、C、D四个选项");
}
}
private boolean hasOption(TheoreticalPaperDetailEntity question, char option) {
switch (option) {
case 'A': return StringUtils.hasText(question.getOptionA());
case 'B': return StringUtils.hasText(question.getOptionB());
case 'C': return StringUtils.hasText(question.getOptionC());
case 'D': return StringUtils.hasText(question.getOptionD());
case 'E': return StringUtils.hasText(question.getOptionE());
default: return false;
}
}
private void appendRandomQuestions(List<TheoreticalPaperDetailEntity> target,
Set<String> uniqueness,
PaperDistributionEntity distribution,
String level, String type, int count,
Map<String, Double> scoreRules) {
if (count == 0) {
return;
}
String scope = StringUtils.hasText(distribution.getLev()) ? distribution.getLev() : level;
List<TheoreticalPaperDetailEntity> selected = theoreticalLibraryService.randomQuestions(
scope, type, count, distribution.getChapter(), distribution.getSection());
if (selected == null || selected.size() != count) {
throw new BusinessException("“" + distribution.getChapter() + "-"
+ distribution.getSection() + "”的" + type + "可用题量不足,需要" + count + "题");
}
for (TheoreticalPaperDetailEntity question : selected) {
String key = type + "\u0000" + (StringUtils.hasText(question.getCode())
? question.getCode().trim() : question.getProblem());
if (!uniqueness.add(key)) {
throw new BusinessException("组卷规则存在重叠,随机抽取到了重复题目,请调整规则后重试");
}
question.setScore(scoreOf(scoreRules, type).doubleValue());
target.add(question);
}
}
private Map<String, Double> buildScoreRules(List<PaperRuleEntity> rules) {
if (rules == null || rules.isEmpty()) {
throw new BusinessException("当前职级尚未配置配分规则");
}
Map<String, Double> result = new HashMap<>();
for (PaperRuleEntity rule : rules) {
if (rule == null || !StringUtils.hasText(rule.getType())) {
throw new BusinessException("配分规则存在空题型");
}
BigDecimal score = decimal(rule.getEachQuestion(), rule.getType() + "每题分值");
if (score.compareTo(BigDecimal.ZERO) <= 0 || score.compareTo(new BigDecimal("1000")) > 0) {
throw new BusinessException(rule.getType() + "每题分值必须大于0且不超过1000");
}
if (result.put(rule.getType(), score.doubleValue()) != null) {
throw new BusinessException("同一职级的" + rule.getType() + "配分规则不能重复");
}
}
return result;
}
/** 数量为0时不强制配置该题型分值;一旦需要抽题,则必须存在明确的配分规则。 */
private BigDecimal scoreSubtotal(Map<String, Double> scoreRules, String type, int count) {
return count == 0 ? BigDecimal.ZERO
: scoreOf(scoreRules, type).multiply(BigDecimal.valueOf(count));
}
private BigDecimal scoreOf(Map<String, Double> scoreRules, String type) {
Double score = scoreRules.get(type);
if (score == null) {
throw new BusinessException("当前职级缺少" + type + "配分规则");
}
return BigDecimal.valueOf(score);
}
private int requireCount(Integer value, String fieldName) {
int count = value == null ? 0 : value;
if (count < 0 || count > TheoreticalPaperAdminConstants.MAX_QUESTION_COUNT) {
throw new BusinessException(fieldName + "必须在0到"
+ TheoreticalPaperAdminConstants.MAX_QUESTION_COUNT + "之间");
}
return count;
}
private BigDecimal normalizePassScore(Double value, BigDecimal totalScore) {
BigDecimal passScore = value == null
? totalScore.multiply(new BigDecimal("0.60")).setScale(2, RoundingMode.HALF_UP)
: decimal(value, "及格分").setScale(2, RoundingMode.HALF_UP);
if (passScore.compareTo(BigDecimal.ZERO) < 0 || passScore.compareTo(totalScore) > 0) {
throw new BusinessException("及格分必须在0到试卷总分之间");
}
return passScore;
}
private BigDecimal decimal(Double value, String fieldName) {
if (value == null || value.isNaN() || value.isInfinite()) {
throw new BusinessException(fieldName + "不能为空且必须是有效数字");
}
return BigDecimal.valueOf(value);
}
private String normalizeSequence(String sequence) {
if (!StringUtils.hasText(sequence)) {
return TheoreticalPaperAdminConstants.SEQUENCE_ORDERED;
}
String normalized = sequence.trim();
if (!TheoreticalPaperAdminConstants.SEQUENCE_ORDERED.equals(normalized)
&& !TheoreticalPaperAdminConstants.SEQUENCE_RANDOM.equals(normalized)) {
throw new BusinessException("试题顺序只支持顺序或乱序");
}
return normalized;
}
private String normalizeCreateStatus(String status) {
String normalized = normalizeNullableStatus(status);
if (TheoreticalPaperAdminConstants.STATUS_ARCHIVED.equals(normalized)) {
throw new BusinessException("新建试卷不能直接保存为已归档");
}
return normalized;
}
private String normalizeNullableStatus(String status) {
return StringUtils.hasText(status) ? normalizeStatus(status)
: TheoreticalPaperAdminConstants.STATUS_DRAFT;
}
private String normalizeStatus(String status) {
if (!StringUtils.hasText(status)) {
throw new BusinessException("试卷状态不能为空");
}
String normalized = status.trim().toUpperCase(Locale.ROOT);
if (!TheoreticalPaperAdminConstants.STATUSES.contains(normalized)) {
throw new BusinessException("试卷状态只支持DRAFT、PUBLISHED或ARCHIVED");
}
return normalized;
}
private void ensureUniqueName(String name, String excludeId) {
if (paperMapper.countAdminDuplicateName(name, excludeId) > 0) {
throw new BusinessException("试卷名称已存在");
}
}
private TheoreticalPaperEntity lockPaper(String paperId) {
requirePaperId(paperId);
TheoreticalPaperEntity paper = paperMapper.lockAdminPaper(paperId.trim());
if (paper == null) {
throw new BusinessException("试卷不存在或已删除");
}
if (!StringUtils.hasText(paper.getStatus())) {
paper.setStatus(TheoreticalPaperAdminConstants.STATUS_PUBLISHED);
}
return paper;
}
private void requirePaperId(String paperId) {
requireText(paperId, 64, "试卷ID");
}
private String nextCopyName(String sourceName) {
String base = StringUtils.hasText(sourceName) ? sourceName.trim() : "未命名试卷";
for (int index = 1; index <= 99; index++) {
String suffix = index == 1 ? "(副本)" : "(副本" + index + ")";
String prefix = base.length() + suffix.length() <= 200
? base : base.substring(0, 200 - suffix.length());
String candidate = prefix + suffix;
if (paperMapper.countAdminDuplicateName(candidate, null) == 0) {
return candidate;
}
}
throw new BusinessException("同名试卷副本过多,请先重命名后再复制");
}
private void decorate(TheoreticalPaperVO paper) {
int usageCount = paper.getUsageCount() == null ? 0 : paper.getUsageCount();
String status = StringUtils.hasText(paper.getStatus())
? paper.getStatus() : TheoreticalPaperAdminConstants.STATUS_PUBLISHED;
paper.setStatus(status);
paper.setUsageCount(usageCount);
paper.setStatusLabel(statusLabel(status));
paper.setEditable(usageCount == 0);
paper.setDeletable(usageCount == 0
&& !TheoreticalPaperAdminConstants.STATUS_PUBLISHED.equals(status));
}
private String statusLabel(String status) {
if (TheoreticalPaperAdminConstants.STATUS_DRAFT.equals(status)) {
return "草稿";
}
if (TheoreticalPaperAdminConstants.STATUS_ARCHIVED.equals(status)) {
return "已归档";
}
return "已发布";
}
private String requireText(String value, int maxLength, String fieldName) {
if (!StringUtils.hasText(value)) {
throw new BusinessException(fieldName + "不能为空");
}
String normalized = value.trim();
if (normalized.length() > maxLength) {
throw new BusinessException(fieldName + "不能超过" + maxLength + "个字符");
}
return normalized;
}
private String trimOptional(String value, int maxLength, String fieldName) {
if (!StringUtils.hasText(value)) {
return null;
}
String normalized = value.trim();
if (normalized.length() > maxLength) {
throw new BusinessException(fieldName + "不能超过" + maxLength + "个字符");
}
return normalized;
}
private static final class PreparedQuestions {
private final List<TheoreticalPaperDetailEntity> questions;
private final BigDecimal totalScore;
private PreparedQuestions(List<TheoreticalPaperDetailEntity> questions,
BigDecimal totalScore) {
this.questions = questions;
this.totalScore = totalScore;
}
}
private static final class PreparedPaper {
private String level;
private String name;
private BigDecimal passScore;
private String sequence;
private String status;
private List<TheoreticalPaperDetailEntity> questions;
private BigDecimal totalScore;
}
}
...@@ -379,6 +379,8 @@ ...@@ -379,6 +379,8 @@
concat(coalesce(paper.num, 0), '题 · ', coalesce(paper.sum, 0), '分') as extra concat(coalesce(paper.num, 0), '题 · ', coalesce(paper.sum, 0), '分') as extra
from theoretical_paper paper from theoretical_paper paper
where paper.lev = #{levelName} where paper.lev = #{levelName}
<!-- 只有已发布试卷可以继续安排新考试;NULL兼容尚未执行迁移的历史记录。 -->
and coalesce(paper.status, 'PUBLISHED') = 'PUBLISHED'
order by paper.create_time desc, paper.id desc order by paper.create_time desc, paper.id desc
</select> </select>
......
...@@ -31,4 +31,134 @@ ...@@ -31,4 +31,134 @@
order by order by
create_time desc create_time desc
</select> </select>
<!--
管理端列表需要同时展示题型、真实题量和使用次数。先在派生表内分别聚合,避免
theoretical_paper_detail与exam直接联表时产生笛卡尔放大,导致题量和次数重复。
-->
<select id="pageAdmin" resultType="com.platform.business.model.vo.TheoreticalPaperVO">
select
paper.id,
paper.lev,
paper.name,
coalesce(question_summary.question_count, paper.num, 0) as num,
paper.sum,
paper.pass_score,
paper.create_type,
paper.create_user,
paper.create_time,
paper.sequence,
coalesce(paper.status, 'PUBLISHED') as status,
paper.update_time,
coalesce(question_summary.question_types, '') as question_types,
coalesce(exam_summary.usage_count, 0) as usage_count
from theoretical_paper paper
left join (
select
detail.paper_id,
count(*) as question_count,
group_concat(
distinct detail.type
order by field(detail.type, '判断题', '单选题', '多选题', '主观题')
separator '/'
) as question_types
from theoretical_paper_detail detail
group by detail.paper_id
) question_summary on question_summary.paper_id = paper.id
left join (
select exam.paper_id, count(*) as usage_count
from exam
where exam.paper_id is not null and exam.paper_id != ''
group by exam.paper_id
) exam_summary on exam_summary.paper_id = paper.id
<where>
<if test="lev != null and lev != ''">
and paper.lev = #{lev}
</if>
<if test="createType != null and createType != ''">
and paper.create_type = #{createType}
</if>
<if test="status != null and status != ''">
and coalesce(paper.status, 'PUBLISHED') = #{status}
</if>
<if test="search != null and search != ''">
and paper.name like concat('%', #{search}, '%')
</if>
</where>
order by coalesce(paper.update_time, paper.create_time) desc, paper.id desc
</select>
<select id="selectAdminDetail" resultType="com.platform.business.model.vo.TheoreticalPaperVO">
select
paper.id,
paper.lev,
paper.name,
coalesce(question_summary.question_count, paper.num, 0) as num,
paper.sum,
paper.pass_score,
paper.create_type,
paper.create_user,
paper.create_time,
paper.sequence,
coalesce(paper.status, 'PUBLISHED') as status,
paper.update_time,
coalesce(question_summary.question_types, '') as question_types,
coalesce(exam_summary.usage_count, 0) as usage_count
from theoretical_paper paper
left join (
select
detail.paper_id,
count(*) as question_count,
group_concat(
distinct detail.type
order by field(detail.type, '判断题', '单选题', '多选题', '主观题')
separator '/'
) as question_types
from theoretical_paper_detail detail
where detail.paper_id = #{paperId}
group by detail.paper_id
) question_summary on question_summary.paper_id = paper.id
left join (
select exam.paper_id, count(*) as usage_count
from exam
where exam.paper_id = #{paperId}
group by exam.paper_id
) exam_summary on exam_summary.paper_id = paper.id
where paper.id = #{paperId}
</select>
<select id="selectAdminQuestions"
resultType="com.platform.business.model.entity.TheoreticalPaperDetailEntity">
select
id, paper_id, scope, is_problem, lev, sequence, code,
first_level_name, second_level_name, third_level_name, fourth_level_name,
type, problem, answer, option_a, option_b, option_c, option_d, option_e, score
from theoretical_paper_detail
where paper_id = #{paperId}
order by field(type, '判断题', '单选题', '多选题', '主观题'),
cast(sequence as unsigned), sequence, id
</select>
<select id="lockAdminPaper"
resultType="com.platform.business.model.entity.TheoreticalPaperEntity">
select
id, lev, name, num, sum, pass_score, create_type, create_user,
create_time, sequence, coalesce(status, 'PUBLISHED') as status, update_time
from theoretical_paper
where id = #{paperId}
for update
</select>
<select id="countAdminDuplicateName" resultType="int">
select count(*)
from theoretical_paper
where name = #{name}
<if test="excludeId != null and excludeId != ''">
and id != #{excludeId}
</if>
</select>
<select id="countAdminUsage" resultType="int">
select count(*) from exam where paper_id = #{paperId}
</select>
</mapper> </mapper>
-- 管理员端“智能考评-理论试卷管理”增量数据库脚本(MySQL 5.7+/8.0)。
--
-- 设计说明:
-- 1. 复用现有theoretical_paper、theoretical_paper_detail和exam表,不复制业务数据。
-- 2. 新增及格分、发布状态和更新时间;历史试卷默认视为已发布,避免升级后从考试选项消失。
-- 3. 所有DDL先查询information_schema,可在开发、测试和生产环境重复执行。
-- 4. 沿用项目现状不新增外键;服务层在编辑、复制和删除事务中校验exam引用关系。
delimiter $$
drop procedure if exists migrate_theoretical_paper_management$$
create procedure migrate_theoretical_paper_management()
begin
if not exists (
select 1 from information_schema.columns
where table_schema = database()
and table_name = 'theoretical_paper'
and column_name = 'pass_score'
) then
alter table theoretical_paper
add column pass_score decimal(10,2) null comment '试卷及格分,安排考试时复制为快照' after sum;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema = database()
and table_name = 'theoretical_paper'
and column_name = 'status'
) then
alter table theoretical_paper
add column status varchar(20) null comment 'DRAFT/PUBLISHED/ARCHIVED' after sequence;
end if;
if not exists (
select 1 from information_schema.columns
where table_schema = database()
and table_name = 'theoretical_paper'
and column_name = 'update_time'
) then
alter table theoretical_paper
add column update_time datetime null comment '最后更新时间' after status;
end if;
-- 状态筛选和更新时间倒序是管理端试卷库的主查询路径。
if not exists (
select 1 from information_schema.statistics
where table_schema = database()
and table_name = 'theoretical_paper'
and index_name = 'idx_theoretical_paper_status_time'
) then
alter table theoretical_paper
add index idx_theoretical_paper_status_time (status, update_time, id);
end if;
if not exists (
select 1 from information_schema.statistics
where table_schema = database()
and table_name = 'theoretical_paper_detail'
and index_name = 'idx_theoretical_paper_detail_paper'
) then
alter table theoretical_paper_detail
add index idx_theoretical_paper_detail_paper (paper_id, type, sequence);
end if;
-- 使用次数、编辑和删除保护均按paper_id检查考试引用。
if not exists (
select 1 from information_schema.statistics
where table_schema = database()
and table_name = 'exam'
and index_name = 'idx_exam_paper'
) then
alter table exam add index idx_exam_paper (paper_id, id);
end if;
end$$
call migrate_theoretical_paper_management()$$
drop procedure if exists migrate_theoretical_paper_management$$
delimiter ;
-- 以题目明细为准修复旧主表题量和总分;没有明细的异常空试卷保持原值,留待人工处理。
update theoretical_paper paper
inner join (
select paper_id, count(*) as question_count, round(sum(coalesce(score, 0)), 2) as total_score
from theoretical_paper_detail
group by paper_id
) detail_summary on detail_summary.paper_id = paper.id
set paper.num = detail_summary.question_count,
paper.sum = detail_summary.total_score;
-- 历史试卷在新增状态字段前已经可以被安排考试,因此统一回填为已发布。
update theoretical_paper
set pass_score = coalesce(pass_score, round(coalesce(sum, 0) * 0.60, 2)),
status = coalesce(nullif(trim(status), ''), 'PUBLISHED'),
update_time = coalesce(update_time, create_time, now());
-- 只读核查:执行后若有结果,需要人工修复空试卷、非法状态或及格分配置。
select id, name, num, sum, pass_score, status
from theoretical_paper
where coalesce(num, 0) <= 0
or coalesce(sum, 0) <= 0
or pass_score < 0
or pass_score > sum
or status not in ('DRAFT', 'PUBLISHED', 'ARCHIVED');
# 管理员端理论试卷管理接口
页面路径为“管理员 → 智能考评 → 理论试卷管理”,接口统一使用
`/theoretical/paper/admin` 前缀。所有请求都必须携带 `Authorization`;服务端从JWT解析
用户并校验“管理员”角色,创建人、题量和总分不接受客户端指定。
部署前执行:
```text
practical-business/src/main/resources/sql/theoretical_paper_management.sql
```
状态代码为 `DRAFT`(草稿)、`PUBLISHED`(已发布)、`ARCHIVED`(已归档)。升级前的
历史试卷会回填为 `PUBLISHED`,只有已发布试卷会出现在新增考试的试卷下拉框中。
## 1. 试卷库分页
`POST /theoretical/paper/admin/page`
```json
{
"pageNum": 1,
"pageSize": 10,
"search": "污水一级",
"lev": "污水一级",
"createType": "自动组卷",
"status": "PUBLISHED"
}
```
返回项目统一 `TableDataInfo`。每行除主表字段外还包含:
- `questionTypes`:按“判断题/单选题/多选题/主观题”顺序汇总;
- `usageCount`:被考试计划引用的次数;
- `statusLabel`:状态中文名称;
- `editable`:没有考试引用时为 `true`;
- `deletable`:没有考试引用且不是已发布状态时为 `true`。
## 2. 预览和编辑回显
`GET /theoretical/paper/admin/{paperId}`
返回列表字段及 `theoreticalPaperDetailList` 完整题目。题目按题型和题号稳定排序。
## 3. 自动组卷
规则预览:
`GET /theoretical/paper/admin/auto-configuration?lev=污水三级`
返回 `paper_distribution` 抽题分布、`paper_rule` 每题配分、服务端计算的题量和总分。
确认创建:
`POST /theoretical/paper/admin/auto`
```json
{
"lev": "污水三级",
"name": "污水三级·理论大考卷",
"passScore": 60,
"sequence": "乱序",
"status": "DRAFT"
}
```
抽题分布和配分只读取提交瞬间的数据库配置。若任一章/节可用题量不足、规则重叠抽到
重复题、总题量超过500或配分不完整,整个事务回滚,不会留下空试卷。
## 4. 手动组卷
`POST /theoretical/paper/admin/manual`
```json
{
"lev": "污水一级",
"name": "污水一级·理论摸底卷 A",
"passScore": 60,
"sequence": "顺序",
"status": "PUBLISHED",
"questions": [
{
"type": "单选题",
"problem": "示例题干",
"optionA": "选项A",
"optionB": "选项B",
"optionC": "选项C",
"optionD": "选项D",
"answer": "A",
"score": 2
}
]
}
```
支持判断题、单选题、多选题、主观题。服务端忽略题目中的 `id`、`paperId`、`sequence`,
按数组顺序重新编号,并根据每题 `score` 计算 `num` 和 `sum`。及格分为空时默认为总分的
60%。同一张试卷不允许重复题目。
## 5. 编辑、复制与状态
- `PUT /theoretical/paper/admin/{paperId}`:请求体同手动组卷;未传 `status` 时保持原状态。
已被考试引用时禁止改题,页面应使用返回的 `editable` 控制按钮。
- `POST /theoretical/paper/admin/{paperId}/copy`:深复制主表和全部题目,名称自动追加
“(副本)”,新试卷固定为草稿且使用次数为0。
- `PUT /theoretical/paper/admin/{paperId}/status`:请求体为
`{"status":"ARCHIVED"}`。空试卷不能发布;已被使用的试卷不能退回草稿,但可以归档,
从而停止被新考试选择。
## 6. 删除和导出
- `DELETE /theoretical/paper/admin/{paperId}`:仅可删除未发布且未被考试使用的试卷;
主表与题目明细在同一事务中删除。
- `GET /theoretical/paper/admin/{paperId}/export`:导出无答案Word。
- `GET /theoretical/paper/admin/{paperId}/export/answer`:导出带答案Word。
导出继续复用项目现有职级Word模板。当前模板覆盖判断题、单选题和多选题;包含主观题的
试卷应以前端预览为准,若需要主观题Word版需另外补充对应职级模板占位区。
package com.platform.business.controller;
import com.platform.business.model.dto.TheoreticalPaperAutoSaveDTO;
import com.platform.business.model.dto.TheoreticalPaperDTO;
import com.platform.business.model.dto.TheoreticalPaperManualSaveDTO;
import com.platform.business.model.dto.TheoreticalPaperStatusDTO;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.service.AuthenticatedUserService;
import com.platform.business.service.TheoreticalPaperAdminService;
import com.platform.business.service.TheoreticalPaperService;
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.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 管理员理论试卷控制器的鉴权、身份快照和分页边界测试。 */
@ExtendWith(MockitoExtension.class)
class TheoreticalPaperAdminControllerTest {
@Mock
private TheoreticalPaperAdminService paperAdminService;
@Mock
private TheoreticalPaperService legacyPaperService;
@Mock
private AuthenticatedUserService authenticatedUserService;
private TheoreticalPaperAdminController controller;
@BeforeEach
void setUp() {
controller = new TheoreticalPaperAdminController();
ReflectionTestUtils.setField(controller, "paperAdminService", paperAdminService);
ReflectionTestUtils.setField(controller, "legacyPaperService", legacyPaperService);
ReflectionTestUtils.setField(controller, "authenticatedUserService", authenticatedUserService);
}
@Test
void everyEndpointShouldRequireAdminAndUseAuthenticatedCreator() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
UserEntity administrator = new UserEntity();
administrator.setNickName("管理员甲");
when(authenticatedUserService.current(request)).thenReturn(administrator);
when(paperAdminService.page(org.mockito.ArgumentMatchers.any()))
.thenReturn(Collections.emptyList());
TheoreticalPaperDTO query = new TheoreticalPaperDTO();
TheoreticalPaperAutoSaveDTO automatic = new TheoreticalPaperAutoSaveDTO();
TheoreticalPaperManualSaveDTO manual = new TheoreticalPaperManualSaveDTO();
TheoreticalPaperStatusDTO status = new TheoreticalPaperStatusDTO();
status.setStatus("ARCHIVED");
controller.page(query, request);
controller.autoConfiguration("污水一级", request);
controller.createAutomatic(automatic, request);
controller.createManual(manual, request);
controller.detail("paper-1", request);
controller.update("paper-1", manual, request);
controller.copy("paper-1", request);
controller.changeStatus("paper-1", status, request);
controller.delete("paper-1", request);
controller.export("paper-1", request, response);
controller.exportWithAnswer("paper-1", request, response);
verify(authenticatedUserService, times(11)).requireAdmin(administrator);
verify(paperAdminService).createAutomatic(automatic, "管理员甲");
verify(paperAdminService).createManual(manual, "管理员甲");
verify(paperAdminService).copy("paper-1", "管理员甲");
verify(paperAdminService).changeStatus("paper-1", "ARCHIVED");
verify(legacyPaperService).export("paper-1", response);
verify(legacyPaperService).exportWithAnswer("paper-1", response);
}
@Test
void pageShouldNormalizeUnsafePagination() {
TheoreticalPaperDTO query = new TheoreticalPaperDTO();
query.setPageNum(0);
query.setPageSize(1000);
controller.normalizePage(query);
assertEquals(1, query.getPageNum());
assertEquals(100, query.getPageSize());
}
@Test
void endpointShouldStopBeforeServiceWhenUserIsNotAdmin() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserEntity teacher = new UserEntity();
when(authenticatedUserService.current(request)).thenReturn(teacher);
doThrow(new BusinessException("只有管理员可以访问管理端接口"))
.when(authenticatedUserService).requireAdmin(teacher);
assertThrows(BusinessException.class, () -> controller.detail("paper-1", request));
}
}
package com.platform.business.mapper;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 在应用启动前验证管理员试卷聚合、锁定和引用检查SQL能够被MyBatis完整解析。 */
class TheoreticalPaperMapperXmlTest {
@Test
void mapperXmlShouldRegisterAdminStatements() throws Exception {
String resource = "com/platform/business/mapper/TheoreticalPaperMapper.xml";
Configuration configuration = new Configuration();
try (InputStream input = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder builder = new XMLMapperBuilder(
input, configuration, resource, configuration.getSqlFragments());
builder.parse();
}
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.TheoreticalPaperMapper.pageAdmin"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.TheoreticalPaperMapper.selectAdminDetail"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.TheoreticalPaperMapper.lockAdminPaper"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.TheoreticalPaperMapper.countAdminUsage"));
}
}
package com.platform.business.service.impl;
import com.platform.business.mapper.TheoreticalPaperMapper;
import com.platform.business.model.dto.TheoreticalPaperAutoSaveDTO;
import com.platform.business.model.dto.TheoreticalPaperManualSaveDTO;
import com.platform.business.model.entity.PaperDistributionEntity;
import com.platform.business.model.entity.PaperRuleEntity;
import com.platform.business.model.entity.TheoreticalPaperDetailEntity;
import com.platform.business.model.entity.TheoreticalPaperEntity;
import com.platform.business.model.vo.TheoreticalPaperVO;
import com.platform.business.service.PaperDistributionService;
import com.platform.business.service.PaperRuleService;
import com.platform.business.service.TheoreticalLibraryService;
import com.platform.business.service.TheoreticalPaperDetailService;
import com.platform.exception.BusinessException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 管理员理论试卷的服务端汇总、引用保护、复制和自动抽题失败回滚规则测试。 */
@ExtendWith(MockitoExtension.class)
class TheoreticalPaperAdminServiceImplTest {
@Mock
private TheoreticalPaperMapper paperMapper;
@Mock
private TheoreticalPaperDetailService paperDetailService;
@Mock
private PaperDistributionService paperDistributionService;
@Mock
private PaperRuleService paperRuleService;
@Mock
private TheoreticalLibraryService theoreticalLibraryService;
@InjectMocks
private TheoreticalPaperAdminServiceImpl service;
@Test
void manualCreateShouldRecalculateQuestionCountScoreAndCreator() {
TheoreticalPaperManualSaveDTO request = manualRequest("测试试卷");
when(paperMapper.countAdminDuplicateName("测试试卷", null)).thenReturn(0);
when(paperMapper.insert(any(TheoreticalPaperEntity.class))).thenAnswer(invocation -> {
TheoreticalPaperEntity paper = invocation.getArgument(0);
paper.setId("paper-new");
return 1;
});
when(paperDetailService.saveBatch(any())).thenReturn(true);
TheoreticalPaperVO saved = new TheoreticalPaperVO();
saved.setId("paper-new");
saved.setStatus("DRAFT");
when(paperMapper.selectAdminDetail("paper-new")).thenReturn(saved);
when(paperMapper.selectAdminQuestions("paper-new")).thenReturn(request.getQuestions());
TheoreticalPaperVO result = service.createManual(request, "管理员甲");
ArgumentCaptor<TheoreticalPaperEntity> paperCaptor =
ArgumentCaptor.forClass(TheoreticalPaperEntity.class);
verify(paperMapper).insert(paperCaptor.capture());
assertEquals(1, paperCaptor.getValue().getNum());
assertEquals(2.0D, paperCaptor.getValue().getSum());
assertEquals(1.2D, paperCaptor.getValue().getPassScore());
assertEquals("管理员甲", paperCaptor.getValue().getCreateUser());
assertEquals("DRAFT", paperCaptor.getValue().getStatus());
assertEquals("paper-new", result.getId());
}
@Test
void automaticCreateShouldRejectWhenQuestionBankIsInsufficient() {
TheoreticalPaperAutoSaveDTO request = new TheoreticalPaperAutoSaveDTO();
request.setLev("污水一级");
request.setName("自动卷");
PaperDistributionEntity distribution = new PaperDistributionEntity();
distribution.setLev("污水一级");
distribution.setChapter("第一章");
distribution.setSection("第一节");
distribution.setJudgmentCount(2);
distribution.setSingleCount(0);
distribution.setMoreCount(0);
PaperRuleEntity rule = new PaperRuleEntity();
rule.setType("判断题");
rule.setEachQuestion(1D);
when(paperDistributionService.list(any())).thenReturn(Collections.singletonList(distribution));
when(paperRuleService.list(any())).thenReturn(Collections.singletonList(rule));
when(paperMapper.countAdminDuplicateName("自动卷", null)).thenReturn(0);
when(theoreticalLibraryService.randomQuestions(anyString(), anyString(), any(), any(), any()))
.thenReturn(Collections.singletonList(judgmentQuestion()));
BusinessException error = assertThrows(BusinessException.class,
() -> service.createAutomatic(request, "管理员甲"));
assertTrue(error.getMessage().contains("可用题量不足"));
verify(paperMapper, never()).insert(any(TheoreticalPaperEntity.class));
}
@Test
void updateShouldRejectPaperAlreadyUsedByExam() {
TheoreticalPaperEntity existing = existingPaper("paper-1", "DRAFT");
when(paperMapper.lockAdminPaper("paper-1")).thenReturn(existing);
when(paperMapper.countAdminUsage("paper-1")).thenReturn(2);
BusinessException error = assertThrows(BusinessException.class,
() -> service.update("paper-1", manualRequest("修改后试卷")));
assertEquals("试卷已被考试使用,请复制后再编辑", error.getMessage());
verify(paperMapper, never()).updateById(any(TheoreticalPaperEntity.class));
}
@Test
void updateWithoutStatusShouldKeepExistingPublishedStatus() {
TheoreticalPaperEntity existing = existingPaper("paper-1", "PUBLISHED");
TheoreticalPaperManualSaveDTO request = manualRequest("修改后试卷");
request.setStatus(null);
when(paperMapper.lockAdminPaper("paper-1")).thenReturn(existing);
when(paperMapper.countAdminUsage("paper-1")).thenReturn(0);
when(paperMapper.countAdminDuplicateName("修改后试卷", "paper-1")).thenReturn(0);
when(paperMapper.selectAdminQuestions("paper-1"))
.thenReturn(Collections.singletonList(judgmentQuestion()));
when(paperDetailService.remove(any())).thenReturn(true);
when(paperMapper.updateById(any(TheoreticalPaperEntity.class))).thenReturn(1);
when(paperDetailService.saveBatch(any())).thenReturn(true);
TheoreticalPaperVO detail = new TheoreticalPaperVO();
detail.setId("paper-1");
detail.setStatus("PUBLISHED");
when(paperMapper.selectAdminDetail("paper-1")).thenReturn(detail);
service.update("paper-1", request);
ArgumentCaptor<TheoreticalPaperEntity> paperCaptor =
ArgumentCaptor.forClass(TheoreticalPaperEntity.class);
verify(paperMapper).updateById(paperCaptor.capture());
assertEquals("PUBLISHED", paperCaptor.getValue().getStatus());
}
@Test
void copyShouldCreateIndependentDraftQuestions() {
TheoreticalPaperEntity existing = existingPaper("paper-1", "PUBLISHED");
existing.setName("原试卷");
existing.setPassScore(1.2D);
when(paperMapper.lockAdminPaper("paper-1")).thenReturn(existing);
when(paperMapper.selectAdminQuestions("paper-1"))
.thenReturn(Collections.singletonList(judgmentQuestion()));
when(paperMapper.countAdminDuplicateName("原试卷(副本)", null)).thenReturn(0);
when(paperMapper.insert(any(TheoreticalPaperEntity.class))).thenAnswer(invocation -> {
TheoreticalPaperEntity paper = invocation.getArgument(0);
paper.setId("paper-copy");
return 1;
});
when(paperDetailService.saveBatch(any())).thenReturn(true);
TheoreticalPaperVO copied = new TheoreticalPaperVO();
copied.setId("paper-copy");
copied.setStatus("DRAFT");
when(paperMapper.selectAdminDetail("paper-copy")).thenReturn(copied);
when(paperMapper.selectAdminQuestions("paper-copy"))
.thenReturn(Collections.singletonList(judgmentQuestion()));
TheoreticalPaperVO result = service.copy("paper-1", "管理员甲");
ArgumentCaptor<TheoreticalPaperEntity> paperCaptor =
ArgumentCaptor.forClass(TheoreticalPaperEntity.class);
verify(paperMapper).insert(paperCaptor.capture());
assertEquals("原试卷(副本)", paperCaptor.getValue().getName());
assertEquals("DRAFT", paperCaptor.getValue().getStatus());
assertEquals("复制组卷", paperCaptor.getValue().getCreateType());
assertEquals("paper-copy", result.getId());
}
@Test
void deleteShouldRejectPublishedPaperAndAllowUnreferencedDraft() {
when(paperMapper.lockAdminPaper("published"))
.thenReturn(existingPaper("published", "PUBLISHED"));
when(paperMapper.countAdminUsage("published")).thenReturn(0);
assertThrows(BusinessException.class, () -> service.delete("published"));
when(paperMapper.lockAdminPaper("draft"))
.thenReturn(existingPaper("draft", "DRAFT"));
when(paperMapper.countAdminUsage("draft")).thenReturn(0);
when(paperMapper.deleteById("draft")).thenReturn(1);
assertTrue(service.delete("draft"));
verify(paperMapper).deleteById("draft");
}
@Test
void detailShouldExposeSafeActionFlags() {
TheoreticalPaperVO detail = new TheoreticalPaperVO();
detail.setId("paper-1");
detail.setStatus("PUBLISHED");
detail.setUsageCount(3);
when(paperMapper.selectAdminDetail("paper-1")).thenReturn(detail);
when(paperMapper.selectAdminQuestions("paper-1")).thenReturn(Collections.emptyList());
TheoreticalPaperVO result = service.detail("paper-1");
assertEquals("已发布", result.getStatusLabel());
assertFalse(result.getEditable());
assertFalse(result.getDeletable());
}
private TheoreticalPaperManualSaveDTO manualRequest(String name) {
TheoreticalPaperManualSaveDTO request = new TheoreticalPaperManualSaveDTO();
request.setLev("污水一级");
request.setName(name);
request.setSequence("顺序");
request.setStatus("DRAFT");
request.setQuestions(Collections.singletonList(judgmentQuestion()));
return request;
}
private TheoreticalPaperDetailEntity judgmentQuestion() {
TheoreticalPaperDetailEntity question = new TheoreticalPaperDetailEntity();
question.setType("判断题");
question.setProblem("示例判断题");
question.setAnswer("正确");
question.setScore(2D);
return question;
}
private TheoreticalPaperEntity existingPaper(String id, String status) {
TheoreticalPaperEntity paper = new TheoreticalPaperEntity();
paper.setId(id);
paper.setLev("污水一级");
paper.setName("原试卷");
paper.setSequence("顺序");
paper.setStatus(status);
paper.setSum(2D);
return paper;
}
}
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