Commit 74d345cb authored by wujipeng's avatar wujipeng
Browse files

bug修复

parent b18b0873
...@@ -8,17 +8,6 @@ import lombok.EqualsAndHashCode; ...@@ -8,17 +8,6 @@ import lombok.EqualsAndHashCode;
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public class StudentLevelCertDTO extends StudentLevelCertEntity { public class StudentLevelCertDTO extends StudentLevelCertEntity {
/**
* 证书列表的统一搜索关键字。
*
* <p>该字段不能复用父类的 {@code name}:{@code name} 对应证书表自身的名称列,
* 而管理端搜索框传递的是 {@code keyword}。显式声明后,Jackson 才会保留前端提交的
* 参数,MyBatis 也才能据此拼接姓名、身份证号和证书编号的模糊查询条件。</p>
*/
@ApiModelProperty("姓名、身份证号或证书编号关键字,支持模糊查询")
private String keyword;
private int pageNum; private int pageNum;
private int pageSize; private int pageSize;
} }
...@@ -86,10 +86,6 @@ public class ExamEntity { ...@@ -86,10 +86,6 @@ public class ExamEntity {
@TableField("update_time") @TableField("update_time")
private Date updateTime; private Date updateTime;
@ApiModelProperty(value = "考试状态")
@TableField(exist = false)
private Boolean status;
/** /**
* 阅卷发布标记。 * 阅卷发布标记。
* *
......
package com.platform.business.model.vo;
import com.platform.page.TableDataInfo;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 考试分页响应。
*
* <p>继承公共分页响应以原样保留code、total和rows字段,仅增加顶部汇总数据,
* 因此已有前端分页逻辑无需调整。</p>
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class ExamPageVO extends TableDataInfo {
private static final long serialVersionUID = 1L;
/** 不随列表筛选条件变化的考试全局汇总。 */
private ExamSummaryVO summary;
}
package com.platform.business.model.vo;
import lombok.Data;
/**
* 考试管理列表顶部的全局汇总。
*
* <p>四项数据统计全部考试,不受分页、考试名称、类型、等级或班级筛选影响。</p>
*/
@Data
public class ExamSummaryVO {
/** 全部考试数量。 */
private Long totalCount;
/** 当前时间早于考试开始时间的考试数量。 */
private Long notStartedCount;
/** 已到开始时间但尚未到结束时间的考试数量。 */
private Long ongoingCount;
/** 已到结束时间以及时间配置异常的历史考试数量。 */
private Long endedCount;
}
...@@ -19,4 +19,12 @@ public class ExamVO extends ExamEntity { ...@@ -19,4 +19,12 @@ public class ExamVO extends ExamEntity {
private List<ExamStudentVO> examStudentList; private List<ExamStudentVO> examStudentList;
private String score; private String score;
/**
* 根据考试开始时间和时长实时计算的中文状态。
*
* <p>状态不保存到exam表,避免定时更新带来的临界时刻不一致。当前稳定取值为
* “未开始”“进行中”“已结束”。</p>
*/
private String status;
} }
...@@ -10,6 +10,8 @@ import java.math.BigDecimal; ...@@ -10,6 +10,8 @@ import java.math.BigDecimal;
public class ScoreAdminQuestionStatisticsVO { public class ScoreAdminQuestionStatisticsVO {
private String questionCode; private String questionCode;
@ApiModelProperty("理论题在当前试卷中从1开始的连续题号;实训题使用questionCode")
private String sequence; private String sequence;
private String questionType; private String questionType;
private String title; private String title;
......
package com.platform.business.controller; package com.platform.business.controller;
import com.platform.business.model.dto.ExamDTO; import com.platform.business.model.dto.ExamDTO;
import com.platform.business.model.vo.ExamPageVO;
import com.platform.business.model.vo.ExamStudentVO; import com.platform.business.model.vo.ExamStudentVO;
import com.platform.business.model.vo.ExamSummaryVO;
import com.platform.business.model.vo.ExamVO; import com.platform.business.model.vo.ExamVO;
import com.platform.business.service.ExamService; import com.platform.business.service.ExamService;
import com.platform.business.service.ExamStudentService; import com.platform.business.service.ExamStudentService;
...@@ -12,6 +14,8 @@ import io.swagger.annotations.ApiOperation; ...@@ -12,6 +14,8 @@ import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.List;
@RestController @RestController
@RequestMapping("/exam") @RequestMapping("/exam")
public class ExamController extends BaseController { public class ExamController extends BaseController {
...@@ -21,10 +25,24 @@ public class ExamController extends BaseController { ...@@ -21,10 +25,24 @@ public class ExamController extends BaseController {
@Resource @Resource
private ExamStudentService examStudentService; private ExamStudentService examStudentService;
@ApiOperation(value = "考试分页列表及顶部全局汇总")
@PostMapping("/page") @PostMapping("/page")
public TableDataInfo page(@RequestBody ExamDTO examDTO) { public ExamPageVO page(@RequestBody ExamDTO examDTO) {
startPage(examDTO.getPageNum(), examDTO.getPageSize()); startPage(examDTO.getPageNum(), examDTO.getPageSize());
return getDataTable(examService.queryList(examDTO)); List<ExamVO> rows = examService.queryList(examDTO);
TableDataInfo page = getDataTable(rows);
/*
* 公共TableDataInfo只提供code、total和rows。这里复制原分页字段后附加summary,
* 可以保持旧版前端对分页响应的读取方式,同时让顶部四张卡片只发起一次请求。
*/
ExamPageVO response = new ExamPageVO();
response.setCode(page.getCode());
response.setTotal(page.getTotal());
response.setRows(page.getRows());
ExamSummaryVO summary = examService.summary();
response.setSummary(summary);
return response;
} }
@PostMapping("/save") @PostMapping("/save")
......
...@@ -8,6 +8,7 @@ import com.platform.business.model.vo.ExamAdminClassVO; ...@@ -8,6 +8,7 @@ import com.platform.business.model.vo.ExamAdminClassVO;
import com.platform.business.model.vo.ExamAdminDetailVO; import com.platform.business.model.vo.ExamAdminDetailVO;
import com.platform.business.model.vo.ExamAdminStudentOptionVO; import com.platform.business.model.vo.ExamAdminStudentOptionVO;
import com.platform.business.model.vo.ExamStudentVO; import com.platform.business.model.vo.ExamStudentVO;
import com.platform.business.model.vo.ExamSummaryVO;
import com.platform.business.model.vo.ExamVO; import com.platform.business.model.vo.ExamVO;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
...@@ -20,6 +21,11 @@ public interface ExamMapper extends BaseMapper<ExamEntity> { ...@@ -20,6 +21,11 @@ public interface ExamMapper extends BaseMapper<ExamEntity> {
List<ExamVO> queryList(ExamDTO examDTO); List<ExamVO> queryList(ExamDTO examDTO);
/**
* 按指定业务时刻统计全部考试的三态数量,不应用分页列表的任何筛选条件。
*/
ExamSummaryVO summary(@Param("now") Date now);
ExamVO getInfoById(int id); ExamVO getInfoById(int id);
List<ExamVO> queryListGroupByClass(ExamDTO examDTO); List<ExamVO> queryListGroupByClass(ExamDTO examDTO);
......
...@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.service.IService; ...@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
import com.platform.business.model.dto.ExamDTO; import com.platform.business.model.dto.ExamDTO;
import com.platform.business.model.entity.ExamEntity; import com.platform.business.model.entity.ExamEntity;
import com.platform.business.model.vo.ExamStudentVO; import com.platform.business.model.vo.ExamStudentVO;
import com.platform.business.model.vo.ExamSummaryVO;
import com.platform.business.model.vo.ExamVO; import com.platform.business.model.vo.ExamVO;
import java.util.List; import java.util.List;
...@@ -11,6 +12,9 @@ import java.util.List; ...@@ -11,6 +12,9 @@ import java.util.List;
public interface ExamService extends IService<ExamEntity> { public interface ExamService extends IService<ExamEntity> {
List<ExamVO> queryList(ExamDTO examDTO); List<ExamVO> queryList(ExamDTO examDTO);
/** 返回不受列表筛选和分页影响的考试全局汇总。 */
ExamSummaryVO summary();
boolean saveOrUpdateExam(ExamDTO examDTO); boolean saveOrUpdateExam(ExamDTO examDTO);
ExamVO detail(int id); ExamVO detail(int id);
......
...@@ -11,6 +11,7 @@ import com.platform.business.model.entity.ExamStudentEntity; ...@@ -11,6 +11,7 @@ import com.platform.business.model.entity.ExamStudentEntity;
import com.platform.business.model.entity.SysLevelEntity; import com.platform.business.model.entity.SysLevelEntity;
import com.platform.business.model.entity.UserEntity; import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.ExamStudentVO; import com.platform.business.model.vo.ExamStudentVO;
import com.platform.business.model.vo.ExamSummaryVO;
import com.platform.business.model.vo.ExamVO; import com.platform.business.model.vo.ExamVO;
import com.platform.business.service.ExamService; import com.platform.business.service.ExamService;
import com.platform.business.service.ExamStudentService; import com.platform.business.service.ExamStudentService;
...@@ -23,9 +24,14 @@ import org.springframework.transaction.annotation.Transactional; ...@@ -23,9 +24,14 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.StringJoiner; import java.util.StringJoiner;
import static com.platform.business.constant.ExamAdminConstants.BUSINESS_ZONE;
/** /**
* 通用及历史后台考试服务。 * 通用及历史后台考试服务。
* *
...@@ -46,7 +52,35 @@ public class ExamServiceImpl extends ServiceImpl<ExamMapper, ExamEntity> impleme ...@@ -46,7 +52,35 @@ public class ExamServiceImpl extends ServiceImpl<ExamMapper, ExamEntity> impleme
@Override @Override
public List<ExamVO> queryList(ExamDTO examDTO) { public List<ExamVO> queryList(ExamDTO examDTO) {
return baseMapper.queryList(examDTO); List<ExamVO> rows = baseMapper.queryList(examDTO);
if (rows == null || rows.isEmpty()) {
return rows == null ? Collections.emptyList() : rows;
}
/*
* 一次分页查询中的所有记录必须共享同一个时间快照。若在循环内重复取当前时间,
* 位于开考或结束临界点的两条相同场次可能得到不同状态,导致列表和顶部统计难以理解。
*/
Date now = businessNow();
for (ExamVO row : rows) {
applyStatus(row, now);
}
return rows;
}
@Override
public ExamSummaryVO summary() {
ExamSummaryVO summary = baseMapper.summary(businessNow());
if (summary == null) {
summary = new ExamSummaryVO();
}
// 聚合函数在空表或兼容数据库中可能返回null;对外统一返回数字0,避免顶部展示“—”。
summary.setTotalCount(zeroIfNull(summary.getTotalCount()));
summary.setNotStartedCount(zeroIfNull(summary.getNotStartedCount()));
summary.setOngoingCount(zeroIfNull(summary.getOngoingCount()));
summary.setEndedCount(zeroIfNull(summary.getEndedCount()));
return summary;
} }
@Override @Override
...@@ -113,4 +147,39 @@ public class ExamServiceImpl extends ServiceImpl<ExamMapper, ExamEntity> impleme ...@@ -113,4 +147,39 @@ public class ExamServiceImpl extends ServiceImpl<ExamMapper, ExamEntity> impleme
public List<ExamVO> queryByClassId(Integer classId) { public List<ExamVO> queryByClassId(Integer classId) {
return baseMapper.queryByClassId(classId); return baseMapper.queryByClassId(classId);
} }
/**
* 按管理员考试管理已经采用的边界计算中文三态。
*
* <p>开始时刻计入“进行中”,结束时刻计入“已结束”。历史脏数据若缺少开始时间,
* 无法判定其仍可参加,按已结束处理;空时长或负时长按0分钟处理。</p>
*/
void applyStatus(ExamVO exam, Date now) {
if (exam == null) {
return;
}
Date examTime = exam.getExamTime();
if (examTime == null) {
exam.setStatus("已结束");
return;
}
if (now.before(examTime)) {
exam.setStatus("未开始");
return;
}
long durationMinutes = exam.getDuration() == null
? 0L : Math.max(0L, exam.getDuration().longValue());
long endTime = examTime.getTime() + durationMinutes * 60_000L;
exam.setStatus(now.getTime() < endTime ? "进行中" : "已结束");
}
/** 使用项目约定的Asia/Shanghai业务时区生成状态计算时刻,便于测试覆盖边界。 */
Date businessNow() {
return Date.from(ZonedDateTime.now(BUSINESS_ZONE).toInstant());
}
private long zeroIfNull(Long value) {
return value == null ? 0L : value;
}
} }
...@@ -161,10 +161,35 @@ public class ScoreAdminServiceImpl implements ScoreAdminService { ...@@ -161,10 +161,35 @@ public class ScoreAdminServiceImpl implements ScoreAdminService {
if (!Boolean.TRUE.equals(exam.getPublished())) { if (!Boolean.TRUE.equals(exam.getPublished())) {
throw new BusinessException("本场考试成绩尚未正式发布,不能查看题目统计"); throw new BusinessException("本场考试成绩尚未正式发布,不能查看题目统计");
} }
List<ScoreAdminQuestionStatisticsVO> result = isPractice(exam.getExamType()) boolean practiceExam = isPractice(exam.getExamType());
List<ScoreAdminQuestionStatisticsVO> result = practiceExam
? scoreAdminMapper.queryPracticeStatistics(examId) ? scoreAdminMapper.queryPracticeStatistics(examId)
: scoreAdminMapper.queryTheoryStatistics(examId); : scoreAdminMapper.queryTheoryStatistics(examId);
return result == null ? Collections.emptyList() : result; if (result == null || result.isEmpty()) {
return Collections.emptyList();
}
// 仿真实训项目使用外部系统上报的questionCode标识,不能被理论题的展示序号覆盖。
if (!practiceExam) {
fillTheoryQuestionSequences(result);
}
return result;
}
/**
* 按统计查询已确定的顺序生成从1开始的全卷题号。
*
* <p>新试卷明细通常已保存连续sequence,但历史试卷可能从题库复制到null、
* 空字符串或非数字序号。统计列表的“题号”语义是当前全卷顺序,因此在返回边界
* 统一重编号,既保证前端始终收到非空值,也避免为了展示修复去改写历史作答数据。</p>
*/
private void fillTheoryQuestionSequences(List<ScoreAdminQuestionStatisticsVO> statistics) {
for (int index = 0; index < statistics.size(); index++) {
ScoreAdminQuestionStatisticsVO question = statistics.get(index);
if (question != null) {
question.setSequence(String.valueOf(index + 1));
}
}
} }
@Override @Override
......
...@@ -39,14 +39,6 @@ public class StudentLevelCertServiceImpl extends ServiceImpl<StudentLevelCertMap ...@@ -39,14 +39,6 @@ public class StudentLevelCertServiceImpl extends ServiceImpl<StudentLevelCertMap
@Override @Override
public List<StudentLevelCertVO> queryList(StudentLevelCertDTO studentLevelCertDTO) { public List<StudentLevelCertVO> queryList(StudentLevelCertDTO studentLevelCertDTO) {
/*
* 去除搜索框输入首尾的无效空白,保证“ 王 ”与“王”生成相同的LIKE条件。
* 空白字符串转换为null后,Mapper不会附加搜索条件,行为与未输入关键字一致。
*/
if (studentLevelCertDTO != null) {
String keyword = studentLevelCertDTO.getKeyword();
studentLevelCertDTO.setKeyword(StringUtils.isEmpty(keyword) ? null : trimToNull(keyword));
}
return baseMapper.queryList(studentLevelCertDTO); return baseMapper.queryList(studentLevelCertDTO);
} }
......
...@@ -18,16 +18,31 @@ ...@@ -18,16 +18,31 @@
left join role r on r.id = ur.role_id left join role r on r.id = ur.role_id
</sql> </sql>
<!--
account_status是学员和教职工共用的历史字段,旧数据可能残留另一类账户的状态值。
必须先按当前页签的账户类型校验状态白名单,不能只判断字段是否为空:例如教师记录
若残留STUDYING,直接返回会让列表和Excel把教师展示为“在读”。合法历史值先清理
首尾空格并统一为大写;非法或未知状态回退到旧字段推导结果,既不修改存量数据,
也能让列表、状态筛选和导出保持同一口径。
-->
<sql id="statusExpression"> <sql id="statusExpression">
case case
when #{query.accountType} = 'STUDENT' then coalesce( when #{query.accountType} = 'STUDENT' then
nullif(u.account_status, ''), case
case when coalesce(u.del_flag, 0) = 1 then 'ARCHIVED' when upper(trim(u.account_status))
in ('PENDING', 'STUDYING', 'GRADUATED', 'ARCHIVED')
then upper(trim(u.account_status))
when coalesce(u.del_flag, 0) = 1 then 'ARCHIVED'
when coalesce(u.first_login_flag, 1) = 1 then 'PENDING' when coalesce(u.first_login_flag, 1) = 1 then 'PENDING'
else 'STUDYING' end) else 'STUDYING'
else coalesce( end
nullif(u.account_status, ''), else
case when coalesce(u.del_flag, 0) = 1 then 'DISABLED' else 'ENABLED' end) case
when upper(trim(u.account_status)) in ('ENABLED', 'DISABLED')
then upper(trim(u.account_status))
when coalesce(u.del_flag, 0) = 1 then 'DISABLED'
else 'ENABLED'
end
end end
</sql> </sql>
......
...@@ -12,7 +12,8 @@ ...@@ -12,7 +12,8 @@
c.name className, c.name className,
sys_level.name level, sys_level.name level,
e.class_id, e.class_id,
e.type e.type,
e.duration
from from
exam e exam e
left join left join
...@@ -38,6 +39,28 @@ ...@@ -38,6 +39,28 @@
STR_TO_DATE(SUBSTRING_INDEX(exam_time, '-', 1), '%Y.%m.%d %H:%i:%s') DESC STR_TO_DATE(SUBSTRING_INDEX(exam_time, '-', 1), '%Y.%m.%d %H:%i:%s') DESC
</select> </select>
<!--
顶部卡片是全局KPI,因此本查询不能复用queryList中的名称、类型、等级或班级筛选。
三态边界与服务层保持一致:开始时刻进入进行中,结束时刻进入已结束;缺失开始时间、
空时长和负时长均按不可继续参加的已结束记录兼容处理。
-->
<select id="summary" resultType="com.platform.business.model.vo.ExamSummaryVO">
select count(*) as totalCount,
coalesce(sum(case
when e.exam_time is not null and e.exam_time &gt; #{now}
then 1 else 0 end), 0) as notStartedCount,
coalesce(sum(case
when e.exam_time is not null
and e.exam_time &lt;= #{now}
and timestampadd(minute, greatest(coalesce(e.duration, 0), 0), e.exam_time) &gt; #{now}
then 1 else 0 end), 0) as ongoingCount,
coalesce(sum(case
when e.exam_time is null
or timestampadd(minute, greatest(coalesce(e.duration, 0), 0), e.exam_time) &lt;= #{now}
then 1 else 0 end), 0) as endedCount
from exam e
</select>
<select id="getInfoById" resultType="com.platform.business.model.vo.ExamVO"> <select id="getInfoById" resultType="com.platform.business.model.vo.ExamVO">
select e.id, select e.id,
e.name, e.name,
......
...@@ -227,11 +227,15 @@ ...@@ -227,11 +227,15 @@
WHERE peer.exam_id = es.exam_id WHERE peer.exam_id = es.exam_id
AND IFNULL(peer.mark_flag, 0) = 1 AND IFNULL(peer.mark_flag, 0) = 1
AND peer.score IS NOT NULL) AS classAverageScore, AND peer.score IS NOT NULL) AS classAverageScore,
<!--
rank自MySQL 8.0.2起是窗口函数保留字,作为列别名时必须使用反引号转义。
只转义SQL标识符,不改变MyBatis映射后的JSON字段名,接口仍返回rank。
-->
(SELECT COUNT(*) + 1 (SELECT COUNT(*) + 1
FROM exam_student peer FROM exam_student peer
WHERE peer.exam_id = es.exam_id WHERE peer.exam_id = es.exam_id
AND IFNULL(peer.mark_flag, 0) = 1 AND IFNULL(peer.mark_flag, 0) = 1
AND peer.score &gt; es.score) AS rank, AND peer.score &gt; es.score) AS `rank`,
CASE WHEN es.score &gt;= IFNULL(e.pass_score, 60) THEN TRUE ELSE FALSE END AS passed, CASE WHEN es.score &gt;= IFNULL(e.pass_score, 60) THEN TRUE ELSE FALSE END AS passed,
CASE CASE
WHEN es.score &gt;= 90 THEN '优秀' WHEN es.score &gt;= 90 THEN '优秀'
...@@ -299,6 +303,11 @@ ...@@ -299,6 +303,11 @@
ORDER BY g.code, g.id ORDER BY g.code, g.id
</select> </select>
<!--
新试卷的sequence是从1开始的数字序号;历史试卷可能存在空值或非数字值。
查询先排有效数字序号,再用原值和最早明细ID稳定历史题目顺序;服务层
最终把这个稳定顺序转换为连续的1..N展示题号,不回写作答明细。
-->
<select id="queryTheoryStatistics" resultType="com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO"> <select id="queryTheoryStatistics" resultType="com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO">
SELECT SELECT
NULL AS questionCode, NULL AS questionCode,
...@@ -340,7 +349,18 @@ ...@@ -340,7 +349,18 @@
WHERE d.exam_id = #{examId} WHERE d.exam_id = #{examId}
AND IFNULL(d.is_problem, 1) = 1 AND IFNULL(d.is_problem, 1) = 1
GROUP BY d.sequence, d.type, d.problem GROUP BY d.sequence, d.type, d.problem
ORDER BY d.sequence ORDER BY
CASE
WHEN TRIM(IFNULL(d.sequence, '')) REGEXP '^[0-9]+$' THEN 0
ELSE 1
END,
CASE
WHEN TRIM(IFNULL(d.sequence, '')) REGEXP '^[0-9]+$'
THEN CAST(TRIM(d.sequence) AS UNSIGNED)
ELSE NULL
END,
NULLIF(TRIM(d.sequence), ''),
MIN(d.id)
</select> </select>
<select id="queryPracticeStatistics" resultType="com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO"> <select id="queryPracticeStatistics" resultType="com.platform.business.model.vo.ScoreAdminQuestionStatisticsVO">
......
...@@ -32,23 +32,9 @@ ...@@ -32,23 +32,9 @@
<if test="factory != null and factory != ''"> <if test="factory != null and factory != ''">
and student_level_cert.factory = #{factory} and student_level_cert.factory = #{factory}
</if> </if>
<!-- <if test="name != null and name != ''">
管理端搜索框统一提交keyword。姓名、身份证号和证书编号均属于页面可见的
人员身份信息,因此使用同一个关键字进行包含匹配;旧版客户端提交name时
仍保留原有姓名查询能力,避免接口升级后出现兼容性问题。
-->
<choose>
<when test="keyword != null and keyword != ''">
and (
student_level_cert.user_name like concat('%', #{keyword}, '%')
or student_level_cert.id_card like concat('%', #{keyword}, '%')
or student_level_cert.cert_no like concat('%', #{keyword}, '%')
)
</when>
<when test="name != null and name != ''">
and student_level_cert.user_name like concat('%', #{name}, '%') and student_level_cert.user_name like concat('%', #{name}, '%')
</when> </if>
</choose>
</where> </where>
</select> </select>
</mapper> </mapper>
...@@ -67,7 +67,8 @@ JWT解析当前用户并校验 `phone_role.role_name=管理员`。本模块只 ...@@ -67,7 +67,8 @@ JWT解析当前用户并校验 `phone_role.role_name=管理员`。本模块只
- `GET /exam/admin/scores/exam-students/{examStudentId}`:只允许读取正式发布成绩。理论考试返回 - `GET /exam/admin/scores/exam-students/{examStudentId}`:只允许读取正式发布成绩。理论考试返回
`theoryQuestions`;实训考试返回 `practiceItems`。 `theoryQuestions`;实训考试返回 `practiceItems`。
- `GET /exam/admin/scores/exams/{examId}/questions/statistics`:理论题返回满分、平均分、得分率、 - `GET /exam/admin/scores/exams/{examId}/questions/statistics`:理论题返回满分、平均分、得分率、
答对人数和难度;实训协议没有每题满分,因此 `maxScore/scoreRate/difficulty` 为 `null`。 答对人数和难度,`sequence` 为从 `1` 开始的全卷连续题号;实训题使用
`questionCode`,且实训协议没有每题满分,因此 `maxScore/scoreRate/difficulty` 为 `null`。
## 5. Excel导出 ## 5. Excel导出
......
package com.platform.business.controller;
import com.platform.business.model.dto.ExamDTO;
import com.platform.business.model.vo.ExamPageVO;
import com.platform.business.model.vo.ExamSummaryVO;
import com.platform.business.model.vo.ExamVO;
import com.platform.business.service.ExamService;
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.test.util.ReflectionTestUtils;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.when;
/** `/exam/page`分页兼容字段及新增顶部汇总的控制器测试。 */
@ExtendWith(MockitoExtension.class)
class ExamControllerTest {
@Mock
private ExamService examService;
private ExamController controller;
@BeforeEach
void setUp() {
controller = new ExamController();
ReflectionTestUtils.setField(controller, "examService", examService);
}
@Test
void pageShouldPreserveCommonPaginationFieldsAndAppendSummary() {
ExamDTO query = new ExamDTO();
query.setPageNum(1);
query.setPageSize(8);
ExamVO row = new ExamVO();
row.setStatus("未开始");
ExamSummaryVO summary = new ExamSummaryVO();
summary.setTotalCount(15L);
summary.setNotStartedCount(5L);
summary.setOngoingCount(3L);
summary.setEndedCount(7L);
when(examService.queryList(query)).thenReturn(Collections.singletonList(row));
when(examService.summary()).thenReturn(summary);
ExamPageVO response = controller.page(query);
assertEquals(200, response.getCode());
assertEquals(1L, response.getTotal());
assertEquals(Collections.singletonList(row), response.getRows());
assertSame(summary, response.getSummary());
assertEquals("未开始", ((ExamVO) response.getRows().get(0)).getStatus());
}
}
package com.platform.business.mapper; package com.platform.business.mapper;
import com.platform.business.model.dto.AccountAdminQueryDTO;
import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.InputStream; import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 防止账户管理Mapper XML在合并时出现标签未闭合或关键语句被误删。 */ /** 防止账户管理Mapper XML在合并时出现标签未闭合或关键语句被误删。 */
class AccountAdminMapperXmlTest { class AccountAdminMapperXmlTest {
@Test @Test
void mapperXmlShouldBeWellFormedAndContainCoreStatements() throws Exception { void mapperXmlShouldBeWellFormedAndContainCoreStatements() throws Exception {
try (InputStream input = getClass().getClassLoader().getResourceAsStream( Configuration configuration = parseMapper();
"com/platform/business/mapper/AccountAdminMapper.xml")) {
assertNotNull(input);
Configuration configuration = new Configuration();
new XMLMapperBuilder(input, configuration,
"com/platform/business/mapper/AccountAdminMapper.xml",
configuration.getSqlFragments()).parse();
assertTrue(configuration.hasStatement( assertTrue(configuration.hasStatement(
"com.platform.business.mapper.AccountAdminMapper.selectAccounts")); "com.platform.business.mapper.AccountAdminMapper.selectAccounts"));
assertTrue(configuration.hasStatement( assertTrue(configuration.hasStatement(
...@@ -30,5 +30,94 @@ class AccountAdminMapperXmlTest { ...@@ -30,5 +30,94 @@ class AccountAdminMapperXmlTest {
assertTrue(configuration.hasStatement( assertTrue(configuration.hasStatement(
"com.platform.business.mapper.AccountAdminMapper.insertOperationLog")); "com.platform.business.mapper.AccountAdminMapper.insertOperationLog"));
} }
/**
* 教师列表和导出共用selectAccounts。这里检查MyBatis展开后的真实SQL,确保教职工分支
* 只接收ENABLED/DISABLED;STUDYING等学员状态必须落入del_flag兜底逻辑。
*/
@Test
void staffStatusExpressionShouldWhitelistStaffStatusesAndFallbackByDeleteFlag()
throws Exception {
AccountAdminQueryDTO query = new AccountAdminQueryDTO();
query.setAccountType("TEACHER");
String sql = selectAccountsSql(query);
assertTrue(sql.contains("else case when upper(trim(u.account_status)) in "
+ "('enabled', 'disabled') then upper(trim(u.account_status)) "
+ "when coalesce(u.del_flag, 0) = 1 then 'disabled' else 'enabled' "
+ "end end as status"),
() -> "教职工状态白名单或兜底逻辑不正确,实际SQL:" + sql);
}
/**
* 状态筛选必须复用与结果列完全相同的表达式,否则页面可能显示“启用”,却无法通过
* ENABLED条件筛出该教师。表达式出现两次分别对应SELECT结果列和WHERE筛选条件。
*/
@Test
void staffStatusFilterShouldReuseNormalizedStatusExpression() throws Exception {
AccountAdminQueryDTO query = new AccountAdminQueryDTO();
query.setAccountType("TEACHER");
query.setStatus("ENABLED");
String sql = selectAccountsSql(query);
String staffExpression = "when upper(trim(u.account_status)) in "
+ "('enabled', 'disabled') then upper(trim(u.account_status)) "
+ "when coalesce(u.del_flag, 0) = 1 then 'disabled' else 'enabled'";
assertTrue(countOccurrences(sql, staffExpression) == 2,
() -> "结果列与筛选条件没有复用同一教职工状态表达式,实际SQL:" + sql);
assertTrue(sql.contains("end = ? order by"),
() -> "状态表达式没有用于WHERE筛选,实际SQL:" + sql);
}
/** 学员合法状态仍直接保留,避免修复教师数据时改变学员列表和花名册的状态口径。 */
@Test
void studentStatusExpressionShouldKeepStudentStatusWhitelist() throws Exception {
AccountAdminQueryDTO query = new AccountAdminQueryDTO();
query.setAccountType("STUDENT");
String sql = selectAccountsSql(query);
assertTrue(sql.contains("when upper(trim(u.account_status)) in "
+ "('pending', 'studying', 'graduated', 'archived') "
+ "then upper(trim(u.account_status))"),
() -> "学员合法状态白名单缺失,实际SQL:" + sql);
assertTrue(sql.contains("when coalesce(u.first_login_flag, 1) = 1 then 'pending' "
+ "else 'studying'"),
() -> "学员历史状态兜底逻辑被改变,实际SQL:" + sql);
}
/** 构造与Mapper接口@Param命名一致的参数,获取动态标签展开后的最终查询SQL。 */
private String selectAccountsSql(AccountAdminQueryDTO query) throws Exception {
Map<String, Object> parameters = new HashMap<>();
parameters.put("query", query);
parameters.put("broadRole", "TEACHER".equals(query.getAccountType()) ? "教师" : "学生");
parameters.put("sixMonthsAgo", new Date(0L));
BoundSql boundSql = parseMapper().getMappedStatement(
"com.platform.business.mapper.AccountAdminMapper.selectAccounts")
.getBoundSql(parameters);
return boundSql.getSql().replaceAll("\\s+", " ").trim().toLowerCase(Locale.ROOT);
}
/** 统计完整片段出现次数,防止只修正展示列而遗漏WHERE状态筛选。 */
private int countOccurrences(String source, String target) {
int count = 0;
int fromIndex = 0;
while ((fromIndex = source.indexOf(target, fromIndex)) >= 0) {
count++;
fromIndex += target.length();
}
return count;
}
/** 每个测试独立解析真实Mapper资源,避免共享Configuration造成测试间状态污染。 */
private Configuration parseMapper() throws Exception {
Configuration configuration = new Configuration();
try (InputStream input = getClass().getClassLoader().getResourceAsStream(
"com/platform/business/mapper/AccountAdminMapper.xml")) {
assertNotNull(input);
new XMLMapperBuilder(input, configuration,
"com/platform/business/mapper/AccountAdminMapper.xml",
configuration.getSqlFragments()).parse();
}
return configuration;
} }
} }
...@@ -6,6 +6,7 @@ import org.apache.ibatis.session.Configuration; ...@@ -6,6 +6,7 @@ import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.InputStream; import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Collections; import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
...@@ -31,6 +32,32 @@ class ExamMapperXmlTest { ...@@ -31,6 +32,32 @@ class ExamMapperXmlTest {
"com.platform.business.mapper.ExamMapper.selectAdminExamConflicts")); "com.platform.business.mapper.ExamMapper.selectAdminExamConflicts"));
assertTrue(configuration.hasStatement( assertTrue(configuration.hasStatement(
"com.platform.business.mapper.ExamMapper.updateAdminExam")); "com.platform.business.mapper.ExamMapper.updateAdminExam"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.ExamMapper.summary"));
/*
* 通用考试分页必须查出时长供服务层计算三态;顶部汇总则必须独立统计全表,
* 不能意外继承分页中的名称、类型、等级或班级筛选条件。
*/
org.apache.ibatis.mapping.BoundSql pageBoundSql = configuration.getMappedStatement(
"com.platform.business.mapper.ExamMapper.queryList")
.getBoundSql(Collections.emptyMap());
String pageSql = pageBoundSql.getSql().replaceAll("\\s+", " ").toLowerCase();
assertTrue(pageSql.contains("e.duration"));
org.apache.ibatis.mapping.BoundSql summaryBoundSql = configuration.getMappedStatement(
"com.platform.business.mapper.ExamMapper.summary")
.getBoundSql(Collections.singletonMap(
"now", Timestamp.valueOf("2026-09-18 09:00:00")));
String summarySql = summaryBoundSql.getSql().replaceAll("\\s+", " ").toLowerCase();
assertTrue(summarySql.contains("count(*) as totalcount"));
assertTrue(summarySql.contains("as notstartedcount"));
assertTrue(summarySql.contains("as ongoingcount"));
assertTrue(summarySql.contains("as endedcount"));
assertTrue(summarySql.contains("greatest(coalesce(e.duration, 0), 0)"));
assertFalse(summarySql.contains("e.name like"));
assertFalse(summarySql.contains("e.type ="));
assertFalse(summarySql.contains("e.class_id ="));
/* /*
* 考试管理必须返回完整历史,不能再用当前时间过滤已结束考试;同时固定按考试时间和 * 考试管理必须返回完整历史,不能再用当前时间过滤已结束考试;同时固定按考试时间和
......
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