"src/main/java/com/ruzhoukj/sms/dao/ContractDao.java" did not exist on "7047e831fbdf9f6872edb72e1a9eee18c0226fab"
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 {
@ApiModelProperty("试卷总分")
private Double sum;
/**
* 试卷自身的及格分配置。
*
* <p>考试计划创建时会把该值复制到exam.pass_score形成快照,避免试卷后续调整影响
* 已经安排的考试。历史数据由增量SQL按总分的60%回填。</p>
*/
@ApiModelProperty("及格分")
@TableField("pass_score")
private Double passScore;
@ApiModelProperty("创建形式")
@TableField("create_type")
private String createType;
......@@ -51,4 +61,13 @@ public class TheoreticalPaperEntity {
@ApiModelProperty("顺序/乱序")
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;
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 io.swagger.annotations.ApiModelProperty;
......@@ -20,6 +18,21 @@ import java.util.List;
@Data
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("试卷详情列表")
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;
import com.platform.business.model.entity.TheoreticalPaperEntity;
import com.platform.business.model.vo.TheoreticalPaperVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
......@@ -18,4 +19,22 @@ import java.util.List;
public interface TheoreticalPaperMapper extends BaseMapper<TheoreticalPaperEntity> {
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);
}
......@@ -379,6 +379,8 @@
concat(coalesce(paper.num, 0), '题 · ', coalesce(paper.sum, 0), '分') as extra
from theoretical_paper paper
where paper.lev = #{levelName}
<!-- 只有已发布试卷可以继续安排新考试;NULL兼容尚未执行迁移的历史记录。 -->
and coalesce(paper.status, 'PUBLISHED') = 'PUBLISHED'
order by paper.create_time desc, paper.id desc
</select>
......
......@@ -31,4 +31,134 @@
order by
create_time desc
</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>
-- 管理员端“智能考评-理论试卷管理”增量数据库脚本(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