Przeglądaj źródła

feat(k8): 还原水文章优先+读完降权(关键词加分/家庭成员读完直接赋minScore, 新增按家庭查读完mapper, ContentRecommendService article分支接入) + TDD 4例

Xiaogang Liao 5 dni temu
rodzic
commit
e34c5d14b0

+ 10 - 8
cfc-backend/src/main/java/com/etotem/cfc/mapper/ArticleReadingRecordMapper.java

@@ -4,9 +4,9 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.etotem.cfc.entity.ArticleReadingRecord;
 import org.apache.ibatis.annotations.Mapper;
 import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
 import org.apache.ibatis.annotations.Result;
 import org.apache.ibatis.annotations.Results;
-import org.apache.ibatis.annotations.Select;
 import java.util.List;
 import java.util.Map;
 
@@ -18,9 +18,6 @@ public interface ArticleReadingRecordMapper extends BaseMapper<ArticleReadingRec
     Integer selectTotalDurationByChildSince(@Param("childId") Long memberId,
                                             @Param("since") java.util.Date since);
 
-    /**
-     * 按文章 ID 分页查询阅读记录(每人聚合一行),JOIN family_members 获取昵称
-     */
     @Select("SELECT " +
             "  m.nickname, " +
             "  SUM(r.duration_seconds) AS total_duration_seconds, " +
@@ -48,13 +45,18 @@ public interface ArticleReadingRecordMapper extends BaseMapper<ArticleReadingRec
     @Select("SELECT COUNT(DISTINCT child_id) FROM article_reading_records WHERE article_id = #{articleId}")
     long countDistinctByArticle(@Param("articleId") Long articleId);
 
-    /**
-     * 查询某成员已完成阅读且获得CF值的文章 ID 列表
-     * (阅读达标 reading_completed=1 + 答题获得CF值 cf_earned>0 才从列表中隐藏)
-     */
     @Select("SELECT DISTINCT r.article_id FROM article_reading_records r " +
             "WHERE r.child_id = #{childId} AND r.reading_completed = 1 " +
             "AND EXISTS (SELECT 1 FROM article_quiz_records q " +
             "            WHERE q.article_id = r.article_id AND q.member_id = r.child_id AND q.cf_earned > 0)")
     List<Long> selectCompletedArticleIdsByChild(@Param("childId") Long memberId);
+
+    /**
+     * K8 读完降权:查家庭成员任一已读完(reading_completed=1)的文章ID(不要求答题得CF)。
+     * 通过 child_id 关联 family_members 定位家庭。
+     */
+    @Select("SELECT DISTINCT r.article_id FROM article_reading_records r " +
+            "JOIN family_members m ON r.child_id = m.id " +
+            "WHERE m.family_id = #{familyId} AND r.reading_completed = 1")
+    List<Long> selectCompletedArticleIdsByFamily(@Param("familyId") Long familyId);
 }

+ 2 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ContentRecommendService.java

