fix: 统一学习会话结算并修正结束幂等

This commit is contained in:
2026-10-09 10:48:12 +08:00
parent 04d1f40c6c
commit d8c8b76c32
6 changed files with 409 additions and 25 deletions
@@ -0,0 +1,36 @@
package com.guo.learningprogresstracker.common;
/**
* 学习会话的时间口径常量。
*
* <p>番茄钟长度、遗忘判定阈值与有效时间下限集中在此处定义,避免阈值散落在实体与服务的各个角落。
* 修改口径时只改这里,不要就地写死数字。</p>
*/
public final class StudyTimePolicy {
/**
* 番茄钟长度(分钟)。
*/
public static final int WORK_DURATION_MINUTES = 25;
/**
* 番茄钟长度(毫秒)。
*/
public static final long WORK_DURATION_MILLIS = WORK_DURATION_MINUTES * 60_000L;
/**
* 遗忘判定阈值(分钟):2 × 番茄钟。
*
* <p>最后一段学习在超过该时长后仍没有任何操作,判定为「忘了点暂停/结束」,
* 该段只按一个番茄钟结算(见 {@code StudySessionsEntity#resolveSettlementTime})。</p>
*/
public static final int FORGET_THRESHOLD_MINUTES = WORK_DURATION_MINUTES * 2;
/**
* 有效学习时间下限(秒):低于该值的一次学习不计入总学习时间。
*/
public static final long MIN_EFFECTIVE_TIME_SECONDS = 10 * 60L;
private StudyTimePolicy() {
}
}
@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.google.protobuf.ServiceException;
import com.guo.learningprogresstracker.common.StudyTimePolicy;
import com.guo.learningprogresstracker.enums.StudySessionStateEnum;
import com.guo.learningprogresstracker.utils.GenerateNumTool;
import lombok.Data;
@@ -15,8 +16,6 @@ import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDateTime;
import static com.guo.learningprogresstracker.service.impl.StudySessionsServiceImpl.WORK_DURATION;
/**
* 记录每次学习会话的具体数据
* @TableName study_sessions
@@ -96,7 +95,7 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
studySessionsEntity.setSessionNum(GenerateNumTool.generateNum("SESSION"));
studySessionsEntity.setStartTime(LocalDateTime.now());
studySessionsEntity.setLastStartTime(LocalDateTime.now());
studySessionsEntity.setPointerPosition(WORK_DURATION * 60 * 1000L);
studySessionsEntity.setPointerPosition(StudyTimePolicy.WORK_DURATION_MILLIS);
studySessionsEntity.setLastModifiedTime(LocalDateTime.now());
studySessionsEntity.setSessionState(StudySessionStateEnum.ONGOING.name());
return studySessionsEntity;
@@ -124,7 +123,8 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
if (this.getSessionState().equals(StudySessionStateEnum.PAUSED.name())) {
log.warn("不应出现的情况:暂停了一个状态为【{}】的学习会话({})", this.getSessionState(), this.getSessionNum());
} else {
this.setEndTime(ObjectUtils.isEmpty(endTime) ? LocalDateTime.now() : endTime);
LocalDateTime settlementTime = this.resolveSettlementTime(endTime);
this.setEndTime(settlementTime);
this.setActualTime(Duration.between(this.startTime, this.endTime).toSeconds());
this.setEffectiveTime(this.getEffectiveTime() + Duration.between(this.lastStartTime, this.endTime).toSeconds());
this.setEffectivenessRatio(this.effectiveTime / this.actualTime);
@@ -133,21 +133,37 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
/**
* 有效学习时间的最小阈值(秒),低于此值不计入总学习时间
* 计算本次学习分段的结算时间:暂停、结束与超时收敛都必须走这里,避免同一行为产生两种统计结果。
*
* <p>{@code lastStartTime} 到候选结束时间超过遗忘判定阈值
* ({@link StudyTimePolicy#FORGET_THRESHOLD_MINUTES})时,按「忘了点暂停/结束」处理,
* 只结算一个番茄钟({@link StudyTimePolicy#WORK_DURATION_MINUTES} 分钟);否则按候选结束时间结算。</p>
*/
private static final double MIN_EFFECTIVE_TIME_SECONDS = 10 * 60;
public LocalDateTime resolveSettlementTime(LocalDateTime candidateEndTime) {
LocalDateTime end = ObjectUtils.isEmpty(candidateEndTime) ? LocalDateTime.now() : candidateEndTime;
if (ObjectUtils.isEmpty(this.lastStartTime)) {
return end;
}
long minutes = Duration.between(this.lastStartTime, end).toMinutes();
if (minutes >= StudyTimePolicy.FORGET_THRESHOLD_MINUTES) {
log.info("会话[{}]本段学习已超过{}分钟无操作,按{}分钟结算",
this.getSessionNum(), StudyTimePolicy.FORGET_THRESHOLD_MINUTES, StudyTimePolicy.WORK_DURATION_MINUTES);
return this.lastStartTime.plusMinutes(StudyTimePolicy.WORK_DURATION_MINUTES);
}
return end;
}
/**
* 结束会话
*/
public void endedStudySession() {
if (this.getSessionState().equals(StudySessionStateEnum.ENDED.name())){
if (this.isEnded()){
log.warn("不应出现的情况:结束了一个状态为【{}】的学习会话",this.getSessionState());
}else {
if (this.getSessionState().equals(StudySessionStateEnum.ONGOING.name())) {
this.pausedStudySession(LocalDateTime.now());
}
if (this.getEffectiveTime() < MIN_EFFECTIVE_TIME_SECONDS) {
if (this.getEffectiveTime() < StudyTimePolicy.MIN_EFFECTIVE_TIME_SECONDS) {
log.info("会话[{}]有效学习时间({}秒)不足10分钟,不计入总学习时间", this.getSessionNum(), this.getEffectiveTime());
this.setEffectiveTime(0);
this.setEffectivenessRatio(0);
@@ -178,7 +194,7 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
*/
public void calculatePointerPosition() throws ServiceException {
if (isFirstRun()) {
this.pointerPosition = WORK_DURATION * 60 * 1000L; // 毫秒
this.pointerPosition = StudyTimePolicy.WORK_DURATION_MILLIS; // 毫秒
return;
}
@@ -193,12 +209,12 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
case ONGOING:
long elapsedMillis = Duration.between(lastStartTime, LocalDateTime.now()).toMillis();
long basePointerPosition = ObjectUtils.isEmpty(pointerPosition)
? WORK_DURATION * 60 * 1000L
? StudyTimePolicy.WORK_DURATION_MILLIS
: pointerPosition;
long newPointerPosition = basePointerPosition - elapsedMillis;
if (newPointerPosition <= 0) {
// 如果循环已经结束,则需要重置指针位置
this.pointerPosition = WORK_DURATION * 60 * 1000L;
this.pointerPosition = StudyTimePolicy.WORK_DURATION_MILLIS;
} else {
this.pointerPosition = newPointerPosition;
}
@@ -218,9 +234,33 @@ public class StudySessionsEntity extends BaseEntity implements Serializable {
}
public boolean isOverTime() {
LocalDateTime now = LocalDateTime.now();
long minutes = Duration.between(ObjectUtils.isEmpty(lastStartTime) ? LocalDateTime.now() : lastStartTime, now).toMinutes();
return minutes >= WORK_DURATION * 2;
/**
* 学习会话是否已经结束。
*/
public boolean isEnded() {
return StudySessionStateEnum.ENDED.name().equals(this.sessionState);
}
/**
* 本段学习是否已判定为「忘了点暂停/结束」,即需要按遗忘规则截断。
*
* <p>只有进行中的会话才成立:暂停与已结束的会话,其时间已在结算时入账,再次截断会重复扣减。
* 同时要求本段尚未结算过({@code end_time} 不早于 {@code last_start_time} 时视为已结算)。</p>
*/
public boolean isForgotten() {
return isForgotten(LocalDateTime.now());
}
public boolean isForgotten(LocalDateTime now) {
if (!StudySessionStateEnum.ONGOING.name().equals(this.sessionState)) {
return false;
}
if (ObjectUtils.isEmpty(this.lastStartTime)) {
return false;
}
if (!ObjectUtils.isEmpty(this.endTime) && !this.endTime.isBefore(this.lastStartTime)) {
return false;
}
return Duration.between(this.lastStartTime, now).toMinutes() >= StudyTimePolicy.FORGET_THRESHOLD_MINUTES;
}
}
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.protobuf.ServiceException;
import com.guo.learningprogresstracker.common.StudyTimePolicy;
import com.guo.learningprogresstracker.dto.StudySessionsDto;
import com.guo.learningprogresstracker.dto.response.StudySessionResponse;
import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity;
@@ -38,8 +39,6 @@ import java.util.stream.Collectors;
public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, StudySessionsEntity>
implements StudySessionsService {
public static final int WORK_DURATION = 25;
/**
* 误操作结束的确认语:用户必须输入完全一致的内容才能零数据关闭会话
*/
@@ -74,8 +73,10 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
session.calculatePointerPosition();
if (session.isOverTime()) {
session.pausedStudySession(session.getLastStartTime().plusMinutes(WORK_DURATION));
// 只有进行中且本段尚未结算的会话才需要收敛;已暂停/已结束的会话不再重复截断
boolean forgotten = session.isForgotten();
if (forgotten) {
session.pausedStudySession(null);
this.updateById(session);
}
@@ -84,8 +85,10 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
response.setMaterialUrl(taskEntity.getMaterialUrl());
response.setTaskId(taskEntity.getId());
if (session.isOverTime()) {
response.setSystemMessage("上段学习任务已经超时25分钟,将仅计算为25分钟的有效学习时间,请注意休息!");
if (forgotten) {
response.setSystemMessage(String.format(
"上段学习已超过%d分钟没有任何操作,仅计算为%d分钟的有效学习时间,请注意休息!",
StudyTimePolicy.FORGET_THRESHOLD_MINUTES, StudyTimePolicy.WORK_DURATION_MINUTES));
}
return response;
@@ -113,9 +116,26 @@ public class StudySessionsServiceImpl extends ServiceImpl<StudySessionsMapper, S
StudySessionsEntity studySessionsEntity = this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class)
.eq(StudySessionsEntity::getSessionNum, sessionNum))
.orElseThrow(() -> sessionNotFound(sessionNum));
// 幂等:已结束的会话不再重复结算,也不会重复生成学习报告
if (studySessionsEntity.isEnded()) {
log.warn("会话[{}]已结束,本次结束请求按幂等处理,不重复生成学习报告", sessionNum);
return null;
}
boolean wasOngoing = StudySessionStateEnum.ONGOING.name().equals(studySessionsEntity.getSessionState());
studySessionsEntity.endedStudySession();
this.updateById(studySessionsEntity);
// 条件更新:只有数据库中仍未结束的会话才会被写入结算结果,
// 避免重复点击/网络重试等并发请求各自插入一条学习报告
boolean ended = this.update(studySessionsEntity, Wrappers.<StudySessionsEntity>lambdaUpdate()
.eq(StudySessionsEntity::getId, studySessionsEntity.getId())
.ne(StudySessionsEntity::getSessionState, StudySessionStateEnum.ENDED.name()));
if (!ended) {
log.warn("会话[{}]已被其他请求结束,本次不重复生成学习报告", sessionNum);
return null;
}
StudyReportsEntity studyReportsEntity = new StudyReportsEntity();
studyReportsEntity.setSessionNum(sessionNum);
studyReportsEntity.setContent(content);
@@ -298,4 +298,105 @@ class StudySessionsEntityTest {
assertTrue(session.getEffectiveTime() > 0, "PAUSED 状态结束,15分钟 > 10分钟应保留");
assertEquals(StudySessionStateEnum.ENDED.name(), session.getSessionState());
}
// ============ 会话-01:结算时间统一 ============
/**
* 场景17:未达遗忘阈值时,结算时间就是候选结束时间
*/
@Test
void resolveSettlementTime_belowForgetThreshold_shouldReturnCandidate() {
StudySessionsEntity session = createOngoingSession(49);
LocalDateTime candidate = LocalDateTime.now();
assertEquals(candidate, session.resolveSettlementTime(candidate),
"未达 50 分钟阈值时应按候选结束时间结算");
}
/**
* 场景18:达到遗忘阈值时,结算时间截断为 last_start_time + 25 分钟
*/
@Test
void resolveSettlementTime_atForgetThreshold_shouldTruncateToOnePomodoro() {
StudySessionsEntity session = createOngoingSession(50);
LocalDateTime expected = session.getLastStartTime().plusMinutes(25);
assertEquals(expected, session.resolveSettlementTime(LocalDateTime.now()),
"达到 50 分钟阈值时应截断为一个番茄钟");
}
/**
* 场景19:暂停路径同样执行遗忘截断(原先只有重新进入页面才会截断)
*/
@Test
void pausedSession_threeHoursGap_shouldTruncateToOnePomodoro() {
StudySessionsEntity session = createOngoingSession(180);
LocalDateTime expectedEnd = session.getLastStartTime().plusMinutes(25);
session.pausedStudySession(null);
assertEquals(StudySessionStateEnum.PAUSED.name(), session.getSessionState());
assertEquals(expectedEnd, session.getEndTime(), "暂停时也应按遗忘规则截断");
assertEquals(25 * 60, session.getEffectiveTime(), "3 小时无人操作只应计入 25 分钟");
}
/**
* 场景20:结束路径同样执行遗忘截断
*/
@Test
void endedSession_threeHoursGap_shouldTruncateToOnePomodoro() {
StudySessionsEntity session = createOngoingSession(180);
LocalDateTime expectedEnd = session.getLastStartTime().plusMinutes(25);
session.endedStudySession();
assertEquals(StudySessionStateEnum.ENDED.name(), session.getSessionState());
assertEquals(expectedEnd, session.getEndTime(), "结束时也应按遗忘规则截断");
assertEquals(25 * 60, session.getEffectiveTime(), "3 小时无人操作只应计入 25 分钟");
}
// ============ 会话-02:遗忘判定纳入 state / end_time ============
/**
* 场景21:已暂停的会话即使 last_start_time 很旧,也不应判定为遗忘(时间已入账)
*/
@Test
void isForgotten_pausedSessionWithOldLastStartTime_shouldBeFalse() {
StudySessionsEntity session = createOngoingSession(180);
session.pausedStudySession(null);
assertFalse(session.isForgotten(), "已暂停的会话不应再次触发遗忘截断");
}
/**
* 场景22:已结束的会话不应判定为遗忘
*/
@Test
void isForgotten_endedSession_shouldBeFalse() {
StudySessionsEntity session = createOngoingSession(180);
session.endedStudySession();
assertFalse(session.isForgotten(), "已结束的会话不应再次触发遗忘截断");
}
/**
* 场景23:本段已结算(end_time 不早于 last_start_time)时不应重复判定遗忘
*/
@Test
void isForgotten_alreadySettledSegment_shouldBeFalse() {
StudySessionsEntity session = createOngoingSession(180);
session.setEndTime(session.getLastStartTime().plusMinutes(25));
assertFalse(session.isForgotten(), "已结算过的分段不应重复截断");
}
/**
* 场景24:进行中且超过阈值时才判定为遗忘
*/
@Test
void isForgotten_ongoingBeyondThreshold_shouldBeTrue() {
StudySessionsEntity session = createOngoingSession(60);
assertTrue(session.isForgotten(), "进行中超过 50 分钟无操作应判定为遗忘");
}
}
@@ -3,6 +3,7 @@ package com.guo.learningprogresstracker.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
import com.guo.learningprogresstracker.entity.StudySessionsEntity;
import com.guo.learningprogresstracker.entity.TaskEntity;
import com.guo.learningprogresstracker.enums.StudySessionStateEnum;
import com.guo.learningprogresstracker.exception.ErrorParameterException;
import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper;
@@ -25,6 +26,7 @@ import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@@ -47,10 +49,18 @@ class StudySessionsServiceImplTest {
@Mock
private StudyExpectationsService studyExpectationsService;
@Mock
private TasksServiceImpl tasksServiceImpl;
@Mock
private AiServiceClient aiServiceClient;
@BeforeEach
void setUp() {
// stub updateById,避免调用真实的 getBaseMapper()
doReturn(true).when(studySessionsService).updateById(any());
// stub 条件更新(结束会话抢占),默认视为抢占成功
doReturn(true).when(studySessionsService).update(any(StudySessionsEntity.class), any(Wrapper.class));
// stub removeById,避免调用真实的 getBaseMapper()
doReturn(true).when(studySessionsService).removeById(any(Serializable.class));
}
@@ -207,16 +217,17 @@ class StudySessionsServiceImplTest {
}
/**
* 场景10:确认 updateById 被调用(会话状态持久化)
* 场景10:确认会话状态被持久化(条件更新:仅当仍未结束时写入)
*/
@Test
void endedStudySession_shouldCallUpdateById() throws Exception {
void endedStudySession_shouldCallUpdateWithNotEndedCondition() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 5);
session.setId(10);
mockGetOneOpt(session);
studySessionsService.endedStudySession("SESSION_TEST", "内容");
verify(studySessionsService).updateById(session);
verify(studySessionsService).update(eq(session), any(Wrapper.class));
}
// ============ 误操作结束(零数据关闭) ============
@@ -313,4 +324,91 @@ class StudySessionsServiceImplTest {
studySessionsService.abortStudySession("NOT_EXIST", StudySessionsServiceImpl.MISOPERATION_CONFIRMATION));
}
// ============ 会话-01:结算路径统一 ============
/**
* 场景17:ONGOING 且上一段开始于 3 小时前 → 结束时应截断为 25 分钟
*/
@Test
void endedStudySession_ongoingThreeHoursGap_shouldTruncateToOnePomodoro() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 180);
session.setId(20);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", "内容");
assertNull(message, "截断后 25 分钟 ≥ 10 分钟,不应提示时间不足");
assertEquals(25 * 60, session.getEffectiveTime(), "3 小时无人操作只应计入 25 分钟");
verify(studyReportsMapper).insert(any(StudyReportsEntity.class));
}
/**
* 场景18:ONGOING 且上一段开始于 3 小时前 → 暂停时同样应截断为 25 分钟
*/
@Test
void pauseStudySession_ongoingThreeHoursGap_shouldTruncateToOnePomodoro() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 180);
mockGetOneOpt(session);
studySessionsService.pauseStudySession("SESSION_TEST", null);
assertEquals(StudySessionStateEnum.PAUSED.name(), session.getSessionState());
assertEquals(25 * 60, session.getEffectiveTime(), "暂停路径也应按遗忘规则截断");
}
// ============ 会话-02:暂停会话不再弹出超时提示 ============
/**
* 场景19:PAUSED 且 end_time 已存在、last_start_time 很旧 → 不返回 systemMessage
*/
@Test
void startOrContinueStudySession_pausedStaleSession_shouldNotReturnSystemMessage() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.PAUSED.name(), 180);
session.setEndTime(session.getLastStartTime().plusMinutes(25));
session.setEffectiveTime(25 * 60);
mockGetOneOpt(session);
TaskEntity task = new TaskEntity();
task.setTaskNum("TASK_TEST");
task.setTaskName("测试任务");
doReturn(Optional.of(task)).when(tasksServiceImpl).getOneOpt(any(Wrapper.class));
var response = studySessionsService.startOrContinueStudySession("TASK_TEST");
assertNull(response.getSystemMessage(), "已暂停的会话不应再提示超时");
}
// ============ 会话-03:结束会话幂等 ============
/**
* 场景20:重复结束已 ENDED 的会话 → 不重复生成学习报告
*/
@Test
void endedStudySession_alreadyEnded_shouldNotInsertReport() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ENDED.name(), 5);
session.setEffectiveTime(5 * 60);
mockGetOneOpt(session);
String message = studySessionsService.endedStudySession("SESSION_TEST", "内容");
assertNull(message);
verify(studyReportsMapper, never()).insert(any(StudyReportsEntity.class));
verify(studySessionsService, never()).update(any(StudySessionsEntity.class), any(Wrapper.class));
}
/**
* 场景21:并发结束抢占失败(其他请求已先结束)→ 不重复生成学习报告
*/
@Test
void endedStudySession_concurrentClaimLost_shouldNotInsertReport() throws Exception {
StudySessionsEntity session = createSession(StudySessionStateEnum.ONGOING.name(), 15);
session.setId(30);
mockGetOneOpt(session);
doReturn(false).when(studySessionsService).update(any(StudySessionsEntity.class), any(Wrapper.class));
String message = studySessionsService.endedStudySession("SESSION_TEST", "内容");
assertNull(message);
verify(studyReportsMapper, never()).insert(any(StudyReportsEntity.class));
}
}
@@ -0,0 +1,89 @@
package com.guo.learningprogresstracker.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
import com.guo.learningprogresstracker.entity.StudySessionsEntity;
import com.guo.learningprogresstracker.enums.StudySessionStateEnum;
import com.guo.learningprogresstracker.mapper.StudyReportsMapper;
import com.guo.learningprogresstracker.utils.GenerateNumTool;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.Duration;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 会话结算的落库集成测试:验证统一结算路径与结束幂等在真实 SQL(含租户条件与条件更新)下成立。
*/
@SpringBootTest
class StudySessionsSettlementIntegrationTest {
@Autowired
private StudySessionsServiceImpl studySessionsService;
@Autowired
private StudyReportsMapper studyReportsMapper;
@BeforeEach
void setUp() {
StpUtil.login("会话结算集成测试用户", "test_device");
}
/**
* 造一个「ONGOING 且最后一段开始于 3 小时前」的会话,模拟用户忘了点暂停/结束。
*/
private StudySessionsEntity saveForgottenOngoingSession() {
StudySessionsEntity session = new StudySessionsEntity();
session.setSessionNum(GenerateNumTool.generateNum("SESSIONIT"));
session.setTaskNum(GenerateNumTool.generateNum("TASKIT"));
session.setStartTime(LocalDateTime.now().minusHours(3));
session.setLastStartTime(LocalDateTime.now().minusHours(3));
session.setEffectiveTime(0);
session.setActualTime(0);
session.setSessionState(StudySessionStateEnum.ONGOING.name());
assertTrue(studySessionsService.save(session), "测试会话应保存成功");
return session;
}
private StudySessionsEntity reload(String sessionNum) {
return studySessionsService.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class)
.eq(StudySessionsEntity::getSessionNum, sessionNum)).orElseThrow();
}
@Test
void pauseStudySession_forgottenSession_shouldTruncateToOnePomodoro() throws Exception {
StudySessionsEntity session = saveForgottenOngoingSession();
studySessionsService.pauseStudySession(session.getSessionNum(), null);
StudySessionsEntity reloaded = reload(session.getSessionNum());
assertEquals(StudySessionStateEnum.PAUSED.name(), reloaded.getSessionState());
assertEquals(25 * 60, reloaded.getEffectiveTime(), 0.001,
"3 小时无人操作,暂停接口应只计入 25 分钟");
assertEquals(25 * 60, Duration.between(reloaded.getLastStartTime(), reloaded.getEndTime()).getSeconds(),
"结算时间应截断为 last_start_time + 25 分钟");
}
@Test
void endedStudySession_repeatedCall_shouldCreateOnlyOneReport() throws Exception {
StudySessionsEntity session = saveForgottenOngoingSession();
studySessionsService.endedStudySession(session.getSessionNum(), "第一次结束");
studySessionsService.endedStudySession(session.getSessionNum(), "重复结束");
StudySessionsEntity reloaded = reload(session.getSessionNum());
assertEquals(StudySessionStateEnum.ENDED.name(), reloaded.getSessionState());
assertEquals(25 * 60, reloaded.getEffectiveTime(), 0.001,
"3 小时无人操作,结束接口应只计入 25 分钟");
Long reportCount = studyReportsMapper.selectCount(Wrappers.lambdaQuery(StudyReportsEntity.class)
.eq(StudyReportsEntity::getSessionNum, session.getSessionNum()));
assertEquals(1L, reportCount, "重复结束不应生成多条学习报告");
}
}