Commit ebb3cc24 authored by wujipeng's avatar wujipeng
Browse files

bug修复

parent 72c5471e
......@@ -9,6 +9,7 @@ import com.platform.business.model.vo.TeachingPlanVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/** 教案主表数据访问接口,所有自定义查询均显式带入当前教师 ID。 */
......@@ -30,19 +31,25 @@ public interface TeachingPlanMapper extends BaseMapper<TeachingPlanEntity> {
TeachingPlanEntity selectTeacherPlanForUpdate(@Param("id") String id,
@Param("teacherId") String teacherId);
/** 仅更新仍属于当前教师且仍为草稿的教案主表字段;教学环节由独立 Mapper 替换。 */
/**
* 仅更新仍属于当前教师且仍为草稿的教案主表字段;教学环节由独立 Mapper 替换。
* 更新时间由应用端传入,避免数据库会话时区与业务时区不一致时产生固定偏移。
*/
int updateDraft(@Param("plan") TeachingPlanEntity plan,
@Param("teacherId") String teacherId);
@Param("teacherId") String teacherId,
@Param("now") Date now);
/** 按预期原状态更新目标状态,实现并发安全的状态机。 */
int updateStatus(@Param("id") String id,
@Param("teacherId") String teacherId,
@Param("currentStatus") String currentStatus,
@Param("targetStatus") String targetStatus);
@Param("targetStatus") String targetStatus,
@Param("now") Date now);
/** 仅逻辑删除仍属于当前教师且仍为草稿的教案。 */
/** 仅逻辑删除仍属于当前教师且仍为草稿的教案,并使用应用端操作时间更新时间。 */
int deleteDraft(@Param("id") String id,
@Param("teacherId") String teacherId);
@Param("teacherId") String teacherId,
@Param("now") Date now);
/** 管理员查询全部教师的教案,分页由控制器中的 PageHelper 提供。 */
List<TeachingPlanVO> selectAdminList(@Param("query") TeachingPlanAdminQueryDTO query);
......
......@@ -29,6 +29,12 @@ public interface TheoreticalPracticeStudentQuestionBankMapper extends BaseMapper
Boolean reAnswer(TheoreticalPracticeStudentQuestionBankDTO theoreticalPracticeStudentQuestionBankDTO);
Date countdown(@Param("id") String id,@Param("date") Date date);
/**
* 查询当前登录学员“当前班级”的开放理论练习结束时间。
*
* <p>学员换班后旧练习名单仍用于历史统计,因此查询必须同时限制当前班级,不能仅按
* {@code theoretical_practice_student.student_id}判断。</p>
*/
Date countdown(@Param("studentId") String studentId, @Param("now") Date now);
}
......@@ -133,8 +133,10 @@ public class TeachingPlanServiceImpl implements TeachingPlanService {
TeachingPlanEntity update = toEntity(request);
update.setId(id);
// 应用端时钟与新增流程保持一致,避免数据库 CURRENT_TIMESTAMP 使用 UTC 导致少 8 小时。
Date now = new Date();
// SQL 同时限制 teacher_id、DRAFT 和 del_flag,处理校验后发生的并发状态变化。
if (teachingPlanMapper.updateDraft(update, teacherId) != 1) {
if (teachingPlanMapper.updateDraft(update, teacherId, now) != 1) {
throw new BusinessException("教案状态已变化,请刷新后重试");
}
replaceSteps(id, request.getSteps());
......@@ -152,7 +154,7 @@ public class TeachingPlanServiceImpl implements TeachingPlanService {
requireDraft(plan, "只有草稿状态的教案可以删除");
List<Integer> fileIds = attachmentMapper.selectFileIds(id);
if (teachingPlanMapper.deleteDraft(id, teacherId) != 1) {
if (teachingPlanMapper.deleteDraft(id, teacherId, new Date()) != 1) {
throw new BusinessException("教案状态已变化,请刷新后重试");
}
attachmentMapper.deleteByPlanId(id);
......@@ -185,8 +187,11 @@ public class TeachingPlanServiceImpl implements TeachingPlanService {
if (!TeachingPlanConstants.canTransition(current.getStatus(), targetStatus)) {
throw new BusinessException("不允许从 " + current.getStatus() + " 变更为 " + targetStatus);
}
// 提交时间与更新时间必须复用同一个应用端时刻,既保证审计一致,也不依赖数据库时区。
Date now = new Date();
// 原状态进入 WHERE 条件;两个并发状态请求最多只有一个能够成功。
if (teachingPlanMapper.updateStatus(id, teacherId, current.getStatus(), targetStatus) != 1) {
if (teachingPlanMapper.updateStatus(
id, teacherId, current.getStatus(), targetStatus, now) != 1) {
throw new BusinessException("教案状态已变化,请刷新后重试");
}
return detail(id, teacherId);
......@@ -307,7 +312,10 @@ public class TeachingPlanServiceImpl implements TeachingPlanService {
update.setReviewerId(reviewerId);
update.setReviewerName(reviewerName);
update.setReviewOpinion(reviewOpinion);
update.setReviewTime(new Date());
// 审核时间和更新时间使用同一操作时刻,避免数据库会话 UTC 造成列表时间少 8 小时。
Date now = new Date();
update.setReviewTime(now);
update.setUpdateTime(now);
if (teachingPlanMapper.updateAdmin(update) != 1) {
throw new BusinessException("教案状态已变化,请刷新后重试");
}
......
......@@ -13,6 +13,12 @@
c.name className,
e.name examName,
es.score score,
<!--
exam_student.submit 是教师端判断学员是否已经交卷的唯一事实来源,不能用
score、start_time 或考试结束时间推断。历史记录可能保存为 NULL,因此在查询
边界统一转换为 false,确保详情接口始终返回明确的布尔值而不是省略该字段。
-->
case when coalesce(es.submit, 0) = 1 then true else false end submit,
e.exam_time examTime,
es.class_id classId,
es.student_id studentId
......
......@@ -102,7 +102,11 @@
teaching_aids = #{plan.teachingAids},
teaching_note = #{plan.teachingNote},
signature = #{plan.signature},
update_time = CURRENT_TIMESTAMP
<!--
使用应用端生成的操作时刻,避免数据库会话为 UTC 时 CURRENT_TIMESTAMP
比中国标准时间少 8 小时;Date 参数仍由 JDBC 按项目连接时区统一落库。
-->
update_time = #{now}
WHERE id = #{plan.id}
AND teacher_id = #{teacherId}
AND status = 'DRAFT'
......@@ -114,10 +118,10 @@
UPDATE teaching_plan
SET status = #{targetStatus},
submitted_time = CASE
WHEN #{targetStatus} = 'PENDING' THEN CURRENT_TIMESTAMP
WHEN #{targetStatus} = 'PENDING' THEN #{now}
ELSE submitted_time
END,
update_time = CURRENT_TIMESTAMP
update_time = #{now}
WHERE id = #{id}
AND teacher_id = #{teacherId}
AND status = #{currentStatus}
......@@ -127,7 +131,7 @@
<update id="deleteDraft">
UPDATE teaching_plan
SET del_flag = 1,
update_time = CURRENT_TIMESTAMP
update_time = #{now}
WHERE id = #{id}
AND teacher_id = #{teacherId}
AND status = 'DRAFT'
......@@ -212,7 +216,8 @@
reviewer_name = #{plan.reviewerName},
review_opinion = #{plan.reviewOpinion},
review_time = #{plan.reviewTime},
update_time = CURRENT_TIMESTAMP
<!-- 审核时间和更新时间复用同一个应用端时刻,保证两个审计字段完全一致。 -->
update_time = #{plan.updateTime}
WHERE id = #{plan.id}
AND del_flag = 0
</update>
......
......@@ -206,6 +206,28 @@
from theoretical_practice tp
join theoretical_practice_student ps
on ps.practice_id = tp.id and ps.student_id = #{studentId}
<!--
与倒计时入口使用同一当前班级选择顺序。即使客户端保存了换班前的题目ID,也不能
在新班级没有理论练习时继续向旧练习写入作答记录。这里保留独立子查询,确保本
Mapper可单独解析,也避免跨Mapper SQL片段造成启动顺序依赖。
-->
join (
select c.id
from class_student current_member
join `class` c on c.id = current_member.class_id
where current_member.user_id = #{studentId}
and coalesce(c.archived_flag, 0) = 0
order by
case
when (c.start_date is null or c.start_date &lt;= date(#{now}))
and (c.end_date is null or c.end_date &gt;= date(#{now})) then 0
when c.end_date is null or c.end_date &gt;= date(#{now}) then 1
else 2
end,
c.start_date desc,
c.id desc
limit 1
) current_class on current_class.id = tp.class_id
join theoretical_practice_student_question_bank qb
on qb.id = #{questionId}
and qb.student_id = ps.student_id
......
......@@ -3,6 +3,35 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.platform.business.mapper.TheoreticalPracticeStudentQuestionBankMapper">
<!--
理论练习入口和答题权限必须跟随学员“当前班级”,不能只依赖练习创建时生成的
theoretical_practice_student名单。学员换班后旧名单会保留用于历史统计,如果直接
查询旧名单,就会把原班级的练习倒计时继续返回给新班级学员。
当前班级的选择顺序与StudentHomeMapper一致:正在培训的班级优先,其次是尚未结束
的未来班级,最后才是最近一次历史班级。同一优先级下选择开始时间更新、ID更大的
班级,从而兼容class_student保留多条历史关系的现有数据结构。
-->
<sql id="currentStudentClassJoin">
inner join (
select c.id
from class_student current_member
inner join `class` c on c.id = current_member.class_id
where current_member.user_id = #{studentId}
and coalesce(c.archived_flag, 0) = 0
order by
case
when (c.start_date is null or c.start_date &lt;= date(#{now}))
and (c.end_date is null or c.end_date &gt;= date(#{now})) then 0
when c.end_date is null or c.end_date &gt;= date(#{now}) then 1
else 2
end,
c.start_date desc,
c.id desc
limit 1
) current_class on current_class.id = tp.class_id
</sql>
<select id="groupByStudentId" resultType="java.lang.String">
select
......@@ -76,25 +105,16 @@
type = #{type}
</select>
<select id="countdown" resultType="java.util.Date">
select
end_time
from
theoretical_practice
where
id
in (
select
practice_id
from
theoretical_practice_student
where
student_id = #{id}
)
and is_close = false
and end_time > #{date}
and start_time &lt; #{date}
order by
end_time
select tp.end_time
from theoretical_practice tp
inner join theoretical_practice_student assigned
on assigned.practice_id = tp.id
and assigned.student_id = #{studentId}
<include refid="currentStudentClassJoin"/>
where coalesce(tp.is_close, false) = false
and tp.end_time &gt; #{now}
and tp.start_time &lt;= #{now}
order by tp.end_time
limit 1
</select>
<update id="reAnswer">
......
package com.platform.business.mapper;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 教师端考试详情中的应考学员查询回归测试。
*
* <p>详情接口复用ExamStudentVO,并由queryByExamId负责填充交卷标记。该测试直接检查
* MyBatis最终生成的SQL,防止后续调整查询列时再次遗漏submit,导致前端把已交卷学员
* 错误展示为“未交卷”。</p>
*/
class ExamStudentMapperXmlTest {
@Test
void queryByExamIdShouldReturnNormalizedBooleanSubmitStatus() throws Exception {
String resource = "com/platform/business/mapper/ExamStudentMapper.xml";
Configuration configuration = new Configuration();
try (InputStream input = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder builder = new XMLMapperBuilder(
input, configuration, resource, configuration.getSqlFragments());
builder.parse();
}
/*
* 使用实际MappedStatement生成SQL,而不是只搜索XML文本:这样既能验证Mapper能够
* 被MyBatis完整解析,也能锁定NULL必须按false返回、字段别名必须为submit的契约。
* 成绩字段不参与表达式,避免历史数据中“有成绩但未交卷”被错误推断为已交卷。
*/
BoundSql boundSql = configuration.getMappedStatement(
"com.platform.business.mapper.ExamStudentMapper.queryByExamId")
.getBoundSql(Collections.singletonMap("id", 1));
String sql = boundSql.getSql().replaceAll("\\s+", " ").toLowerCase();
assertTrue(sql.contains(
"case when coalesce(es.submit, 0) = 1 then true else false end submit"));
}
}
......@@ -5,8 +5,11 @@ import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** 确保教案主表和教学环节 SQL 在应用启动前即可被 MyBatis 完整解析和注册。 */
......@@ -30,6 +33,27 @@ class TeachingPlanMapperXmlTest {
assertTrue(configuration.hasStatement(namespace + "selectAdminTeacherOptions"));
}
@Test
void teachingPlanWritesShouldUseApplicationClockInsteadOfDatabaseClock() throws Exception {
String resource = "com/platform/business/mapper/TeachingPlanMapper.xml";
String xml;
try (InputStream input = Resources.getResourceAsStream(resource)) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) >= 0) {
output.write(buffer, 0, read);
}
xml = new String(output.toByteArray(), StandardCharsets.UTF_8);
}
// 数据库节点可能运行在 UTC;教案审计时间必须由应用端传入,才能与新增流程保持一致。
assertFalse(xml.matches("(?s).*update_time\\s*=\\s*CURRENT_TIMESTAMP.*"));
assertFalse(xml.matches("(?s).*THEN\\s+CURRENT_TIMESTAMP.*"));
assertTrue(xml.contains("update_time = #{now}"));
assertTrue(xml.contains("update_time = #{plan.updateTime}"));
}
@Test
void stepMapperXmlShouldParseAndRegisterReplaceStatements() throws Exception {
String resource = "com/platform/business/mapper/TeachingPlanStepMapper.xml";
......
package com.platform.business.mapper;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 学员换班后理论练习入口与作答权限的数据范围回归测试。
*
* <p>theoretical_practice_student是练习创建时的名单快照,旧记录不能删除,否则会破坏
* 历史统计。因此查询端必须从class_student的全部历史关系中选出当前班级,再匹配
* theoretical_practice.class_id。本测试直接解析MyBatis最终SQL,防止以后退回到仅按旧
* 练习名单判断,导致无理论练习的新等级继续显示入口。</p>
*/
class TheoreticalPracticeCurrentClassScopeTest {
@Test
void countdownShouldOnlyReturnPracticeFromStudentsCurrentClass() throws Exception {
Configuration configuration = parse(
"com/platform/business/mapper/TheoreticalPracticeStudentQuestionBankMapper.xml");
Map<String, Object> parameters = commonParameters();
BoundSql boundSql = configuration.getMappedStatement(
"com.platform.business.mapper.TheoreticalPracticeStudentQuestionBankMapper.countdown")
.getBoundSql(parameters);
String sql = normalize(boundSql.getSql());
/*
* assigned保留“曾被分配过该练习”的约束;current_class额外要求练习属于首页选出的
* 当前班级。两者缺一不可:只查前者会复现三级换四级后旧入口仍显示的问题。
*/
assertTrue(sql.contains("inner join theoretical_practice_student assigned"));
assertTrue(sql.contains("assigned.student_id = ?"));
assertCurrentClassScope(sql);
assertFalse(sql.contains("where id in"));
}
@Test
void answerSubmissionShouldRejectQuestionFromPreviousClassPractice() throws Exception {
Configuration configuration = parse(
"com/platform/business/mapper/TheoreticalPracticeMapper.xml");
Map<String, Object> parameters = commonParameters();
parameters.put("questionId", "question-1");
BoundSql boundSql = configuration.getMappedStatement(
"com.platform.business.mapper.TheoreticalPracticeMapper.activePracticeIdsForAnswer")
.getBoundSql(parameters);
String sql = normalize(boundSql.getSql());
/*
* 入口隐藏之外还要约束写接口,避免客户端缓存换班前题目ID后绕过页面继续提交旧练习。
*/
assertTrue(sql.contains("ps.student_id = ?"));
assertTrue(sql.contains("qb.id = ?"));
assertCurrentClassScope(sql);
}
/** 验证SQL选择的是唯一当前班级,而不是任意一条历史班级关系。 */
private void assertCurrentClassScope(String sql) {
assertTrue(sql.contains("from class_student current_member"));
assertTrue(sql.contains("current_member.user_id = ?"));
assertTrue(sql.contains("coalesce(c.archived_flag, 0) = 0"));
assertTrue(sql.contains("current_class.id = tp.class_id"));
assertTrue(sql.contains("c.start_date desc, c.id desc limit 1"));
}
/** 创建两个Mapper共同使用的命名参数,日期固定以保证BoundSql生成过程可重复。 */
private Map<String, Object> commonParameters() {
Map<String, Object> parameters = new HashMap<>();
parameters.put("studentId", "student-1");
parameters.put("now", new Date(0L));
return parameters;
}
/** 独立解析Mapper,既验证SQL片段完整,也能提前发现XML或include配置错误。 */
private Configuration parse(String resource) throws Exception {
Configuration configuration = new Configuration();
try (InputStream input = Resources.getResourceAsStream(resource)) {
XMLMapperBuilder builder = new XMLMapperBuilder(
input, configuration, resource, configuration.getSqlFragments());
builder.parse();
}
return configuration;
}
/** 折叠空白并统一大小写,避免格式调整导致与业务无关的测试失败。 */
private String normalize(String sql) {
return sql.replaceAll("\\s+", " ").trim().toLowerCase();
}
}
......@@ -109,6 +109,8 @@ class TeachingPlanAdminServiceImplTest {
assertEquals("教务管理员", update.getReviewerName());
assertEquals("退回草稿重新整理", update.getReviewOpinion());
assertNotNull(update.getReviewTime());
// 两个字段必须复用同一个应用端时刻,防止 update_time 再次落回数据库 UTC 时间。
assertEquals(update.getReviewTime(), update.getUpdateTime());
}
@Test
......
......@@ -213,7 +213,7 @@ class TeachingPlanServiceImplTest {
assertThrows(BusinessException.class,
() -> teachingPlanService.update("plan-1", validRequest(), TEACHER_ID));
verify(teachingPlanMapper, never()).updateDraft(any(), anyString());
verify(teachingPlanMapper, never()).updateDraft(any(), anyString(), any(Date.class));
}
@Test
......@@ -227,7 +227,7 @@ class TeachingPlanServiceImplTest {
.thenReturn(pending);
assertThrows(BusinessException.class,
() -> teachingPlanService.delete("plan-1", TEACHER_ID));
verify(teachingPlanMapper, never()).deleteDraft(anyString(), anyString());
verify(teachingPlanMapper, never()).deleteDraft(anyString(), anyString(), any(Date.class));
}
@ParameterizedTest
......@@ -237,7 +237,8 @@ class TeachingPlanServiceImplTest {
})
void updateStatusShouldAllowEveryDefinedTransition(String currentStatus, String targetStatus) {
when(teachingPlanMapper.selectById("plan-1")).thenReturn(plan(currentStatus));
when(teachingPlanMapper.updateStatus("plan-1", TEACHER_ID, currentStatus, targetStatus))
when(teachingPlanMapper.updateStatus(
eq("plan-1"), eq(TEACHER_ID), eq(currentStatus), eq(targetStatus), any(Date.class)))
.thenReturn(1);
TeachingPlanVO detail = new TeachingPlanVO();
detail.setId("plan-1");
......@@ -261,15 +262,17 @@ class TeachingPlanServiceImplTest {
assertThrows(BusinessException.class,
() -> teachingPlanService.updateStatus("plan-1", request, TEACHER_ID));
verify(teachingPlanMapper, never()).updateStatus(anyString(), anyString(), anyString(), anyString());
verify(teachingPlanMapper, never()).updateStatus(
anyString(), anyString(), anyString(), anyString(), any(Date.class));
}
@Test
void statusUpdateShouldDetectConcurrentStateChange() {
when(teachingPlanMapper.selectById("plan-1"))
.thenReturn(plan(TeachingPlanConstants.STATUS_DRAFT));
when(teachingPlanMapper.updateStatus("plan-1", TEACHER_ID,
TeachingPlanConstants.STATUS_DRAFT, TeachingPlanConstants.STATUS_PENDING))
when(teachingPlanMapper.updateStatus(
eq("plan-1"), eq(TEACHER_ID), eq(TeachingPlanConstants.STATUS_DRAFT),
eq(TeachingPlanConstants.STATUS_PENDING), any(Date.class)))
.thenReturn(0);
TeachingPlanStatusDTO request = new TeachingPlanStatusDTO();
request.setStatus(TeachingPlanConstants.STATUS_PENDING);
......
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