feat: 新增学习数据导出接口

This commit is contained in:
2026-10-09 12:20:36 +08:00
parent 3cc3be1c8b
commit faaaa132c1
12 changed files with 950 additions and 1 deletions
+2 -1
View File
@@ -44,7 +44,7 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/
- entity 使用 `@TableName`、`@TableField` 映射数据库字段。
- mapStruct 承载 DTO 转换。
## API 端点总览(44 个)
## API 端点总览(46 个)
| 模块 | 端点数 | 端点 |
|------|--------|------|
@@ -53,6 +53,7 @@ lpt-be/src/main/java/com/guo/learningprogresstracker/
| 任务管理 | 13 | `GET/POST /tasks`, `GET/PUT/DELETE /tasks/{taskId}`, `GET/PUT /tasks/priority-weights`, `GET/POST /tasks/{taskNum}/applications`, `PUT/DELETE /tasks/applications/{id}`, `GET /tasks/{taskNum}/study-sessions/start-or-continue`, `GET /tasks/{taskNum}/not-ended-study-session` |
| 复习与导图 | 13 | `GET /review/feed`, `GET /review/tasks`, `GET /review/tasks/{taskNum}`, `GET /review/task/{taskNum}`, `GET /review/report/{id}`, `GET /review/fragment/{id}`, `GET /review/standard-mind-map/{taskNum}`, `POST /review/standard-mind-map/{taskNum}/regenerate`, `PUT /review/standard-mind-map/{taskNum}`, `POST /review/standard-mind-map/{taskNum}/recall`, `POST /review/standard-mind-map/{taskNum}/find-node`, `GET /review/standard-mind-map/{taskNum}/recall-records`, `GET /review/standard-mind-map/recall-records/{recordId}` |
| 学习残片 | 3 | `POST /report-fragments`, `PUT /report-fragments/{id}`, `GET /report-fragments/session/{sessionNum}` |
| 数据导出 | 2 | `GET /export/task/{taskNum}`, `GET /export/range` |
| 工具 | 1 | `GET /utils/fetch-title?url=...` |
| 测试 | 1 | `GET /test/{id}` |
@@ -0,0 +1,50 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.ExportResult;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.exception.OperationFailedException;
import com.guo.learningprogresstracker.service.ExportService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
/**
* 数据导出控制层(导出-01):把学习报告、知识碎片与任务统计导出为 Markdown / JSON。
*/
@RequestMapping("/export")
@RestController
@Validated
@RequiredArgsConstructor
public class ExportController {
private final ExportService exportService;
/**
* 导出单个学习任务的全部学习记录
* @param format markdown(默认)或 json
*/
@GetMapping("/task/{taskNum}")
public CommonResult<ExportResult> exportTask(
@PathVariable String taskNum,
@RequestParam(defaultValue = "markdown") String format)
throws NotFindEntitiesException, OperationFailedException {
return CommonResult.success(exportService.exportTask(taskNum, format));
}
/**
* 按时间范围导出学习记录(起止日期都可省略,都省略为全部时间)
* @param format markdown(默认)或 json
*/
@GetMapping("/range")
public CommonResult<ExportResult> exportRange(
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
@RequestParam(defaultValue = "markdown") String format)
throws OperationFailedException {
return CommonResult.success(exportService.exportRange(startDate, endDate, format));
}
}
@@ -0,0 +1,29 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* 一次导出的完整文档(导出-01)。Markdown 与 JSON 都由它渲染,保证两种格式内容一致。
*/
@Data
public class ExportDocument {
private LocalDateTime generatedTime;
/** TASK / RANGE / ALL */
private String scopeType;
/** 面向读者的范围描述 */
private String scopeLabel;
private LocalDate startDate;
private LocalDate endDate;
private List<ExportTaskSection> tasks = new ArrayList<>();
}
@@ -0,0 +1,22 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 导出的一条内容(学习报告或知识碎片,导出-01)。
*/
@Data
public class ExportEntry {
private Integer id;
/** 记录上下文:产生这条内容的学习会话编号 */
private String sessionNum;
private LocalDateTime createdTime;
/** 报告或碎片的原文 */
private String content;
}
@@ -0,0 +1,25 @@
package com.guo.learningprogresstracker.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 导出结果(导出-01)。
* <p>内容随统一响应体返回,由前端落成文件下载;这样既保持 {@code CommonResult} 的统一包装,
* 也不需要在服务端拼 Content-Disposition。</p>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExportResult {
/** 建议的文件名,含扩展名 */
private String fileName;
/** text/markdown; charset=UTF-8 或 application/json; charset=UTF-8 */
private String contentType;
/** 可独立阅读的导出正文 */
private String content;
}
@@ -0,0 +1,24 @@
package com.guo.learningprogresstracker.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 导出文档中的一个学习任务段落(导出-01)。
*/
@Data
public class ExportTaskSection {
private String taskNum;
private String taskName;
/** 任务维度统计:学习时长、复习耗时、报告/碎片数量等 */
private ReviewTaskStats stats;
private List<ExportEntry> reports = new ArrayList<>();
private List<ExportEntry> fragments = new ArrayList<>();
}
@@ -0,0 +1,31 @@
package com.guo.learningprogresstracker.service;
import com.guo.learningprogresstracker.dto.ExportResult;
import com.guo.learningprogresstracker.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.exception.OperationFailedException;
import java.time.LocalDate;
/**
* 数据导出服务(导出-01)。
* <p>导出学习报告、知识碎片与任务统计,支持按任务或时间范围筛选,输出 Markdown 或 JSON。</p>
*/
public interface ExportService {
/**
* 导出单个学习任务的全部学习记录。
*
* @param taskNum 任务编号
* @param format markdown / md / json,缺省为 markdown
*/
ExportResult exportTask(String taskNum, String format) throws NotFindEntitiesException, OperationFailedException;
/**
* 按时间范围导出学习记录;起止日期都可为空,都为空表示导出全部时间。
*
* @param startDate 起始日期(含),可为空
* @param endDate 结束日期(含),可为空
* @param format markdown / md / json,缺省为 markdown
*/
ExportResult exportRange(LocalDate startDate, LocalDate endDate, String format) throws OperationFailedException;
}
@@ -0,0 +1,274 @@
package com.guo.learningprogresstracker.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guo.learningprogresstracker.dto.*;
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.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.exception.OperationFailedException;
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.service.ExportService;
import com.guo.learningprogresstracker.service.ReviewService;
import com.guo.learningprogresstracker.utils.ExportMarkdownRenderer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
/**
* 数据导出实现(导出-01)。
* <p>两种格式共用同一个 {@link ExportDocument} 模型,保证 Markdown 与 JSON 内容一致。</p>
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class ExportServiceImpl implements ExportService {
private static final String FORMAT_MARKDOWN = "markdown";
private static final String FORMAT_MD_ALIAS = "md";
private static final String FORMAT_JSON = "json";
private static final String CONTENT_TYPE_MARKDOWN = "text/markdown; charset=UTF-8";
private static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
private static final String SOURCE_REPORT = "REPORT";
private static final String SCOPE_TASK = "TASK";
private static final String SCOPE_RANGE = "RANGE";
private static final String SCOPE_ALL = "ALL";
private static final DateTimeFormatter FILE_TIMESTAMP = DateTimeFormatter.ofPattern("yyyyMMdd-HHmm");
/** 文件名里的不安全字符 */
private static final String UNSAFE_FILE_CHARS = "[\\\\/:*?\"<>|\\r\\n]";
private static final int MAX_FILE_NAME_PART_LENGTH = 40;
private final TasksMapper tasksMapper;
private final StudyReportsMapper studyReportsMapper;
private final StudyReportFragmentsMapper studyReportFragmentsMapper;
private final StudySessionsMapper studySessionsMapper;
private final ReviewService reviewService;
private final ObjectMapper objectMapper;
@Override
public ExportResult exportTask(String taskNum, String format)
throws NotFindEntitiesException, OperationFailedException {
String safeFormat = normalizeFormat(format);
TaskEntity task = tasksMapper.selectList(Wrappers.<TaskEntity>lambdaQuery()
.eq(TaskEntity::getTaskNum, taskNum)
.last("LIMIT 1"))
.stream()
.findFirst()
.orElseThrow(() -> {
log.warn("任务[{}]不存在,无法导出", taskNum);
return new NotFindEntitiesException("找不到这个学习任务,可能已经被删除了");
});
ExportTaskSection section = new ExportTaskSection();
section.setTaskNum(task.getTaskNum());
section.setTaskName(task.getTaskName());
section.setStats(reviewService.getReviewTaskStats(taskNum));
applyFeedItems(section, reviewService.getTaskReview(taskNum));
ExportDocument document = new ExportDocument();
document.setGeneratedTime(LocalDateTime.now());
document.setScopeType(SCOPE_TASK);
document.setScopeLabel("学习任务「" + task.getTaskName() + "」(" + task.getTaskNum() + ")");
document.setTasks(List.of(section));
return buildResult(document, safeFormat, "LPT-学习数据-" + sanitizeFileName(task.getTaskName()));
}
@Override
public ExportResult exportRange(LocalDate startDate, LocalDate endDate, String format)
throws OperationFailedException {
String safeFormat = normalizeFormat(format);
if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
throw new OperationFailedException("开始日期不能晚于结束日期");
}
LocalDateTime from = startDate == null ? null : startDate.atStartOfDay();
LocalDateTime to = endDate == null ? null : endDate.atTime(LocalTime.MAX);
List<StudyReportsEntity> reports = studyReportsMapper.selectList(Wrappers.<StudyReportsEntity>lambdaQuery()
.ge(from != null, StudyReportsEntity::getCreatedTime, from)
.le(to != null, StudyReportsEntity::getCreatedTime, to)
.orderByDesc(StudyReportsEntity::getCreatedTime));
List<StudyReportFragmentsEntity> fragments = studyReportFragmentsMapper.selectList(
Wrappers.<StudyReportFragmentsEntity>lambdaQuery()
.ge(from != null, StudyReportFragmentsEntity::getCreatedTime, from)
.le(to != null, StudyReportFragmentsEntity::getCreatedTime, to)
.orderByDesc(StudyReportFragmentsEntity::getCreatedTime));
Map<String, ExportTaskSection> sections = new LinkedHashMap<>();
appendRangeItems(sections, reports, fragments);
sections.values().forEach(section -> section.setStats(reviewService.getReviewTaskStats(section.getTaskNum())));
ExportDocument document = new ExportDocument();
document.setGeneratedTime(LocalDateTime.now());
document.setScopeType(startDate == null && endDate == null ? SCOPE_ALL : SCOPE_RANGE);
document.setScopeLabel(scopeLabel(startDate, endDate));
document.setStartDate(startDate);
document.setEndDate(endDate);
document.setTasks(new ArrayList<>(sections.values()));
return buildResult(document, safeFormat, "LPT-学习数据");
}
/** 任务级导出:把 feed 条目按来源拆成报告与碎片 */
private void applyFeedItems(ExportTaskSection section, List<ReviewFeedItem> items) {
if (items == null) {
return;
}
for (ReviewFeedItem item : items) {
ExportEntry entry = new ExportEntry();
entry.setId(item.getId());
entry.setSessionNum(item.getSessionNum());
entry.setCreatedTime(item.getCreatedTime());
entry.setContent(item.getContent());
if (SOURCE_REPORT.equals(item.getSourceType())) {
section.getReports().add(entry);
} else {
section.getFragments().add(entry);
}
}
}
/**
* 范围级导出:报告与碎片先按时间倒序合并,再按内容归属(学习任务)分组,
* 保证同一任务下两种内容交错时顺序仍然正确。
*/
private void appendRangeItems(Map<String, ExportTaskSection> sections,
List<StudyReportsEntity> reports,
List<StudyReportFragmentsEntity> fragments) {
List<RangeItem> items = new ArrayList<>();
for (StudyReportsEntity report : reports) {
items.add(new RangeItem(report.getSessionNum(), report.getId(), report.getCreatedTime(), report.getContent(), true));
}
for (StudyReportFragmentsEntity fragment : fragments) {
items.add(new RangeItem(fragment.getSessionNum(), fragment.getId(), fragment.getCreatedTime(), fragment.getContent(), false));
}
items.sort(Comparator.comparing(RangeItem::createdTime, Comparator.nullsLast(Comparator.reverseOrder())));
Set<String> sessionNums = items.stream()
.map(RangeItem::sessionNum)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Map<String, String> sessionToTask = resolveSessionToTask(sessionNums);
Map<String, String> taskNames = resolveTaskNames(new HashSet<>(sessionToTask.values()));
for (RangeItem item : items) {
String taskNum = sessionToTask.get(item.sessionNum());
if (taskNum == null) {
// 学习会话已被删除时无法归属,跳过而不是塞进错误的段落
continue;
}
ExportTaskSection section = sections.computeIfAbsent(taskNum, num -> {
ExportTaskSection created = new ExportTaskSection();
created.setTaskNum(num);
created.setTaskName(taskNames.get(num));
return created;
});
ExportEntry entry = new ExportEntry();
entry.setId(item.id());
entry.setSessionNum(item.sessionNum());
entry.setCreatedTime(item.createdTime());
entry.setContent(item.content());
if (item.report()) {
section.getReports().add(entry);
} else {
section.getFragments().add(entry);
}
}
}
private Map<String, String> resolveSessionToTask(Set<String> sessionNums) {
if (sessionNums.isEmpty()) {
return Collections.emptyMap();
}
return studySessionsMapper.selectList(Wrappers.<StudySessionsEntity>lambdaQuery()
.in(StudySessionsEntity::getSessionNum, sessionNums)
.select(StudySessionsEntity::getSessionNum, StudySessionsEntity::getTaskNum))
.stream()
.filter(session -> session.getSessionNum() != null && session.getTaskNum() != null)
.collect(Collectors.toMap(
StudySessionsEntity::getSessionNum,
StudySessionsEntity::getTaskNum,
(a, b) -> a));
}
private Map<String, String> resolveTaskNames(Set<String> taskNums) {
if (taskNums.isEmpty()) {
return Collections.emptyMap();
}
return tasksMapper.selectList(Wrappers.<TaskEntity>lambdaQuery()
.in(TaskEntity::getTaskNum, taskNums)
.select(TaskEntity::getTaskNum, TaskEntity::getTaskName))
.stream()
.filter(task -> task.getTaskNum() != null)
.collect(Collectors.toMap(
TaskEntity::getTaskNum,
task -> task.getTaskName() == null ? "" : task.getTaskName(),
(a, b) -> a));
}
private ExportResult buildResult(ExportDocument document, String format, String fileNamePrefix)
throws OperationFailedException {
String timestamp = LocalDateTime.now().format(FILE_TIMESTAMP);
if (FORMAT_JSON.equals(format)) {
try {
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(document);
return new ExportResult(fileNamePrefix + "-" + timestamp + ".json", CONTENT_TYPE_JSON, json);
} catch (JsonProcessingException e) {
log.error("导出内容序列化为 JSON 失败", e);
throw new OperationFailedException("导出内容生成失败了,请稍后再试");
}
}
return new ExportResult(fileNamePrefix + "-" + timestamp + ".md", CONTENT_TYPE_MARKDOWN,
ExportMarkdownRenderer.render(document));
}
private String normalizeFormat(String format) throws OperationFailedException {
String value = format == null ? "" : format.trim();
if (!StringUtils.hasText(value) || FORMAT_MARKDOWN.equalsIgnoreCase(value) || FORMAT_MD_ALIAS.equalsIgnoreCase(value)) {
return FORMAT_MARKDOWN;
}
if (FORMAT_JSON.equalsIgnoreCase(value)) {
return FORMAT_JSON;
}
log.warn("不支持的导出格式: {}", format);
throw new OperationFailedException("导出格式只能选 Markdown 或 JSON 哦");
}
private String scopeLabel(LocalDate startDate, LocalDate endDate) {
if (startDate == null && endDate == null) {
return "全部时间";
}
if (startDate != null && endDate != null) {
return startDate + " 至 " + endDate;
}
return startDate != null ? startDate + " 起" : "截至 " + endDate;
}
private String sanitizeFileName(String name) {
if (!StringUtils.hasText(name)) {
return "未命名任务";
}
String safe = name.replaceAll(UNSAFE_FILE_CHARS, "_").trim();
return safe.length() > MAX_FILE_NAME_PART_LENGTH ? safe.substring(0, MAX_FILE_NAME_PART_LENGTH) : safe;
}
/** 合并排序用的中间载体 */
private record RangeItem(String sessionNum, Integer id, LocalDateTime createdTime, String content,
boolean report) {
}
}
@@ -0,0 +1,106 @@
package com.guo.learningprogresstracker.utils;
import com.guo.learningprogresstracker.dto.ExportDocument;
import com.guo.learningprogresstracker.dto.ExportEntry;
import com.guo.learningprogresstracker.dto.ExportTaskSection;
import com.guo.learningprogresstracker.dto.ReviewTaskStats;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* 把导出文档渲染成可独立阅读的 Markdown(导出-01)。
* <p>纯函数,不依赖 Spring,便于单测。</p>
*/
public final class ExportMarkdownRenderer {
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private ExportMarkdownRenderer() {
}
public static String render(ExportDocument document) {
StringBuilder md = new StringBuilder();
md.append("# LPT 学习数据导出\n\n");
md.append("- 导出时间:").append(formatTime(document.getGeneratedTime())).append('\n');
md.append("- 导出范围:").append(nullToDash(document.getScopeLabel())).append('\n');
md.append("- 任务数:").append(document.getTasks() == null ? 0 : document.getTasks().size()).append("\n\n");
List<ExportTaskSection> tasks = document.getTasks();
if (tasks == null || tasks.isEmpty()) {
md.append("该范围内没有学习报告或知识碎片。\n");
return md.toString();
}
for (ExportTaskSection task : tasks) {
renderTask(md, task);
}
return md.toString();
}
private static void renderTask(StringBuilder md, ExportTaskSection task) {
md.append("---\n\n");
md.append("## 学习任务:").append(nullToDash(task.getTaskName())).append("\n\n");
md.append("- 任务编号:`").append(nullToDash(task.getTaskNum())).append("`\n");
ReviewTaskStats stats = task.getStats();
if (stats != null) {
md.append("- 累计有效学习时长:").append(formatDuration((long) stats.getEffectiveTime())).append('\n');
md.append("- 累计复习耗时:").append(formatDuration(stats.getReviewDurationSeconds())).append('\n');
md.append("- 学习会话:").append(stats.getSessionCount()).append(" 次\n");
md.append("- 学习报告:").append(stats.getReportCount()).append(" 份\n");
md.append("- 知识碎片:").append(stats.getFragmentCount()).append(" 条\n");
} else {
md.append("- 学习报告:").append(countOf(task.getReports())).append(" 份\n");
md.append("- 知识碎片:").append(countOf(task.getFragments())).append(" 条\n");
}
md.append('\n');
md.append("### 学习报告\n\n");
renderEntries(md, task.getReports(), "暂无学习报告");
md.append("### 知识碎片\n\n");
renderEntries(md, task.getFragments(), "暂无知识碎片");
}
private static void renderEntries(StringBuilder md, List<ExportEntry> entries, String emptyText) {
if (entries == null || entries.isEmpty()) {
md.append(emptyText).append("\n\n");
return;
}
int index = 1;
for (ExportEntry entry : entries) {
md.append("#### ").append(index++).append(". ")
.append(formatTime(entry.getCreatedTime()))
.append("(会话 `").append(nullToDash(entry.getSessionNum())).append("`)\n\n");
md.append(nullToDash(entry.getContent())).append("\n\n");
}
}
private static int countOf(List<ExportEntry> entries) {
return entries == null ? 0 : entries.size();
}
private static String formatTime(LocalDateTime time) {
return time == null ? "-" : DATE_TIME.format(time);
}
/** 秒 → 「X 小时 Y 分钟」;不足 1 分钟显示秒,避免把真实的分钟级投入显示成 0 */
static String formatDuration(Long seconds) {
long value = seconds == null ? 0L : Math.max(0L, seconds);
long hours = value / 3600;
long minutes = (value % 3600) / 60;
if (hours > 0) {
return hours + " 小时 " + minutes + " 分钟";
}
if (value >= 60) {
return minutes + " 分钟";
}
return value + " 秒";
}
private static String nullToDash(String text) {
return (text == null || text.isBlank()) ? "-" : text;
}
}
@@ -0,0 +1,65 @@
package com.guo.learningprogresstracker.controller;
import com.guo.learningprogresstracker.dto.ExportResult;
import com.guo.learningprogresstracker.entity.CommonResult;
import com.guo.learningprogresstracker.service.ExportService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* ExportController 纯单元测试(导出-01):直接 new 控制器并 mock 服务接口。
*/
@ExtendWith(MockitoExtension.class)
class ExportControllerUnitTest {
@Mock
private ExportService exportService;
@InjectMocks
private ExportController controller;
@Test
void exportTask_passesTaskNumAndFormat() throws Exception {
ExportResult result = new ExportResult("a.md", "text/markdown; charset=UTF-8", "# 内容");
when(exportService.exportTask("TASK-1", "markdown")).thenReturn(result);
CommonResult<ExportResult> response = controller.exportTask("TASK-1", "markdown");
assertEquals(200, response.getCode());
assertSame(result, response.getData());
}
@Test
void exportRange_passesDatesAndFormat() throws Exception {
ExportResult result = new ExportResult("a.json", "application/json; charset=UTF-8", "{}");
when(exportService.exportRange(LocalDate.of(2026, 10, 1), LocalDate.of(2026, 10, 9), "json"))
.thenReturn(result);
CommonResult<ExportResult> response = controller.exportRange(
LocalDate.of(2026, 10, 1), LocalDate.of(2026, 10, 9), "json");
assertEquals(200, response.getCode());
assertSame(result, response.getData());
}
@Test
void exportRange_nullDates_areForwardedAsNull() throws Exception {
ExportResult result = new ExportResult("a.md", "text/markdown; charset=UTF-8", "# 内容");
when(exportService.exportRange(null, null, "markdown")).thenReturn(result);
CommonResult<ExportResult> response = controller.exportRange(null, null, "markdown");
assertEquals(200, response.getCode());
verify(exportService).exportRange(null, null, "markdown");
}
}
@@ -0,0 +1,218 @@
package com.guo.learningprogresstracker.service.impl;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.guo.learningprogresstracker.dto.ExportResult;
import com.guo.learningprogresstracker.dto.ReviewFeedItem;
import com.guo.learningprogresstracker.dto.ReviewTaskStats;
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.exception.NotFindEntitiesException;
import com.guo.learningprogresstracker.exception.OperationFailedException;
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.service.ReviewService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* 导出服务单元测试(导出-01)。
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class ExportServiceImplTest {
@BeforeAll
static void initTableInfo() {
MybatisConfiguration configuration = new MybatisConfiguration();
MapperBuilderAssistant assistant = new MapperBuilderAssistant(configuration, "");
TableInfoHelper.initTableInfo(assistant, TaskEntity.class);
TableInfoHelper.initTableInfo(assistant, StudyReportsEntity.class);
TableInfoHelper.initTableInfo(assistant, StudyReportFragmentsEntity.class);
TableInfoHelper.initTableInfo(assistant, StudySessionsEntity.class);
}
private ExportServiceImpl exportService;
@Mock
private TasksMapper tasksMapper;
@Mock
private StudyReportsMapper studyReportsMapper;
@Mock
private StudyReportFragmentsMapper studyReportFragmentsMapper;
@Mock
private StudySessionsMapper studySessionsMapper;
@Mock
private ReviewService reviewService;
/** 用真实的 JSON 序列化能力,验证 json 分支确实产出结构化内容 */
private final ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
@BeforeEach
void setUp() {
exportService = new ExportServiceImpl(tasksMapper, studyReportsMapper, studyReportFragmentsMapper,
studySessionsMapper, reviewService, objectMapper);
}
@Test
void exportTask_markdown_containsReportsAndFragments() throws Exception {
when(tasksMapper.selectList(any())).thenReturn(List.of(task("TASK-1", "学习 Vue3")));
when(reviewService.getReviewTaskStats("TASK-1")).thenReturn(stats("TASK-1"));
when(reviewService.getTaskReview("TASK-1")).thenReturn(List.of(
feedItem(1, "SESSION-1", "REPORT", "报告正文", LocalDateTime.of(2026, 10, 1, 20, 15)),
feedItem(2, "SESSION-1", "FRAGMENT", "碎片正文", LocalDateTime.of(2026, 10, 1, 20, 18))));
ExportResult result = exportService.exportTask("TASK-1", "markdown");
assertTrue(result.getFileName().startsWith("LPT-学习数据-学习 Vue3-"));
assertTrue(result.getFileName().endsWith(".md"));
assertEquals("text/markdown; charset=UTF-8", result.getContentType());
assertTrue(result.getContent().contains("报告正文"));
assertTrue(result.getContent().contains("碎片正文"));
assertTrue(result.getContent().contains("2026-10-01 20:15:00"));
assertTrue(result.getContent().contains("累计复习耗时:20 分钟"));
}
@Test
void exportTask_json_isStructuredAndContainsOriginalText() throws Exception {
when(tasksMapper.selectList(any())).thenReturn(List.of(task("TASK-1", "学习 Vue3")));
when(reviewService.getReviewTaskStats("TASK-1")).thenReturn(stats("TASK-1"));
when(reviewService.getTaskReview("TASK-1")).thenReturn(List.of(
feedItem(1, "SESSION-1", "FRAGMENT", "碎片正文", LocalDateTime.of(2026, 10, 1, 20, 18))));
ExportResult result = exportService.exportTask("TASK-1", "json");
assertTrue(result.getFileName().endsWith(".json"));
assertEquals("application/json; charset=UTF-8", result.getContentType());
assertTrue(result.getContent().contains("\"taskNum\" : \"TASK-1\""));
assertTrue(result.getContent().contains("碎片正文"));
assertTrue(result.getContent().contains("2026-10-01T20:18:00"));
}
@Test
void exportTask_unknownTask_throwsNotFindEntities() {
when(tasksMapper.selectList(any())).thenReturn(List.of());
assertThrows(NotFindEntitiesException.class, () -> exportService.exportTask("TASK-NONE", "markdown"));
}
@Test
void exportTask_invalidFormat_throwsOperationFailed() {
assertThrows(OperationFailedException.class, () -> exportService.exportTask("TASK-1", "pdf"));
}
@Test
void exportRange_groupsByTaskAndKeepsTimeOrder() throws Exception {
StudyReportsEntity report = new StudyReportsEntity();
report.setId(1);
report.setSessionNum("SESSION-1");
report.setContent("报告正文");
report.setCreatedTime(LocalDateTime.of(2026, 10, 1, 20, 15));
StudyReportFragmentsEntity fragment = new StudyReportFragmentsEntity();
fragment.setId(2);
fragment.setSessionNum("SESSION-2");
fragment.setContent("碎片正文");
fragment.setCreatedTime(LocalDateTime.of(2026, 10, 2, 9, 0));
when(studyReportsMapper.selectList(any())).thenReturn(List.of(report));
when(studyReportFragmentsMapper.selectList(any())).thenReturn(List.of(fragment));
when(studySessionsMapper.selectList(any())).thenReturn(List.of(
session("SESSION-1", "TASK-1"),
session("SESSION-2", "TASK-2")));
when(tasksMapper.selectList(any())).thenReturn(List.of(
task("TASK-1", "任务一"),
task("TASK-2", "任务二")));
when(reviewService.getReviewTaskStats(anyString())).thenReturn(stats("TASK-X"));
ExportResult result = exportService.exportRange(LocalDate.of(2026, 9, 1), LocalDate.of(2026, 10, 9), "md");
assertTrue(result.getFileName().startsWith("LPT-学习数据-"));
assertTrue(result.getFileName().endsWith(".md"));
assertTrue(result.getContent().contains("2026-09-01 至 2026-10-09"));
assertTrue(result.getContent().contains("## 学习任务:任务一"));
assertTrue(result.getContent().contains("## 学习任务:任务二"));
// 碎片(10-02)晚于报告(10-01),任务二应排在前
assertTrue(result.getContent().indexOf("任务二") < result.getContent().indexOf("任务一"),
result.getContent());
}
@Test
void exportRange_withoutDates_labelsAllTime() throws Exception {
when(studyReportsMapper.selectList(any())).thenReturn(List.of());
when(studyReportFragmentsMapper.selectList(any())).thenReturn(List.of());
ExportResult result = exportService.exportRange(null, null, "markdown");
assertTrue(result.getContent().contains("导出范围:全部时间"));
assertTrue(result.getContent().contains("该范围内没有学习报告或知识碎片"));
}
@Test
void exportRange_startAfterEnd_throwsOperationFailed() {
assertThrows(OperationFailedException.class,
() -> exportService.exportRange(LocalDate.of(2026, 10, 9), LocalDate.of(2026, 10, 1), "markdown"));
}
private static TaskEntity task(String taskNum, String taskName) {
TaskEntity task = new TaskEntity();
task.setTaskNum(taskNum);
task.setTaskName(taskName);
return task;
}
private static StudySessionsEntity session(String sessionNum, String taskNum) {
StudySessionsEntity session = new StudySessionsEntity();
session.setSessionNum(sessionNum);
session.setTaskNum(taskNum);
return session;
}
private static ReviewTaskStats stats(String taskNum) {
ReviewTaskStats stats = new ReviewTaskStats();
stats.setTaskNum(taskNum);
stats.setEffectiveTime(9000);
stats.setReviewDurationSeconds(1200L);
stats.setSessionCount(3);
stats.setReportCount(3);
stats.setFragmentCount(5);
return stats;
}
private static ReviewFeedItem feedItem(int id, String sessionNum, String sourceType, String content,
LocalDateTime createdTime) {
ReviewFeedItem item = new ReviewFeedItem();
item.setId(id);
item.setSessionNum(sessionNum);
item.setSourceType(sourceType);
item.setContent(content);
item.setCreatedTime(createdTime);
return item;
}
}
@@ -0,0 +1,104 @@
package com.guo.learningprogresstracker.utils;
import com.guo.learningprogresstracker.dto.ExportDocument;
import com.guo.learningprogresstracker.dto.ExportEntry;
import com.guo.learningprogresstracker.dto.ExportTaskSection;
import com.guo.learningprogresstracker.dto.ReviewTaskStats;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Markdown 导出渲染测试(导出-01):导出内容必须可独立阅读,包含原文与时间信息。
*/
class ExportMarkdownRendererTest {
@Test
void render_containsScopeTaskStatsAndContent() {
ReviewTaskStats stats = new ReviewTaskStats();
stats.setTaskNum("TASK-1");
stats.setEffectiveTime(9000);
stats.setReviewDurationSeconds(1200L);
stats.setSessionCount(3);
stats.setReportCount(1);
stats.setFragmentCount(1);
ExportTaskSection section = new ExportTaskSection();
section.setTaskNum("TASK-1");
section.setTaskName("学习 Vue3");
section.setStats(stats);
section.getReports().add(entry("SESSION-1", LocalDateTime.of(2026, 10, 1, 20, 15, 30), "报告正文"));
section.getFragments().add(entry("SESSION-1", LocalDateTime.of(2026, 10, 1, 20, 18, 0), "碎片正文"));
ExportDocument document = new ExportDocument();
document.setGeneratedTime(LocalDateTime.of(2026, 10, 9, 11, 30, 0));
document.setScopeType("TASK");
document.setScopeLabel("学习任务「学习 Vue3」(TASK-1)");
document.setTasks(List.of(section));
String markdown = ExportMarkdownRenderer.render(document);
assertTrue(markdown.startsWith("# LPT 学习数据导出"), markdown);
assertTrue(markdown.contains("导出时间:2026-10-09 11:30:00"));
assertTrue(markdown.contains("学习任务「学习 Vue3」(TASK-1)"));
assertTrue(markdown.contains("## 学习任务:学习 Vue3"));
assertTrue(markdown.contains("累计有效学习时长:2 小时 30 分钟"));
assertTrue(markdown.contains("累计复习耗时:20 分钟"));
assertTrue(markdown.contains("学习报告:1 份"));
assertTrue(markdown.contains("2026-10-01 20:15:30"));
assertTrue(markdown.contains("报告正文"));
assertTrue(markdown.contains("碎片正文"));
}
@Test
void render_emptyRange_saysNoContent() {
ExportDocument document = new ExportDocument();
document.setGeneratedTime(LocalDateTime.of(2026, 10, 9, 11, 30, 0));
document.setScopeLabel("全部时间");
String markdown = ExportMarkdownRenderer.render(document);
assertTrue(markdown.contains("该范围内没有学习报告或知识碎片"));
assertFalse(markdown.contains("## 学习任务"));
}
@Test
void render_emptySections_usePlaceholderText() {
ExportTaskSection section = new ExportTaskSection();
section.setTaskNum("TASK-2");
section.setTaskName("空任务");
ExportDocument document = new ExportDocument();
document.setScopeLabel("全部时间");
document.setTasks(List.of(section));
String markdown = ExportMarkdownRenderer.render(document);
assertTrue(markdown.contains("暂无学习报告"));
assertTrue(markdown.contains("暂无知识碎片"));
// 没有统计时应退化成实际条目数,而不是抛异常
assertTrue(markdown.contains("学习报告:0 份"));
}
@Test
void formatDuration_neverRoundsRealMinutesDownToZero() {
assertEquals("0 秒", ExportMarkdownRenderer.formatDuration(0L));
assertEquals("45 秒", ExportMarkdownRenderer.formatDuration(45L));
assertEquals("5 分钟", ExportMarkdownRenderer.formatDuration(300L));
assertEquals("1 小时 0 分钟", ExportMarkdownRenderer.formatDuration(3600L));
assertEquals("0 秒", ExportMarkdownRenderer.formatDuration(null));
}
private static ExportEntry entry(String sessionNum, LocalDateTime createdTime, String content) {
ExportEntry entry = new ExportEntry();
entry.setSessionNum(sessionNum);
entry.setCreatedTime(createdTime);
entry.setContent(content);
return entry;
}
}