| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541 |
- package com.etotem.cfc.service;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.etotem.cfc.dto.CfEarnResult;
- import com.etotem.cfc.dto.ReadingStatsDTO;
- import com.etotem.cfc.entity.Article;
- import com.etotem.cfc.entity.ArticleCategory;
- import com.etotem.cfc.entity.ArticleQuizRecord;
- import com.etotem.cfc.entity.ArticleReadingRecord;
- import com.etotem.cfc.entity.ContentDimensionThreshold;
- import com.etotem.cfc.entity.FamilyMember;
- import com.etotem.cfc.entity.PointsLog;
- import com.etotem.cfc.entity.Product;
- import com.etotem.cfc.entity.Task;
- import com.etotem.cfc.entity.User;
- import com.etotem.cfc.mapper.ArticleMapper;
- import com.etotem.cfc.mapper.ProductMapper;
- import com.etotem.cfc.mapper.ArticleQuizRecordMapper;
- import com.etotem.cfc.mapper.ArticleReadingRecordMapper;
- import com.etotem.cfc.mapper.FamilyMemberMapper;
- import com.etotem.cfc.mapper.PointsLogMapper;
- import com.etotem.cfc.mapper.TaskMapper;
- import com.etotem.cfc.mapper.UserMapper;
- import com.fasterxml.jackson.core.type.TypeReference;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import lombok.extern.slf4j.Slf4j;
- import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.transaction.support.TransactionSynchronization;
- import org.springframework.transaction.support.TransactionSynchronizationManager;
- import javax.annotation.Resource;
- import java.util.*;
- import java.util.stream.Collectors;
- import com.etotem.cfc.util.DimensionCodes;
- import com.etotem.cfc.util.SortUtil;
- @Slf4j
- @Service
- public class ArticleService {
- @Resource
- private ArticleMapper articleMapper;
- @Resource
- private ProductMapper productMapper;
- @Resource
- private ArticlePermissionService articlePermissionService;
- @Resource
- private ArticleCategoryService articleCategoryService;
- @Resource
- private ArticleReadingRecordMapper articleReadingRecordMapper;
- @Resource
- private SysConfigService sysConfigService;
- @Resource
- private TaskMapper taskMapper;
- @Resource
- private FamilyMemberMapper familyMemberMapper;
- @Resource
- private PointsLogMapper pointsLogMapper;
- @Resource
- private EnergyService energyService;
- @Resource
- private CfPathwayEarnService cfPathwayEarnService;
- @Resource
- private AIService aiService;
- @Resource
- private ArticleQuizRecordMapper articleQuizRecordMapper;
- @Resource
- private UserMapper userMapper;
- @Resource
- private FiveDimensionScoreService fiveDimensionScoreService;
- @Resource
- private ContentDimensionThresholdService contentDimensionThresholdService;
- @Resource
- private JdbcTemplate jdbcTemplate;
- @Resource(name = "taskExecutor")
- private ThreadPoolTaskExecutor taskExecutor;
- @Resource
- private ArticleAudioService articleAudioService;
- private final ObjectMapper objectMapper = new ObjectMapper();
- public Page<Article> getPublicList(Long categoryId, String keyword, String dimensionCode, int page, int size,
- Long userId, Long familyId, String vendorType) {
- return getPublicList(categoryId, keyword, dimensionCode, null, page, size, userId, familyId, vendorType, null);
- }
- public Page<Article> getPublicList(Long categoryId, String keyword, String dimensionCode, int page, int size,
- Long userId, Long familyId, String vendorType, Long memberId) {
- return getPublicList(categoryId, keyword, dimensionCode, null, page, size, userId, familyId, vendorType, memberId);
- }
- /**
- * 知识中心文章列表:支持按文章标签筛选(知识中心 Tab 从「五维」改为「文章标签」)。
- * tag 为空时行为与旧版一致;tag 非空时仅返回 tags 字段包含该标签的文章。
- * tags 字段为 JSON 数组字符串(如 ["减脂","睡眠"])或逗号分隔,统一由 parseCommaOrJsonTags 解析后内存过滤。
- */
- public Page<Article> getPublicList(Long categoryId, String keyword, String dimensionCode, String tag,
- int page, int size, Long userId, Long familyId, String vendorType, Long memberId) {
- LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
- .eq(Article::getStatus, "published")
- .orderByDesc(Article::getIsFeatured)
- .orderByAsc(Article::getSortOrder)
- .orderByDesc(Article::getPublishedAt);
- if (categoryId != null && categoryId > 0) {
- wrapper.eq(Article::getCategoryId, categoryId);
- }
- if (keyword != null && !keyword.trim().isEmpty()) {
- String kw = keyword.trim();
- wrapper.and(w -> w.like(Article::getTitle, kw).or().like(Article::getSummary, kw).or().like(Article::getTags, kw));
- }
- if (dimensionCode != null && !dimensionCode.trim().isEmpty() && DimensionCodes.isValid(dimensionCode)) {
- String dim = dimensionCode.trim();
- // P1: 权重感知查询 — 匹配 dimension_weights > 0 或兼容旧版 relatedDimensions
- wrapper.and(w -> w
- .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
- .or().like(Article::getRelatedDimensions, dim)
- );
- }
- // 先查全量(不含分页),内存中做权限过滤后再手动分页。
- // 原因:可见性过滤规则含 JSON visible_to,无法下推 SQL;
- // 若先 selectPage 后过滤,total 会被设为本页过滤后条数(<= size),
- // 前端 noMore = 已加载数 >= total 恒为真,导致只显示一页、无法加载更多。
- List<Article> all = articleMapper.selectList(wrapper);
- // 按文章标签筛选(与 parseCommaOrJsonTags 解析语义对齐,兼容 JSON 数组 / 逗号分隔两种存储格式)
- if (tag != null && !tag.trim().isEmpty()) {
- String targetTag = tag.trim();
- all = all.stream()
- .filter(a -> parseCommaOrJsonTags(a.getTags()).contains(targetTag))
- .collect(Collectors.toList());
- }
- List<Article> visible = articlePermissionService.filterVisible(all, userId, familyId, vendorType);
- // 过滤已完成阅读且获得CF值的文章(达到阈值且答题得CF后不再出现在文章列表中)
- if (memberId != null) {
- List<Long> completedIds = articleReadingRecordMapper.selectCompletedArticleIdsByChild(memberId);
- if (!completedIds.isEmpty()) {
- visible.removeIf(a -> completedIds.contains(a.getId()));
- }
- }
- // 内容维度阈值显隐过滤(A-后端):OR 逻辑,fail-open 不误隐藏
- applyDimensionThresholdFilter(visible, familyId);
- enrichTotalDurationSeconds(visible);
- // 手动分页(与 getFeatured 相同模式),total 为过滤后的真实总数
- int total = visible.size();
- int fromIndex = Math.min((page - 1) * size, total);
- int toIndex = Math.min(fromIndex + size, total);
- List<Article> pageList = visible.subList(fromIndex, toIndex);
- Page<Article> filtered = new Page<>(page, size);
- filtered.setTotal(total);
- filtered.setRecords(new ArrayList<>(pageList));
- return filtered;
- }
- /**
- * 内容维度阈值显隐过滤(A-后端)。
- * 家庭维度指标取家庭成员平均值;无家庭得分数据 → fail-open 不误隐藏。
- * 显隐规则(OR 逻辑):任一配置维度得分 < 阈值 → 显示;全部 >= 阈值 → 隐藏。
- */
- private void applyDimensionThresholdFilter(List<Article> visible, Long familyId) {
- if (visible == null || visible.isEmpty()) return;
- Map<String, Integer> familyAvg = fiveDimensionScoreService.getFamilyAverageScores(familyId);
- if (familyAvg.isEmpty()) return; // 无家庭得分数据 → fail-open
- List<Long> ids = visible.stream().map(Article::getId).collect(Collectors.toList());
- Map<Long, List<ContentDimensionThreshold>> byId =
- contentDimensionThresholdService.listByContents("ARTICLE", ids);
- DimensionThresholdFilter.filterVisible(visible, Article::getId, "ARTICLE", familyAvg, byId);
- }
- /**
- * 聚合已发布文章的标签,按出现频次降序返回 Top N(知识中心 Tab 动态标签列表数据源)。
- * 标签格式兼容 JSON 数组 / 逗号分隔,统一由 parseCommaOrJsonTags 解析拆分去重。
- */
- public List<String> listTopTags(int limit) {
- int n = limit > 0 ? limit : 20;
- LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
- .eq(Article::getStatus, "published")
- .and(w -> w.isNotNull(Article::getTags).or().apply("TRIM(tags) <> ''"));
- List<Article> articles = articleMapper.selectList(wrapper);
- Map<String, Integer> freq = new HashMap<>();
- for (Article a : articles) {
- for (String t : parseCommaOrJsonTags(a.getTags())) {
- if (!t.isEmpty()) {
- freq.merge(t, 1, Integer::sum);
- }
- }
- }
- return freq.entrySet().stream()
- .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
- .thenComparing(Map.Entry.comparingByKey()))
- .limit(n)
- .map(Map.Entry::getKey)
- .collect(Collectors.toList());
- }
- public List<Article> getFeatured(int size, Long userId, Long familyId, String vendorType, Long memberId) {
- return getFeatured(size, null, userId, familyId, vendorType, memberId);
- }
- public List<Article> getFeatured(int size, String dimensionCode, Long userId, Long familyId, String vendorType, Long memberId) {
- LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
- .eq(Article::getStatus, "published")
- .eq(Article::getIsFeatured, 1)
- .orderByAsc(Article::getSortOrder)
- .orderByDesc(Article::getPublishedAt)
- .last("LIMIT " + Math.max(size, 50));
- if (dimensionCode != null && !dimensionCode.trim().isEmpty() && DimensionCodes.isValid(dimensionCode)) {
- String dim = dimensionCode.trim();
- // P1: 权重感知查询 — 匹配 dimension_weights > 0 或兼容旧版 relatedDimensions
- wrapper.and(w -> w
- .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
- .or().like(Article::getRelatedDimensions, dim)
- );
- }
- List<Article> all = articleMapper.selectList(wrapper);
- List<Article> visible = articlePermissionService.filterVisible(all, userId, familyId, vendorType);
- // 过滤已阅读达标的文章(达到阈值后不再出现在推荐阅读中)
- if (memberId != null) {
- List<Long> completedIds = articleReadingRecordMapper.selectCompletedArticleIdsByChild(memberId);
- if (!completedIds.isEmpty()) {
- visible.removeIf(a -> completedIds.contains(a.getId()));
- }
- }
- enrichTotalDurationSeconds(visible);
- return visible.size() > size ? visible.subList(0, size) : visible;
- }
- /**
- * 存量回填:为所有「已发布且 tags 为空」的文章异步触发自动打标(幂等,可重复调用)。
- * @return 触发的文章数
- */
- public int backfillEmptyPublishedTags() {
- List<Article> list = articleMapper.selectList(new LambdaQueryWrapper<Article>()
- .eq(Article::getStatus, "published")
- .and(w -> w.isNull(Article::getTags).or().apply("TRIM(tags) = ''")));
- for (Article a : list) {
- ensureAutoTagsIfEmpty(a.getId());
- }
- log.info("存量空标签文章回填触发: {} 篇", list.size());
- return list.size();
- }
- /**
- * 相关文章:按标签匹配(FIND_IN_SET 精确匹配整标签),共享标签数降序 → 发布时间降序,
- * 排除自身,仅取已发布,经可见性过滤后按 (page-1)*size ~ page*size 分页窗口截取。
- * 无标签/无匹配返回空。
- */
- public List<Article> getRelatedArticles(Long articleId, int size, int page, Long userId, Long familyId, String vendorType) {
- Article current = articleMapper.selectById(articleId);
- if (current == null || current.getTags() == null || current.getTags().trim().isEmpty()) {
- return Collections.emptyList();
- }
- List<String> tags = new ArrayList<>();
- for (String t : current.getTags().split(",")) {
- String tag = t.trim();
- if (!tag.isEmpty() && !tags.contains(tag)) {
- tags.add(tag);
- }
- }
- return getRelatedArticlesByTags(tags, articleId, size, page, userId, familyId, vendorType);
- }
- /**
- * 相关文章(按源标签匹配,通用入口):供内容关联服务(活动/商品 ↔ 文章)复用,
- * 语义与 {@link #getRelatedArticles} 一致:共享标签数降序 → 发布时间降序,仅取已发布,
- * 经可见性过滤后分页窗口截取。excludeArticleId 为空表示不排除(源为其他表内容)。
- *
- * @param tags 源标签集合
- * @param excludeArticleId 需排除的文章ID(文章源排除自身;其他源为 null)
- * @param size 每页条数
- * @param page 页码(从1开始)
- * @param userId 当前用户ID(可为空)
- * @param familyId 家庭ID(可为空,私有文章可见性判定用)
- * @param vendorType 服务商类型(可为空)
- * @return 相关文章列表,无匹配返回空列表
- */
- public List<Article> getRelatedArticlesByTags(List<String> tags, Long excludeArticleId, int size, int page,
- Long userId, Long familyId, String vendorType) {
- return matchArticlesByTags(tags, excludeArticleId, size, page, userId, familyId, vendorType);
- }
- /**
- * 商品详情页「相关文章」:按商品标签匹配文章(共享标签数降序 → 发布时间降序),
- * 支持分页窗口截取。商品标签为 JSON 数组或逗号分隔字符串。
- */
- public List<Article> getRelatedArticlesByProduct(Long productId, int size, int page, Long userId, Long familyId, String vendorType) {
- if (productId == null) return Collections.emptyList();
- Product product = productMapper.selectById(productId);
- if (product == null || product.getTags() == null || product.getTags().trim().isEmpty()) {
- return Collections.emptyList();
- }
- List<String> tags = parseCommaOrJsonTags(product.getTags());
- // 商品来源无需排除文章自身(productId 与 articleId 分属不同表),excludeArticleId 传 null
- return matchArticlesByTags(tags, null, size, page, userId, familyId, vendorType);
- }
- /**
- * 标签匹配文章核心逻辑:FIND_IN_SET 候选 → 共享标签计数 → 排序 → 可见性过滤 → 分页窗口截取。
- */
- private List<Article> matchArticlesByTags(List<String> tags, Long excludeArticleId, int size, int page,
- Long userId, Long familyId, String vendorType) {
- if (tags == null || tags.isEmpty() || size < 1) {
- return Collections.emptyList();
- }
- int p = page < 1 ? 1 : page;
- LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
- .eq(Article::getStatus, "published");
- if (excludeArticleId != null) {
- wrapper.ne(Article::getId, excludeArticleId);
- }
- wrapper.and(w -> {
- boolean first = true;
- for (String tag : tags) {
- if (first) {
- w.apply("FIND_IN_SET({0}, tags) > 0", tag);
- first = false;
- } else {
- w.or().apply("FIND_IN_SET({0}, tags) > 0", tag);
- }
- }
- });
- List<Article> candidates = articleMapper.selectList(wrapper);
- // 共享标签计数,剔除零共享(SQL 已限定至少一个标签命中,此处防御)
- Map<Long, Integer> score = new HashMap<>();
- List<Article> matched = new ArrayList<>();
- for (Article a : candidates) {
- if (excludeArticleId != null && a.getId() != null && a.getId().equals(excludeArticleId)) {
- continue;
- }
- int s = 0;
- if (a.getTags() != null) {
- for (String t : a.getTags().split(",")) {
- if (tags.contains(t.trim())) {
- s++;
- }
- }
- }
- if (s > 0) {
- matched.add(a);
- score.put(a.getId(), s);
- }
- }
- matched.sort((x, y) -> {
- int diff = score.getOrDefault(y.getId(), 0) - score.getOrDefault(x.getId(), 0);
- if (diff != 0) {
- return diff;
- }
- Date px = x.getPublishedAt();
- Date py = y.getPublishedAt();
- if (px == null && py == null) return 0;
- if (px == null) return 1;
- if (py == null) return -1;
- return py.compareTo(px);
- });
- List<Article> visible = articlePermissionService.filterVisible(matched, userId, familyId, vendorType);
- if (visible == null) {
- visible = Collections.emptyList();
- }
- // 分页窗口截取:兼容旧调用方(size 截断)与分页调用方
- int from = (p - 1) * size;
- if (from >= visible.size()) {
- return Collections.emptyList();
- }
- int to = Math.min(from + size, visible.size());
- return new ArrayList<>(visible.subList(from, to));
- }
- /** 商品标签解析:兼容 JSON 数组字符串(["标签1","标签2"])与逗号分隔(标签1,标签2) */
- private List<String> parseCommaOrJsonTags(String raw) {
- if (raw == null || raw.trim().isEmpty()) return Collections.emptyList();
- String trimmed = raw.trim();
- if (trimmed.startsWith("[")) {
- try {
- com.alibaba.fastjson.JSONArray arr = com.alibaba.fastjson.JSON.parseArray(trimmed);
- if (arr == null) return Collections.emptyList();
- List<String> tags = new ArrayList<>();
- for (int i = 0; i < arr.size(); i++) {
- Object o = arr.get(i);
- if (o != null && !o.toString().trim().isEmpty()) {
- tags.add(o.toString().trim());
- }
- }
- return tags;
- } catch (Exception e) {
- log.warn("解析商品标签失败: {}", e.getMessage());
- return Collections.emptyList();
- }
- }
- List<String> tags = new ArrayList<>();
- for (String t : trimmed.split(",")) {
- String tag = t.trim();
- if (!tag.isEmpty() && !tags.contains(tag)) {
- tags.add(tag);
- }
- }
- return tags;
- }
- public Article getDetail(Long id, Long userId, Long familyId, String vendorType) {
- Article article = articleMapper.selectById(id);
- if (article == null) return null;
- if (!"published".equals(article.getStatus())) return null;
- if (!articlePermissionService.isVisible(article, userId, familyId, vendorType)) return null;
- return article;
- }
- private int calculateWordCount(String htmlContent) {
- if (htmlContent == null || htmlContent.isEmpty()) return 0;
- // Strip HTML tags
- String text = htmlContent.replaceAll("<[^>]*>", "");
- // Strip HTML entities
- text = text.replaceAll("&[a-zA-Z]+;", " ");
- // Remove extra whitespace
- text = text.replaceAll("\\s+", " ").trim();
- // Count characters (Chinese text: each character is a "word")
- return text.length();
- }
- @Transactional
- public Map<String, Object> recordRead(Long articleId, Long userId, Long memberId, int durationSeconds) {
- Map<String, Object> result = new HashMap<>();
- result.put("taskId", null);
- result.put("pointsEarned", 0);
- // 1. Increment view count
- LambdaUpdateWrapper<Article> wrapper = Wrappers.lambdaUpdate(Article.class)
- .setSql("view_count = view_count + 1")
- .eq(Article::getId, articleId);
- articleMapper.update(null, wrapper);
- // 2. Save reading record
- ArticleReadingRecord record = new ArticleReadingRecord();
- record.setArticleId(articleId);
- record.setUserId(userId);
- record.setMemberId(memberId);
- record.setContent("");
- record.setDurationSeconds(durationSeconds);
- int minSeconds = getArticleReadingMinSeconds();
- record.setReadingCompleted(memberId != null && durationSeconds >= minSeconds);
- record.setReadAt(new Date());
- record.setCreatedAt(new Date());
- articleReadingRecordMapper.insert(record);
- // 3. If no memberId, can't create task (reading as parent, not child)
- if (memberId == null) {
- return result;
- }
- // 4. Check reading duration threshold
- if (durationSeconds < minSeconds) {
- result.put("belowThreshold", true);
- result.put("minSeconds", minSeconds);
- return result;
- }
- // If no userId, can't create task (unauthenticated request)
- if (userId == null) {
- result.put("belowThreshold", true);
- result.put("minSeconds", minSeconds);
- return result;
- }
- // 5. Check if a task already exists for this article+child (avoid duplicates)
- Task existingTask = taskMapper.selectOne(
- new LambdaQueryWrapper<Task>()
- .eq(Task::getSourceType, "article")
- .eq(Task::getSourceId, articleId)
- .eq(Task::getMemberId, memberId)
- .last("LIMIT 1")
- );
- if (existingTask != null) {
- result.put("taskId", existingTask.getId());
- result.put("pointsEarned", 0);
- result.put("alreadyCompleted", true);
- return result;
- }
- // 6. Load article to get wordCount and articleType
- Article article = articleMapper.selectById(articleId);
- if (article == null) return result;
- int wordCount = article.getWordCount() != null ? article.getWordCount() : 0;
- String articleType = article.getArticleType() != null ? article.getArticleType() : "normal";
- // 7. Calculate points based on wordCount × type rate
- int rate = 1; // default for 'normal'
- String rateStr = sysConfigService.getValue("article_energy_rate_" + articleType);
- if (rateStr != null && !rateStr.isEmpty()) {
- try { rate = Integer.parseInt(rateStr); } catch (NumberFormatException e) { /* use default */ }
- }
- int points = Math.max(1, wordCount / 100 * rate);
- // 8. Create task with status='completed' (auto-completed by reading)
- Task task = new Task();
- task.setFamilyId(null); // will set after getting child
- task.setCreatorId(userId);
- task.setExecutorType("child"); // 非登录用户(不可登录成员)
- task.setExecutorId(memberId);
- task.setMemberId(memberId);
- task.setTitle("阅读文章: " + article.getTitle());
- task.setDescription("自动生成 - 阅读文章《" + article.getTitle() + "》" + durationSeconds + "秒");
- task.setPoints(points);
- task.setRepeatType("none");
- task.setCategory("学习类");
- task.setNeedReview(0);
- task.setReviewByCategory(0);
- task.setTaskType("onetime");
- task.setSourceType("article");
- task.setSourceId(articleId);
- task.setStatus("completed");
- task.setCompletedAt(new Date());
- task.setCreatedAt(new Date());
- task.setUpdatedAt(new Date());
- // Set deadline to today end
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.HOUR_OF_DAY, 23);
- cal.set(Calendar.MINUTE, 59);
- cal.set(Calendar.SECOND, 59);
- task.setDeadline(cal.getTime());
- // Get child to set familyId
- FamilyMember child = familyMemberMapper.selectById(memberId);
- if (child != null) {
- task.setFamilyId(child.getFamilyId());
- }
- taskMapper.insert(task);
- // 9. Update child totalPoints
- if (child != null) {
- child.setTotalPoints(child.getTotalPoints() + points);
- child.setUpdatedAt(new Date());
- familyMemberMapper.updateById(child);
- }
- // 10. Insert PointsLog
- PointsLog pointsLog = new PointsLog();
- pointsLog.setMemberId(memberId);
- pointsLog.setTaskId(task.getId());
- pointsLog.setAmount(points);
- pointsLog.setType("earn");
- pointsLog.setCategory("task");
- pointsLog.setDescription("阅读文章: " + article.getTitle());
- pointsLog.setCreatedAt(new Date());
- pointsLogMapper.insert(pointsLog);
- // 11. Award energy via EnergyService
- try {
- energyService.awardEnergy(memberId, "article", articleId, points,
- "阅读文章: " + article.getTitle(), null);
- } catch (Exception e) {
- log.warn("能量发放失败(不影响积分): memberId={}, articleId={}, error={}",
- memberId, articleId, e.getMessage());
- }
- // 12. Link taskId to reading record
- record.setTaskId(task.getId());
- articleReadingRecordMapper.updateById(record);
- // 13. Return result
- result.put("taskId", task.getId());
- result.put("pointsEarned", points);
- result.put("belowThreshold", false);
- return result;
- }
- public void reportReadingTime(Long articleId, Long userId, Long memberId, int durationSeconds) {
- if (memberId == null) return;
- // 查找当日已有记录(同文章+同家庭成员)
- LambdaQueryWrapper<ArticleReadingRecord> wrapper = new LambdaQueryWrapper<ArticleReadingRecord>()
- .eq(ArticleReadingRecord::getArticleId, articleId)
- .eq(ArticleReadingRecord::getMemberId, memberId)
- .apply("DATE(read_at) = CURDATE()")
- .last("LIMIT 1");
- ArticleReadingRecord existing = articleReadingRecordMapper.selectOne(wrapper);
- // 获取阅读达标阈值
- int minSeconds = getArticleReadingMinSeconds();
- boolean isCompleted = false;
- if (existing != null) {
- // 累加时长
- existing.setDurationSeconds(existing.getDurationSeconds() + durationSeconds);
- // 累计时长达到阈值时标记为已阅读
- if (existing.getReadingCompleted() == null || !existing.getReadingCompleted()) {
- existing.setReadingCompleted(existing.getDurationSeconds() >= minSeconds);
- isCompleted = existing.getReadingCompleted();
- }
- existing.setUpdatedAt(new Date());
- articleReadingRecordMapper.updateById(existing);
- } else {
- // 新建记录
- ArticleReadingRecord record = new ArticleReadingRecord();
- record.setArticleId(articleId);
- record.setUserId(userId);
- record.setMemberId(memberId);
- record.setDurationSeconds(durationSeconds);
- record.setReadingCompleted(durationSeconds >= minSeconds);
- record.setReadAt(new Date());
- record.setCreatedAt(new Date());
- articleReadingRecordMapper.insert(record);
- }
- }
- /**
- * 获取文章阅读达标最低秒数,默认 60 秒
- */
- private int getArticleReadingMinSeconds() {
- String val = sysConfigService.getValue("article_reading_min_seconds");
- if (val != null && !val.isEmpty()) {
- try { return Integer.parseInt(val); } catch (NumberFormatException e) {}
- }
- return 60;
- }
- /**
- * 递增文章浏览数(打开详情页即计数,匿名/登录用户均计)
- */
- public void incrementViewCount(Long id) {
- if (id == null) return;
- articleMapper.update(null, Wrappers.<Article>lambdaUpdate()
- .eq(Article::getId, id)
- .setSql("view_count = view_count + 1"));
- }
- /**
- * 按文章 ID 分页查询阅读记录(每人聚合一行),返回昵称、累计时长、阅读次数、最后阅读时间
- */
- public Page<Map<String, Object>> getArticleReadingRecords(Long articleId, int page, int size) {
- long total = articleReadingRecordMapper.countDistinctByArticle(articleId);
- if (total == 0) {
- Page<Map<String, Object>> empty = new Page<>(page, size);
- empty.setTotal(0);
- empty.setRecords(Collections.emptyList());
- return empty;
- }
- int offset = (page - 1) * size;
- List<Map<String, Object>> records = articleReadingRecordMapper.selectByArticleAggregated(articleId, offset, size);
- Page<Map<String, Object>> result = new Page<>(page, size);
- result.setTotal(total);
- result.setRecords(records);
- return result;
- }
- public Article getById(Long id) {
- return articleMapper.selectById(id);
- }
- private void enrichTotalDurationSeconds(List<Article> articles) {
- if (articles == null || articles.isEmpty()) return;
- String ids = articles.stream()
- .map(a -> String.valueOf(a.getId()))
- .collect(Collectors.joining(","));
- List<Map<String, Object>> durationRows = jdbcTemplate.queryForList(
- "SELECT article_id, SUM(duration_seconds) AS total_duration " +
- "FROM article_reading_records WHERE article_id IN (" + ids + ") GROUP BY article_id");
- Map<Long, Integer> durationMap = new HashMap<>();
- for (Map<String, Object> row : durationRows) {
- Number aid = (Number) row.get("article_id");
- Number total = (Number) row.get("total_duration");
- if (aid != null && total != null) {
- durationMap.put(aid.longValue(), total.intValue());
- }
- }
- for (Article article : articles) {
- article.setTotalDurationSeconds(durationMap.getOrDefault(article.getId(), 0));
- }
- }
- public void enrichWithCategoryName(List<Article> articles) {
- if (articles == null || articles.isEmpty()) return;
- }
- public Page<Article> getAdminList(String status, Long categoryId, String keyword,
- String contentType, Integer difficultyLevel,
- String dimensionCode, Long tagId, String auditStatus, int page, int size,
- List<Map<String, String>> sortSpecs) {
- LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
- .orderByDesc(Article::getCreatedAt);
- if (status != null && !status.isEmpty()) {
- wrapper.eq(Article::getStatus, status);
- }
- if (categoryId != null && categoryId > 0) {
- wrapper.eq(Article::getCategoryId, categoryId);
- }
- if (keyword != null && !keyword.trim().isEmpty()) {
- String kw = keyword.trim();
- wrapper.and(w -> w.like(Article::getTitle, kw).or().like(Article::getSummary, kw).or().like(Article::getTags, kw));
- }
- if (contentType != null && !contentType.isEmpty()) {
- wrapper.eq(Article::getContentType, contentType);
- }
- if (difficultyLevel != null && difficultyLevel > 0) {
- wrapper.eq(Article::getDifficultyLevel, difficultyLevel);
- }
- if (dimensionCode != null && !dimensionCode.isEmpty()) {
- wrapper.like(Article::getRelatedDimensions, dimensionCode);
- }
- if (tagId != null && tagId > 0) {
- wrapper.inSql(Article::getId, "SELECT article_id FROM article_tags WHERE tag_id = " + tagId);
- }
- if (auditStatus != null && !auditStatus.isEmpty()) {
- wrapper.eq(Article::getAuditStatus, auditStatus);
- }
- SortUtil.applySort(wrapper, sortSpecs, null);
- Page<Article> pageResult = articleMapper.selectPage(new Page<>(page, size), wrapper);
- // 批量填充每篇文章的总阅读时长(按 child 聚合去重后求和)
- List<Article> records = pageResult.getRecords();
- if (records != null && !records.isEmpty()) {
- String ids = records.stream()
- .map(a -> String.valueOf(a.getId()))
- .collect(Collectors.joining(","));
- List<Map<String, Object>> durationRows = jdbcTemplate.queryForList(
- "SELECT article_id, SUM(duration_seconds) AS total_duration " +
- "FROM article_reading_records WHERE article_id IN (" + ids + ") GROUP BY article_id");
- Map<Long, Integer> durationMap = new HashMap<>();
- for (Map<String, Object> row : durationRows) {
- Number articleId = (Number) row.get("article_id");
- Number total = (Number) row.get("total_duration");
- if (articleId != null && total != null) {
- durationMap.put(articleId.longValue(), total.intValue());
- }
- }
- for (Article article : records) {
- article.setTotalDurationSeconds(durationMap.getOrDefault(article.getId(), 0));
- }
- }
- return pageResult;
- }
- @Transactional
- public void create(Article article, Long adminId) {
- // 幂等检查:同一标题不允许重复创建
- if (article.getTitle() != null && !article.getTitle().trim().isEmpty()) {
- LambdaQueryWrapper<Article> dupCheck = new LambdaQueryWrapper<Article>()
- .eq(Article::getTitle, article.getTitle().trim());
- Long existingCount = articleMapper.selectCount(dupCheck);
- if (existingCount != null && existingCount > 0) {
- throw new RuntimeException("标题「" + article.getTitle().trim() + "」已存在,请勿重复创建");
- }
- }
- // Auto-calculate wordCount from content
- if (article.getContent() != null) {
- article.setWordCount(calculateWordCount(article.getContent()));
- }
- // Default articleType to 'normal' if not set
- if (article.getArticleType() == null) {
- article.setArticleType("normal");
- }
- article.setCreatedBy(adminId);
- article.setViewCount(0);
- article.setCreatedAt(new Date());
- article.setUpdatedAt(new Date());
- if ("published".equals(article.getStatus())) {
- article.setPublishedAt(new Date());
- }
- articleMapper.insert(article);
- // 发布后异步预生成朗读音频(不阻塞创建响应)
- ensureArticleAudioAfterPublish(article.getId());
- // AI auto-tagging (异步,不阻塞 HTTP 响应)
- final Long articleId = article.getId();
- final String content = article.getContent();
- taskExecutor.execute(() -> {
- try {
- List<String> tagNames = autoGenerateTags(content);
- if (!tagNames.isEmpty()) {
- saveAutoTags(articleId, tagNames);
- }
- } catch (Exception e) {
- log.warn("AI 自动标签生成失败(不影响文章创建): articleId={}, error={}",
- articleId, e.getMessage());
- }
- });
- }
- @Transactional
- public void update(Article article) {
- Article existing = article.getId() != null ? articleMapper.selectById(article.getId()) : null;
- // Recalculate wordCount if content changed
- boolean contentChanged = false;
- if (article.getContent() != null) {
- String oldContent = existing != null ? existing.getContent() : null;
- article.setWordCount(calculateWordCount(article.getContent()));
- contentChanged = oldContent == null || !oldContent.equals(article.getContent());
- }
- // 朗读源变化(朗读文本变化,或朗读文本为空时正文变化)→ 作废旧音频,下次「听文章」重新合成
- if (existing != null) {
- String newAudioText = article.getAudioText() != null ? article.getAudioText() : existing.getAudioText();
- String newContent = article.getContent() != null ? article.getContent() : existing.getContent();
- if (shouldInvalidateAudio(existing.getContent(), newContent,
- existing.getAudioText(), newAudioText)) {
- article.setAudioUrl("");
- }
- }
- article.setUpdatedAt(new Date());
- articleMapper.updateById(article);
- // 已发布文章:朗读源变化导致音频被作废后,异步重新生成
- ensureArticleAudioAfterPublish(article.getId());
- // AI auto-tagging only when content changed (异步,不阻塞 HTTP 响应)
- if (contentChanged && article.getContent() != null) {
- final Long articleId = article.getId();
- final String content = article.getContent();
- taskExecutor.execute(() -> {
- try {
- jdbcTemplate.update("DELETE FROM article_tags WHERE article_id = ?", articleId);
- List<String> tagNames = autoGenerateTags(content);
- if (!tagNames.isEmpty()) {
- saveAutoTags(articleId, tagNames);
- }
- } catch (Exception e) {
- log.warn("AI 自动标签更新失败(不影响文章更新): articleId={}, error={}",
- articleId, e.getMessage());
- }
- });
- }
- }
- /**
- * 判断文章更新是否应作废已生成音频。
- * 朗读文本优先;朗读文本为空时以正文为朗读源,正文变化即作废。
- */
- static boolean shouldInvalidateAudio(String oldContent, String newContent,
- String oldAudioText, String newAudioText) {
- String oldText = trimToNull(oldAudioText);
- String newText = trimToNull(newAudioText);
- if (!Objects.equals(oldText, newText)) {
- return true;
- }
- if (newText != null) {
- return false; // 有朗读文本时,正文变化不影响音频
- }
- if (newContent == null) {
- return false;
- }
- return !Objects.equals(oldContent, newContent);
- }
- private static String trimToNull(String value) {
- if (value == null) {
- return null;
- }
- String trimmed = value.trim();
- return trimmed.isEmpty() ? null : trimmed;
- }
- @Transactional
- public void delete(Long id) {
- articleMapper.deleteById(id);
- }
- @Transactional
- public void toggleStatus(Long id, String status) {
- Article article = articleMapper.selectById(id);
- if (article == null) return;
- article.setStatus(status);
- article.setUpdatedAt(new Date());
- if ("published".equals(status) && article.getPublishedAt() == null) {
- article.setPublishedAt(new Date());
- }
- articleMapper.updateById(article);
- // 发布时若标签为空则异步自动生成
- if ("published".equals(status)) {
- ensureAutoTagsIfEmpty(id);
- // 发布后异步预生成朗读音频
- ensureArticleAudioAfterPublish(id);
- }
- }
- @Transactional
- public void toggleFeatured(Long id, int isFeatured) {
- Article article = articleMapper.selectById(id);
- if (article == null) return;
- article.setIsFeatured(isFeatured);
- article.setUpdatedAt(new Date());
- if (isFeatured == 1) {
- // 设为精选时追加到队尾,不抢占既有顺序
- Integer maxSort = getMaxSortOrder();
- article.setSortOrder((maxSort == null ? 0 : maxSort) + 1);
- }
- articleMapper.updateById(article);
- }
- /**
- * 查询已发布且精选的文章中最大的 sort_order;若没有精选文章返回 null。
- */
- private Integer getMaxSortOrder() {
- LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
- .eq(Article::getStatus, "published")
- .eq(Article::getIsFeatured, 1)
- .select(Article::getSortOrder)
- .orderByDesc(Article::getSortOrder)
- .last("LIMIT 1");
- Article top = articleMapper.selectOne(wrapper);
- return top != null ? top.getSortOrder() : null;
- }
- /**
- * 上移/下移精选文章的推荐顺序。direction: 'up' 或 'down'。
- */
- @Transactional
- public String moveSortOrder(Long id, String direction) {
- Article target = articleMapper.selectById(id);
- if (target == null) {
- throw new RuntimeException("文章不存在");
- }
- if (!"published".equals(target.getStatus()) || !Integer.valueOf(1).equals(target.getIsFeatured())) {
- throw new RuntimeException("仅已发布且精选的文章可调整顺序");
- }
- if (!"up".equals(direction) && !"down".equals(direction)) {
- throw new RuntimeException("direction 只能是 up 或 down");
- }
- LambdaQueryWrapper<Article> listWrapper = new LambdaQueryWrapper<Article>()
- .eq(Article::getStatus, "published")
- .eq(Article::getIsFeatured, 1)
- .orderByAsc(Article::getSortOrder)
- .orderByDesc(Article::getPublishedAt);
- List<Article> featured = articleMapper.selectList(listWrapper);
- int idx = -1;
- for (int i = 0; i < featured.size(); i++) {
- if (featured.get(i).getId().equals(id)) {
- idx = i;
- break;
- }
- }
- if (idx == -1) {
- throw new RuntimeException("文章不存在");
- }
- if ("up".equals(direction) && idx <= 0) {
- throw new RuntimeException("已在最前面");
- }
- if ("down".equals(direction) && idx >= featured.size() - 1) {
- throw new RuntimeException("已在最后面");
- }
- int swapIdx = "up".equals(direction) ? idx - 1 : idx + 1;
- Article a = featured.get(idx);
- Article b = featured.get(swapIdx);
- Integer tmpSort = a.getSortOrder();
- a.setSortOrder(b.getSortOrder());
- b.setSortOrder(tmpSort);
- a.setUpdatedAt(new Date());
- b.setUpdatedAt(new Date());
- articleMapper.updateById(a);
- articleMapper.updateById(b);
- // 全局重编号 1..N,消除并列与空洞
- LambdaQueryWrapper<Article> renumWrapper = new LambdaQueryWrapper<Article>()
- .eq(Article::getStatus, "published")
- .eq(Article::getIsFeatured, 1)
- .orderByAsc(Article::getSortOrder)
- .orderByDesc(Article::getPublishedAt);
- List<Article> sorted = articleMapper.selectList(renumWrapper);
- Date now = new Date();
- for (int i = 0; i < sorted.size(); i++) {
- sorted.get(i).setSortOrder(i + 1);
- sorted.get(i).setUpdatedAt(now);
- articleMapper.updateById(sorted.get(i));
- }
- return "已调整顺序";
- }
- public ReadingStatsDTO getReadingStats(Long memberId) {
- ReadingStatsDTO dto = new ReadingStatsDTO();
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.DAY_OF_MONTH, 1);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- Date since = cal.getTime();
- Integer totalDuration = articleReadingRecordMapper.selectTotalDurationByChildSince(memberId, since);
- if (totalDuration == null) totalDuration = 0;
- LambdaQueryWrapper<ArticleReadingRecord> countWrapper = new LambdaQueryWrapper<ArticleReadingRecord>()
- .eq(ArticleReadingRecord::getMemberId, memberId)
- .ge(ArticleReadingRecord::getReadAt, since);
- Integer totalArticles = Math.toIntExact(articleReadingRecordMapper.selectCount(countWrapper));
- int targetSeconds = 6000; // 100分钟/月目标
- int progress = totalDuration >= targetSeconds ? 100 : totalDuration * 100 / targetSeconds;
- dto.setTotalArticles(totalArticles);
- dto.setTotalDurationSeconds(totalDuration);
- dto.setTargetDurationSeconds(targetSeconds);
- dto.setProgress((double) progress);
- return dto;
- }
- public Map<String, Object> getDailyTip() {
- LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
- .eq(Article::getStatus, "published")
- .and(w -> w.like(Article::getRelatedDimensions, "mind")
- .or().like(Article::getRelatedDimensions, "心理"))
- .orderByDesc(Article::getPublishedAt)
- .last("LIMIT 10");
- List<Article> candidates = articleMapper.selectList(wrapper);
- if (candidates != null && !candidates.isEmpty()) {
- int dayOfYear = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
- Article tip = candidates.get(dayOfYear % candidates.size());
- Map<String, Object> result = new HashMap<>();
- result.put("id", tip.getId());
- result.put("title", tip.getTitle());
- result.put("summary", tip.getSummary());
- result.put("coverImage", tip.getCoverImage());
- return result;
- }
- Map<String, Object> fallback = new HashMap<>();
- fallback.put("id", null);
- fallback.put("title", "每日心理小贴士");
- fallback.put("summary", "每天花5分钟与家人聊聊今天的心情,倾听比建议更重要。");
- fallback.put("coverImage", null);
- return fallback;
- }
- /**
- * 根据文章内容和用户画像生成 2 道选择题
- */
- @Transactional
- public Map<String, Object> getAiQuestions(Long articleId, Long userId, Long memberId) {
- Map<String, Object> result = new HashMap<>();
- // 1. 获取文章
- Article article = articleMapper.selectById(articleId);
- if (article == null) {
- throw new RuntimeException("文章不存在");
- }
- // 2. 构建 Dify prompt
- String contentPreview = article.getContent() != null ? article.getContent() : "";
- if (contentPreview.length() > 800) {
- contentPreview = contentPreview.substring(0, 800);
- }
- String prompt = "你是一个家庭教育助手。根据以下文章内容,为儿童生成 2 道选择题(每题 4 个选项)。"
- + "题目应该适合该年龄段的儿童理解。"
- + "请以 JSON 数组格式返回,格式:[{\"question\":\"问题\",\"options\":[\"A.选项 1\",\"B.选项 2\",\"C.选项 3\",\"D.选项 4\"],\"answer\":\"A\"}]"
- + "不要返回其他文字,只返回 JSON 数组。"
- + "\n\n文章标题:" + article.getTitle()
- + "\n文章内容:" + contentPreview;
- // 3. 调用 Dify AI
- Map<String, Object> aiResult = aiService.sendMessage(prompt, String.valueOf(userId), "", null);
- String aiResponse = (String) aiResult.get("answer");
- if (aiResponse == null) {
- aiResponse = "";
- }
- // 4. 提取 JSON 数组
- String questionsJson = extractJsonFromResponse(aiResponse);
- // 5. 保存记录
- ArticleQuizRecord record = new ArticleQuizRecord();
- record.setArticleId(articleId);
- record.setUserId(userId);
- record.setMemberId(memberId);
- record.setQuestions(questionsJson);
- record.setAnswers(null);
- record.setScore(0);
- record.setCfEarned(0);
- record.setCreatedAt(new Date());
- record.setUpdatedAt(new Date());
- articleQuizRecordMapper.insert(record);
- result.put("recordId", record.getId());
- result.put("questions", questionsJson);
- return result;
- }
- private String extractJsonFromResponse(String response) {
- if (response == null || response.isEmpty()) return "[]";
- int start = response.indexOf('[');
- int end = response.lastIndexOf(']');
- if (start >= 0 && end > start) {
- return response.substring(start, end + 1);
- }
- return "[]";
- }
- @Transactional
- public Map<String, Object> submitAnswers(Long recordId, String answersJson, Long userId, Long memberId) {
- Map<String, Object> result = new HashMap<>();
- // 1. 获取记录
- ArticleQuizRecord record = articleQuizRecordMapper.selectById(recordId);
- if (record == null) {
- throw new RuntimeException("答题记录不存在");
- }
- if (record.getAnswers() != null) {
- throw new RuntimeException("已作答,不可重复提交");
- }
- // 2. 解析题目和答案,计算分数
- int score = 0;
- int totalQuestions = 0;
- try {
- List<Map<String, Object>> questions = objectMapper.readValue(record.getQuestions(), objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class));
- List<Map<String, Object>> answers = objectMapper.readValue(answersJson, objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class));
- totalQuestions = questions.size();
- Map<String, Object> answerMap = new HashMap<>();
- for (Map<String, Object> a : answers) {
- answerMap.put(String.valueOf(a.get("questionIndex")), a.get("selected"));
- }
- for (int i = 0; i < questions.size(); i++) {
- Map<String, Object> q = questions.get(i);
- String correct = (String) q.get("answer");
- String selected = (String) answerMap.get(String.valueOf(i));
- if (correct != null && correct.equalsIgnoreCase(selected != null ? selected.toString() : "")) {
- score++;
- }
- }
- } catch (Exception e) {
- log.warn("解析答题结果失败:{}", e.getMessage());
- }
- // 3. CF 值发放(F08 统一入口:仅全部答对才发,数量取自 cf_earn_rule F08,代码不再硬编码;
- // 幂等 ref_id = 答题记录ID,同一记录只发一次)
- boolean allCorrect = score == totalQuestions && totalQuestions > 0;
- int pointsEarned = 0;
- if (allCorrect && memberId != null) {
- try {
- CfEarnResult earnResult = cfPathwayEarnService.earnAiReadingQuizCf(
- memberId, record.getId(), true);
- if (Boolean.TRUE.equals(earnResult.getEarned()) && earnResult.getAmount() != null) {
- pointsEarned = earnResult.getAmount();
- }
- } catch (Exception e) {
- log.warn("CF值发放失败:{}", e.getMessage());
- }
- }
- // 4. 更新答题记录(cfEarned 记本次实际发放数量,日限/幂等命中时记 0)
- record.setAnswers(answersJson);
- record.setScore(score);
- record.setCfEarned(pointsEarned);
- record.setUpdatedAt(new Date());
- articleQuizRecordMapper.updateById(record);
- result.put("score", score);
- result.put("totalQuestions", totalQuestions);
- result.put("pointsEarned", pointsEarned);
- return result;
- }
- /**
- * 用户发布文章(成长记录)
- * @param visibility private=仅家庭(直接发布), public=公开(需审核)
- */
- @Transactional
- public Article publishByUser(String title, String content, String coverImage, String visibility,
- String relatedDimensions, Long userId, String userRole) {
- Article article = new Article();
- article.setTitle(title);
- article.setContent(content);
- article.setCoverImage(coverImage);
- article.setAuthorType("parent");
- article.setCreatedBy(userId);
- article.setWordCount(calculateWordCount(content));
- // 可见范围
- article.setVisibility(visibility != null ? visibility : "private");
- // 关联维度
- article.setRelatedDimensions(relatedDimensions);
- article.setDimensionWeights(buildEqualWeights(relatedDimensions));
- // 私有(家庭可见)→ 设置 visibleTo
- if ("private".equals(visibility)) {
- User user = userMapper.selectById(userId);
- if (user != null && user.getFamilyId() != null) {
- article.setVisibleTo("[{\"type\":\"family\",\"familyId\":" + user.getFamilyId() + "}]");
- }
- }
- // 公开文章需要审核,家庭内部可见直接发布
- if ("public".equals(visibility)) {
- article.setStatus("draft");
- article.setAuditStatus("pending");
- } else {
- article.setStatus("published");
- article.setAuditStatus("approved");
- article.setPublishedAt(new Date());
- }
- article.setArticleType("original");
- article.setViewCount(0);
- article.setCreatedAt(new Date());
- article.setUpdatedAt(new Date());
- articleMapper.insert(article);
- // 家庭可见直接发布:发布时若标签为空则异步自动生成(公开文章待审核,内部守卫跳过)
- ensureAutoTagsIfEmpty(article.getId());
- // 家庭可见直接发布:异步预生成朗读音频(公开文章待审核,内部守卫跳过)
- ensureArticleAudioAfterPublish(article.getId());
- return article;
- }
- private String buildEqualWeights(String relatedDimensions) {
- if (relatedDimensions == null || relatedDimensions.trim().isEmpty()) {
- return null;
- }
- String[] parts = relatedDimensions.split(",");
- int n = parts.length;
- if (n == 0) return null;
- int base = 100 / n;
- int remainder = 100 - base * n;
- Map<String, Integer> weights = new LinkedHashMap<>();
- for (int i = 0; i < n; i++) {
- String dim = parts[i].trim().toLowerCase();
- if (dim.isEmpty()) continue;
- weights.put(dim, i < remainder ? base + 1 : base);
- }
- if (weights.isEmpty()) return null;
- try {
- return objectMapper.writeValueAsString(weights);
- } catch (Exception e) {
- return null;
- }
- }
- /**
- * 获取我的发布列表
- */
- public Page<Article> getMyPosts(Long userId, int page, int size) {
- LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
- .eq(Article::getCreatedBy, userId)
- // 非登录用户(不可登录成员)
- .in(Article::getAuthorType, "parent", "child")
- .orderByDesc(Article::getCreatedAt);
- return articleMapper.selectPage(new Page<>(page, size), wrapper);
- }
- /**
- * 增量查询:获取指定时间之后更新的文章(供 LangGraph RAG 使用)
- */
- public List<Article> getUpdatedSince(Date since, String status) {
- LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
- .ge(Article::getUpdatedAt, since)
- .orderByDesc(Article::getUpdatedAt);
- String s = (status != null && !status.trim().isEmpty()) ? status.trim() : "published";
- wrapper.eq(Article::getStatus, s);
- return articleMapper.selectList(wrapper);
- }
- /**
- * 管理员审核文章
- */
- @Transactional
- public void auditArticle(Long articleId, String auditStatus, String auditReason, Long auditorId) {
- Article article = articleMapper.selectById(articleId);
- if (article == null) {
- throw new RuntimeException("文章不存在");
- }
- if (!"pending".equals(article.getAuditStatus())) {
- throw new RuntimeException("仅待审核状态可审核");
- }
- article.setAuditStatus(auditStatus);
- article.setAuditorId(auditorId);
- article.setAuditedAt(new Date());
- if ("approved".equals(auditStatus)) {
- article.setStatus("published");
- article.setPublishedAt(new Date());
- article.setAuditReason(null);
- } else if ("rejected".equals(auditStatus)) {
- article.setStatus("rejected");
- article.setAuditReason(auditReason);
- }
- article.setUpdatedAt(new Date());
- articleMapper.updateById(article);
- // 审核通过发布:若标签为空则异步自动生成
- if ("approved".equals(auditStatus)) {
- ensureAutoTagsIfEmpty(articleId);
- // 审核通过发布:异步预生成朗读音频
- ensureArticleAudioAfterPublish(articleId);
- }
- }
- /**
- * 发布路径语音预生成入口:仅已发布且尚无音频时,事务提交后异步生成。
- * 失败仅记录 warn,不阻塞发布流程。
- */
- private void ensureArticleAudioAfterPublish(Long articleId) {
- if (articleId == null) {
- return;
- }
- Article article = articleMapper.selectById(articleId);
- if (article == null || !"published".equals(article.getStatus())) {
- return;
- }
- if (article.getAudioUrl() != null && !article.getAudioUrl().trim().isEmpty()) {
- return;
- }
- final Long id = articleId;
- runAfterCommit(() -> {
- try {
- articleAudioService.generateIfMissing(id);
- } catch (Exception e) {
- log.warn("文章语音自动生成失败(不影响文章): articleId={}, error={}", id, e.getMessage());
- }
- });
- }
- /**
- * 在当前事务提交后执行任务;无事务时立即提交到线程池。
- * 避免异步任务读到未提交的文章数据。
- */
- private void runAfterCommit(Runnable task) {
- if (TransactionSynchronizationManager.isSynchronizationActive()) {
- TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
- @Override
- public void afterCommit() {
- taskExecutor.execute(task);
- }
- });
- } else {
- taskExecutor.execute(task);
- }
- }
- /**
- * 发布路径自动打标入口:仅当文章已发布且 tags 为空时,异步调 LLM 生成并写回。
- * 失败仅记录 warn,不阻塞发布流程。
- */
- private void ensureAutoTagsIfEmpty(Long articleId) {
- Article article = articleMapper.selectById(articleId);
- if (article == null || !"published".equals(article.getStatus())) {
- return;
- }
- if (article.getTags() != null && !article.getTags().trim().isEmpty()) {
- return;
- }
- final Long id = article.getId();
- final String content = article.getContent();
- taskExecutor.execute(() -> {
- try {
- List<String> tagNames = autoGenerateTags(content);
- if (!tagNames.isEmpty()) {
- saveAutoTags(id, tagNames);
- }
- } catch (Exception e) {
- log.warn("AI 自动标签生成失败(不影响文章): articleId={}, error={}", id, e.getMessage());
- }
- });
- }
- /**
- * 调用 Dify AI 从文章内容中自动提取 3-5 个中文关键词作为标签
- */
- private List<String> autoGenerateTags(String content) {
- if (content == null || content.trim().isEmpty()) {
- return Collections.emptyList();
- }
- // 去除 HTML 标签,避免干扰 AI 提取
- String plainText = content.replaceAll("<[^>]*>", " ").replaceAll("\\s+", " ").trim();
- if (plainText.isEmpty()) {
- return Collections.emptyList();
- }
- // 截取前 1500 字,避免 prompt 过长
- if (plainText.length() > 1500) {
- plainText = plainText.substring(0, 1500);
- }
- String prompt = "你是一个家庭教育内容分析助手。请根据以下文章内容,提取 3 到 5 个最能代表文章主题的中文关键词作为标签。"
- + "要求:1) 关键词为中文短语或名词,2-6 个字;2) 用英文逗号分隔;3) 不要包含编号、引号或解释文字;4) 只返回标签列表本身。"
- + "\n\n文章内容:" + plainText;
- try {
- Map<String, Object> aiResult = aiService.sendMessage(prompt, "0", "", null);
- String aiResponse = (String) aiResult.get("answer");
- if (aiResponse == null || aiResponse.trim().isEmpty()) {
- return Collections.emptyList();
- }
- // 解析逗号分隔的标签
- List<String> tags = new ArrayList<>();
- for (String raw : aiResponse.split(",")) {
- String tag = raw.trim()
- .replaceAll("^[\\d\\.\\-\\s、。,]+", "")
- .replaceAll("[\\s、。,]+$", "")
- .trim();
- if (!tag.isEmpty() && tag.length() <= 20 && tags.size() < 5) {
- tags.add(tag);
- }
- }
- return tags;
- } catch (Exception e) {
- log.warn("AI 自动生成标签失败:{}", e.getMessage());
- return Collections.emptyList();
- }
- }
- /**
- * 将 AI 生成的标签保存到 dan_knowledge_tag 与 article_tags 表,并回写 article.tags 字段
- */
- private void saveAutoTags(Long articleId, List<String> tagNames) {
- if (articleId == null || tagNames == null || tagNames.isEmpty()) {
- return;
- }
- List<String> savedTags = new ArrayList<>();
- for (String tagName : tagNames) {
- if (tagName == null || tagName.trim().isEmpty()) continue;
- String name = tagName.trim();
- try {
- // 查询是否已存在同名标签
- List<Long> existing = jdbcTemplate.queryForList(
- "SELECT id FROM dan_knowledge_tag WHERE tag_name = ? LIMIT 1",
- Long.class, name);
- Long tagId;
- if (existing != null && !existing.isEmpty()) {
- tagId = existing.get(0);
- } else {
- // 插入新标签
- jdbcTemplate.update(
- "INSERT INTO dan_knowledge_tag (tag_name, tag_type, created_at) VALUES (?, 'auto', NOW())",
- name);
- tagId = jdbcTemplate.queryForObject(
- "SELECT id FROM dan_knowledge_tag WHERE tag_name = ? ORDER BY id DESC LIMIT 1",
- Long.class, name);
- }
- if (tagId != null) {
- jdbcTemplate.update(
- "INSERT IGNORE INTO article_tags (article_id, tag_id) VALUES (?, ?)",
- articleId, tagId);
- savedTags.add(name);
- }
- } catch (Exception e) {
- log.warn("保存自动标签失败:tagName={}, error={}", name, e.getMessage());
- }
- }
- // 回写 article.tags 字段(逗号分隔)
- if (!savedTags.isEmpty()) {
- String tagsStr = String.join(",", savedTags);
- jdbcTemplate.update("UPDATE articles SET tags = ? WHERE id = ?", tagsStr, articleId);
- }
- }
- @Transactional
- public void submitForReview(Long id) {
- Article article = articleMapper.selectById(id);
- if (article == null) {
- throw new RuntimeException("文章不存在");
- }
- if (!"draft".equals(article.getStatus())) {
- throw new RuntimeException("仅草稿状态可提交审核");
- }
- article.setStatus("pending");
- article.setAuditStatus("pending");
- article.setUpdatedAt(new Date());
- articleMapper.updateById(article);
- }
- @Transactional
- public void withdraw(Long id) {
- Article article = articleMapper.selectById(id);
- if (article == null) {
- throw new RuntimeException("文章不存在");
- }
- if (!"published".equals(article.getStatus())) {
- throw new RuntimeException("仅发布中的文章可撤回");
- }
- article.setStatus("withdrawn");
- article.setUpdatedAt(new Date());
- articleMapper.updateById(article);
- }
- @Transactional
- public void reDraft(Long id) {
- Article article = articleMapper.selectById(id);
- if (article == null) {
- throw new RuntimeException("文章不存在");
- }
- if (!"rejected".equals(article.getStatus()) && !"withdrawn".equals(article.getStatus())) {
- throw new RuntimeException("仅已驳回或已撤回的文章可重新编辑");
- }
- article.setStatus("draft");
- article.setAuditStatus(null);
- article.setAuditReason(null);
- article.setAuditorId(null);
- article.setAuditedAt(null);
- article.setUpdatedAt(new Date());
- articleMapper.updateById(article);
- }
- }
|