package com.guo.learningprogresstracker.service.impl; 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.ReportSections; import com.guo.learningprogresstracker.dto.StudySessionsDto; import com.guo.learningprogresstracker.dto.response.StudySessionResponse; import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity; 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.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.mapStruct.StudySessionConvert; import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; import com.guo.learningprogresstracker.mapper.StudyReportsMapper; import com.guo.learningprogresstracker.mapper.StudySessionsMapper; import com.guo.learningprogresstracker.service.StudyExpectationsService; import com.guo.learningprogresstracker.service.StudySessionsService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * 针对表【study_sessions(记录每次学习会话的具体数据)】的数据库操作Service实现 */ @Slf4j @Service @RequiredArgsConstructor public class StudySessionsServiceImpl extends ServiceImpl implements StudySessionsService { /** * 误操作结束的确认语:用户必须输入完全一致的内容才能零数据关闭会话 */ public static final String MISOPERATION_CONFIRMATION = "我误操作导致开启了本次学习"; /** 单次定时扫描最多处理的会话数,避免一次拉回过多数据 */ private static final int SCAN_BATCH_SIZE = 200; private final TasksServiceImpl tasksServiceImpl; private final StudyReportFragmentsServiceImpl studyReportFragmentsServiceImpl; private final StudyReportFragmentsMapper studyReportFragmentsMapper; private final StudyReportsMapper studyReportsMapper; private final AiServiceClient aiServiceClient; private final StudyExpectationsService studyExpectationsService; private final StudyTimePolicy studyTimePolicy; public StudySessionResponse startOrContinueStudySession(String taskNum) throws NotFindEntitiesException, ServiceException { TaskEntity taskEntity = tasksServiceImpl.getOneOpt( Wrappers.lambdaQuery(TaskEntity.class).eq(TaskEntity::getTaskNum, taskNum)) .orElseThrow(() -> { log.warn("[{}]不存在", taskNum); return new NotFindEntitiesException("这个任务不存在或已被删除"); }); StudySessionsEntity session = this.getOneOpt(Wrappers.lambdaQuery() .eq(StudySessionsEntity::getTaskNum, taskNum) .ne(StudySessionsEntity::getSessionState, StudySessionStateEnum.ENDED.name())) .orElseGet(() -> { // 如果没有则创建新会话 StudySessionsEntity newSession = StudySessionsEntity.initNewSession(studyTimePolicy); newSession.setTaskNum(taskNum); newSession.setLastStartTime(LocalDateTime.now()); this.save(newSession); return newSession; }); LocalDateTime now = LocalDateTime.now(); session.calculatePointerPosition(studyTimePolicy); // 只有进行中且本段尚未结算的会话才需要收敛;已暂停/已结束的会话不再重复截断 boolean forgotten = session.isForgotten(now, studyTimePolicy); if (forgotten) { session.pausedStudySession(null, studyTimePolicy); this.updateById(session); } StudySessionResponse response = StudySessionConvert.MAPPER.toStudySessionResponse(session); response.setTaskName(taskEntity.getTaskName()); response.setMaterialUrl(taskEntity.getMaterialUrl()); response.setTaskId(taskEntity.getId()); if (forgotten) { response.setSystemMessage(String.format( "上段学习已超过%d分钟没有任何操作,仅计算为%d分钟的有效学习时间,请注意休息!", studyTimePolicy.getForgetThresholdMinutes(), studyTimePolicy.getWorkDurationMinutes())); } return response; } @Override public void pauseStudySession(String sessionNum, LocalDateTime endTime) throws ErrorParameterException, ServiceException { StudySessionsEntity studySessionsEntity = this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class) .eq(StudySessionsEntity::getSessionNum, sessionNum)) .orElseThrow(() -> sessionNotFound(sessionNum)); if (StudySessionStateEnum.PAUSED.name().equals(studySessionsEntity.getSessionState())) { log.error("会话[" + studySessionsEntity.getSessionNum() + "]重复暂停"); throw new ErrorParameterException("这次学习会话已经暂停了,不用重复暂停哦"); } studySessionsEntity.calculatePointerPosition(studyTimePolicy); studySessionsEntity.pausedStudySession(endTime, studyTimePolicy); this.updateById(studySessionsEntity); } @Override @Transactional public String endedStudySession(String sessionNum, ReportSections report) throws ErrorParameterException { 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(studyTimePolicy); // 条件更新:只有数据库中仍未结束的会话才会被写入结算结果, // 避免重复点击/网络重试等并发请求各自插入一条学习报告 boolean ended = this.update(studySessionsEntity, Wrappers.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); // 结构化三段:摘要、达成判断、自由总结。第四部分(按归属分组的碎片)是实时聚合的视图,不落库。 ReportSections sections = (report == null ? new ReportSections(null, null, null) : report) .orFallbackTo("本次学习未填写总结"); studyReportsEntity.setSessionSummary(sections.sessionSummary()); studyReportsEntity.setExpectationVerdict(sections.expectationVerdict()); studyReportsEntity.setFreeSummary(sections.freeSummary()); studyReportsMapper.insert(studyReportsEntity); if (wasOngoing && studySessionsEntity.getEffectiveTime() == 0) { return "本次有效学习时间不足" + (studyTimePolicy.getMinEffectiveTimeSeconds() / 60) + "分钟,不计入总学习时间"; } return null; } @Override @Transactional public void abortStudySession(String sessionNum, String confirmation) throws ErrorParameterException { StudySessionsEntity studySessionsEntity = this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class) .eq(StudySessionsEntity::getSessionNum, sessionNum)) .orElseThrow(() -> sessionNotFound(sessionNum)); if (StudySessionStateEnum.ENDED.name().equals(studySessionsEntity.getSessionState())) { log.warn("会话[{}]已结束,不能误操作结束", sessionNum); throw new ErrorParameterException("这次学习会话已经结束,不能再误操作结束了"); } if (!MISOPERATION_CONFIRMATION.equals(confirmation == null ? "" : confirmation.trim())) { log.warn("会话[{}]误操作结束的确认语不正确", sessionNum); throw new ErrorParameterException("确认语输入不正确,请核对后重新输入"); } long fragmentCount = studyReportFragmentsMapper.selectCount(Wrappers.lambdaQuery(StudyReportFragmentsEntity.class) .eq(StudyReportFragmentsEntity::getContextNum, sessionNum)); if (fragmentCount > 0) { log.warn("会话[{}]已产生{}条学习残片,不能误操作结束", sessionNum, fragmentCount); throw new ErrorParameterException("这次学习已经产生了学习残片,不能按误操作结束了哦"); } // 严格零数据:学习预期与会话本身一并删除,系统视角下会话从未发生 studyExpectationsService.deleteBySessionNum(sessionNum); this.removeById(studySessionsEntity.getId()); log.info("会话[{}]误操作结束,未产生任何学习数据", sessionNum); } @Override public StudySessionResponse getNotEndedStudySessionByTaskNum(String taskNum) throws ErrorParameterException { // 惰性收敛:先把悬挂会话收敛掉,避免返回一个早该暂停的进行中会话 convergeStaleSessionsOfCurrentUser(); TaskEntity task = tasksServiceImpl.getOneOpt(Wrappers.lambdaQuery(TaskEntity.class) .eq(TaskEntity::getTaskNum, taskNum)) .orElseThrow(() -> taskNotFound(taskNum)); StudySessionsDto dto = Optional.ofNullable(studyReportsMapper.getNotEndedStudySessionDtoByTaskNum(taskNum)) .orElseThrow(() -> { log.warn("任务[{}]不存在进行中或暂停中的会话", taskNum); return new ErrorParameterException("这个任务当前没有进行中或已暂停的学习会话"); }); return StudySessionConvert.MAPPER.toStudySessionResponse(dto); } @Override public ArrayList getAllFragments(String sessionNum) throws ErrorParameterException { if (this.exists(Wrappers.lambdaQuery(StudySessionsEntity.class) .eq(StudySessionsEntity::getSessionNum, sessionNum))) { return studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery(StudyReportFragmentsEntity.class) .eq(StudyReportFragmentsEntity::getContextNum, sessionNum)) .stream().map(StudyReportFragmentsEntity::getContent).collect(Collectors.toCollection(ArrayList::new)); } else { throw sessionNotFound(sessionNum); } } @Override @Transactional public void continueStudySession(String sessionNum) throws ErrorParameterException, ServiceException { StudySessionsEntity studySessionsEntity = this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class) .eq(StudySessionsEntity::getSessionNum, sessionNum)) .orElseThrow(() -> sessionNotFound(sessionNum)); if (StudySessionStateEnum.ONGOING.name().equals(studySessionsEntity.getSessionState())) { log.error("会话[" + studySessionsEntity.getSessionNum() + "]重复开始"); throw new ErrorParameterException("这次学习会话已经开始了,不用重复开始哦"); } else if (StudySessionStateEnum.ENDED.name().equals(studySessionsEntity.getSessionState())) { log.error("会话[" + studySessionsEntity.getSessionNum() + "]处于结束状态,不可开始该会话!"); throw new ErrorParameterException("这次学习会话已经结束,无法再次开始"); } studySessionsEntity.continueStudySession(studyTimePolicy); this.updateById(studySessionsEntity); } /** * 通过 sessionNum 获取学习会话 */ public StudySessionResponse getStudySessionBySessionNum(String sessionNum) throws ErrorParameterException { StudySessionsEntity session = this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class) .eq(StudySessionsEntity::getSessionNum, sessionNum)) .orElseThrow(() -> sessionNotFound(sessionNum)); return StudySessionConvert.MAPPER.toStudySessionResponse(session); } /** * 生成学习报告草稿:优先调用 lpt-ai 聚合残片,服务不可用时降级为按序拼接。 * 草稿仅作为编辑起点返回,不落库——最终报告由用户确认后经 endedStudySession 保存。 * *

由 AI 任务执行器在请求线程之外调用(AI-02):聚合可能等待 AI 数分钟, * 不能放在读取接口里,否则一个 GET 就会阻塞并按 AI 计费。

*/ @Override public ReportSections buildReportDraft(String sessionNum) throws ErrorParameterException { StudySessionsEntity session = this.getOneOpt(Wrappers.lambdaQuery(StudySessionsEntity.class) .eq(StudySessionsEntity::getSessionNum, sessionNum)) .orElseThrow(() -> sessionNotFound(sessionNum)); ArrayList fragments = getAllFragments(sessionNum); if (fragments.isEmpty()) { return new ReportSections(null, null, null); } String taskName = tasksServiceImpl.getOneOpt( Wrappers.lambdaQuery(TaskEntity.class).eq(TaskEntity::getTaskNum, session.getTaskNum())) .map(TaskEntity::getTaskName) .orElse("学习任务"); String expectation = Optional.ofNullable(studyExpectationsService.getBySessionNum(sessionNum)) .map(e -> e.getDescription()) .orElse(null); // AI 可用时由它给出三段草稿;不可用(或失败)时降级为规则拼接: // 会话摘要 = 碎片条数 + 首条摘要,自由总结留给用户填写,达成判断只在有预期时给一句规则结论。 return aiServiceClient.aggregateReport(taskName, fragments, expectation) .orElseGet(() -> ruleBasedReportDraft(fragments, expectation)); } /** * 规则降级:不依赖 AI 也能给出一份可编辑的草稿。 *

只做能确定的事——摘要按碎片拼接、达成判断只在存在学习预期时给规则结论, * 自由总结刻意留空由用户填写(AI 不可用时不应该替他编造卡点与下一步)。

*/ private ReportSections ruleBasedReportDraft(List fragments, String expectation) { String summary = String.join("\n", fragments); String verdict = (expectation == null || expectation.isBlank()) ? null : "本次学习记录了 " + fragments.size() + " 条知识碎片,请对照预期自行判断达成情况。"; return new ReportSections(summary, verdict, null); } // ============ 分页查询任务的历史残片/报告 ============ @Override public Page getTaskFragments(String taskNum, int page, int size, String keyword) { Page pg = new Page<>(page, size); // 归属-01:按内容归属取,而不是按产生于该任务的哪次会话取 var wrapper = Wrappers.lambdaQuery(StudyReportFragmentsEntity.class) .eq(StudyReportFragmentsEntity::getOwnerTaskNum, taskNum) .orderByDesc(StudyReportFragmentsEntity::getCreatedTime); if (keyword != null && !keyword.isBlank()) { wrapper.like(StudyReportFragmentsEntity::getContent, keyword); } return studyReportFragmentsMapper.selectPage(pg, wrapper); } @Override public Page getTaskReports(String taskNum, int page, int size, String keyword) { Page pg = new Page<>(page, size); var wrapper = Wrappers.lambdaQuery(StudyReportsEntity.class) .apply("session_num in (select session_num from study_sessions where task_num = {0})", taskNum) .orderByDesc(StudyReportsEntity::getCreatedTime); if (keyword != null && !keyword.isBlank()) { wrapper.and(w -> w.like(StudyReportsEntity::getFreeSummary, keyword) .or().like(StudyReportsEntity::getSessionSummary, keyword) .or().like(StudyReportsEntity::getExpectationVerdict, keyword)); } Page result = studyReportsMapper.selectPage(pg, wrapper); // 填充每个报告对应会话的预期目标 for (StudyReportsEntity report : result.getRecords()) { if (report.getSessionNum() != null) { Optional.ofNullable(studyExpectationsService.getBySessionNum(report.getSessionNum())) .ifPresent(e -> report.setSessionExpectation(e.getDescription())); } } return result; } // ============ 活跃会话查询 ============ /** * 查询当前用户是否有活跃会话(ONGOING 或 PAUSED)。 * * @param excludeTaskNum 可选,排除指定任务(同一任务继续学习时不会视为冲突) * @return 活跃会话响应;无活跃会话时返回 null */ @Override public StudySessionResponse getActiveSession(String excludeTaskNum) { // 惰性收敛:用户不访问任务页时,统计与阻塞问题靠这里先行修正(定时扫描兜底) convergeStaleSessionsOfCurrentUser(); var wrapper = Wrappers.lambdaQuery(StudySessionsEntity.class) .in(StudySessionsEntity::getSessionState, StudySessionStateEnum.ONGOING.name(), StudySessionStateEnum.PAUSED.name()) .orderByDesc(StudySessionsEntity::getCreatedTime) .last("LIMIT 1"); StudySessionsEntity session = this.getOne(wrapper); if (session == null) return null; // 如果活跃会话属于被排除的任务,视为无冲突 if (excludeTaskNum != null && excludeTaskNum.equals(session.getTaskNum())) { return null; } String taskName = tasksServiceImpl.getOneOpt( Wrappers.lambdaQuery(TaskEntity.class).eq(TaskEntity::getTaskNum, session.getTaskNum())) .map(TaskEntity::getTaskName) .orElse(null); StudySessionResponse response = StudySessionConvert.MAPPER.toStudySessionResponse(session); response.setTaskName(taskName); return response; } private ErrorParameterException sessionNotFound(String sessionNum) { log.warn("会话[{}]不存在", sessionNum); return new ErrorParameterException("这次学习会话不存在或已结束"); } private ErrorParameterException taskNotFound(String taskNum) { log.warn("任务[{}]不存在", taskNum); return new ErrorParameterException("这个任务不存在或已被删除"); } // ============ 悬挂会话收敛(会话-04)============ @Override public int convergeStaleSessionsOfCurrentUser() { LocalDateTime now = LocalDateTime.now(); LocalDateTime cutoff = now.minusMinutes(studyTimePolicy.getForcePauseMinutes()); // 惰性收敛走租户隔离路径:只可能读到当前用户自己的会话 List staleSessions = this.list(Wrappers.lambdaQuery() .eq(StudySessionsEntity::getSessionState, StudySessionStateEnum.ONGOING.name()) .le(StudySessionsEntity::getLastStartTime, cutoff) .orderByAsc(StudySessionsEntity::getLastStartTime)); int converged = 0; for (StudySessionsEntity session : staleSessions) { if (convergeOne(session, now)) { converged++; } } return converged; } @Override public int scanAndConvergeStaleSessions() { LocalDateTime now = LocalDateTime.now(); LocalDateTime cutoff = now.minusMinutes(studyTimePolicy.getForcePauseMinutes()); // 定时任务在请求之外执行,没有登录态,走忽略租户条件的扫描(系统级兜底) List staleSessions = baseMapper.selectForcePausableSessions(cutoff, SCAN_BATCH_SIZE); int converged = 0; for (StudySessionsEntity session : staleSessions) { if (convergeOne(session, now)) { converged++; } } return converged; } /** * 收敛单个悬挂会话:先按硬兜底阈值复核,再用「状态仍为 ONGOING」的条件更新写入。 * *

条件更新保证惰性收敛与定时扫描并发时只结算一次(与结束会话的幂等处理同一思路), * 写入按主键定位,所以定时扫描分支可以安全地忽略租户条件。

* * @return 是否由本次调用完成收敛 */ private boolean convergeOne(StudySessionsEntity session, LocalDateTime now) { if (!session.forceConverge(now, studyTimePolicy)) { return false; } return baseMapper.convergeStaleSession(session) > 0; } }