package com.guo.learningprogresstracker.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.guo.learningprogresstracker.dto.IdRange; import com.guo.learningprogresstracker.dto.ReviewFeedItem; import com.guo.learningprogresstracker.dto.ReviewSummary; import com.guo.learningprogresstracker.dto.ReviewTaskStats; import com.guo.learningprogresstracker.dto.StudyReportDetail; import com.guo.learningprogresstracker.dto.TaskRecallRatio; import com.guo.learningprogresstracker.dto.TaskContentCount; import com.guo.learningprogresstracker.dto.TaskReviewDuration; import com.guo.learningprogresstracker.dto.TaskSessionStats; import com.guo.learningprogresstracker.entity.ReviewRecallRecordEntity; import com.guo.learningprogresstracker.entity.UserReviewPreferencesEntity; 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.FragmentContextTypeEnum; import com.guo.learningprogresstracker.enums.ReviewSortPresetEnum; import com.guo.learningprogresstracker.dto.ReviewSortPreference; import com.guo.learningprogresstracker.dto.request.ReviewFeedbackRequest; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.mapper.ReviewRecallRecordMapper; import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper; import com.guo.learningprogresstracker.mapper.StudyReportsMapper; import com.guo.learningprogresstracker.mapper.StudySessionsMapper; import com.guo.learningprogresstracker.mapper.TasksMapper; import com.guo.learningprogresstracker.mapper.UserReviewPreferencesMapper; import com.guo.learningprogresstracker.dto.request.UpdateStudyReportRequest; import com.guo.learningprogresstracker.service.ReviewService; import com.guo.learningprogresstracker.service.StudyExpectationsService; import com.guo.learningprogresstracker.service.StudyReportFragmentsService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 复习模块 Service 实现 */ @Slf4j @Service @RequiredArgsConstructor public class ReviewServiceImpl implements ReviewService { private static final int DEFAULT_LIMIT = 30; private static final int MAX_LIMIT = 100; private static final String RANDOM_MODE = "random"; private static final String SMART_MODE = "smart"; private static final int SMART_CANDIDATE_MULTIPLIER = 5; private static final String SOURCE_REPORT = "REPORT"; private static final String SOURCE_FRAGMENT = "FRAGMENT"; /** 待归类分组在内部的键名(不会作为任务编号出现在响应里,响应里 taskNum 为 null) */ private static final String PENDING_OWNERSHIP_KEY = "__PENDING__"; /** Feed 条目只返回这么长的摘要;全文由详情接口按需拉取(复习-05) */ private static final int FEED_SUMMARY_MAX_LENGTH = 200; /** 时间效应封顶天数 */ private static final int AGE_CEILING_DAYS = 90; /** 「稍后再看」的权重倍数(提高出现概率) */ private static final double REVISIT_FACTOR = 1.6; /** 「已掌握」的权重倍数:降低但不归零,保留文档要求的随机性 */ private static final double MASTERED_FACTOR = 0.3; private final StudyReportsMapper studyReportsMapper; private final StudyReportFragmentsMapper studyReportFragmentsMapper; private final StudyReportFragmentsService studyReportFragmentsService; private final StudySessionsMapper studySessionsMapper; private final TasksMapper tasksMapper; private final ReviewRecallRecordMapper reviewRecallRecordMapper; private final StudyExpectationsService studyExpectationsService; private final UserReviewPreferencesMapper userReviewPreferencesMapper; @Override public List getReviewFeed(int limit, String mode) { int safeLimit = normalizeLimit(limit); if (SMART_MODE.equalsIgnoreCase(mode)) { return getSmartFeed(safeLimit); } boolean random = RANDOM_MODE.equalsIgnoreCase(mode); List fragments = random ? randomFragments(safeLimit) : studyReportFragmentsMapper.selectList(Wrappers.lambdaQuery() .orderByDesc(StudyReportFragmentsEntity::getCreatedTime) .last("LIMIT " + safeLimit)); List items = mergeAndConvert(List.of(), fragments); if (random) { Collections.shuffle(items); } return items.stream().limit(safeLimit).collect(Collectors.toList()); } /** * 随机取样知识碎片(复习-03)。 * *

不使用 {@code ORDER BY RAND()}:那在 MySQL 上是全表随机排序,一次 Feed 请求会触发两次。 * 改为「随机起点 + 顺序取窗口」:先取主键区间,随机选一个起点,再按 id 顺序取够数量; * 不足时从头回绕补齐(id 与创建时间同向,回绕等价于取更早的内容)。删除造成的 id 空洞会让 * 靠后的内容被略微偏重,对「偶遇式」的 Feed 来说可以接受。

*/ private List randomFragments(int limit) { IdRange range = studyReportFragmentsMapper.selectIdRange(); if (range == null || range.isEmpty()) { return Collections.emptyList(); } long start = range.getMinId() + (long) (ThreadLocalRandom.current().nextDouble() * range.span()); // 用 LinkedHashMap 去重:回绕补齐时可能取到与首轮相同的行 Map picked = new LinkedHashMap<>(); collectFrom(start, limit, picked); if (picked.size() < limit) { collectFrom(range.getMinId(), limit - picked.size(), picked); } return new ArrayList<>(picked.values()); } /** 从 startId 起按 id 顺序取至多 count 条,按主键去重后并入 picked */ private void collectFrom(long startId, int count, Map picked) { if (count <= 0) { return; } List window = studyReportFragmentsMapper.selectList( Wrappers.lambdaQuery() .ge(StudyReportFragmentsEntity::getId, startId) .orderByAsc(StudyReportFragmentsEntity::getId) .last("LIMIT " + count)); for (StudyReportFragmentsEntity fragment : window) { picked.putIfAbsent(fragment.getId(), fragment); } } /** * 智能模式:加权随机采样,让更需要复习的内容有更高概率出现。 * 权重 = 时间衰减(越久未见权重越高) × 任务回忆掌握度(覆盖率越低权重越高)。 * 仍保持随机性,只是"随机得不那么均匀"——符合复习模块无压力、偶遇式的设计理念。 */ private List getSmartFeed(int safeLimit) { int candidateLimit = Math.min(safeLimit * SMART_CANDIDATE_MULTIPLIER, 500); List fragments = randomFragments(candidateLimit); List candidates = mergeAndConvert(List.of(), fragments); if (candidates.size() <= safeLimit) { Collections.shuffle(candidates); return candidates; } // 各任务最近一次回忆对比的覆盖率(没有记录视为 0 = 最需要复习) Map taskRecallRatio = latestRecallRatioByTask( candidates.stream().map(ReviewFeedItem::getTaskNum) .filter(Objects::nonNull).collect(Collectors.toSet())); LocalDateTime now = LocalDateTime.now(); // 排序信号强度由用户的档位决定(复习-01) ReviewSortPresetEnum preset = loadSortPreset(); List weights = new ArrayList<>(candidates.size()); for (ReviewFeedItem item : candidates) { weights.add(reviewNeedWeight(item, taskRecallRatio, now, preset)); } return weightedSample(candidates, weights, safeLimit); } /** * 单条内容的复习需求权重:三个信号相乘。 * *
    *
  1. 多久没接触:从「最近接触时间」算起(没有则用创建时间),90 天封顶。
  2. *
  3. 任务掌握度:最近一次回忆覆盖率越低权重越高。
  4. *
  5. 反馈动作:「稍后再看」提高权重;「已掌握」降低但不归零——文档要求保留随机性, * 「每条内容都有机会出现」。
  6. *
* *

前两个信号的相对强度由用户的排序档位决定(复习-01)。

*/ private double reviewNeedWeight(ReviewFeedItem item, Map taskRecallRatio, LocalDateTime now, ReviewSortPresetEnum preset) { // 信号一:时间效应。以「最近接触时间」为准,这样展开看过的内容会重新变「新」 LocalDateTime basis = item.getLastReviewedTime() != null ? item.getLastReviewedTime() : item.getCreatedTime(); double ageDays = basis == null ? 30 : Math.max(0, java.time.Duration.between(basis, now).toDays()); double ageProgress = Math.min(ageDays, AGE_CEILING_DAYS) / AGE_CEILING_DAYS; double ageFactor = (1 - preset.getAgeInfluence()) + ageProgress * preset.getAgeInfluence(); // 信号二:任务掌握度 double ratio = item.getTaskNum() == null ? 0 : taskRecallRatio.getOrDefault(item.getTaskNum(), 0D); double masteryFactor = 1.0 - ratio * preset.getMasteryInfluence(); // 信号三:反馈动作。「稍后再看」是明确的「想再看」,优先于「已掌握」 double feedbackFactor = 1.0; if (Boolean.TRUE.equals(item.getRevisit())) { feedbackFactor = REVISIT_FACTOR; } else if (Boolean.TRUE.equals(item.getMastered())) { feedbackFactor = MASTERED_FACTOR; } return ageFactor * masteryFactor * feedbackFactor; } /** 查询每个任务最近一次回忆对比的覆盖率 */ private Map latestRecallRatioByTask(Set taskNums) { if (taskNums.isEmpty()) { return Collections.emptyMap(); } // 复习-04:在 SQL 侧按任务分组取最新一条,只带回 任务编号 + 覆盖率 Map result = new HashMap<>(); for (TaskRecallRatio row : reviewRecallRecordMapper.selectLatestRatioByTask(taskNums)) { result.put(row.getTaskNum(), row.getRecallRatio() == null ? 0D : row.getRecallRatio()); } return result; } /** 按权重不放回采样 */ private List weightedSample(List items, List weights, int count) { List pool = new ArrayList<>(items); List poolWeights = new ArrayList<>(weights); List selected = new ArrayList<>(count); Random random = new Random(); while (selected.size() < count && !pool.isEmpty()) { double total = poolWeights.stream().mapToDouble(Double::doubleValue).sum(); double r = random.nextDouble() * total; double cumulative = 0; int chosen = pool.size() - 1; for (int i = 0; i < pool.size(); i++) { cumulative += poolWeights.get(i); if (r <= cumulative) { chosen = i; break; } } selected.add(pool.remove(chosen)); poolWeights.remove(chosen); } return selected; } @Override public ReviewSummary summary() { // 口径必须与 /review/tasks 的列表一致(列表逐页相加 == 这里的汇总): // 报告按「报告 → 会话 → 任务」归属,碎片按内容归属(owner_task_num)统计。 // 不能用裸表的 selectCount:那样「学习残片」会把待归类碎片也算进来, // 与列表逐页相加的结果对不上(待归类在总览里有独立区块展示)。 return new ReviewSummary( tasksMapper.selectCount(null), studyReportsMapper.countOwnedReports(), studyReportFragmentsMapper.countOwnedFragments()); } @Override public Page getReviewTaskStats(int pageNum, int pageSize, String markerName) { // 点标签即筛选:过滤下推到 SQL(EXISTS 子查询),由数据库一次算出命中任务并分页; // 不再「先查全部命中对象号、再拼 IN 回查」——命中量大时 IN 会膨胀。 IPage taskPage; if (StringUtils.hasText(markerName)) { taskPage = tasksMapper.selectPageByMarker(new Page<>(pageNum, pageSize), markerName.trim()); } else { taskPage = tasksMapper.selectPage(new Page<>(pageNum, pageSize), Wrappers.lambdaQuery() .orderByDesc(TaskEntity::getCalculatedPriority) // 优先级相同的任务之间要有稳定次序,否则翻页会重复或漏掉 .orderByDesc(TaskEntity::getId)); } List stats = taskPage.getRecords().stream() .map(this::newTaskStats) .collect(Collectors.toList()); // 聚合只算这一页的任务,不再对全部任务做 IN 聚合 fillReviewTaskStats(stats); Page result = new Page<>(taskPage.getCurrent(), taskPage.getSize(), taskPage.getTotal()); result.setRecords(stats); return result; } @Override public ReviewTaskStats getReviewTaskStats(String taskNum) { TaskEntity task = tasksMapper.selectList( Wrappers.lambdaQuery() .eq(TaskEntity::getTaskNum, taskNum) .last("LIMIT 1")) .stream() .findFirst() .orElse(null); ReviewTaskStats stats = newTaskStats(taskNum, task == null ? null : task.getTaskName()); fillReviewTaskStats(Collections.singletonList(stats)); return stats; } @Override public List getTaskReview(String taskNum) { // 报告按会话生成:取属于该任务的会话所产生的报告 List sessionNums = studySessionsMapper.selectList( Wrappers.lambdaQuery() .eq(StudySessionsEntity::getTaskNum, taskNum) .select(StudySessionsEntity::getSessionNum)) .stream() .map(StudySessionsEntity::getSessionNum) .collect(Collectors.toList()); List reports = sessionNums.isEmpty() ? List.of() : studyReportsMapper.selectList( Wrappers.lambdaQuery() .in(StudyReportsEntity::getSessionNum, sessionNums) .orderByDesc(StudyReportsEntity::getCreatedTime)); // 知识碎片按内容归属:只看它属于谁,不看它产生于哪次会话(归属-01) List fragments = studyReportFragmentsMapper.selectList( Wrappers.lambdaQuery() .eq(StudyReportFragmentsEntity::getOwnerTaskNum, taskNum) .orderByDesc(StudyReportFragmentsEntity::getCreatedTime)); return mergeAndConvert(reports, fragments); } @Override public StudyReportsEntity getReportDetail(int id) throws NotFindEntitiesException { return Optional.ofNullable(studyReportsMapper.selectById(id)) .orElseThrow(() -> { log.warn("学习报告[{}]不存在", id); return new NotFindEntitiesException("这份学习报告不存在或已被删除"); }); } @Override public StudyReportDetail getReportDetailStructured(int id) throws NotFindEntitiesException { StudyReportsEntity report = getReportDetail(id); StudyReportDetail detail = StudyReportDetail.of(report); // 报告所属会话与任务:用于判断哪些碎片是「旁支」(归属不等于本会话的任务) StudySessionsEntity session = StringUtils.hasText(report.getSessionNum()) ? studySessionsMapper.selectOne(Wrappers.lambdaQuery() .eq(StudySessionsEntity::getSessionNum, report.getSessionNum()) .last("LIMIT 1")) : null; if (session != null) { detail.setSessionTaskNum(session.getTaskNum()); detail.setSessionTaskName(loadTaskName(session.getTaskNum())); } Optional.ofNullable(studyExpectationsService.getBySessionNum(report.getSessionNum())) .ifPresent(e -> detail.setSessionExpectation(e.getDescription())); // 第四部分不落库:按会话产生的碎片 + 它们的**当前**内容归属实时聚合 List fragments = studyReportFragmentsMapper.selectList( Wrappers.lambdaQuery() .eq(StudyReportFragmentsEntity::getContextNum, report.getSessionNum()) .orderByAsc(StudyReportFragmentsEntity::getCreatedTime)); Map groups = new LinkedHashMap<>(); for (StudyReportFragmentsEntity fragment : fragments) { String owner = fragment.getOwnerTaskNum(); String key = StringUtils.hasText(owner) ? owner : PENDING_OWNERSHIP_KEY; StudyReportDetail.FragmentGroup group = groups.computeIfAbsent(key, k -> { StudyReportDetail.FragmentGroup created = new StudyReportDetail.FragmentGroup(); created.setTaskNum(StringUtils.hasText(owner) ? owner : null); created.setTaskName(StringUtils.hasText(owner) ? loadTaskName(owner) : null); // 旁支 = 归属不是本会话所属任务的内容 created.setBranch(!StringUtils.hasText(owner) || !Objects.equals(owner, detail.getSessionTaskNum())); return created; }); group.getFragments().add(fragment); } detail.setFragmentGroups(new ArrayList<>(groups.values())); return detail; } @Override public void updateReport(int id, UpdateStudyReportRequest request) throws NotFindEntitiesException { StudyReportsEntity existing = getReportDetail(id); StudyReportsEntity patch = new StudyReportsEntity(); patch.setId(existing.getId()); patch.setSessionSummary(request.getSessionSummary()); patch.setExpectationVerdict(request.getExpectationVerdict()); patch.setFreeSummary(request.getFreeSummary()); studyReportsMapper.updateById(patch); // 报告-02:报告内容作为导图参考上下文,改动后相关导图置「待更新」 studyReportFragmentsService.markMindMapsStaleForSession(existing.getSessionNum()); log.info("学习报告[{}]已修改", id); } @Override public void deleteReport(int id) throws NotFindEntitiesException { StudyReportsEntity existing = getReportDetail(id); // 软删除。刻意不连带删除同一会话的知识碎片:碎片是独立原料,可能已被归类到其他任务 studyReportsMapper.deleteById(existing.getId()); // 报告-02:报告不再作为参考上下文,相关导图置「待更新」 studyReportFragmentsService.markMindMapsStaleForSession(existing.getSessionNum()); log.info("学习报告[{}]已删除(知识碎片保留)", id); } /** 取任务名,任务不存在时返回 null(任务被删除后碎片会进入待归类,报告仍可能引用旧任务号) */ @Override public ReviewFeedbackRequest submitFeedback(Integer fragmentId, ReviewFeedbackRequest request) throws NotFindEntitiesException { StudyReportFragmentsEntity existing = getFragmentForUpdate(fragmentId); StudyReportFragmentsEntity patch = new StudyReportFragmentsEntity(); patch.setId(fragmentId); boolean changed = false; if (request.getMastered() != null) { patch.setMastered(request.getMastered()); changed = true; } if (request.getRevisit() != null) { patch.setRevisit(request.getRevisit()); changed = true; } if (changed) { // 反馈动作同时算一次接触:用户刚刚看过这条内容 patch.setLastReviewedTime(LocalDateTime.now()); studyReportFragmentsMapper.updateById(patch); } ReviewFeedbackRequest result = new ReviewFeedbackRequest(); result.setMastered(request.getMastered() != null ? request.getMastered() : existing.getMastered()); result.setRevisit(request.getRevisit() != null ? request.getRevisit() : existing.getRevisit()); return result; } @Override public void touchFragment(Integer fragmentId) throws NotFindEntitiesException { getFragmentForUpdate(fragmentId); StudyReportFragmentsEntity patch = new StudyReportFragmentsEntity(); patch.setId(fragmentId); patch.setLastReviewedTime(LocalDateTime.now()); studyReportFragmentsMapper.updateById(patch); } /** 反馈与接触都要先确认碎片存在(属于当前用户由租户拦截器保证) */ private StudyReportFragmentsEntity getFragmentForUpdate(Integer fragmentId) throws NotFindEntitiesException { StudyReportFragmentsEntity existing = studyReportFragmentsMapper.selectById(fragmentId); if (existing == null) { log.warn("未能找到知识碎片id[{}]", fragmentId); throw new NotFindEntitiesException("这条知识碎片不存在或已被删除"); } return existing; } @Override public ReviewSortPreference getSortPreference() { return toPreference(loadSortPreset()); } @Override public ReviewSortPreference saveSortPreference(String preset) { ReviewSortPresetEnum parsed = ReviewSortPresetEnum.parse(preset); UserReviewPreferencesEntity existing = userReviewPreferencesMapper.selectOne( Wrappers.lambdaQuery().last("LIMIT 1")); if (existing == null) { UserReviewPreferencesEntity created = new UserReviewPreferencesEntity(); created.setSortPreset(parsed.name()); userReviewPreferencesMapper.insert(created); } else { UserReviewPreferencesEntity patch = new UserReviewPreferencesEntity(); patch.setId(existing.getId()); patch.setSortPreset(parsed.name()); userReviewPreferencesMapper.updateById(patch); } log.info("复习排序偏好已更新为[{}]", parsed); return toPreference(parsed); } /** 读取当前用户的排序档位;未设置或存坏时回落默认 */ private ReviewSortPresetEnum loadSortPreset() { UserReviewPreferencesEntity preference = userReviewPreferencesMapper.selectOne( Wrappers.lambdaQuery().last("LIMIT 1")); return preference == null ? ReviewSortPresetEnum.DEFAULT : ReviewSortPresetEnum.parse(preference.getSortPreset()); } private static ReviewSortPreference toPreference(ReviewSortPresetEnum preset) { return new ReviewSortPreference(preset.name(), preset.getDescription()); } private String loadTaskName(String taskNum) { if (!StringUtils.hasText(taskNum)) { return null; } return tasksMapper.selectOne(Wrappers.lambdaQuery() .eq(TaskEntity::getTaskNum, taskNum) .select(TaskEntity::getTaskName) .last("LIMIT 1")) .getTaskName(); } @Override public StudyReportFragmentsEntity getFragmentDetail(int id) throws NotFindEntitiesException { return Optional.ofNullable(studyReportFragmentsMapper.selectById(id)) .orElseThrow(() -> { log.warn("学习残片[{}]不存在", id); return new NotFindEntitiesException("这条学习残片不存在或已被删除"); }); } /** * 将报告和残片合并转换为 ReviewFeedItem 列表,按创建时间倒序排列 */ private List mergeAndConvert(List reports, List fragments) { // 报告的任务取自它所属的会话(报告按会话生成) Set reportSessionNums = reports.stream() .map(StudyReportsEntity::getSessionNum) .filter(Objects::nonNull) .collect(Collectors.toSet()); Map sessionToTaskMap = reportSessionNums.isEmpty() ? Collections.emptyMap() : studySessionsMapper.selectList( Wrappers.lambdaQuery() .in(StudySessionsEntity::getSessionNum, reportSessionNums) .select(StudySessionsEntity::getSessionNum, StudySessionsEntity::getTaskNum)) .stream() .collect(Collectors.toMap( StudySessionsEntity::getSessionNum, StudySessionsEntity::getTaskNum, (a, b) -> a)); // 碎片的任务取自它自己的内容归属 Set taskNums = new HashSet<>(sessionToTaskMap.values()); fragments.stream() .map(StudyReportFragmentsEntity::getOwnerTaskNum) .filter(StringUtils::hasText) .forEach(taskNums::add); taskNums.removeIf(num -> !StringUtils.hasText(num)); Map taskNameMap = taskNums.isEmpty() ? Collections.emptyMap() : tasksMapper.selectList( Wrappers.lambdaQuery() .in(TaskEntity::getTaskNum, taskNums) .select(TaskEntity::getTaskNum, TaskEntity::getTaskName)) .stream() .collect(Collectors.toMap( TaskEntity::getTaskNum, task -> task.getTaskName() == null ? "" : task.getTaskName(), (a, b) -> a)); List reportItems = reports.stream().map(r -> { ReviewFeedItem item = new ReviewFeedItem(); item.setId(r.getId()); item.setSourceType(SOURCE_REPORT); applySummary(item, reportDisplayText(r)); item.setCreatedTime(r.getCreatedTime()); item.setContextType(FragmentContextTypeEnum.SESSION.name()); item.setContextNum(r.getSessionNum()); String taskNum = sessionToTaskMap.get(r.getSessionNum()); item.setTaskNum(taskNum); item.setTaskName(taskNum != null ? taskNameMap.get(taskNum) : null); return item; }).collect(Collectors.toList()); List fragmentItems = fragments.stream().map(f -> { ReviewFeedItem item = new ReviewFeedItem(); item.setId(f.getId()); item.setSourceType(SOURCE_FRAGMENT); applySummary(item, f.getContent()); item.setCreatedTime(f.getCreatedTime()); item.setContextType(f.getContextType()); item.setContextNum(f.getContextNum()); // 内容归属:为空即「待归类」,前端据此打标并提供就地归类入口 item.setPendingOwnership(f.isPendingOwnership()); // 反馈状态与最近接触时间只参与排序计算,不用于列表展示(复习-02:不产生状态展示) item.setMastered(f.getMastered()); item.setRevisit(f.getRevisit()); item.setLastReviewedTime(f.getLastReviewedTime()); item.setTaskNum(f.getOwnerTaskNum()); item.setTaskName(StringUtils.hasText(f.getOwnerTaskNum()) ? taskNameMap.get(f.getOwnerTaskNum()) : null); return item; }).collect(Collectors.toList()); return Stream.concat(reportItems.stream(), fragmentItems.stream()) .sorted(Comparator.comparing(ReviewFeedItem::getCreatedTime, Comparator.nullsLast(Comparator.reverseOrder()))) .collect(Collectors.toList()); } /** * 把原文放进 Feed 条目:只保留摘要与总长度(复习-05)。 *

摘要把换行压成空格,避免多行内容在列表里撑高卡片。

*/ private static void applySummary(ReviewFeedItem item, String rawContent) { String full = rawContent == null ? "" : rawContent; item.setContentLength(full.length()); if (full.length() <= FEED_SUMMARY_MAX_LENGTH) { item.setContent(full); item.setContentTruncated(false); return; } String summary = full.substring(0, FEED_SUMMARY_MAX_LENGTH) .replaceAll("\\s+", " ") .trim(); item.setContent(summary); item.setContentTruncated(true); } /** * 报告在列表/Feed 中的展示文本:结构化报告由三段组成,这里按段拼接。 */ private static String reportDisplayText(StudyReportsEntity report) { StringBuilder text = new StringBuilder(); appendSection(text, "会话摘要", report.getSessionSummary()); appendSection(text, "预期达成判断", report.getExpectationVerdict()); appendSection(text, "自由总结", report.getFreeSummary()); return text.length() == 0 ? "" : text.toString().trim(); } private static void appendSection(StringBuilder text, String title, String body) { if (body == null || body.isBlank()) { return; } if (text.length() > 0) { text.append("\n\n"); } text.append("【").append(title).append("】\n").append(body.trim()); } private ReviewTaskStats newTaskStats(TaskEntity task) { return newTaskStats(task.getTaskNum(), task.getTaskName()); } private ReviewTaskStats newTaskStats(String taskNum, String taskName) { ReviewTaskStats stats = new ReviewTaskStats(); stats.setTaskNum(taskNum); stats.setTaskName(taskName); return stats; } private int normalizeLimit(int limit) { if (limit <= 0) { return DEFAULT_LIMIT; } return Math.min(limit, MAX_LIMIT); } private void ensureTaskExists(String taskNum) throws NotFindEntitiesException { if (!StringUtils.hasText(taskNum) || !tasksMapper.exists( Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { log.warn("任务[{}]不存在", taskNum); throw new NotFindEntitiesException("这个任务不存在或已被删除"); } } /** * 填充任务维度统计(数据-02):三类聚合(会话统计、报告数、碎片数)全部下推到 SQL, * 每次查询只返回「任务数」量级的行,不随历史会话/内容条数线性增长。 */ private void fillReviewTaskStats(List statsList) { Map statsByTaskNum = statsList.stream() .filter(item -> StringUtils.hasText(item.getTaskNum())) .collect(Collectors.toMap( ReviewTaskStats::getTaskNum, item -> item, (a, b) -> a, LinkedHashMap::new)); if (statsByTaskNum.isEmpty()) { return; } Set taskNums = statsByTaskNum.keySet(); LocalDateTime todayStart = LocalDate.now().atStartOfDay(); LocalDateTime weekStart = LocalDate.now().with(DayOfWeek.MONDAY).atStartOfDay(); for (TaskSessionStats row : studySessionsMapper.sumStudyStatsByTask(taskNums, todayStart, weekStart)) { ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); if (stats == null) { continue; } long sessionCount = row.getSessionCount() == null ? 0L : row.getSessionCount(); stats.setSessionCount(sessionCount); stats.setEffectiveTime(nullToZero(row.getEffectiveTime())); stats.setTodayEffectiveTime(nullToZero(row.getTodayEffectiveTime())); stats.setWeekEffectiveTime(nullToZero(row.getWeekEffectiveTime())); if (sessionCount > 0) { stats.setAvgEffectiveTime(stats.getEffectiveTime() / sessionCount); stats.setAvgEffectivenessRatio(nullToZero(row.getEffectivenessRatioSum()) / sessionCount); } } fillContentCounts(statsByTaskNum, taskNums); fillReviewDuration(statsByTaskNum); } /** 报告数与碎片数:同样在 SQL 侧按内容归属分组计数 */ private void fillContentCounts(Map statsByTaskNum, Set taskNums) { for (TaskContentCount row : studyReportsMapper.countReportsByTask(taskNums)) { ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); if (stats != null) { stats.setReportCount(row.getContentCount() == null ? 0L : row.getContentCount()); } } for (TaskContentCount row : studyReportFragmentsMapper.countFragmentsByTask(taskNums)) { ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); if (stats != null) { stats.setFragmentCount(row.getContentCount() == null ? 0L : row.getContentCount()); } } } private static double nullToZero(Double value) { return value == null ? 0D : value; } /** * 按任务汇总复习行为累计耗时(复习-07)。聚合在 SQL 侧完成,只把任务数量的行拉回内存, * 不随回忆记录条数增长;结果由 {@code TaskReviewDuration} 承载,不走 Map。 */ private void fillReviewDuration(Map statsByTaskNum) { List rows = reviewRecallRecordMapper.sumReviewDurationByTask(statsByTaskNum.keySet()); for (TaskReviewDuration row : rows) { ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum()); if (stats != null && row.getReviewDurationSeconds() != null) { stats.setReviewDurationSeconds(row.getReviewDurationSeconds()); } } } }