ArticleService.java 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  1. package com.etotem.cfc.service;
  2. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  3. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  4. import com.etotem.cfc.dto.CfEarnResult;
  5. import com.etotem.cfc.dto.ReadingStatsDTO;
  6. import com.etotem.cfc.entity.Article;
  7. import com.etotem.cfc.entity.ArticleCategory;
  8. import com.etotem.cfc.entity.ArticleQuizRecord;
  9. import com.etotem.cfc.entity.ArticleReadingRecord;
  10. import com.etotem.cfc.entity.ContentDimensionThreshold;
  11. import com.etotem.cfc.entity.FamilyMember;
  12. import com.etotem.cfc.entity.PointsLog;
  13. import com.etotem.cfc.entity.Product;
  14. import com.etotem.cfc.entity.Task;
  15. import com.etotem.cfc.entity.User;
  16. import com.etotem.cfc.mapper.ArticleMapper;
  17. import com.etotem.cfc.mapper.ProductMapper;
  18. import com.etotem.cfc.mapper.ArticleQuizRecordMapper;
  19. import com.etotem.cfc.mapper.ArticleReadingRecordMapper;
  20. import com.etotem.cfc.mapper.FamilyMemberMapper;
  21. import com.etotem.cfc.mapper.PointsLogMapper;
  22. import com.etotem.cfc.mapper.TaskMapper;
  23. import com.etotem.cfc.mapper.UserMapper;
  24. import com.fasterxml.jackson.core.type.TypeReference;
  25. import com.fasterxml.jackson.databind.ObjectMapper;
  26. import lombok.extern.slf4j.Slf4j;
  27. import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  28. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  29. import org.springframework.jdbc.core.JdbcTemplate;
  30. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  31. import org.springframework.stereotype.Service;
  32. import org.springframework.transaction.annotation.Transactional;
  33. import org.springframework.transaction.support.TransactionSynchronization;
  34. import org.springframework.transaction.support.TransactionSynchronizationManager;
  35. import javax.annotation.Resource;
  36. import java.util.*;
  37. import java.util.stream.Collectors;
  38. import com.etotem.cfc.util.DimensionCodes;
  39. import com.etotem.cfc.util.SortUtil;
  40. @Slf4j
  41. @Service
  42. public class ArticleService {
  43. @Resource
  44. private ArticleMapper articleMapper;
  45. @Resource
  46. private ProductMapper productMapper;
  47. @Resource
  48. private ArticlePermissionService articlePermissionService;
  49. @Resource
  50. private ArticleCategoryService articleCategoryService;
  51. @Resource
  52. private ArticleReadingRecordMapper articleReadingRecordMapper;
  53. @Resource
  54. private SysConfigService sysConfigService;
  55. @Resource
  56. private TaskMapper taskMapper;
  57. @Resource
  58. private FamilyMemberMapper familyMemberMapper;
  59. @Resource
  60. private PointsLogMapper pointsLogMapper;
  61. @Resource
  62. private EnergyService energyService;
  63. @Resource
  64. private CfPathwayEarnService cfPathwayEarnService;
  65. @Resource
  66. private AIService aiService;
  67. @Resource
  68. private ArticleQuizRecordMapper articleQuizRecordMapper;
  69. @Resource
  70. private UserMapper userMapper;
  71. @Resource
  72. private FiveDimensionScoreService fiveDimensionScoreService;
  73. @Resource
  74. private ContentDimensionThresholdService contentDimensionThresholdService;
  75. @Resource
  76. private JdbcTemplate jdbcTemplate;
  77. @Resource(name = "taskExecutor")
  78. private ThreadPoolTaskExecutor taskExecutor;
  79. @Resource
  80. private ArticleAudioService articleAudioService;
  81. private final ObjectMapper objectMapper = new ObjectMapper();
  82. public Page<Article> getPublicList(Long categoryId, String keyword, String dimensionCode, int page, int size,
  83. Long userId, Long familyId, String vendorType) {
  84. return getPublicList(categoryId, keyword, dimensionCode, null, page, size, userId, familyId, vendorType, null);
  85. }
  86. public Page<Article> getPublicList(Long categoryId, String keyword, String dimensionCode, int page, int size,
  87. Long userId, Long familyId, String vendorType, Long memberId) {
  88. return getPublicList(categoryId, keyword, dimensionCode, null, page, size, userId, familyId, vendorType, memberId);
  89. }
  90. /**
  91. * 知识中心文章列表:支持按文章标签筛选(知识中心 Tab 从「五维」改为「文章标签」)。
  92. * tag 为空时行为与旧版一致;tag 非空时仅返回 tags 字段包含该标签的文章。
  93. * tags 字段为 JSON 数组字符串(如 ["减脂","睡眠"])或逗号分隔,统一由 parseCommaOrJsonTags 解析后内存过滤。
  94. */
  95. public Page<Article> getPublicList(Long categoryId, String keyword, String dimensionCode, String tag,
  96. int page, int size, Long userId, Long familyId, String vendorType, Long memberId) {
  97. LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
  98. .eq(Article::getStatus, "published")
  99. .orderByDesc(Article::getIsFeatured)
  100. .orderByAsc(Article::getSortOrder)
  101. .orderByDesc(Article::getPublishedAt);
  102. if (categoryId != null && categoryId > 0) {
  103. wrapper.eq(Article::getCategoryId, categoryId);
  104. }
  105. if (keyword != null && !keyword.trim().isEmpty()) {
  106. String kw = keyword.trim();
  107. wrapper.and(w -> w.like(Article::getTitle, kw).or().like(Article::getSummary, kw).or().like(Article::getTags, kw));
  108. }
  109. if (dimensionCode != null && !dimensionCode.trim().isEmpty() && DimensionCodes.isValid(dimensionCode)) {
  110. String dim = dimensionCode.trim();
  111. // P1: 权重感知查询 — 匹配 dimension_weights > 0 或兼容旧版 relatedDimensions
  112. wrapper.and(w -> w
  113. .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
  114. .or().like(Article::getRelatedDimensions, dim)
  115. );
  116. }
  117. // 先查全量(不含分页),内存中做权限过滤后再手动分页。
  118. // 原因:可见性过滤规则含 JSON visible_to,无法下推 SQL;
  119. // 若先 selectPage 后过滤,total 会被设为本页过滤后条数(<= size),
  120. // 前端 noMore = 已加载数 >= total 恒为真,导致只显示一页、无法加载更多。
  121. List<Article> all = articleMapper.selectList(wrapper);
  122. // 按文章标签筛选(与 parseCommaOrJsonTags 解析语义对齐,兼容 JSON 数组 / 逗号分隔两种存储格式)
  123. if (tag != null && !tag.trim().isEmpty()) {
  124. String targetTag = tag.trim();
  125. all = all.stream()
  126. .filter(a -> parseCommaOrJsonTags(a.getTags()).contains(targetTag))
  127. .collect(Collectors.toList());
  128. }
  129. List<Article> visible = articlePermissionService.filterVisible(all, userId, familyId, vendorType);
  130. // 过滤已完成阅读且获得CF值的文章(达到阈值且答题得CF后不再出现在文章列表中)
  131. if (memberId != null) {
  132. List<Long> completedIds = articleReadingRecordMapper.selectCompletedArticleIdsByChild(memberId);
  133. if (!completedIds.isEmpty()) {
  134. visible.removeIf(a -> completedIds.contains(a.getId()));
  135. }
  136. }
  137. // 内容维度阈值显隐过滤(A-后端):OR 逻辑,fail-open 不误隐藏
  138. applyDimensionThresholdFilter(visible, familyId);
  139. enrichTotalDurationSeconds(visible);
  140. // 手动分页(与 getFeatured 相同模式),total 为过滤后的真实总数
  141. int total = visible.size();
  142. int fromIndex = Math.min((page - 1) * size, total);
  143. int toIndex = Math.min(fromIndex + size, total);
  144. List<Article> pageList = visible.subList(fromIndex, toIndex);
  145. Page<Article> filtered = new Page<>(page, size);
  146. filtered.setTotal(total);
  147. filtered.setRecords(new ArrayList<>(pageList));
  148. return filtered;
  149. }
  150. /**
  151. * 内容维度阈值显隐过滤(A-后端)。
  152. * 家庭维度指标取家庭成员平均值;无家庭得分数据 → fail-open 不误隐藏。
  153. * 显隐规则(OR 逻辑):任一配置维度得分 < 阈值 → 显示;全部 >= 阈值 → 隐藏。
  154. */
  155. private void applyDimensionThresholdFilter(List<Article> visible, Long familyId) {
  156. if (visible == null || visible.isEmpty()) return;
  157. Map<String, Integer> familyAvg = fiveDimensionScoreService.getFamilyAverageScores(familyId);
  158. if (familyAvg.isEmpty()) return; // 无家庭得分数据 → fail-open
  159. List<Long> ids = visible.stream().map(Article::getId).collect(Collectors.toList());
  160. Map<Long, List<ContentDimensionThreshold>> byId =
  161. contentDimensionThresholdService.listByContents("ARTICLE", ids);
  162. DimensionThresholdFilter.filterVisible(visible, Article::getId, "ARTICLE", familyAvg, byId);
  163. }
  164. /**
  165. * 聚合已发布文章的标签,按出现频次降序返回 Top N(知识中心 Tab 动态标签列表数据源)。
  166. * 标签格式兼容 JSON 数组 / 逗号分隔,统一由 parseCommaOrJsonTags 解析拆分去重。
  167. */
  168. public List<String> listTopTags(int limit) {
  169. int n = limit > 0 ? limit : 20;
  170. LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
  171. .eq(Article::getStatus, "published")
  172. .and(w -> w.isNotNull(Article::getTags).or().apply("TRIM(tags) <> ''"));
  173. List<Article> articles = articleMapper.selectList(wrapper);
  174. Map<String, Integer> freq = new HashMap<>();
  175. for (Article a : articles) {
  176. for (String t : parseCommaOrJsonTags(a.getTags())) {
  177. if (!t.isEmpty()) {
  178. freq.merge(t, 1, Integer::sum);
  179. }
  180. }
  181. }
  182. return freq.entrySet().stream()
  183. .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
  184. .thenComparing(Map.Entry.comparingByKey()))
  185. .limit(n)
  186. .map(Map.Entry::getKey)
  187. .collect(Collectors.toList());
  188. }
  189. public List<Article> getFeatured(int size, Long userId, Long familyId, String vendorType, Long memberId) {
  190. return getFeatured(size, null, userId, familyId, vendorType, memberId);
  191. }
  192. public List<Article> getFeatured(int size, String dimensionCode, Long userId, Long familyId, String vendorType, Long memberId) {
  193. LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
  194. .eq(Article::getStatus, "published")
  195. .eq(Article::getIsFeatured, 1)
  196. .orderByAsc(Article::getSortOrder)
  197. .orderByDesc(Article::getPublishedAt)
  198. .last("LIMIT " + Math.max(size, 50));
  199. if (dimensionCode != null && !dimensionCode.trim().isEmpty() && DimensionCodes.isValid(dimensionCode)) {
  200. String dim = dimensionCode.trim();
  201. // P1: 权重感知查询 — 匹配 dimension_weights > 0 或兼容旧版 relatedDimensions
  202. wrapper.and(w -> w
  203. .apply("COALESCE(JSON_EXTRACT(dimension_weights, CONCAT('$.', {0})), 0) > 0", dim)
  204. .or().like(Article::getRelatedDimensions, dim)
  205. );
  206. }
  207. List<Article> all = articleMapper.selectList(wrapper);
  208. List<Article> visible = articlePermissionService.filterVisible(all, userId, familyId, vendorType);
  209. // 过滤已阅读达标的文章(达到阈值后不再出现在推荐阅读中)
  210. if (memberId != null) {
  211. List<Long> completedIds = articleReadingRecordMapper.selectCompletedArticleIdsByChild(memberId);
  212. if (!completedIds.isEmpty()) {
  213. visible.removeIf(a -> completedIds.contains(a.getId()));
  214. }
  215. }
  216. enrichTotalDurationSeconds(visible);
  217. return visible.size() > size ? visible.subList(0, size) : visible;
  218. }
  219. /**
  220. * 存量回填:为所有「已发布且 tags 为空」的文章异步触发自动打标(幂等,可重复调用)。
  221. * @return 触发的文章数
  222. */
  223. public int backfillEmptyPublishedTags() {
  224. List<Article> list = articleMapper.selectList(new LambdaQueryWrapper<Article>()
  225. .eq(Article::getStatus, "published")
  226. .and(w -> w.isNull(Article::getTags).or().apply("TRIM(tags) = ''")));
  227. for (Article a : list) {
  228. ensureAutoTagsIfEmpty(a.getId());
  229. }
  230. log.info("存量空标签文章回填触发: {} 篇", list.size());
  231. return list.size();
  232. }
  233. /**
  234. * 相关文章:按标签匹配(FIND_IN_SET 精确匹配整标签),共享标签数降序 → 发布时间降序,
  235. * 排除自身,仅取已发布,经可见性过滤后按 (page-1)*size ~ page*size 分页窗口截取。
  236. * 无标签/无匹配返回空。
  237. */
  238. public List<Article> getRelatedArticles(Long articleId, int size, int page, Long userId, Long familyId, String vendorType) {
  239. Article current = articleMapper.selectById(articleId);
  240. if (current == null || current.getTags() == null || current.getTags().trim().isEmpty()) {
  241. return Collections.emptyList();
  242. }
  243. List<String> tags = new ArrayList<>();
  244. for (String t : current.getTags().split(",")) {
  245. String tag = t.trim();
  246. if (!tag.isEmpty() && !tags.contains(tag)) {
  247. tags.add(tag);
  248. }
  249. }
  250. return getRelatedArticlesByTags(tags, articleId, size, page, userId, familyId, vendorType);
  251. }
  252. /**
  253. * 相关文章(按源标签匹配,通用入口):供内容关联服务(活动/商品 ↔ 文章)复用,
  254. * 语义与 {@link #getRelatedArticles} 一致:共享标签数降序 → 发布时间降序,仅取已发布,
  255. * 经可见性过滤后分页窗口截取。excludeArticleId 为空表示不排除(源为其他表内容)。
  256. *
  257. * @param tags 源标签集合
  258. * @param excludeArticleId 需排除的文章ID(文章源排除自身;其他源为 null)
  259. * @param size 每页条数
  260. * @param page 页码(从1开始)
  261. * @param userId 当前用户ID(可为空)
  262. * @param familyId 家庭ID(可为空,私有文章可见性判定用)
  263. * @param vendorType 服务商类型(可为空)
  264. * @return 相关文章列表,无匹配返回空列表
  265. */
  266. public List<Article> getRelatedArticlesByTags(List<String> tags, Long excludeArticleId, int size, int page,
  267. Long userId, Long familyId, String vendorType) {
  268. return matchArticlesByTags(tags, excludeArticleId, size, page, userId, familyId, vendorType);
  269. }
  270. /**
  271. * 商品详情页「相关文章」:按商品标签匹配文章(共享标签数降序 → 发布时间降序),
  272. * 支持分页窗口截取。商品标签为 JSON 数组或逗号分隔字符串。
  273. */
  274. public List<Article> getRelatedArticlesByProduct(Long productId, int size, int page, Long userId, Long familyId, String vendorType) {
  275. if (productId == null) return Collections.emptyList();
  276. Product product = productMapper.selectById(productId);
  277. if (product == null || product.getTags() == null || product.getTags().trim().isEmpty()) {
  278. return Collections.emptyList();
  279. }
  280. List<String> tags = parseCommaOrJsonTags(product.getTags());
  281. // 商品来源无需排除文章自身(productId 与 articleId 分属不同表),excludeArticleId 传 null
  282. return matchArticlesByTags(tags, null, size, page, userId, familyId, vendorType);
  283. }
  284. /**
  285. * 标签匹配文章核心逻辑:FIND_IN_SET 候选 → 共享标签计数 → 排序 → 可见性过滤 → 分页窗口截取。
  286. */
  287. private List<Article> matchArticlesByTags(List<String> tags, Long excludeArticleId, int size, int page,
  288. Long userId, Long familyId, String vendorType) {
  289. if (tags == null || tags.isEmpty() || size < 1) {
  290. return Collections.emptyList();
  291. }
  292. int p = page < 1 ? 1 : page;
  293. LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
  294. .eq(Article::getStatus, "published");
  295. if (excludeArticleId != null) {
  296. wrapper.ne(Article::getId, excludeArticleId);
  297. }
  298. wrapper.and(w -> {
  299. boolean first = true;
  300. for (String tag : tags) {
  301. if (first) {
  302. w.apply("FIND_IN_SET({0}, tags) > 0", tag);
  303. first = false;
  304. } else {
  305. w.or().apply("FIND_IN_SET({0}, tags) > 0", tag);
  306. }
  307. }
  308. });
  309. List<Article> candidates = articleMapper.selectList(wrapper);
  310. // 共享标签计数,剔除零共享(SQL 已限定至少一个标签命中,此处防御)
  311. Map<Long, Integer> score = new HashMap<>();
  312. List<Article> matched = new ArrayList<>();
  313. for (Article a : candidates) {
  314. if (excludeArticleId != null && a.getId() != null && a.getId().equals(excludeArticleId)) {
  315. continue;
  316. }
  317. int s = 0;
  318. if (a.getTags() != null) {
  319. for (String t : a.getTags().split(",")) {
  320. if (tags.contains(t.trim())) {
  321. s++;
  322. }
  323. }
  324. }
  325. if (s > 0) {
  326. matched.add(a);
  327. score.put(a.getId(), s);
  328. }
  329. }
  330. matched.sort((x, y) -> {
  331. int diff = score.getOrDefault(y.getId(), 0) - score.getOrDefault(x.getId(), 0);
  332. if (diff != 0) {
  333. return diff;
  334. }
  335. Date px = x.getPublishedAt();
  336. Date py = y.getPublishedAt();
  337. if (px == null && py == null) return 0;
  338. if (px == null) return 1;
  339. if (py == null) return -1;
  340. return py.compareTo(px);
  341. });
  342. List<Article> visible = articlePermissionService.filterVisible(matched, userId, familyId, vendorType);
  343. if (visible == null) {
  344. visible = Collections.emptyList();
  345. }
  346. // 分页窗口截取:兼容旧调用方(size 截断)与分页调用方
  347. int from = (p - 1) * size;
  348. if (from >= visible.size()) {
  349. return Collections.emptyList();
  350. }
  351. int to = Math.min(from + size, visible.size());
  352. return new ArrayList<>(visible.subList(from, to));
  353. }
  354. /** 商品标签解析:兼容 JSON 数组字符串(["标签1","标签2"])与逗号分隔(标签1,标签2) */
  355. private List<String> parseCommaOrJsonTags(String raw) {
  356. if (raw == null || raw.trim().isEmpty()) return Collections.emptyList();
  357. String trimmed = raw.trim();
  358. if (trimmed.startsWith("[")) {
  359. try {
  360. com.alibaba.fastjson.JSONArray arr = com.alibaba.fastjson.JSON.parseArray(trimmed);
  361. if (arr == null) return Collections.emptyList();
  362. List<String> tags = new ArrayList<>();
  363. for (int i = 0; i < arr.size(); i++) {
  364. Object o = arr.get(i);
  365. if (o != null && !o.toString().trim().isEmpty()) {
  366. tags.add(o.toString().trim());
  367. }
  368. }
  369. return tags;
  370. } catch (Exception e) {
  371. log.warn("解析商品标签失败: {}", e.getMessage());
  372. return Collections.emptyList();
  373. }
  374. }
  375. List<String> tags = new ArrayList<>();
  376. for (String t : trimmed.split(",")) {
  377. String tag = t.trim();
  378. if (!tag.isEmpty() && !tags.contains(tag)) {
  379. tags.add(tag);
  380. }
  381. }
  382. return tags;
  383. }
  384. public Article getDetail(Long id, Long userId, Long familyId, String vendorType) {
  385. Article article = articleMapper.selectById(id);
  386. if (article == null) return null;
  387. if (!"published".equals(article.getStatus())) return null;
  388. if (!articlePermissionService.isVisible(article, userId, familyId, vendorType)) return null;
  389. return article;
  390. }
  391. private int calculateWordCount(String htmlContent) {
  392. if (htmlContent == null || htmlContent.isEmpty()) return 0;
  393. // Strip HTML tags
  394. String text = htmlContent.replaceAll("<[^>]*>", "");
  395. // Strip HTML entities
  396. text = text.replaceAll("&[a-zA-Z]+;", " ");
  397. // Remove extra whitespace
  398. text = text.replaceAll("\\s+", " ").trim();
  399. // Count characters (Chinese text: each character is a "word")
  400. return text.length();
  401. }
  402. @Transactional
  403. public Map<String, Object> recordRead(Long articleId, Long userId, Long memberId, int durationSeconds) {
  404. Map<String, Object> result = new HashMap<>();
  405. result.put("taskId", null);
  406. result.put("pointsEarned", 0);
  407. // 1. Increment view count
  408. LambdaUpdateWrapper<Article> wrapper = Wrappers.lambdaUpdate(Article.class)
  409. .setSql("view_count = view_count + 1")
  410. .eq(Article::getId, articleId);
  411. articleMapper.update(null, wrapper);
  412. // 2. Save reading record
  413. ArticleReadingRecord record = new ArticleReadingRecord();
  414. record.setArticleId(articleId);
  415. record.setUserId(userId);
  416. record.setMemberId(memberId);
  417. record.setContent("");
  418. record.setDurationSeconds(durationSeconds);
  419. int minSeconds = getArticleReadingMinSeconds();
  420. record.setReadingCompleted(memberId != null && durationSeconds >= minSeconds);
  421. record.setReadAt(new Date());
  422. record.setCreatedAt(new Date());
  423. articleReadingRecordMapper.insert(record);
  424. // 3. If no memberId, can't create task (reading as parent, not child)
  425. if (memberId == null) {
  426. return result;
  427. }
  428. // 4. Check reading duration threshold
  429. if (durationSeconds < minSeconds) {
  430. result.put("belowThreshold", true);
  431. result.put("minSeconds", minSeconds);
  432. return result;
  433. }
  434. // If no userId, can't create task (unauthenticated request)
  435. if (userId == null) {
  436. result.put("belowThreshold", true);
  437. result.put("minSeconds", minSeconds);
  438. return result;
  439. }
  440. // 5. Check if a task already exists for this article+child (avoid duplicates)
  441. Task existingTask = taskMapper.selectOne(
  442. new LambdaQueryWrapper<Task>()
  443. .eq(Task::getSourceType, "article")
  444. .eq(Task::getSourceId, articleId)
  445. .eq(Task::getMemberId, memberId)
  446. .last("LIMIT 1")
  447. );
  448. if (existingTask != null) {
  449. result.put("taskId", existingTask.getId());
  450. result.put("pointsEarned", 0);
  451. result.put("alreadyCompleted", true);
  452. return result;
  453. }
  454. // 6. Load article to get wordCount and articleType
  455. Article article = articleMapper.selectById(articleId);
  456. if (article == null) return result;
  457. int wordCount = article.getWordCount() != null ? article.getWordCount() : 0;
  458. String articleType = article.getArticleType() != null ? article.getArticleType() : "normal";
  459. // 7. Calculate points based on wordCount × type rate
  460. int rate = 1; // default for 'normal'
  461. String rateStr = sysConfigService.getValue("article_energy_rate_" + articleType);
  462. if (rateStr != null && !rateStr.isEmpty()) {
  463. try { rate = Integer.parseInt(rateStr); } catch (NumberFormatException e) { /* use default */ }
  464. }
  465. int points = Math.max(1, wordCount / 100 * rate);
  466. // 8. Create task with status='completed' (auto-completed by reading)
  467. Task task = new Task();
  468. task.setFamilyId(null); // will set after getting child
  469. task.setCreatorId(userId);
  470. task.setExecutorType("child"); // 非登录用户(不可登录成员)
  471. task.setExecutorId(memberId);
  472. task.setMemberId(memberId);
  473. task.setTitle("阅读文章: " + article.getTitle());
  474. task.setDescription("自动生成 - 阅读文章《" + article.getTitle() + "》" + durationSeconds + "秒");
  475. task.setPoints(points);
  476. task.setRepeatType("none");
  477. task.setCategory("学习类");
  478. task.setNeedReview(0);
  479. task.setReviewByCategory(0);
  480. task.setTaskType("onetime");
  481. task.setSourceType("article");
  482. task.setSourceId(articleId);
  483. task.setStatus("completed");
  484. task.setCompletedAt(new Date());
  485. task.setCreatedAt(new Date());
  486. task.setUpdatedAt(new Date());
  487. // Set deadline to today end
  488. Calendar cal = Calendar.getInstance();
  489. cal.set(Calendar.HOUR_OF_DAY, 23);
  490. cal.set(Calendar.MINUTE, 59);
  491. cal.set(Calendar.SECOND, 59);
  492. task.setDeadline(cal.getTime());
  493. // Get child to set familyId
  494. FamilyMember child = familyMemberMapper.selectById(memberId);
  495. if (child != null) {
  496. task.setFamilyId(child.getFamilyId());
  497. }
  498. taskMapper.insert(task);
  499. // 9. Update child totalPoints
  500. if (child != null) {
  501. child.setTotalPoints(child.getTotalPoints() + points);
  502. child.setUpdatedAt(new Date());
  503. familyMemberMapper.updateById(child);
  504. }
  505. // 10. Insert PointsLog
  506. PointsLog pointsLog = new PointsLog();
  507. pointsLog.setMemberId(memberId);
  508. pointsLog.setTaskId(task.getId());
  509. pointsLog.setAmount(points);
  510. pointsLog.setType("earn");
  511. pointsLog.setCategory("task");
  512. pointsLog.setDescription("阅读文章: " + article.getTitle());
  513. pointsLog.setCreatedAt(new Date());
  514. pointsLogMapper.insert(pointsLog);
  515. // 11. Award energy via EnergyService
  516. try {
  517. energyService.awardEnergy(memberId, "article", articleId, points,
  518. "阅读文章: " + article.getTitle(), null);
  519. } catch (Exception e) {
  520. log.warn("能量发放失败(不影响积分): memberId={}, articleId={}, error={}",
  521. memberId, articleId, e.getMessage());
  522. }
  523. // 12. Link taskId to reading record
  524. record.setTaskId(task.getId());
  525. articleReadingRecordMapper.updateById(record);
  526. // 13. Return result
  527. result.put("taskId", task.getId());
  528. result.put("pointsEarned", points);
  529. result.put("belowThreshold", false);
  530. return result;
  531. }
  532. public void reportReadingTime(Long articleId, Long userId, Long memberId, int durationSeconds) {
  533. if (memberId == null) return;
  534. // 查找当日已有记录(同文章+同家庭成员)
  535. LambdaQueryWrapper<ArticleReadingRecord> wrapper = new LambdaQueryWrapper<ArticleReadingRecord>()
  536. .eq(ArticleReadingRecord::getArticleId, articleId)
  537. .eq(ArticleReadingRecord::getMemberId, memberId)
  538. .apply("DATE(read_at) = CURDATE()")
  539. .last("LIMIT 1");
  540. ArticleReadingRecord existing = articleReadingRecordMapper.selectOne(wrapper);
  541. // 获取阅读达标阈值
  542. int minSeconds = getArticleReadingMinSeconds();
  543. boolean isCompleted = false;
  544. if (existing != null) {
  545. // 累加时长
  546. existing.setDurationSeconds(existing.getDurationSeconds() + durationSeconds);
  547. // 累计时长达到阈值时标记为已阅读
  548. if (existing.getReadingCompleted() == null || !existing.getReadingCompleted()) {
  549. existing.setReadingCompleted(existing.getDurationSeconds() >= minSeconds);
  550. isCompleted = existing.getReadingCompleted();
  551. }
  552. existing.setUpdatedAt(new Date());
  553. articleReadingRecordMapper.updateById(existing);
  554. } else {
  555. // 新建记录
  556. ArticleReadingRecord record = new ArticleReadingRecord();
  557. record.setArticleId(articleId);
  558. record.setUserId(userId);
  559. record.setMemberId(memberId);
  560. record.setDurationSeconds(durationSeconds);
  561. record.setReadingCompleted(durationSeconds >= minSeconds);
  562. record.setReadAt(new Date());
  563. record.setCreatedAt(new Date());
  564. articleReadingRecordMapper.insert(record);
  565. }
  566. }
  567. /**
  568. * 获取文章阅读达标最低秒数,默认 60 秒
  569. */
  570. private int getArticleReadingMinSeconds() {
  571. String val = sysConfigService.getValue("article_reading_min_seconds");
  572. if (val != null && !val.isEmpty()) {
  573. try { return Integer.parseInt(val); } catch (NumberFormatException e) {}
  574. }
  575. return 60;
  576. }
  577. /**
  578. * 递增文章浏览数(打开详情页即计数,匿名/登录用户均计)
  579. */
  580. public void incrementViewCount(Long id) {
  581. if (id == null) return;
  582. articleMapper.update(null, Wrappers.<Article>lambdaUpdate()
  583. .eq(Article::getId, id)
  584. .setSql("view_count = view_count + 1"));
  585. }
  586. /**
  587. * 按文章 ID 分页查询阅读记录(每人聚合一行),返回昵称、累计时长、阅读次数、最后阅读时间
  588. */
  589. public Page<Map<String, Object>> getArticleReadingRecords(Long articleId, int page, int size) {
  590. long total = articleReadingRecordMapper.countDistinctByArticle(articleId);
  591. if (total == 0) {
  592. Page<Map<String, Object>> empty = new Page<>(page, size);
  593. empty.setTotal(0);
  594. empty.setRecords(Collections.emptyList());
  595. return empty;
  596. }
  597. int offset = (page - 1) * size;
  598. List<Map<String, Object>> records = articleReadingRecordMapper.selectByArticleAggregated(articleId, offset, size);
  599. Page<Map<String, Object>> result = new Page<>(page, size);
  600. result.setTotal(total);
  601. result.setRecords(records);
  602. return result;
  603. }
  604. public Article getById(Long id) {
  605. return articleMapper.selectById(id);
  606. }
  607. private void enrichTotalDurationSeconds(List<Article> articles) {
  608. if (articles == null || articles.isEmpty()) return;
  609. String ids = articles.stream()
  610. .map(a -> String.valueOf(a.getId()))
  611. .collect(Collectors.joining(","));
  612. List<Map<String, Object>> durationRows = jdbcTemplate.queryForList(
  613. "SELECT article_id, SUM(duration_seconds) AS total_duration " +
  614. "FROM article_reading_records WHERE article_id IN (" + ids + ") GROUP BY article_id");
  615. Map<Long, Integer> durationMap = new HashMap<>();
  616. for (Map<String, Object> row : durationRows) {
  617. Number aid = (Number) row.get("article_id");
  618. Number total = (Number) row.get("total_duration");
  619. if (aid != null && total != null) {
  620. durationMap.put(aid.longValue(), total.intValue());
  621. }
  622. }
  623. for (Article article : articles) {
  624. article.setTotalDurationSeconds(durationMap.getOrDefault(article.getId(), 0));
  625. }
  626. }
  627. public void enrichWithCategoryName(List<Article> articles) {
  628. if (articles == null || articles.isEmpty()) return;
  629. }
  630. public Page<Article> getAdminList(String status, Long categoryId, String keyword,
  631. String contentType, Integer difficultyLevel,
  632. String dimensionCode, Long tagId, String auditStatus, int page, int size,
  633. List<Map<String, String>> sortSpecs) {
  634. LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
  635. .orderByDesc(Article::getCreatedAt);
  636. if (status != null && !status.isEmpty()) {
  637. wrapper.eq(Article::getStatus, status);
  638. }
  639. if (categoryId != null && categoryId > 0) {
  640. wrapper.eq(Article::getCategoryId, categoryId);
  641. }
  642. if (keyword != null && !keyword.trim().isEmpty()) {
  643. String kw = keyword.trim();
  644. wrapper.and(w -> w.like(Article::getTitle, kw).or().like(Article::getSummary, kw).or().like(Article::getTags, kw));
  645. }
  646. if (contentType != null && !contentType.isEmpty()) {
  647. wrapper.eq(Article::getContentType, contentType);
  648. }
  649. if (difficultyLevel != null && difficultyLevel > 0) {
  650. wrapper.eq(Article::getDifficultyLevel, difficultyLevel);
  651. }
  652. if (dimensionCode != null && !dimensionCode.isEmpty()) {
  653. wrapper.like(Article::getRelatedDimensions, dimensionCode);
  654. }
  655. if (tagId != null && tagId > 0) {
  656. wrapper.inSql(Article::getId, "SELECT article_id FROM article_tags WHERE tag_id = " + tagId);
  657. }
  658. if (auditStatus != null && !auditStatus.isEmpty()) {
  659. wrapper.eq(Article::getAuditStatus, auditStatus);
  660. }
  661. SortUtil.applySort(wrapper, sortSpecs, null);
  662. Page<Article> pageResult = articleMapper.selectPage(new Page<>(page, size), wrapper);
  663. // 批量填充每篇文章的总阅读时长(按 child 聚合去重后求和)
  664. List<Article> records = pageResult.getRecords();
  665. if (records != null && !records.isEmpty()) {
  666. String ids = records.stream()
  667. .map(a -> String.valueOf(a.getId()))
  668. .collect(Collectors.joining(","));
  669. List<Map<String, Object>> durationRows = jdbcTemplate.queryForList(
  670. "SELECT article_id, SUM(duration_seconds) AS total_duration " +
  671. "FROM article_reading_records WHERE article_id IN (" + ids + ") GROUP BY article_id");
  672. Map<Long, Integer> durationMap = new HashMap<>();
  673. for (Map<String, Object> row : durationRows) {
  674. Number articleId = (Number) row.get("article_id");
  675. Number total = (Number) row.get("total_duration");
  676. if (articleId != null && total != null) {
  677. durationMap.put(articleId.longValue(), total.intValue());
  678. }
  679. }
  680. for (Article article : records) {
  681. article.setTotalDurationSeconds(durationMap.getOrDefault(article.getId(), 0));
  682. }
  683. }
  684. return pageResult;
  685. }
  686. @Transactional
  687. public void create(Article article, Long adminId) {
  688. // 幂等检查:同一标题不允许重复创建
  689. if (article.getTitle() != null && !article.getTitle().trim().isEmpty()) {
  690. LambdaQueryWrapper<Article> dupCheck = new LambdaQueryWrapper<Article>()
  691. .eq(Article::getTitle, article.getTitle().trim());
  692. Long existingCount = articleMapper.selectCount(dupCheck);
  693. if (existingCount != null && existingCount > 0) {
  694. throw new RuntimeException("标题「" + article.getTitle().trim() + "」已存在,请勿重复创建");
  695. }
  696. }
  697. // Auto-calculate wordCount from content
  698. if (article.getContent() != null) {
  699. article.setWordCount(calculateWordCount(article.getContent()));
  700. }
  701. // Default articleType to 'normal' if not set
  702. if (article.getArticleType() == null) {
  703. article.setArticleType("normal");
  704. }
  705. article.setCreatedBy(adminId);
  706. article.setViewCount(0);
  707. article.setCreatedAt(new Date());
  708. article.setUpdatedAt(new Date());
  709. if ("published".equals(article.getStatus())) {
  710. article.setPublishedAt(new Date());
  711. }
  712. articleMapper.insert(article);
  713. // 发布后异步预生成朗读音频(不阻塞创建响应)
  714. ensureArticleAudioAfterPublish(article.getId());
  715. // AI auto-tagging (异步,不阻塞 HTTP 响应)
  716. final Long articleId = article.getId();
  717. final String content = article.getContent();
  718. taskExecutor.execute(() -> {
  719. try {
  720. List<String> tagNames = autoGenerateTags(content);
  721. if (!tagNames.isEmpty()) {
  722. saveAutoTags(articleId, tagNames);
  723. }
  724. } catch (Exception e) {
  725. log.warn("AI 自动标签生成失败(不影响文章创建): articleId={}, error={}",
  726. articleId, e.getMessage());
  727. }
  728. });
  729. }
  730. @Transactional
  731. public void update(Article article) {
  732. Article existing = article.getId() != null ? articleMapper.selectById(article.getId()) : null;
  733. // Recalculate wordCount if content changed
  734. boolean contentChanged = false;
  735. if (article.getContent() != null) {
  736. String oldContent = existing != null ? existing.getContent() : null;
  737. article.setWordCount(calculateWordCount(article.getContent()));
  738. contentChanged = oldContent == null || !oldContent.equals(article.getContent());
  739. }
  740. // 朗读源变化(朗读文本变化,或朗读文本为空时正文变化)→ 作废旧音频,下次「听文章」重新合成
  741. if (existing != null) {
  742. String newAudioText = article.getAudioText() != null ? article.getAudioText() : existing.getAudioText();
  743. String newContent = article.getContent() != null ? article.getContent() : existing.getContent();
  744. if (shouldInvalidateAudio(existing.getContent(), newContent,
  745. existing.getAudioText(), newAudioText)) {
  746. article.setAudioUrl("");
  747. }
  748. }
  749. article.setUpdatedAt(new Date());
  750. articleMapper.updateById(article);
  751. // 已发布文章:朗读源变化导致音频被作废后,异步重新生成
  752. ensureArticleAudioAfterPublish(article.getId());
  753. // AI auto-tagging only when content changed (异步,不阻塞 HTTP 响应)
  754. if (contentChanged && article.getContent() != null) {
  755. final Long articleId = article.getId();
  756. final String content = article.getContent();
  757. taskExecutor.execute(() -> {
  758. try {
  759. jdbcTemplate.update("DELETE FROM article_tags WHERE article_id = ?", articleId);
  760. List<String> tagNames = autoGenerateTags(content);
  761. if (!tagNames.isEmpty()) {
  762. saveAutoTags(articleId, tagNames);
  763. }
  764. } catch (Exception e) {
  765. log.warn("AI 自动标签更新失败(不影响文章更新): articleId={}, error={}",
  766. articleId, e.getMessage());
  767. }
  768. });
  769. }
  770. }
  771. /**
  772. * 判断文章更新是否应作废已生成音频。
  773. * 朗读文本优先;朗读文本为空时以正文为朗读源,正文变化即作废。
  774. */
  775. static boolean shouldInvalidateAudio(String oldContent, String newContent,
  776. String oldAudioText, String newAudioText) {
  777. String oldText = trimToNull(oldAudioText);
  778. String newText = trimToNull(newAudioText);
  779. if (!Objects.equals(oldText, newText)) {
  780. return true;
  781. }
  782. if (newText != null) {
  783. return false; // 有朗读文本时,正文变化不影响音频
  784. }
  785. if (newContent == null) {
  786. return false;
  787. }
  788. return !Objects.equals(oldContent, newContent);
  789. }
  790. private static String trimToNull(String value) {
  791. if (value == null) {
  792. return null;
  793. }
  794. String trimmed = value.trim();
  795. return trimmed.isEmpty() ? null : trimmed;
  796. }
  797. @Transactional
  798. public void delete(Long id) {
  799. articleMapper.deleteById(id);
  800. }
  801. @Transactional
  802. public void toggleStatus(Long id, String status) {
  803. Article article = articleMapper.selectById(id);
  804. if (article == null) return;
  805. article.setStatus(status);
  806. article.setUpdatedAt(new Date());
  807. if ("published".equals(status) && article.getPublishedAt() == null) {
  808. article.setPublishedAt(new Date());
  809. }
  810. articleMapper.updateById(article);
  811. // 发布时若标签为空则异步自动生成
  812. if ("published".equals(status)) {
  813. ensureAutoTagsIfEmpty(id);
  814. // 发布后异步预生成朗读音频
  815. ensureArticleAudioAfterPublish(id);
  816. }
  817. }
  818. @Transactional
  819. public void toggleFeatured(Long id, int isFeatured) {
  820. Article article = articleMapper.selectById(id);
  821. if (article == null) return;
  822. article.setIsFeatured(isFeatured);
  823. article.setUpdatedAt(new Date());
  824. if (isFeatured == 1) {
  825. // 设为精选时追加到队尾,不抢占既有顺序
  826. Integer maxSort = getMaxSortOrder();
  827. article.setSortOrder((maxSort == null ? 0 : maxSort) + 1);
  828. }
  829. articleMapper.updateById(article);
  830. }
  831. /**
  832. * 查询已发布且精选的文章中最大的 sort_order;若没有精选文章返回 null。
  833. */
  834. private Integer getMaxSortOrder() {
  835. LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
  836. .eq(Article::getStatus, "published")
  837. .eq(Article::getIsFeatured, 1)
  838. .select(Article::getSortOrder)
  839. .orderByDesc(Article::getSortOrder)
  840. .last("LIMIT 1");
  841. Article top = articleMapper.selectOne(wrapper);
  842. return top != null ? top.getSortOrder() : null;
  843. }
  844. /**
  845. * 上移/下移精选文章的推荐顺序。direction: 'up' 或 'down'。
  846. */
  847. @Transactional
  848. public String moveSortOrder(Long id, String direction) {
  849. Article target = articleMapper.selectById(id);
  850. if (target == null) {
  851. throw new RuntimeException("文章不存在");
  852. }
  853. if (!"published".equals(target.getStatus()) || !Integer.valueOf(1).equals(target.getIsFeatured())) {
  854. throw new RuntimeException("仅已发布且精选的文章可调整顺序");
  855. }
  856. if (!"up".equals(direction) && !"down".equals(direction)) {
  857. throw new RuntimeException("direction 只能是 up 或 down");
  858. }
  859. LambdaQueryWrapper<Article> listWrapper = new LambdaQueryWrapper<Article>()
  860. .eq(Article::getStatus, "published")
  861. .eq(Article::getIsFeatured, 1)
  862. .orderByAsc(Article::getSortOrder)
  863. .orderByDesc(Article::getPublishedAt);
  864. List<Article> featured = articleMapper.selectList(listWrapper);
  865. int idx = -1;
  866. for (int i = 0; i < featured.size(); i++) {
  867. if (featured.get(i).getId().equals(id)) {
  868. idx = i;
  869. break;
  870. }
  871. }
  872. if (idx == -1) {
  873. throw new RuntimeException("文章不存在");
  874. }
  875. if ("up".equals(direction) && idx <= 0) {
  876. throw new RuntimeException("已在最前面");
  877. }
  878. if ("down".equals(direction) && idx >= featured.size() - 1) {
  879. throw new RuntimeException("已在最后面");
  880. }
  881. int swapIdx = "up".equals(direction) ? idx - 1 : idx + 1;
  882. Article a = featured.get(idx);
  883. Article b = featured.get(swapIdx);
  884. Integer tmpSort = a.getSortOrder();
  885. a.setSortOrder(b.getSortOrder());
  886. b.setSortOrder(tmpSort);
  887. a.setUpdatedAt(new Date());
  888. b.setUpdatedAt(new Date());
  889. articleMapper.updateById(a);
  890. articleMapper.updateById(b);
  891. // 全局重编号 1..N,消除并列与空洞
  892. LambdaQueryWrapper<Article> renumWrapper = new LambdaQueryWrapper<Article>()
  893. .eq(Article::getStatus, "published")
  894. .eq(Article::getIsFeatured, 1)
  895. .orderByAsc(Article::getSortOrder)
  896. .orderByDesc(Article::getPublishedAt);
  897. List<Article> sorted = articleMapper.selectList(renumWrapper);
  898. Date now = new Date();
  899. for (int i = 0; i < sorted.size(); i++) {
  900. sorted.get(i).setSortOrder(i + 1);
  901. sorted.get(i).setUpdatedAt(now);
  902. articleMapper.updateById(sorted.get(i));
  903. }
  904. return "已调整顺序";
  905. }
  906. public ReadingStatsDTO getReadingStats(Long memberId) {
  907. ReadingStatsDTO dto = new ReadingStatsDTO();
  908. Calendar cal = Calendar.getInstance();
  909. cal.set(Calendar.DAY_OF_MONTH, 1);
  910. cal.set(Calendar.HOUR_OF_DAY, 0);
  911. cal.set(Calendar.MINUTE, 0);
  912. cal.set(Calendar.SECOND, 0);
  913. cal.set(Calendar.MILLISECOND, 0);
  914. Date since = cal.getTime();
  915. Integer totalDuration = articleReadingRecordMapper.selectTotalDurationByChildSince(memberId, since);
  916. if (totalDuration == null) totalDuration = 0;
  917. LambdaQueryWrapper<ArticleReadingRecord> countWrapper = new LambdaQueryWrapper<ArticleReadingRecord>()
  918. .eq(ArticleReadingRecord::getMemberId, memberId)
  919. .ge(ArticleReadingRecord::getReadAt, since);
  920. Integer totalArticles = Math.toIntExact(articleReadingRecordMapper.selectCount(countWrapper));
  921. int targetSeconds = 6000; // 100分钟/月目标
  922. int progress = totalDuration >= targetSeconds ? 100 : totalDuration * 100 / targetSeconds;
  923. dto.setTotalArticles(totalArticles);
  924. dto.setTotalDurationSeconds(totalDuration);
  925. dto.setTargetDurationSeconds(targetSeconds);
  926. dto.setProgress((double) progress);
  927. return dto;
  928. }
  929. public Map<String, Object> getDailyTip() {
  930. LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
  931. .eq(Article::getStatus, "published")
  932. .and(w -> w.like(Article::getRelatedDimensions, "mind")
  933. .or().like(Article::getRelatedDimensions, "心理"))
  934. .orderByDesc(Article::getPublishedAt)
  935. .last("LIMIT 10");
  936. List<Article> candidates = articleMapper.selectList(wrapper);
  937. if (candidates != null && !candidates.isEmpty()) {
  938. int dayOfYear = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
  939. Article tip = candidates.get(dayOfYear % candidates.size());
  940. Map<String, Object> result = new HashMap<>();
  941. result.put("id", tip.getId());
  942. result.put("title", tip.getTitle());
  943. result.put("summary", tip.getSummary());
  944. result.put("coverImage", tip.getCoverImage());
  945. return result;
  946. }
  947. Map<String, Object> fallback = new HashMap<>();
  948. fallback.put("id", null);
  949. fallback.put("title", "每日心理小贴士");
  950. fallback.put("summary", "每天花5分钟与家人聊聊今天的心情,倾听比建议更重要。");
  951. fallback.put("coverImage", null);
  952. return fallback;
  953. }
  954. /**
  955. * 根据文章内容和用户画像生成 2 道选择题
  956. */
  957. @Transactional
  958. public Map<String, Object> getAiQuestions(Long articleId, Long userId, Long memberId) {
  959. Map<String, Object> result = new HashMap<>();
  960. // 1. 获取文章
  961. Article article = articleMapper.selectById(articleId);
  962. if (article == null) {
  963. throw new RuntimeException("文章不存在");
  964. }
  965. // 2. 构建 Dify prompt
  966. String contentPreview = article.getContent() != null ? article.getContent() : "";
  967. if (contentPreview.length() > 800) {
  968. contentPreview = contentPreview.substring(0, 800);
  969. }
  970. String prompt = "你是一个家庭教育助手。根据以下文章内容,为儿童生成 2 道选择题(每题 4 个选项)。"
  971. + "题目应该适合该年龄段的儿童理解。"
  972. + "请以 JSON 数组格式返回,格式:[{\"question\":\"问题\",\"options\":[\"A.选项 1\",\"B.选项 2\",\"C.选项 3\",\"D.选项 4\"],\"answer\":\"A\"}]"
  973. + "不要返回其他文字,只返回 JSON 数组。"
  974. + "\n\n文章标题:" + article.getTitle()
  975. + "\n文章内容:" + contentPreview;
  976. // 3. 调用 Dify AI
  977. Map<String, Object> aiResult = aiService.sendMessage(prompt, String.valueOf(userId), "", null);
  978. String aiResponse = (String) aiResult.get("answer");
  979. if (aiResponse == null) {
  980. aiResponse = "";
  981. }
  982. // 4. 提取 JSON 数组
  983. String questionsJson = extractJsonFromResponse(aiResponse);
  984. // 5. 保存记录
  985. ArticleQuizRecord record = new ArticleQuizRecord();
  986. record.setArticleId(articleId);
  987. record.setUserId(userId);
  988. record.setMemberId(memberId);
  989. record.setQuestions(questionsJson);
  990. record.setAnswers(null);
  991. record.setScore(0);
  992. record.setCfEarned(0);
  993. record.setCreatedAt(new Date());
  994. record.setUpdatedAt(new Date());
  995. articleQuizRecordMapper.insert(record);
  996. result.put("recordId", record.getId());
  997. result.put("questions", questionsJson);
  998. return result;
  999. }
  1000. private String extractJsonFromResponse(String response) {
  1001. if (response == null || response.isEmpty()) return "[]";
  1002. int start = response.indexOf('[');
  1003. int end = response.lastIndexOf(']');
  1004. if (start >= 0 && end > start) {
  1005. return response.substring(start, end + 1);
  1006. }
  1007. return "[]";
  1008. }
  1009. @Transactional
  1010. public Map<String, Object> submitAnswers(Long recordId, String answersJson, Long userId, Long memberId) {
  1011. Map<String, Object> result = new HashMap<>();
  1012. // 1. 获取记录
  1013. ArticleQuizRecord record = articleQuizRecordMapper.selectById(recordId);
  1014. if (record == null) {
  1015. throw new RuntimeException("答题记录不存在");
  1016. }
  1017. if (record.getAnswers() != null) {
  1018. throw new RuntimeException("已作答,不可重复提交");
  1019. }
  1020. // 2. 解析题目和答案,计算分数
  1021. int score = 0;
  1022. int totalQuestions = 0;
  1023. try {
  1024. List<Map<String, Object>> questions = objectMapper.readValue(record.getQuestions(), objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class));
  1025. List<Map<String, Object>> answers = objectMapper.readValue(answersJson, objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class));
  1026. totalQuestions = questions.size();
  1027. Map<String, Object> answerMap = new HashMap<>();
  1028. for (Map<String, Object> a : answers) {
  1029. answerMap.put(String.valueOf(a.get("questionIndex")), a.get("selected"));
  1030. }
  1031. for (int i = 0; i < questions.size(); i++) {
  1032. Map<String, Object> q = questions.get(i);
  1033. String correct = (String) q.get("answer");
  1034. String selected = (String) answerMap.get(String.valueOf(i));
  1035. if (correct != null && correct.equalsIgnoreCase(selected != null ? selected.toString() : "")) {
  1036. score++;
  1037. }
  1038. }
  1039. } catch (Exception e) {
  1040. log.warn("解析答题结果失败:{}", e.getMessage());
  1041. }
  1042. // 3. CF 值发放(F08 统一入口:仅全部答对才发,数量取自 cf_earn_rule F08,代码不再硬编码;
  1043. // 幂等 ref_id = 答题记录ID,同一记录只发一次)
  1044. boolean allCorrect = score == totalQuestions && totalQuestions > 0;
  1045. int pointsEarned = 0;
  1046. if (allCorrect && memberId != null) {
  1047. try {
  1048. CfEarnResult earnResult = cfPathwayEarnService.earnAiReadingQuizCf(
  1049. memberId, record.getId(), true);
  1050. if (Boolean.TRUE.equals(earnResult.getEarned()) && earnResult.getAmount() != null) {
  1051. pointsEarned = earnResult.getAmount();
  1052. }
  1053. } catch (Exception e) {
  1054. log.warn("CF值发放失败:{}", e.getMessage());
  1055. }
  1056. }
  1057. // 4. 更新答题记录(cfEarned 记本次实际发放数量,日限/幂等命中时记 0)
  1058. record.setAnswers(answersJson);
  1059. record.setScore(score);
  1060. record.setCfEarned(pointsEarned);
  1061. record.setUpdatedAt(new Date());
  1062. articleQuizRecordMapper.updateById(record);
  1063. result.put("score", score);
  1064. result.put("totalQuestions", totalQuestions);
  1065. result.put("pointsEarned", pointsEarned);
  1066. return result;
  1067. }
  1068. /**
  1069. * 用户发布文章(成长记录)
  1070. * @param visibility private=仅家庭(直接发布), public=公开(需审核)
  1071. */
  1072. @Transactional
  1073. public Article publishByUser(String title, String content, String coverImage, String visibility,
  1074. String relatedDimensions, Long userId, String userRole) {
  1075. Article article = new Article();
  1076. article.setTitle(title);
  1077. article.setContent(content);
  1078. article.setCoverImage(coverImage);
  1079. article.setAuthorType("parent");
  1080. article.setCreatedBy(userId);
  1081. article.setWordCount(calculateWordCount(content));
  1082. // 可见范围
  1083. article.setVisibility(visibility != null ? visibility : "private");
  1084. // 关联维度
  1085. article.setRelatedDimensions(relatedDimensions);
  1086. article.setDimensionWeights(buildEqualWeights(relatedDimensions));
  1087. // 私有(家庭可见)→ 设置 visibleTo
  1088. if ("private".equals(visibility)) {
  1089. User user = userMapper.selectById(userId);
  1090. if (user != null && user.getFamilyId() != null) {
  1091. article.setVisibleTo("[{\"type\":\"family\",\"familyId\":" + user.getFamilyId() + "}]");
  1092. }
  1093. }
  1094. // 公开文章需要审核,家庭内部可见直接发布
  1095. if ("public".equals(visibility)) {
  1096. article.setStatus("draft");
  1097. article.setAuditStatus("pending");
  1098. } else {
  1099. article.setStatus("published");
  1100. article.setAuditStatus("approved");
  1101. article.setPublishedAt(new Date());
  1102. }
  1103. article.setArticleType("original");
  1104. article.setViewCount(0);
  1105. article.setCreatedAt(new Date());
  1106. article.setUpdatedAt(new Date());
  1107. articleMapper.insert(article);
  1108. // 家庭可见直接发布:发布时若标签为空则异步自动生成(公开文章待审核,内部守卫跳过)
  1109. ensureAutoTagsIfEmpty(article.getId());
  1110. // 家庭可见直接发布:异步预生成朗读音频(公开文章待审核,内部守卫跳过)
  1111. ensureArticleAudioAfterPublish(article.getId());
  1112. return article;
  1113. }
  1114. private String buildEqualWeights(String relatedDimensions) {
  1115. if (relatedDimensions == null || relatedDimensions.trim().isEmpty()) {
  1116. return null;
  1117. }
  1118. String[] parts = relatedDimensions.split(",");
  1119. int n = parts.length;
  1120. if (n == 0) return null;
  1121. int base = 100 / n;
  1122. int remainder = 100 - base * n;
  1123. Map<String, Integer> weights = new LinkedHashMap<>();
  1124. for (int i = 0; i < n; i++) {
  1125. String dim = parts[i].trim().toLowerCase();
  1126. if (dim.isEmpty()) continue;
  1127. weights.put(dim, i < remainder ? base + 1 : base);
  1128. }
  1129. if (weights.isEmpty()) return null;
  1130. try {
  1131. return objectMapper.writeValueAsString(weights);
  1132. } catch (Exception e) {
  1133. return null;
  1134. }
  1135. }
  1136. /**
  1137. * 获取我的发布列表
  1138. */
  1139. public Page<Article> getMyPosts(Long userId, int page, int size) {
  1140. LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
  1141. .eq(Article::getCreatedBy, userId)
  1142. // 非登录用户(不可登录成员)
  1143. .in(Article::getAuthorType, "parent", "child")
  1144. .orderByDesc(Article::getCreatedAt);
  1145. return articleMapper.selectPage(new Page<>(page, size), wrapper);
  1146. }
  1147. /**
  1148. * 增量查询:获取指定时间之后更新的文章(供 LangGraph RAG 使用)
  1149. */
  1150. public List<Article> getUpdatedSince(Date since, String status) {
  1151. LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<Article>()
  1152. .ge(Article::getUpdatedAt, since)
  1153. .orderByDesc(Article::getUpdatedAt);
  1154. String s = (status != null && !status.trim().isEmpty()) ? status.trim() : "published";
  1155. wrapper.eq(Article::getStatus, s);
  1156. return articleMapper.selectList(wrapper);
  1157. }
  1158. /**
  1159. * 管理员审核文章
  1160. */
  1161. @Transactional
  1162. public void auditArticle(Long articleId, String auditStatus, String auditReason, Long auditorId) {
  1163. Article article = articleMapper.selectById(articleId);
  1164. if (article == null) {
  1165. throw new RuntimeException("文章不存在");
  1166. }
  1167. if (!"pending".equals(article.getAuditStatus())) {
  1168. throw new RuntimeException("仅待审核状态可审核");
  1169. }
  1170. article.setAuditStatus(auditStatus);
  1171. article.setAuditorId(auditorId);
  1172. article.setAuditedAt(new Date());
  1173. if ("approved".equals(auditStatus)) {
  1174. article.setStatus("published");
  1175. article.setPublishedAt(new Date());
  1176. article.setAuditReason(null);
  1177. } else if ("rejected".equals(auditStatus)) {
  1178. article.setStatus("rejected");
  1179. article.setAuditReason(auditReason);
  1180. }
  1181. article.setUpdatedAt(new Date());
  1182. articleMapper.updateById(article);
  1183. // 审核通过发布:若标签为空则异步自动生成
  1184. if ("approved".equals(auditStatus)) {
  1185. ensureAutoTagsIfEmpty(articleId);
  1186. // 审核通过发布:异步预生成朗读音频
  1187. ensureArticleAudioAfterPublish(articleId);
  1188. }
  1189. }
  1190. /**
  1191. * 发布路径语音预生成入口:仅已发布且尚无音频时,事务提交后异步生成。
  1192. * 失败仅记录 warn,不阻塞发布流程。
  1193. */
  1194. private void ensureArticleAudioAfterPublish(Long articleId) {
  1195. if (articleId == null) {
  1196. return;
  1197. }
  1198. Article article = articleMapper.selectById(articleId);
  1199. if (article == null || !"published".equals(article.getStatus())) {
  1200. return;
  1201. }
  1202. if (article.getAudioUrl() != null && !article.getAudioUrl().trim().isEmpty()) {
  1203. return;
  1204. }
  1205. final Long id = articleId;
  1206. runAfterCommit(() -> {
  1207. try {
  1208. articleAudioService.generateIfMissing(id);
  1209. } catch (Exception e) {
  1210. log.warn("文章语音自动生成失败(不影响文章): articleId={}, error={}", id, e.getMessage());
  1211. }
  1212. });
  1213. }
  1214. /**
  1215. * 在当前事务提交后执行任务;无事务时立即提交到线程池。
  1216. * 避免异步任务读到未提交的文章数据。
  1217. */
  1218. private void runAfterCommit(Runnable task) {
  1219. if (TransactionSynchronizationManager.isSynchronizationActive()) {
  1220. TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
  1221. @Override
  1222. public void afterCommit() {
  1223. taskExecutor.execute(task);
  1224. }
  1225. });
  1226. } else {
  1227. taskExecutor.execute(task);
  1228. }
  1229. }
  1230. /**
  1231. * 发布路径自动打标入口:仅当文章已发布且 tags 为空时,异步调 LLM 生成并写回。
  1232. * 失败仅记录 warn,不阻塞发布流程。
  1233. */
  1234. private void ensureAutoTagsIfEmpty(Long articleId) {
  1235. Article article = articleMapper.selectById(articleId);
  1236. if (article == null || !"published".equals(article.getStatus())) {
  1237. return;
  1238. }
  1239. if (article.getTags() != null && !article.getTags().trim().isEmpty()) {
  1240. return;
  1241. }
  1242. final Long id = article.getId();
  1243. final String content = article.getContent();
  1244. taskExecutor.execute(() -> {
  1245. try {
  1246. List<String> tagNames = autoGenerateTags(content);
  1247. if (!tagNames.isEmpty()) {
  1248. saveAutoTags(id, tagNames);
  1249. }
  1250. } catch (Exception e) {
  1251. log.warn("AI 自动标签生成失败(不影响文章): articleId={}, error={}", id, e.getMessage());
  1252. }
  1253. });
  1254. }
  1255. /**
  1256. * 调用 Dify AI 从文章内容中自动提取 3-5 个中文关键词作为标签
  1257. */
  1258. private List<String> autoGenerateTags(String content) {
  1259. if (content == null || content.trim().isEmpty()) {
  1260. return Collections.emptyList();
  1261. }
  1262. // 去除 HTML 标签,避免干扰 AI 提取
  1263. String plainText = content.replaceAll("<[^>]*>", " ").replaceAll("\\s+", " ").trim();
  1264. if (plainText.isEmpty()) {
  1265. return Collections.emptyList();
  1266. }
  1267. // 截取前 1500 字,避免 prompt 过长
  1268. if (plainText.length() > 1500) {
  1269. plainText = plainText.substring(0, 1500);
  1270. }
  1271. String prompt = "你是一个家庭教育内容分析助手。请根据以下文章内容,提取 3 到 5 个最能代表文章主题的中文关键词作为标签。"
  1272. + "要求:1) 关键词为中文短语或名词,2-6 个字;2) 用英文逗号分隔;3) 不要包含编号、引号或解释文字;4) 只返回标签列表本身。"
  1273. + "\n\n文章内容:" + plainText;
  1274. try {
  1275. Map<String, Object> aiResult = aiService.sendMessage(prompt, "0", "", null);
  1276. String aiResponse = (String) aiResult.get("answer");
  1277. if (aiResponse == null || aiResponse.trim().isEmpty()) {
  1278. return Collections.emptyList();
  1279. }
  1280. // 解析逗号分隔的标签
  1281. List<String> tags = new ArrayList<>();
  1282. for (String raw : aiResponse.split(",")) {
  1283. String tag = raw.trim()
  1284. .replaceAll("^[\\d\\.\\-\\s、。,]+", "")
  1285. .replaceAll("[\\s、。,]+$", "")
  1286. .trim();
  1287. if (!tag.isEmpty() && tag.length() <= 20 && tags.size() < 5) {
  1288. tags.add(tag);
  1289. }
  1290. }
  1291. return tags;
  1292. } catch (Exception e) {
  1293. log.warn("AI 自动生成标签失败:{}", e.getMessage());
  1294. return Collections.emptyList();
  1295. }
  1296. }
  1297. /**
  1298. * 将 AI 生成的标签保存到 dan_knowledge_tag 与 article_tags 表,并回写 article.tags 字段
  1299. */
  1300. private void saveAutoTags(Long articleId, List<String> tagNames) {
  1301. if (articleId == null || tagNames == null || tagNames.isEmpty()) {
  1302. return;
  1303. }
  1304. List<String> savedTags = new ArrayList<>();
  1305. for (String tagName : tagNames) {
  1306. if (tagName == null || tagName.trim().isEmpty()) continue;
  1307. String name = tagName.trim();
  1308. try {
  1309. // 查询是否已存在同名标签
  1310. List<Long> existing = jdbcTemplate.queryForList(
  1311. "SELECT id FROM dan_knowledge_tag WHERE tag_name = ? LIMIT 1",
  1312. Long.class, name);
  1313. Long tagId;
  1314. if (existing != null && !existing.isEmpty()) {
  1315. tagId = existing.get(0);
  1316. } else {
  1317. // 插入新标签
  1318. jdbcTemplate.update(
  1319. "INSERT INTO dan_knowledge_tag (tag_name, tag_type, created_at) VALUES (?, 'auto', NOW())",
  1320. name);
  1321. tagId = jdbcTemplate.queryForObject(
  1322. "SELECT id FROM dan_knowledge_tag WHERE tag_name = ? ORDER BY id DESC LIMIT 1",
  1323. Long.class, name);
  1324. }
  1325. if (tagId != null) {
  1326. jdbcTemplate.update(
  1327. "INSERT IGNORE INTO article_tags (article_id, tag_id) VALUES (?, ?)",
  1328. articleId, tagId);
  1329. savedTags.add(name);
  1330. }
  1331. } catch (Exception e) {
  1332. log.warn("保存自动标签失败:tagName={}, error={}", name, e.getMessage());
  1333. }
  1334. }
  1335. // 回写 article.tags 字段(逗号分隔)
  1336. if (!savedTags.isEmpty()) {
  1337. String tagsStr = String.join(",", savedTags);
  1338. jdbcTemplate.update("UPDATE articles SET tags = ? WHERE id = ?", tagsStr, articleId);
  1339. }
  1340. }
  1341. @Transactional
  1342. public void submitForReview(Long id) {
  1343. Article article = articleMapper.selectById(id);
  1344. if (article == null) {
  1345. throw new RuntimeException("文章不存在");
  1346. }
  1347. if (!"draft".equals(article.getStatus())) {
  1348. throw new RuntimeException("仅草稿状态可提交审核");
  1349. }
  1350. article.setStatus("pending");
  1351. article.setAuditStatus("pending");
  1352. article.setUpdatedAt(new Date());
  1353. articleMapper.updateById(article);
  1354. }
  1355. @Transactional
  1356. public void withdraw(Long id) {
  1357. Article article = articleMapper.selectById(id);
  1358. if (article == null) {
  1359. throw new RuntimeException("文章不存在");
  1360. }
  1361. if (!"published".equals(article.getStatus())) {
  1362. throw new RuntimeException("仅发布中的文章可撤回");
  1363. }
  1364. article.setStatus("withdrawn");
  1365. article.setUpdatedAt(new Date());
  1366. articleMapper.updateById(article);
  1367. }
  1368. @Transactional
  1369. public void reDraft(Long id) {
  1370. Article article = articleMapper.selectById(id);
  1371. if (article == null) {
  1372. throw new RuntimeException("文章不存在");
  1373. }
  1374. if (!"rejected".equals(article.getStatus()) && !"withdrawn".equals(article.getStatus())) {
  1375. throw new RuntimeException("仅已驳回或已撤回的文章可重新编辑");
  1376. }
  1377. article.setStatus("draft");
  1378. article.setAuditStatus(null);
  1379. article.setAuditReason(null);
  1380. article.setAuditorId(null);
  1381. article.setAuditedAt(null);
  1382. article.setUpdatedAt(new Date());
  1383. articleMapper.updateById(article);
  1384. }
  1385. }