Browse Source

feat(food.rule.weightEngine): S-cfc-464 加权引擎红单测使绿(15/15)

- 新增 FoodRecommendWeightEngine:6 因子默认权重(和=1)/四态映射/clamp/加权公式
- 新增 FoodRecommendWeightRule 实体 + schema.sql 建表 + 迁移501
- recalculateForUser 接入引擎(默认权重保持报告分口径),日志标记引擎版本
- 验证:FoodRuleWeightEngineContractTest 15/15;FoodRecommendServiceTest 21/21
Administrator 21 hours ago
parent
commit
ab1f7595d8

+ 29 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java

@@ -3670,6 +3670,10 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         // 迁移500: 爱云医 AI 检测本地映射表 aiyunyi_mapping(能力键 ai.aiyunyi.mapping,§4.3)
         // 承载家庭/成员 ↔ 爱云医检测用户/套餐/套餐项/报告的关联与状态(0进行中/1完成/2失败)
         createAiYunyiMappingTable();
+
+        // 迁移501: 食材推荐加权规则表 food_recommend_weight_rule(能力键 food.rule.weightEngine,§4.2/§5)
+        // 承载 6 因子权重/阈值/病症分组/版本/灰度开关;CREATE TABLE IF NOT EXISTS 幂等
+        createFoodRecommendWeightRuleTable();
     }
 
     /**
@@ -3700,6 +3704,31 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         }
     }
 
+    /**
+     * 迁移501: 食材推荐加权规则表(能力键 food.rule.weightEngine,§4.2/§5)。
+     * 幂等:CREATE TABLE IF NOT EXISTS + try/catch 忽略「表已存在」异常,可重复执行。
+     */
+    private void createFoodRecommendWeightRuleTable() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS food_recommend_weight_rule ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY, "
+                    + "factor_type VARCHAR(32) NOT NULL COMMENT '因子类型: base_report/health_adjust/preference/pairing/processing/disease_group', "
+                    + "weight DOUBLE NOT NULL DEFAULT 0 COMMENT '权重(六因子默认和 = 1)', "
+                    + "threshold DOUBLE COMMENT '触发阈值', "
+                    + "disease_code VARCHAR(64) COMMENT '病症分组编码,NULL=通用', "
+                    + "version INT NOT NULL DEFAULT 1 COMMENT '规则版本号', "
+                    + "enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用(灰度)', "
+                    + "updated_by BIGINT COMMENT '最后修改人', "
+                    + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', "
+                    + "UNIQUE KEY uk_factor_disease_version (factor_type, disease_code, version), "
+                    + "INDEX idx_enabled (enabled) "
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='食材推荐加权规则表'");
+            log.info("迁移501: 已创建 food_recommend_weight_rule 表");
+        } catch (Exception e) {
+            log.warn("迁移501: 创建 food_recommend_weight_rule 表失败(可能已存在): {}", e.getMessage());
+        }
+    }
+
     /**
      * 迁移462: 创建服务成本价配置表(§7.5,合入自 cfclub)。
      */

+ 46 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/FoodRecommendWeightRule.java

@@ -0,0 +1,46 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 食材推荐加权规则(能力键 {@code food.rule.weightEngine},§4.2 / §5)。
+ *
+ * <p>对应表 {@code food_recommend_weight_rule}:承载 6 因子权重、阈值、病症分组、版本与灰度开关。</p>
+ */
+@Data
+@TableName("food_recommend_weight_rule")
+public class FoodRecommendWeightRule implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 因子类型:base_report/health_adjust/preference/pairing/processing/disease_group */
+    private String factorType;
+
+    /** 权重(默认六因子之和 = 1) */
+    private Double weight;
+
+    /** 触发阈值 */
+    private Double threshold;
+
+    /** 病症分组编码,null = 通用 */
+    private String diseaseCode;
+
+    /** 规则版本号 */
+    private Integer version;
+
+    /** 灰度开关:1启用 0停用 */
+    private Integer enabled;
+
+    /** 最后修改人 */
+    private Long updatedBy;
+
+    /** 最后修改时间 */
+    private Date updatedAt;
+}

+ 10 - 1
cfc-backend/src/main/java/com/etotem/cfc/service/FoodRecommendService.java

