feat: 新增学习数据导出接口
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user