@@ -94,6 +94,8 @@ public class ContentRecommendService {
         } else switch (type) {
             case "article":
                 items = recommendArticles(dimensionCode, userId, familyId, memberId, excludeIds);
+                // K8 还原水文章优先 + 读完降权(spec §6.2,增强失败不影响主推荐)
+                items = k8RecommendationService.applyArticleRules(items, familyId);
                 break;
             case "task":
                 items = recommendTasks(dimensionCode, memberId, excludeIds);

+ 54 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/K8RecommendationBoostService.java

@@ -64,4 +64,58 @@ public class K8RecommendationBoostService {
         result.sort(Comparator.comparingInt((RecommendItemVO v) -> v.getRecommendScore() == null ? 0 : v.getRecommendScore()).reversed());
         return result;
     }
+
+    /**
+     * 文章推荐规则(spec §6.2):还原水关键词加分 + 家庭成员读完直接降到最低分。
+     *
+     * @param items        推荐结果(复制,不改入参)
+     * @param keywords     关键词列表(命中 title/summary 任一即加分)
+     * @param boostScore   关键词加分
+     * @param minScore     读完降权目标分(直接赋值)
+     * @param completedIds 家庭成员读完的文章ID集合
+     * @return 新列表
+     */
+    public List<RecommendItemVO> applyArticleRules(List<RecommendItemVO> items,
+                                                    List<String> keywords, int boostScore, int minScore,
+                                                    java.util.Set<Long> completedIds) {
+        List<RecommendItemVO> result = new ArrayList<>();
+        if (items == null) return result;
+        boolean hasCompleted = completedIds != null && !completedIds.isEmpty();
+        for (RecommendItemVO v : items) {
+            RecommendItemVO copy = new RecommendItemVO();
+            copy.setId(v.getId()); copy.setTitle(v.getTitle()); copy.setSummary(v.getSummary());
+            copy.setCoverImage(v.getCoverImage()); copy.setDimensionCode(v.getDimensionCode());
+            copy.setRecommendScore(v.getRecommendScore() == null ? 0 : v.getRecommendScore());
+            copy.setRecommendReason(v.getRecommendReason()); copy.setBadge(v.getBadge());
+
+            int score = copy.getRecommendScore();
+            boolean keyword = false;
+            if (keywords != null) {
+                String text = (nullToEmpty(v.getTitle()) + " " + nullToEmpty(v.getSummary())).toLowerCase();
+                for (String kw : keywords) {
+                    if (kw != null && !kw.trim().isEmpty() && text.contains(kw.trim().toLowerCase())) {
+                        keyword = true; break;
+                    }
+                }
+            }
+            if (keyword) {
+                score += boostScore;
+                copy.setRecommendReason(joinReason(v.getRecommendReason(), "还原水相关优先"));
+            }
+            if (hasCompleted && completedIds.contains(v.getId())) {
+                score = minScore; // 直接赋值(沉底),不取 Math.min
+                copy.setRecommendReason("已读完");
+            }
+            copy.setRecommendScore(score);
+            result.add(copy);
+        }
+        return result;
+    }
+
+    private static String nullToEmpty(String s) { return s == null ? "" : s; }
+
+    private static String joinReason(String existing, String add) {
+        if (existing == null || existing.trim().isEmpty() || "为你推荐".equals(existing)) return add;
+        return existing + "·" + add;
+    }
 }

+ 29 - 1
cfc-backend/src/main/java/com/etotem/cfc/service/K8RecommendationService.java

@@ -6,12 +6,15 @@ import com.etotem.cfc.entity.DeviceMaintenanceReminder;
 import com.etotem.cfc.entity.Product;
 import com.etotem.cfc.mapper.DeviceMaintenanceReminderMapper;
 import com.etotem.cfc.mapper.ProductMapper;