@@ -203,6 +203,14 @@ public class FoodRecommendService {
         for (Food food : reportFoods) {
             Long foodId = food.getId();
             Integer newIndex = food.getScore();
+            // 加权规则引擎 v1(food.rule.weightEngine / §4.2):finalScore 按六因子公式计算并 clamp 到 [-100,100]。
+            // 默认权重表仅启用 base_report,保持既有「报告分直写 index_score」口径;
+            // 其余因子待 ops.foodRuleManagement 配置 food_recommend_weight_rule 后由 finalScoreWithWeights 启用。
+            if (newIndex != null) {
+                double weighted = FoodRecommendWeightEngine.finalScore(
+                        newIndex.doubleValue(), 0.0, 0.0, 0.0, 0.0, 0.0);
+                newIndex = (int) Math.round(weighted);
+            }
             String foodName = food.getName();
             FoodRecommendIndex existing = existingMap.get(foodId);
 
@@ -226,7 +234,7 @@ public class FoodRecommendService {
                     logEntry.setChangedAt(now);
                     foodRecommendIdxLogMapper.insert(logEntry);
 
-                    log.info("用户{}食材{}推荐指数变更: {} -> {}", userId, foodId, oldIndex, newIndex);
+                    log.info("加权规则引擎 v1 用户{}食材{}推荐指数变更: {} -> {}", userId, foodId, oldIndex, newIndex);
                 }
             } else {
                 FoodRecommendIndex index = new FoodRecommendIndex();
@@ -238,6 +246,7 @@ public class FoodRecommendService {
                 index.setCalculatedAt(now);
                 index.setCreatedAt(now);
                 foodRecommendIndexMapper.insert(index);
+                log.info("加权规则引擎 v1 用户{}食材{}首次建立指数: {}", userId, foodId, newIndex);
 
                 FoodRecommendIdxLog logEntry = new FoodRecommendIdxLog();
                 logEntry.setUserId(writeKey);

+ 130 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/FoodRecommendWeightEngine.java

@@ -0,0 +1,130 @@
+package com.etotem.cfc.service;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * 食材推荐加权规则引擎(能力键 {@code food.rule.weightEngine},S-cfc-464)。
+ *
+ * <p>§4.2 多因子公式:</p>
+ * <pre>
+ * final_score = clamp( base_report_score × w1
+ *                    + health_adjust_score × w2
+ *                    + preference_boost × w3
+ *                    + pairing_effect × w4
+ *                    + processing_effect × w5
+ *                    + disease_group_adjust × w6
+ *                    , -100, 100 )
+ * </pre>
+ *
+ * <p>纯计算服务:不依赖 Spring / DB / 外部服务,规则表 {@code food_recommend_weight_rule}
+ * 的后台 CRUD 与灰度由独立能力键 {@code ops.foodRuleManagement} 承载。默认权重表 v1 以
+ * {@code base_report=1}、其余因子 0 保持既有「报告分直写 index_score」口径,待规则表配置后
+ * 由 {@link #finalScoreWithWeights} 按显式权重启用多因子。</p>
+ */
+public class FoodRecommendWeightEngine {
+
+    /** §4.2 factor_type 枚举:报告分因子。 */
+    public static final String FACTOR_BASE_REPORT = "base_report";
+    /** §4.2 factor_type 枚举:健康调整因子(11-09 四态标记升级)。 */
+    public static final String FACTOR_HEALTH_ADJUST = "health_adjust";
+    /** §4.2 factor_type 枚举:偏好加成因子。 */
+    public static final String FACTOR_PREFERENCE = "preference";
+    /** §4.2 factor_type 枚举:搭配效应因子。 */
+    public static final String FACTOR_PAIRING = "pairing";
+    /** §4.2 factor_type 枚举:加工效应因子。 */
+    public static final String FACTOR_PROCESSING = "processing";
+    /** §4.2 factor_type 枚举:病症分组调整因子。 */
+    public static final String FACTOR_DISEASE_GROUP = "disease_group";
+
+    /** final_score 下界(§4.2)。 */
+    private static final double SCORE_MIN = -100.0;
+    /** final_score 上界(§4.2)。 */
+    private static final double SCORE_MAX = 100.0;
+
+    /**
+     * 6 因子默认权重表,和 = 1(§4.2)。
+     * v1 基线仅启用 base_report,保证接入后既有指数口径不变。
+     */
+    public static Map<String, Double> defaultWeights() {
+        Map<String, Double> weights = new LinkedHashMap<String, Double>();
+        weights.put(FACTOR_BASE_REPORT, 1.0);
+        weights.put(FACTOR_HEALTH_ADJUST, 0.0);
+        weights.put(FACTOR_PREFERENCE, 0.0);
+        weights.put(FACTOR_PAIRING, 0.0);
+        weights.put(FACTOR_PROCESSING, 0.0);
+        weights.put(FACTOR_DISEASE_GROUP, 0.0);
+        return weights;
+    }
+
+    /**
+     * 11-09 标记升级(§4.2):四态 → health_adjust_score。
+     * blocked=-50 / warning=-15 / boost=+10 / normal=0;null 与未知标记兜底 0。
+     */
+    public static double healthAdjustScore(String adjustment) {
+        if (adjustment == null) {
+            return 0.0;
+        }
+        if ("blocked".equalsIgnoreCase(adjustment)) {
+            return -50.0;
+        }
+        if ("warning".equalsIgnoreCase(adjustment)) {
+            return -15.0;
+        }
+        if ("boost".equalsIgnoreCase(adjustment)) {
+            return 10.0;
+        }
+        // normal 及其他未知标记统一视为无调整
+        return 0.0;
+    }
+
+    /** 截断到 [-100, 100](§4.2 / G-2)。 */
+    public static double clamp(double rawScore) {
+        if (rawScore > SCORE_MAX) {
+            return SCORE_MAX;
+        }
+        if (rawScore < SCORE_MIN) {
+            return SCORE_MIN;
+        }
+        return rawScore;
+    }
+
+    /**
+     * 按显式权重表精确计算 §4.2 六因子加权分并 clamp。
+     * 权重缺失的因子按 0 处理(规则表尚未配置该因子时保持中性)。
+     */
+    public static double finalScoreWithWeights(Map<String, Double> weights,
+                                               double baseReportScore,
+                                               double healthAdjustScore,
+                                               double preferenceBoost,
+                                               double pairingEffect,
+                                               double processingEffect,
+                                               double diseaseGroupAdjust) {
+        double raw = baseReportScore * weightOf(weights, FACTOR_BASE_REPORT)
+                + healthAdjustScore * weightOf(weights, FACTOR_HEALTH_ADJUST)
+                + preferenceBoost * weightOf(weights, FACTOR_PREFERENCE)
+                + pairingEffect * weightOf(weights, FACTOR_PAIRING)
+                + processingEffect * weightOf(weights, FACTOR_PROCESSING)
+                + diseaseGroupAdjust * weightOf(weights, FACTOR_DISEASE_GROUP);
+        return clamp(raw);
+    }
+
+    /** 默认权重路径:等价于 {@code finalScoreWithWeights(defaultWeights(), ...)}(§4.2 / G-2)。 */
+    public static double finalScore(double baseReportScore,
+                                    double healthAdjustScore,
+                                    double preferenceBoost,
+                                    double pairingEffect,
+                                    double processingEffect,
+                                    double diseaseGroupAdjust) {
+        return finalScoreWithWeights(defaultWeights(), baseReportScore, healthAdjustScore,
+                preferenceBoost, pairingEffect, processingEffect, diseaseGroupAdjust);
+    }
+
+    private static double weightOf(Map<String, Double> weights, String factorType) {
+        if (weights == null) {
+            return 0.0;
+        }
+        Double w = weights.get(factorType);
+        return w == null ? 0.0 : w.doubleValue();
+    }
+}

+ 18 - 0
cfc-backend/src/main/resources/schema.sql

@@ -7674,3 +7674,21 @@ CREATE TABLE IF NOT EXISTS device_maintenance_reminders (
     INDEX idx_family_status (family_id, status)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='设备维护提醒';
 
+-- ============================================================
+-- 食材推荐加权规则表(迁移501 / food.rule.weightEngine,§4.2 / §5)
+-- 6 因子权重 + 阈值 + 病症分组 + 版本 + 灰度开关;disease_code NULL = 通用
+-- ============================================================
+CREATE TABLE IF NOT EXISTS food_recommend_weight_rule (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    factor_type VARCHAR(32) NOT NULL COMMENT '因子类型: base_report/health_adjust/preference/pairing/processing/disease_group',
+    weight DOUBLE NOT NULL DEFAULT 0 COMMENT '权重(六因子默认和 = 1)',
+    threshold DOUBLE COMMENT '触发阈值',
+    disease_code VARCHAR(64) COMMENT '病症分组编码,NULL=通用',
+    version INT NOT NULL DEFAULT 1 COMMENT '规则版本号',
+    enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用(灰度)',
+    updated_by BIGINT COMMENT '最后修改人',
+    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间',
+    UNIQUE KEY uk_factor_disease_version (factor_type, disease_code, version),
+    KEY idx_enabled (enabled)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='食材推荐加权规则表';
+