diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TaskContentCount.java b/src/main/java/com/guo/learningprogresstracker/dto/TaskContentCount.java
new file mode 100644
index 0000000..27ede09
--- /dev/null
+++ b/src/main/java/com/guo/learningprogresstracker/dto/TaskContentCount.java
@@ -0,0 +1,16 @@
+package com.guo.learningprogresstracker.dto;
+
+import lombok.Data;
+
+/**
+ * 任务维度的内容条数聚合结果(数据-02):学习报告或知识碎片的条数。
+ *
计数在 SQL 侧按内容归属(学习会话 → 任务)分组完成。
+ */
+@Data
+public class TaskContentCount {
+
+ private String taskNum;
+
+ /** 该任务下的报告数或碎片数 */
+ private Long contentCount;
+}
diff --git a/src/main/java/com/guo/learningprogresstracker/dto/TaskSessionStats.java b/src/main/java/com/guo/learningprogresstracker/dto/TaskSessionStats.java
new file mode 100644
index 0000000..861a9d9
--- /dev/null
+++ b/src/main/java/com/guo/learningprogresstracker/dto/TaskSessionStats.java
@@ -0,0 +1,28 @@
+package com.guo.learningprogresstracker.dto;
+
+import lombok.Data;
+
+/**
+ * 任务维度的学习会话统计聚合结果(数据-02)。
+ * 由 Mapper 层的 {@code SUM/COUNT + GROUP BY} 直接映射,避免把全部会话行拉回内存再聚合。
+ */
+@Data
+public class TaskSessionStats {
+
+ private String taskNum;
+
+ /** 该任务的学习会话次数 */
+ private Long sessionCount;
+
+ /** 累计有效学习时间(秒) */
+ private Double effectiveTime;
+
+ /** 有效时间比之和,用于计算平均值(避免在 Java 侧再存一份分母之外的中间量) */
+ private Double effectivenessRatioSum;
+
+ /** 今日有效学习时间(秒),时间窗在 SQL 侧判断 */
+ private Double todayEffectiveTime;
+
+ /** 本周有效学习时间(秒),时间窗在 SQL 侧判断 */
+ private Double weekEffectiveTime;
+}
diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportFragmentsMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportFragmentsMapper.java
index 820cb9d..65d326f 100644
--- a/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportFragmentsMapper.java
+++ b/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportFragmentsMapper.java
@@ -1,8 +1,13 @@
package com.guo.learningprogresstracker.mapper;
+import com.guo.learningprogresstracker.dto.TaskContentCount;
import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.Collection;
+import java.util.List;
/**
* @author guo
@@ -13,6 +18,13 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudyReportFragmentsMapper extends BaseMapper {
+ /**
+ * 按内容归属统计任务下的知识碎片条数(数据-02):碎片 → 会话 → 任务。
+ * 语句见 {@code resources/mapper/StudyReportFragmentsMapper.xml};返回行数与任务数同阶。
+ *
+ * @param taskNums 需要统计的任务编号;为空时返回空列表
+ */
+ List countFragmentsByTask(@Param("taskNums") Collection taskNums);
}
diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportsMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportsMapper.java
index 9c496c4..83c20cb 100644
--- a/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportsMapper.java
+++ b/src/main/java/com/guo/learningprogresstracker/mapper/StudyReportsMapper.java
@@ -1,11 +1,15 @@
package com.guo.learningprogresstracker.mapper;
+import com.guo.learningprogresstracker.dto.TaskContentCount;
import com.guo.learningprogresstracker.dto.StudySessionsDto;
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
+import java.util.Collection;
+import java.util.List;
+
/**
* @author guo
* @description 针对表【study_reports(存储每次学习结束时的完整学习报告)】的数据库操作Mapper
@@ -16,6 +20,14 @@ import org.apache.ibatis.annotations.Param;
public interface StudyReportsMapper extends BaseMapper {
StudySessionsDto getNotEndedStudySessionDtoByTaskNum(@Param("task_num") String taskNum);
+
+ /**
+ * 按内容归属统计任务下的学习报告条数(数据-02):报告 → 会话 → 任务。
+ * 语句见 {@code resources/mapper/StudyReportsMapper.xml};返回行数与任务数同阶。
+ *
+ * @param taskNums 需要统计的任务编号;为空时返回空列表
+ */
+ List countReportsByTask(@Param("taskNums") Collection taskNums);
}
diff --git a/src/main/java/com/guo/learningprogresstracker/mapper/StudySessionsMapper.java b/src/main/java/com/guo/learningprogresstracker/mapper/StudySessionsMapper.java
index 2575767..5bc5ab5 100644
--- a/src/main/java/com/guo/learningprogresstracker/mapper/StudySessionsMapper.java
+++ b/src/main/java/com/guo/learningprogresstracker/mapper/StudySessionsMapper.java
@@ -1,5 +1,6 @@
package com.guo.learningprogresstracker.mapper;
+import com.guo.learningprogresstracker.dto.TaskSessionStats;
import com.guo.learningprogresstracker.entity.StudySessionsEntity;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
@@ -9,6 +10,7 @@ import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.time.LocalDateTime;
+import java.util.Collection;
import java.util.List;
/**
@@ -63,4 +65,17 @@ public interface StudySessionsMapper extends BaseMapper {
AND deleted = 0
""")
int convergeStaleSession(StudySessionsEntity session);
+
+ /**
+ * 任务维度的学习统计聚合(数据-02):次数、累计/今日/本周有效时间与有效时间比之和。
+ * 语句见 {@code resources/mapper/StudySessionsMapper.xml}:时间窗在 SQL 侧判断,
+ * 返回行数与任务数同阶,不随历史会话数增长。
+ *
+ * @param taskNums 需要统计的任务编号;为空时返回空列表
+ * @param todayStart 今日起点(含)
+ * @param weekStart 本周起点(含)
+ */
+ List sumStudyStatsByTask(@Param("taskNums") Collection taskNums,
+ @Param("todayStart") LocalDateTime todayStart,
+ @Param("weekStart") LocalDateTime weekStart);
}
diff --git a/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImpl.java b/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImpl.java
index 6055cf9..717dab7 100644
--- a/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImpl.java
+++ b/src/main/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImpl.java
@@ -3,7 +3,9 @@ package com.guo.learningprogresstracker.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.guo.learningprogresstracker.dto.ReviewFeedItem;
import com.guo.learningprogresstracker.dto.ReviewTaskStats;
+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.StudyReportFragmentsEntity;
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
@@ -325,6 +327,10 @@ public class ReviewServiceImpl implements ReviewService {
}
}
+ /**
+ * 填充任务维度统计(数据-02):三类聚合(会话统计、报告数、碎片数)全部下推到 SQL,
+ * 每次查询只返回「任务数」量级的行,不随历史会话/内容条数线性增长。
+ */
private void fillReviewTaskStats(List statsList) {
Map statsByTaskNum = statsList.stream()
.filter(item -> StringUtils.hasText(item.getTaskNum()))
@@ -338,50 +344,50 @@ public class ReviewServiceImpl implements ReviewService {
return;
}
- List sessions = studySessionsMapper.selectList(
- Wrappers.lambdaQuery()
- .in(StudySessionsEntity::getTaskNum, statsByTaskNum.keySet()));
-
+ Set taskNums = statsByTaskNum.keySet();
LocalDateTime todayStart = LocalDate.now().atStartOfDay();
LocalDateTime weekStart = LocalDate.now().with(DayOfWeek.MONDAY).atStartOfDay();
- Map sessionToTaskNum = new HashMap<>();
- Map effectivenessRatioSum = new HashMap<>();
- for (StudySessionsEntity session : sessions) {
- ReviewTaskStats stats = statsByTaskNum.get(session.getTaskNum());
+ for (TaskSessionStats row : studySessionsMapper.sumStudyStatsByTask(taskNums, todayStart, weekStart)) {
+ ReviewTaskStats stats = statsByTaskNum.get(row.getTaskNum());
if (stats == null) {
continue;
}
-
- if (StringUtils.hasText(session.getSessionNum())) {
- sessionToTaskNum.put(session.getSessionNum(), session.getTaskNum());
- }
-
- double effectiveTime = session.getEffectiveTime();
- stats.setSessionCount(stats.getSessionCount() + 1);
- stats.setEffectiveTime(stats.getEffectiveTime() + effectiveTime);
- effectivenessRatioSum.merge(session.getTaskNum(), session.getEffectivenessRatio(), Double::sum);
-
- LocalDateTime startTime = session.getStartTime();
- if (startTime != null && !startTime.isBefore(todayStart)) {
- stats.setTodayEffectiveTime(stats.getTodayEffectiveTime() + effectiveTime);
- }
- if (startTime != null && !startTime.isBefore(weekStart)) {
- stats.setWeekEffectiveTime(stats.getWeekEffectiveTime() + effectiveTime);
+ 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);
}
}
- statsByTaskNum.forEach((taskNum, stats) -> {
- if (stats.getSessionCount() > 0) {
- stats.setAvgEffectiveTime(stats.getEffectiveTime() / stats.getSessionCount());
- stats.setAvgEffectivenessRatio(effectivenessRatioSum.getOrDefault(taskNum, 0D) / stats.getSessionCount());
- }
- });
-
- fillReportAndFragmentCount(sessionToTaskNum, statsByTaskNum);
+ 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。
@@ -395,34 +401,4 @@ public class ReviewServiceImpl implements ReviewService {
}
}
}
-
- private void fillReportAndFragmentCount(Map sessionToTaskNum,
- Map statsByTaskNum) {
- if (sessionToTaskNum.isEmpty()) {
- return;
- }
-
- Set sessionNums = sessionToTaskNum.keySet();
- List reports = studyReportsMapper.selectList(
- Wrappers.lambdaQuery()
- .in(StudyReportsEntity::getSessionNum, sessionNums)
- .select(StudyReportsEntity::getSessionNum));
- for (StudyReportsEntity report : reports) {
- ReviewTaskStats stats = statsByTaskNum.get(sessionToTaskNum.get(report.getSessionNum()));
- if (stats != null) {
- stats.setReportCount(stats.getReportCount() + 1);
- }
- }
-
- List fragments = studyReportFragmentsMapper.selectList(
- Wrappers.lambdaQuery()
- .in(StudyReportFragmentsEntity::getSessionNum, sessionNums)
- .select(StudyReportFragmentsEntity::getSessionNum));
- for (StudyReportFragmentsEntity fragment : fragments) {
- ReviewTaskStats stats = statsByTaskNum.get(sessionToTaskNum.get(fragment.getSessionNum()));
- if (stats != null) {
- stats.setFragmentCount(stats.getFragmentCount() + 1);
- }
- }
- }
}
diff --git a/src/main/resources/db/migration/V20261009_5__fix_study_sessions_time_column_types.sql b/src/main/resources/db/migration/V20261009_5__fix_study_sessions_time_column_types.sql
new file mode 100644
index 0000000..536d9f1
--- /dev/null
+++ b/src/main/resources/db/migration/V20261009_5__fix_study_sessions_time_column_types.sql
@@ -0,0 +1,28 @@
+-- 修正会话计时列的类型:actual_time / effective_time 是秒数(Java 侧为 double),
+-- 但初始迁移把它们声明成了 mediumtext。后果:
+-- 1. 无法建索引,ORDER BY / 比较按字符串语义;
+-- 2. 任何 SQL 聚合(SUM/AVG)都只能依赖隐式字符串→数字转换;
+-- 3. H2 / PostgreSQL 直接拒绝 SUM(text),导致统计聚合无法下推(数据-02 因此受阻)。
+-- 本迁移把它们改为 DOUBLE,与实体字段语义一致。
+--
+-- 部署前建议先核对是否真的存在非数值内容(应为 0 行):
+-- SELECT id, actual_time, effective_time FROM study_sessions
+-- WHERE (actual_time IS NOT NULL AND actual_time NOT REGEXP '^-?[0-9]+(\\.[0-9]+)?$')
+-- OR (effective_time IS NOT NULL AND effective_time NOT REGEXP '^-?[0-9]+(\\.[0-9]+)?$');
+-- 下面两步先把这些异常值规范为 0(只动确实非数值的行),再改类型,避免 ALTER 期间报错。
+
+UPDATE study_sessions
+SET actual_time = '0'
+WHERE actual_time IS NOT NULL
+ AND actual_time NOT REGEXP '^-?[0-9]+(\\.[0-9]+)?$';
+
+UPDATE study_sessions
+SET effective_time = '0'
+WHERE effective_time IS NOT NULL
+ AND effective_time NOT REGEXP '^-?[0-9]+(\\.[0-9]+)?$';
+
+ALTER TABLE study_sessions
+ MODIFY COLUMN actual_time DOUBLE NULL DEFAULT 0 COMMENT '实际使用时间(秒)';
+
+ALTER TABLE study_sessions
+ MODIFY COLUMN effective_time DOUBLE NULL DEFAULT 0 COMMENT '有效学习时间(秒)';
diff --git a/src/main/resources/mapper/StudyReportFragmentsMapper.xml b/src/main/resources/mapper/StudyReportFragmentsMapper.xml
index f39a103..2908666 100644
--- a/src/main/resources/mapper/StudyReportFragmentsMapper.xml
+++ b/src/main/resources/mapper/StudyReportFragmentsMapper.xml
@@ -19,4 +19,29 @@
created_time,created_by,last_modified_time,
last_modified_by
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/mapper/StudyReportsMapper.xml b/src/main/resources/mapper/StudyReportsMapper.xml
index d199754..61e4b08 100644
--- a/src/main/resources/mapper/StudyReportsMapper.xml
+++ b/src/main/resources/mapper/StudyReportsMapper.xml
@@ -30,4 +30,29 @@
order by ss.last_modified_time desc, ss.created_time desc
limit 1
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/mapper/StudySessionsMapper.xml b/src/main/resources/mapper/StudySessionsMapper.xml
index 886fdcd..7bb5923 100644
--- a/src/main/resources/mapper/StudySessionsMapper.xml
+++ b/src/main/resources/mapper/StudySessionsMapper.xml
@@ -4,4 +4,37 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImplTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImplTest.java
index be6bb40..227aead 100644
--- a/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImplTest.java
+++ b/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewServiceImplTest.java
@@ -4,7 +4,9 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.guo.learningprogresstracker.dto.ReviewFeedItem;
import com.guo.learningprogresstracker.dto.ReviewTaskStats;
+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.StudyReportFragmentsEntity;
import com.guo.learningprogresstracker.entity.StudyReportsEntity;
@@ -149,17 +151,19 @@ class ReviewServiceImplTest {
task.setTaskNum("T1");
task.setTaskName("任务一");
- StudySessionsEntity session = new StudySessionsEntity();
- session.setSessionNum("S1");
- session.setTaskNum("T1");
- session.setEffectiveTime(600);
- session.setEffectivenessRatio(0.8);
- session.setStartTime(LocalDateTime.now());
+ // 数据-02:会话统计、报告数、碎片数均由 SQL 聚合返回,服务层不再加载全部会话
+ TaskSessionStats sessionStats = new TaskSessionStats();
+ sessionStats.setTaskNum("T1");
+ sessionStats.setSessionCount(1L);
+ sessionStats.setEffectiveTime(600D);
+ sessionStats.setEffectivenessRatioSum(0.8D);
+ sessionStats.setTodayEffectiveTime(600D);
+ sessionStats.setWeekEffectiveTime(600D);
when(tasksMapper.selectList(any())).thenReturn(List.of(task));
- when(studySessionsMapper.selectList(any())).thenReturn(List.of(session));
- when(studyReportsMapper.selectList(any())).thenReturn(List.of());
- when(studyReportFragmentsMapper.selectList(any())).thenReturn(List.of());
+ when(studySessionsMapper.sumStudyStatsByTask(any(), any(), any())).thenReturn(List.of(sessionStats));
+ when(studyReportsMapper.countReportsByTask(any())).thenReturn(List.of(count("T1", 2L)));
+ when(studyReportFragmentsMapper.countFragmentsByTask(any())).thenReturn(List.of(count("T1", 3L)));
// 聚合结果里出现了不在任务列表中的 taskNum,应被忽略
when(reviewRecallRecordMapper.sumReviewDurationByTask(any())).thenReturn(List.of(
reviewDuration("T1", 420L),
@@ -169,9 +173,21 @@ class ReviewServiceImplTest {
assertEquals(1, stats.size());
assertEquals(600, stats.get(0).getEffectiveTime());
+ assertEquals(1, stats.get(0).getSessionCount());
+ assertEquals(2, stats.get(0).getReportCount());
+ assertEquals(3, stats.get(0).getFragmentCount());
+ assertEquals(600, stats.get(0).getTodayEffectiveTime());
+ assertEquals(0.8, stats.get(0).getAvgEffectivenessRatio(), 0.0001);
assertEquals(420L, stats.get(0).getReviewDurationSeconds());
}
+ private static TaskContentCount count(String taskNum, Long value) {
+ TaskContentCount row = new TaskContentCount();
+ row.setTaskNum(taskNum);
+ row.setContentCount(value);
+ return row;
+ }
+
private static TaskReviewDuration reviewDuration(String taskNum, Long seconds) {
TaskReviewDuration row = new TaskReviewDuration();
row.setTaskNum(taskNum);
diff --git a/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewStatsAggregationIntegrationTest.java b/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewStatsAggregationIntegrationTest.java
new file mode 100644
index 0000000..5244a43
--- /dev/null
+++ b/src/test/java/com/guo/learningprogresstracker/service/impl/ReviewStatsAggregationIntegrationTest.java
@@ -0,0 +1,184 @@
+package com.guo.learningprogresstracker.service.impl;
+
+import cn.dev33.satoken.stp.StpUtil;
+import com.guo.learningprogresstracker.dto.ReviewTaskStats;
+import com.guo.learningprogresstracker.dto.TaskContentCount;
+import com.guo.learningprogresstracker.dto.TaskSessionStats;
+import com.guo.learningprogresstracker.entity.StudyReportFragmentsEntity;
+import com.guo.learningprogresstracker.entity.StudyReportsEntity;
+import com.guo.learningprogresstracker.entity.StudySessionsEntity;
+import com.guo.learningprogresstracker.enums.StudySessionStateEnum;
+import com.guo.learningprogresstracker.mapper.StudyReportFragmentsMapper;
+import com.guo.learningprogresstracker.mapper.StudyReportsMapper;
+import com.guo.learningprogresstracker.mapper.StudySessionsMapper;
+import com.guo.learningprogresstracker.service.ReviewService;
+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.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * 复习统计聚合的落库集成测试(数据-02)。
+ *
+ * 核心验收:聚合返回的行数与「任务数」同阶,不随历史会话数线性增长;
+ * 同时守住自定义 SQL 的两个隐式条件(租户隔离与逻辑删除)。
+ */
+@SpringBootTest
+class ReviewStatsAggregationIntegrationTest {
+
+ private static final String USER = "统计聚合集成测试用户";
+
+ private static final AtomicInteger SEQ = new AtomicInteger();
+
+ @Autowired
+ private ReviewService reviewService;
+
+ @Autowired
+ private StudySessionsMapper studySessionsMapper;
+
+ @Autowired
+ private StudyReportsMapper studyReportsMapper;
+
+ @Autowired
+ private StudyReportFragmentsMapper studyReportFragmentsMapper;
+
+ @BeforeEach
+ void setUp() {
+ StpUtil.login(USER, "test_device");
+ }
+
+ private static String uniqueTaskNum() {
+ return "TASKAGG-IT-" + System.nanoTime() + "-" + SEQ.incrementAndGet();
+ }
+
+ @Test
+ void aggregation_rowCountIsBoundedByTaskCountNotSessionCount() {
+ String taskNum = uniqueTaskNum();
+ // 同一个任务下堆很多会话:聚合查询只应返回 1 行
+ for (int i = 0; i < 30; i++) {
+ saveSession(taskNum, 60, LocalDateTime.now().minusDays(i));
+ }
+
+ List rows = studySessionsMapper.sumStudyStatsByTask(
+ Set.of(taskNum), LocalDate.now().atStartOfDay(),
+ LocalDate.now().with(DayOfWeek.MONDAY).atStartOfDay());
+
+ assertEquals(1, rows.size(), "同一任务下 30 个会话应聚合成 1 行");
+ assertEquals(30L, rows.get(0).getSessionCount());
+ assertEquals(30 * 60D, rows.get(0).getEffectiveTime(), 0.001);
+ }
+
+ @Test
+ void statsAggregateTimeWindowsAndAveragesInSql() {
+ String taskNum = uniqueTaskNum();
+ saveSession(taskNum, 600, LocalDateTime.now()); // 今日 / 本周
+ saveSession(taskNum, 300, LocalDateTime.now().minusDays(1)); // 本周(若今天是周一则属上周)
+ saveSession(taskNum, 120, LocalDateTime.now().minusDays(20)); // 本月早些时候,肯定不在本周
+
+ ReviewTaskStats stats = reviewService.getReviewTaskStats(taskNum);
+
+ assertEquals(3, stats.getSessionCount());
+ assertEquals(1020D, stats.getEffectiveTime(), 0.001);
+ assertEquals(340D, stats.getAvgEffectiveTime(), 0.001, "平均有效时间 = 累计 / 会话数");
+ assertEquals(600D, stats.getTodayEffectiveTime(), 0.001, "今日窗口只应包含今天的会话");
+ assertTrue(stats.getWeekEffectiveTime() >= 600D, "本周窗口至少包含今天的会话");
+ assertTrue(stats.getWeekEffectiveTime() <= 1020D);
+ }
+
+ @Test
+ void contentCountsAreGroupedByOwnershipNotBySession() {
+ String taskNum = uniqueTaskNum();
+ StudySessionsEntity first = saveSession(taskNum, 60, LocalDateTime.now());
+ StudySessionsEntity second = saveSession(taskNum, 60, LocalDateTime.now());
+
+ insertReport(first.getSessionNum());
+ insertReport(first.getSessionNum());
+ insertFragment(second.getSessionNum());
+
+ List reports = studyReportsMapper.countReportsByTask(Set.of(taskNum));
+ List fragments = studyReportFragmentsMapper.countFragmentsByTask(Set.of(taskNum));
+
+ assertEquals(1, reports.size(), "报告计数也应按任务聚合成 1 行");
+ assertEquals(1, fragments.size(), "碎片计数也应按任务聚合成 1 行");
+ assertEquals(2L, reports.get(0).getContentCount(), "两个会话下的报告都应归属到同一任务");
+ assertEquals(1L, fragments.get(0).getContentCount());
+ }
+
+ @Test
+ void contentCountsExcludeLogicallyDeletedRows() {
+ String taskNum = uniqueTaskNum();
+ StudySessionsEntity session = saveSession(taskNum, 60, LocalDateTime.now());
+
+ StudyReportsEntity kept = insertReport(session.getSessionNum());
+ StudyReportsEntity deleted = insertReport(session.getSessionNum());
+ studyReportsMapper.deleteById(deleted.getId());
+
+ StudyReportFragmentsEntity deletedFragment = insertFragment(session.getSessionNum());
+ studyReportFragmentsMapper.deleteById(deletedFragment.getId());
+
+ List reports = studyReportsMapper.countReportsByTask(Set.of(taskNum));
+ List fragments = studyReportFragmentsMapper.countFragmentsByTask(Set.of(taskNum));
+
+ assertEquals(1L, reports.get(0).getContentCount(), "逻辑删除的报告不应计入");
+ assertTrue(fragments.isEmpty() || fragments.get(0).getContentCount() == 0L,
+ "逻辑删除的碎片不应计入");
+ assertNotNull(kept.getId(), "保留的报告应正常落库");
+ }
+
+ @Test
+ void statsOnlyCountCurrentTenant() {
+ String taskNum = uniqueTaskNum();
+ saveSession(taskNum, 600, LocalDateTime.now());
+
+ StpUtil.login("统计聚合集成测试另一个用户", "test_device");
+ ReviewTaskStats otherStats = reviewService.getReviewTaskStats(taskNum);
+ assertEquals(0, otherStats.getSessionCount(), "统计聚合必须受租户隔离约束");
+ assertEquals(0D, otherStats.getEffectiveTime(), 0.001);
+
+ StpUtil.login(USER, "test_device");
+ assertEquals(1, reviewService.getReviewTaskStats(taskNum).getSessionCount());
+ }
+
+ private StudySessionsEntity saveSession(String taskNum, long effectiveSeconds, LocalDateTime startTime) {
+ StudySessionsEntity session = new StudySessionsEntity();
+ session.setSessionNum(GenerateNumTool.generateNum("SESSIONAGG"));
+ session.setTaskNum(taskNum);
+ session.setStartTime(startTime);
+ session.setLastStartTime(startTime);
+ session.setEndTime(startTime.plusSeconds(effectiveSeconds));
+ session.setActualTime(effectiveSeconds);
+ session.setEffectiveTime(effectiveSeconds);
+ session.setEffectivenessRatio(1.0);
+ session.setSessionState(StudySessionStateEnum.ENDED.name());
+ studySessionsMapper.insert(session);
+ return session;
+ }
+
+ private StudyReportsEntity insertReport(String sessionNum) {
+ StudyReportsEntity report = new StudyReportsEntity();
+ report.setSessionNum(sessionNum);
+ report.setContent("集成测试报告");
+ studyReportsMapper.insert(report);
+ return report;
+ }
+
+ private StudyReportFragmentsEntity insertFragment(String sessionNum) {
+ StudyReportFragmentsEntity fragment = new StudyReportFragmentsEntity();
+ fragment.setSessionNum(sessionNum);
+ fragment.setContent("集成测试碎片");
+ studyReportFragmentsMapper.insert(fragment);
+ return fragment;
+ }
+}