-import com.etotem.cfc.service.SysConfigService;
+import com.etotem.cfc.mapper.ArticleReadingRecordMapper;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.Resource;
 import java.time.LocalDate;
 import java.util.List;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
 
 /**
  * K8 推荐增强门面(spec §5/§6):查窗口内提醒 + 读 sys_config + 调纯逻辑。
@@ -27,6 +30,31 @@ public class K8RecommendationService {
     private SysConfigService sysConfigService;
     @Resource
     private K8RecommendationBoostService boostService;
+    @Resource
+    private ArticleReadingRecordMapper articleReadingRecordMapper;
+
+    /**
+     * 文章推荐规则(spec §6.2):还原水关键词加分 + 家庭成员读完降到最低分。
+     */
+    public List<RecommendItemVO> applyArticleRules(List<RecommendItemVO> items, Long familyId) {
+        try {
+            String kwRaw = sysConfigService.getValue("k8.article.keywords");
+            String boostRaw = sysConfigService.getValue("k8.article.boost_score");
+            String minRaw = sysConfigService.getValue("k8.article.min_score");
+            List<String> keywords = new ArrayList<>();
+            if (kwRaw != null) for (String s : kwRaw.split(",")) if (!s.trim().isEmpty()) keywords.add(s.trim());
+            int boost = parseInt(boostRaw, 50);
+            int min = parseInt(minRaw, -100);
+            Set<Long> completed = new HashSet<>();
+            if (familyId != null) {
+                List<Long> ids = articleReadingRecordMapper.selectCompletedArticleIdsByFamily(familyId);
+                if (ids != null) completed.addAll(ids);
+            }
+            return boostService.applyArticleRules(items, keywords, boost, min, completed);
+        } catch (Exception e) {
+            return items; // 增强失败不影响主推荐
+        }
+    }
 
     /** 换滤芯期滤芯置顶:把结果列表后处理(原地返回新列表)。 */
     public List<RecommendItemVO> applyFilterBoost(List<RecommendItemVO> items, Long userId, Long familyId) {

+ 67 - 0
cfc-backend/src/test/java/com/etotem/cfc/unit/K8ArticleRecommendationTest.java

@@ -0,0 +1,67 @@
+package com.etotem.cfc.unit;
+
+import com.etotem.cfc.dto.RecommendItemVO;
+import com.etotem.cfc.service.K8RecommendationBoostService;
+import org.junit.jupiter.api.Test;
+
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * TDD 契约:还原水文章优先加分 + 读完降权(spec §6.2)。
+ */
+class K8ArticleRecommendationTest {
+
+    private final K8RecommendationBoostService svc = new K8RecommendationBoostService();
+
+    private RecommendItemVO item(Long id, String title, int score) {
+        RecommendItemVO v = new RecommendItemVO();
+        v.setId(id); v.setTitle(title); v.setRecommendScore(score); return v;
+    }
+
+    private static final Set<Long> NO_COMPLETED = Collections.emptySet();
+    private static final List<String> KEYWORDS = Arrays.asList("还原水", "电解水", "Enagic", "富氢水", "水机");
+
+    @Test
+    void keyword_match_gets_boost() {
+        List<RecommendItemVO> items = new ArrayList<>(Arrays.asList(
+                item(1L, "还原水与甲亢", 10),      // 命中
+                item(2L, "肠道菌群与免疫", 10)));  // 不命中
+        List<RecommendItemVO> r = svc.applyArticleRules(items, KEYWORDS, 50, -100, NO_COMPLETED);
+        assertEquals(60, r.get(0).getRecommendScore(), "命中关键词+50");
+        assertEquals(10, r.get(1).getRecommendScore(), "不命中不变");
+        assertTrue(r.get(0).getRecommendReason().contains("还原水") || r.get(0).getRecommendReason() != null);
+    }
+
+    @Test
+    void family_completed_demoted_to_min_directly() {
+        // 文章1 家人读完 → 直接赋 minScore(-100),即便原分 90 或 -50
+        List<RecommendItemVO> items = new ArrayList<>(Arrays.asList(
+                item(1L, "还原水与甲亢", 90),
+                item(2L, "Enagic 强还原水", 40),
+                item(3L, "普通文章", 5)));
+        Set<Long> completed = new HashSet<>(Arrays.asList(1L, 3L));
+        List<RecommendItemVO> r = svc.applyArticleRules(items, KEYWORDS, 50, -100, completed);
+        Map<Long,Integer> byId = new HashMap<>();
+        r.forEach(v -> byId.put(v.getId(), v.getRecommendScore()));
+        assertEquals(-100, byId.get(1L), "原分90→直接赋-100");
+        assertEquals(-100, byId.get(3L), "原分5(非关键词)读完→也赋-100");
+        assertEquals(90, byId.get(2L), "Enagic命中+50=90,未读完保持");
+    }
+
+    @Test
+    void completed_even_if_original_below_min_still_min() {
+        List<RecommendItemVO> items = new ArrayList<>(Arrays.asList(item(1L, "还原水", -200)));
+        Set<Long> completed = Collections.singleton(1L);
+        List<RecommendItemVO> r = svc.applyArticleRules(items, KEYWORDS, 50, -100, completed);
+        assertEquals(-100, r.get(0).getRecommendScore(), "原分-200(<min)读完→赋-100(直接赋值,非Math.min)");
+    }
+
+    @Test
+    void not_mutate_input() {
+        List<RecommendItemVO> items = new ArrayList<>(Arrays.asList(item(1L, "还原水", 10)));
+        svc.applyArticleRules(items, KEYWORDS, 50, -100, NO_COMPLETED);
+        assertEquals(10, items.get(0).getRecommendScore(), "入参不应被修改");
+    }
+}