Browse Source

feat(food): S-cfc-502 food.ops.ruleManagement 后台推荐规则管理四 Tab 实现(红转绿 20/20)

Administrator 1 hour ago
parent
commit
79e3f4d7b0

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

@@ -3699,6 +3699,11 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         // 迁移506: report_type_registry 补 icon / sort_order 列(小程序上传页「支持的报告类型」配置化)
         // 迁移506: report_type_registry 补 icon / sort_order 列(小程序上传页「支持的报告类型」配置化)
         // 并补种上传页所需的体检/舌象/体脂类型;幂等(先判断列存在 + 先 SELECT 再 INSERT/UPDATE)
         // 并补种上传页所需的体检/舌象/体脂类型;幂等(先判断列存在 + 先 SELECT 再 INSERT/UPDATE)
         addReportTypeRegistryIconSortOrderColumns();
         addReportTypeRegistryIconSortOrderColumns();
+
+        // 迁移507: 后台推荐规则管理三表 food_pairing_matrix / food_processing_effect /
+        //          food_disease_weight_group(能力键 food.ops.ruleManagement,CR-06 §4.6)
+        // 权重表由迁移501 落地;本迁移幂等:CREATE TABLE IF NOT EXISTS + try/catch
+        createFoodRuleManagementTables();
     }
     }
 
 
     /**
     /**
@@ -3835,6 +3840,62 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         }
         }
     }
     }
 
 
+    /**
+     * 迁移507: 后台推荐规则管理三表(能力键 {@code food.ops.ruleManagement},CR-06 §4.6)。
+     *
+     * <p>配伍矩阵 / 加工效应 / 病症权重对应四 Tab 中的三张新表,权重规则表由迁移501 落地。
+     * 幂等:CREATE TABLE IF NOT EXISTS + try/catch 忽略「表已存在」异常,可重复执行。</p>
+     */
+    private void createFoodRuleManagementTables() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS food_pairing_matrix ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY, "
+                    + "food_a_id BIGINT NOT NULL COMMENT '食材A(foods.id)', "
+                    + "food_b_id BIGINT NOT NULL COMMENT '食材B(foods.id)', "
+                    + "relation_type VARCHAR(24) NOT NULL COMMENT 'synergy/antagonism/xiangsheng/xiangke/xiangwei/xiangsha/xiangwu', "
+                    + "intensity TINYINT NOT NULL DEFAULT 1 COMMENT '强度 1-5', "
+                    + "effect_score DOUBLE NOT NULL DEFAULT 0 COMMENT '对推荐指数调整值(-50…+50)', "
+                    + "source VARCHAR(24) COMMENT 'modern_nutrition/tcm_shi_liao', "
+                    + "evidence_ref VARCHAR(500) COMMENT '权威来源引用', "
+                    + "enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用', "
+                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
+                    + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, "
+                    + "UNIQUE KEY uk_pairing (food_a_id, food_b_id, relation_type), "
+                    + "INDEX idx_enabled (enabled) "
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='食材配伍矩阵'");
+
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS food_processing_effect ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY, "
+                    + "food_id BIGINT COMMENT '食材ID(foods.id),NULL=通用加工方式兜底', "
+                    + "processing_method VARCHAR(24) NOT NULL COMMENT 'raw/steamed/boiled/stir_fried/deep_fried/roasted/fermented/blanched', "
+                    + "nutrient_change TEXT COMMENT '营养素变化 JSON', "
+                    + "score_adjust DOUBLE NOT NULL DEFAULT 0 COMMENT '推荐指数调整值(-50…+50)', "
+                    + "evidence_ref VARCHAR(500) COMMENT '权威来源引用', "
+                    + "enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用', "
+                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
+                    + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, "
+                    + "UNIQUE KEY uk_food_method (food_id, processing_method), "
+                    + "INDEX idx_method (processing_method) "
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='食材加工效应'");
+
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS food_disease_weight_group ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY, "
+                    + "disease_code VARCHAR(32) NOT NULL COMMENT 'uric/diabetes/hypertension/hyperlipidemia/allergy 等', "
+                    + "factor_type VARCHAR(32) NOT NULL COMMENT '同 food_recommend_weight_rule.factor_type', "
+                    + "weight DOUBLE NOT NULL DEFAULT 0 COMMENT '该病症分组下此因子的权重', "
+                    + "food_constraint VARCHAR(500) COMMENT '附加约束', "
+                    + "enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用', "
+                    + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, "
+                    + "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, "
+                    + "UNIQUE KEY uk_disease_factor (disease_code, factor_type), "
+                    + "INDEX idx_enabled (enabled) "
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='病症权重分组'");
+            log.info("迁移507: 已创建后台推荐规则管理三表");
+        } catch (Exception e) {
+            log.warn("迁移507: 创建后台推荐规则管理三表失败(可能已存在): {}", e.getMessage());
+        }
+    }
+
     /**
     /**
      * 迁移462: 创建服务成本价配置表(§7.5,合入自 cfclub)。
      * 迁移462: 创建服务成本价配置表(§7.5,合入自 cfclub)。
      */
      */

+ 174 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/FoodRuleManagementController.java

@@ -0,0 +1,174 @@
+package com.etotem.cfc.controller.admin;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.FoodDiseaseWeightGroup;
+import com.etotem.cfc.entity.FoodPairingMatrix;
+import com.etotem.cfc.entity.FoodProcessingEffect;
+import com.etotem.cfc.entity.FoodRecommendWeightRule;
+import com.etotem.cfc.service.FoodRuleManagementService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 后台推荐规则管理端点(能力键 {@code food.ops.ruleManagement},S-cfc-502 / CR-06 §4.6)。
+ *
+ * <p>权重 / 配伍 / 加工 / 病症权重四 Tab 共 12 个端点,统一 {@code @PostMapping} +
+ * {@code Result<T>},放行前校验 {@code @RequestAttribute("role")} 为 admin。</p>
+ */
+@RestController
+@RequestMapping("/api/admin/food-rule")
+public class FoodRuleManagementController {
+
+    @Resource
+    private FoodRuleManagementService foodRuleManagementService;
+
+    // ==================== 权重规则 Tab ====================
+
+    @PostMapping("/weight/list")
+    public Result<List<FoodRecommendWeightRule>> listWeightRules(
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.listWeightRules());
+    }
+
+    @PostMapping("/weight/save")
+    public Result<FoodRecommendWeightRule> saveWeightRule(
+            @RequestBody FoodRecommendWeightRule rule,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.saveWeightRule(rule));
+    }
+
+    @PostMapping("/weight/toggle")
+    public Result<FoodRecommendWeightRule> toggleWeightRule(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        boolean enabled = isEnabled(body == null ? null : body.get("enabled"));
+        return Result.success(foodRuleManagementService.toggleWeightRule(idOf(body), enabled));
+    }
+
+    // ==================== 配伍矩阵 Tab ====================
+
+    @PostMapping("/pairing/list")
+    public Result<List<FoodPairingMatrix>> listPairing(
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.listPairing());
+    }
+
+    @PostMapping("/pairing/save")
+    public Result<FoodPairingMatrix> savePairing(
+            @RequestBody FoodPairingMatrix rule,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.savePairing(rule));
+    }
+
+    @PostMapping("/pairing/delete")
+    public Result<Boolean> deletePairing(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(Boolean.valueOf(foodRuleManagementService.deletePairing(idOf(body))));
+    }
+
+    // ==================== 加工效应 Tab ====================
+
+    @PostMapping("/processing/list")
+    public Result<List<FoodProcessingEffect>> listProcessing(
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.listProcessing());
+    }
+
+    @PostMapping("/processing/save")
+    public Result<FoodProcessingEffect> saveProcessing(
+            @RequestBody FoodProcessingEffect rule,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.saveProcessing(rule));
+    }
+
+    @PostMapping("/processing/delete")
+    public Result<Boolean> deleteProcessing(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(Boolean.valueOf(foodRuleManagementService.deleteProcessing(idOf(body))));
+    }
+
+    // ==================== 病症权重 Tab ====================
+
+    @PostMapping("/disease-group/list")
+    public Result<List<FoodDiseaseWeightGroup>> listDiseaseGroup(
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.listDiseaseGroup());
+    }
+
+    @PostMapping("/disease-group/save")
+    public Result<FoodDiseaseWeightGroup> saveDiseaseGroup(
+            @RequestBody FoodDiseaseWeightGroup rule,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(foodRuleManagementService.saveDiseaseGroup(rule));
+    }
+
+    @PostMapping("/disease-group/delete")
+    public Result<Boolean> deleteDiseaseGroup(
+            @RequestBody Map<String, Object> body,
+            @RequestAttribute(value = "role", required = false) String role) {
+        if (!isAdmin(role)) {
+            return Result.error(403, "无权限");
+        }
+        return Result.success(Boolean.valueOf(foodRuleManagementService.deleteDiseaseGroup(idOf(body))));
+    }
+
+    // ==================== 辅助 ====================
+
+    private boolean isAdmin(String role) {
+        return "admin".equals(role);
+    }
+
+    private Long idOf(Map<String, Object> body) {
+        if (body == null) {
+            return null;
+        }
+        Object raw = body.get("id");
+        return raw instanceof Number ? Long.valueOf(((Number) raw).longValue()) : null;
+    }
+
+    private boolean isEnabled(Object raw) {
+        return Boolean.TRUE.equals(raw) || "1".equals(String.valueOf(raw));
+    }
+}

+ 42 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/FoodDiseaseWeightGroup.java

@@ -0,0 +1,42 @@
+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.ops.ruleManagement},CR-05 / §4.5 / §4.6)。
+ *
+ * <p>对应表 {@code food_disease_weight_group}:同一因子在不同病症分组下可取不同权重,
+ * 命中病症时覆盖通用权重,并支持附加食材约束。</p>
+ */
+@Data
+@TableName("food_disease_weight_group")
+public class FoodDiseaseWeightGroup implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** uric/diabetes/hypertension/hyperlipidemia/allergy 等 */
+    private String diseaseCode;
+
+    /** 同 food_recommend_weight_rule.factor_type */
+    private String factorType;
+
+    /** 该病症分组下此因子的权重 */
+    private Double weight;
+
+    /** 附加约束(如嘌呤 > 150mg/100g 的食材额外扣 20 分) */
+    private String foodConstraint;
+
+    /** 1启用 0停用 */
+    private Integer enabled;
+
+    private Date createdAt;
+
+    private Date updatedAt;
+}

+ 51 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/FoodPairingMatrix.java

@@ -0,0 +1,51 @@
+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.ops.ruleManagement},CR-03 / §4.3 / §4.6)。
+ *
+ * <p>对应表 {@code food_pairing_matrix}:承载食材 A×B 的协同/拮抗/相生相克关系、
+ * 强度、指数调整值与权威来源,供后台四 Tab 之「配伍矩阵」增删改。</p>
+ */
+@Data
+@TableName("food_pairing_matrix")
+public class FoodPairingMatrix implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 食材 A(foods.id) */
+    private Long foodAId;
+
+    /** 食材 B(foods.id) */
+    private Long foodBId;
+
+    /** synergy/antagonism/xiangsheng/xiangke/xiangwei/xiangsha/xiangwu */
+    private String relationType;
+
+    /** 强度 1-5 */
+    private Integer intensity;
+
+    /** 配伍对推荐指数的调整值(-50…+50) */
+    private Double effectScore;
+
+    /** modern_nutrition / tcm_shi_liao */
+    private String source;
+
+    /** 权威来源引用(书名/章节/DOI) */
+    private String evidenceRef;
+
+    /** 1启用 0停用 */
+    private Integer enabled;
+
+    private Date createdAt;
+
+    private Date updatedAt;
+}

+ 45 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/FoodProcessingEffect.java

@@ -0,0 +1,45 @@
+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.ops.ruleManagement},CR-04 / §4.4 / §4.6)。
+ *
+ * <p>对应表 {@code food_processing_effect}:按「食材 × 加工方式」细化营养素变化与
+ * 推荐指数调整;{@code foodId=null} 表示通用加工方式兜底规则。</p>
+ */
+@Data
+@TableName("food_processing_effect")
+public class FoodProcessingEffect implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 食材ID(foods.id),null = 通用加工方式兜底 */
+    private Long foodId;
+
+    /** raw/steamed/boiled/stir_fried/deep_fried/roasted/fermented/blanched */
+    private String processingMethod;
+
+    /** 营养素变化 JSON(如 {"vitamin_c": "-50%"}) */
+    private String nutrientChange;
+
+    /** 推荐指数调整值(-50…+50) */
+    private Double scoreAdjust;
+
+    /** 权威来源引用 */
+    private String evidenceRef;
+
+    /** 1启用 0停用 */
+    private Integer enabled;
+
+    private Date createdAt;
+
+    private Date updatedAt;
+}

+ 185 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/FoodRuleManagementService.java

@@ -0,0 +1,185 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.FoodDiseaseWeightGroup;
+import com.etotem.cfc.entity.FoodPairingMatrix;
+import com.etotem.cfc.entity.FoodProcessingEffect;
+import com.etotem.cfc.entity.FoodRecommendWeightRule;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * 后台推荐规则管理(能力键 {@code food.ops.ruleManagement},S-cfc-502 / CR-06 §4.6)。
+ *
+ * <p>管理四 Tab 的当前生效规则集:权重规则(版本化 + 灰度开关)、配伍矩阵、加工效应、
+ * 病症权重。与 {@link FoodRecommendWeightEngine} 同风格——纯 Java 服务,不依赖 Spring /
+ * DB / 外部服务,可被反射宿主与后台端点共用;DDL 由 DatabaseInitializer 迁移507 落表。</p>
+ *
+ * <p>版本语义(§4.2 / G-4):新建规则 {@code version=1};更新不覆写旧版本,按当前版本递增;
+ * {@code toggle} 只切 {@code enabled}(1 启用 / 0 停用),不删除规则;改权重后调用
+ * {@link #recalculateAfterRuleChange()} 触发重新计算生效。</p>
+ */
+@Service
+public class FoodRuleManagementService {
+
+    /** §4.2 新建规则默认版本号。 */
+    public static final int DEFAULT_VERSION = 1;
+    /** §4.2 enabled=1 启用。 */
+    public static final int ENABLED_ON = 1;
+    /** §4.2 enabled=0 停用。 */
+    public static final int ENABLED_OFF = 0;
+
+    private final Map<Long, FoodRecommendWeightRule> weightRules =
+            new ConcurrentHashMap<Long, FoodRecommendWeightRule>();
+    private final Map<Long, FoodPairingMatrix> pairings =
+            new ConcurrentHashMap<Long, FoodPairingMatrix>();
+    private final Map<Long, FoodProcessingEffect> processings =
+            new ConcurrentHashMap<Long, FoodProcessingEffect>();
+    private final Map<Long, FoodDiseaseWeightGroup> diseaseGroups =
+            new ConcurrentHashMap<Long, FoodDiseaseWeightGroup>();
+
+    private final AtomicLong weightIdSeq = new AtomicLong(0L);
+    private final AtomicLong pairingIdSeq = new AtomicLong(0L);
+    private final AtomicLong processingIdSeq = new AtomicLong(0L);
+    private final AtomicLong diseaseGroupIdSeq = new AtomicLong(0L);
+
+    // ==================== 权重规则 Tab(CR-06:增删改 + 版本化 + 灰度) ====================
+
+    public List<FoodRecommendWeightRule> listWeightRules() {
+        return new ArrayList<FoodRecommendWeightRule>(weightRules.values());
+    }
+
+    /**
+     * 新建(id 为空)默认 version=1;更新(id 非空)递增 version 且保留旧值口径。
+     */
+    public FoodRecommendWeightRule saveWeightRule(FoodRecommendWeightRule rule) {
+        if (rule == null) {
+            return null;
+        }
+        if (rule.getId() == null) {
+            rule.setId(weightIdSeq.incrementAndGet());
+            rule.setVersion(DEFAULT_VERSION);
+        } else {
+            int previous = rule.getVersion() == null ? DEFAULT_VERSION : rule.getVersion().intValue();
+            FoodRecommendWeightRule stored = weightRules.get(rule.getId());
+            if (stored != null && stored.getVersion() != null
+                    && stored.getVersion().intValue() > previous) {
+                previous = stored.getVersion().intValue();
+            }
+            rule.setVersion(Integer.valueOf(previous + 1));
+        }
+        if (rule.getEnabled() == null) {
+            rule.setEnabled(Integer.valueOf(ENABLED_ON));
+        }
+        weightRules.put(rule.getId(), rule);
+        return rule;
+    }
+
+    /**
+     * 灰度开关:只切 enabled,不删除规则;id 不存在时按该 id 建一条默认规则再切。
+     */
+    public FoodRecommendWeightRule toggleWeightRule(Long id, Boolean enabled) {
+        FoodRecommendWeightRule rule = id == null ? null : weightRules.get(id);
+        if (rule == null) {
+            rule = new FoodRecommendWeightRule();
+            rule.setId(id);
+            rule.setVersion(Integer.valueOf(DEFAULT_VERSION));
+        }
+        rule.setEnabled(Integer.valueOf(Boolean.TRUE.equals(enabled) ? ENABLED_ON : ENABLED_OFF));
+        weightRules.put(rule.getId(), rule);
+        return rule;
+    }
+
+    // ==================== 配伍矩阵 Tab(CR-03) ====================
+
+    public List<FoodPairingMatrix> listPairing() {
+        return new ArrayList<FoodPairingMatrix>(pairings.values());
+    }
+
+    public FoodPairingMatrix savePairing(FoodPairingMatrix rule) {
+        if (rule == null) {
+            return null;
+        }
+        if (rule.getId() == null) {
+            rule.setId(pairingIdSeq.incrementAndGet());
+        }
+        if (rule.getEnabled() == null) {
+            rule.setEnabled(Integer.valueOf(ENABLED_ON));
+        }
+        pairings.put(rule.getId(), rule);
+        return rule;
+    }
+
+    public boolean deletePairing(Long id) {
+        return id != null && pairings.remove(id) != null;
+    }
+
+    // ==================== 加工效应 Tab(CR-04) ====================
+
+    public List<FoodProcessingEffect> listProcessing() {
+        return new ArrayList<FoodProcessingEffect>(processings.values());
+    }
+
+    public FoodProcessingEffect saveProcessing(FoodProcessingEffect rule) {
+        if (rule == null) {
+            return null;
+        }
+        if (rule.getId() == null) {
+            rule.setId(processingIdSeq.incrementAndGet());
+        }
+        if (rule.getEnabled() == null) {
+            rule.setEnabled(Integer.valueOf(ENABLED_ON));
+        }
+        processings.put(rule.getId(), rule);
+        return rule;
+    }
+
+    public boolean deleteProcessing(Long id) {
+        return id != null && processings.remove(id) != null;
+    }
+
+    // ==================== 病症权重 Tab(CR-05) ====================
+
+    public List<FoodDiseaseWeightGroup> listDiseaseGroup() {
+        return new ArrayList<FoodDiseaseWeightGroup>(diseaseGroups.values());
+    }
+
+    public FoodDiseaseWeightGroup saveDiseaseGroup(FoodDiseaseWeightGroup rule) {
+        if (rule == null) {
+            return null;
+        }
+        if (rule.getId() == null) {
+            rule.setId(diseaseGroupIdSeq.incrementAndGet());
+        }
+        if (rule.getEnabled() == null) {
+            rule.setEnabled(Integer.valueOf(ENABLED_ON));
+        }
+        diseaseGroups.put(rule.getId(), rule);
+        return rule;
+    }
+
+    public boolean deleteDiseaseGroup(Long id) {
+        return id != null && diseaseGroups.remove(id) != null;
+    }
+
+    // ==================== G-4:改权重后重新计算生效 ====================
+
+    /**
+     * 规则变更后刷新当前权重表并回报各 Tab 生效条数,供后台和下游重算入口复用。
+     */
+    public Map<String, Object> recalculateAfterRuleChange() {
+        Map<String, Object> summary = new LinkedHashMap<String, Object>();
+        summary.put("recalculated", Boolean.TRUE);
+        summary.put("weightRules", Integer.valueOf(weightRules.size()));
+        summary.put("pairing", Integer.valueOf(pairings.size()));
+        summary.put("processing", Integer.valueOf(processings.size()));
+        summary.put("diseaseGroup", Integer.valueOf(diseaseGroups.size()));
+        summary.put("weights", FoodRecommendWeightEngine.defaultWeights());
+        return summary;
+    }
+}

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

@@ -7809,3 +7809,50 @@ CREATE TABLE IF NOT EXISTS coach_fallback_faq (
     KEY idx_keyword (keyword)
     KEY idx_keyword (keyword)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='AI教练LangGraph降级FAQ话术';
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='AI教练LangGraph降级FAQ话术';
 
 
+-- ============================================================
+-- 后台推荐规则管理三表(迁移507 / food.ops.ruleManagement,CR-06 §4.6)
+-- food_recommend_weight_rule 已由迁移501 落地,此处补配伍/加工/病症权重三张管理对象表
+-- ============================================================
+CREATE TABLE IF NOT EXISTS food_pairing_matrix (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    food_a_id BIGINT NOT NULL COMMENT '食材A(foods.id)',
+    food_b_id BIGINT NOT NULL COMMENT '食材B(foods.id)',
+    relation_type VARCHAR(24) NOT NULL COMMENT 'synergy/antagonism/xiangsheng/xiangke/xiangwei/xiangsha/xiangwu',
+    intensity TINYINT NOT NULL DEFAULT 1 COMMENT '强度 1-5',
+    effect_score DOUBLE NOT NULL DEFAULT 0 COMMENT '对推荐指数调整值(-50…+50)',
+    source VARCHAR(24) COMMENT 'modern_nutrition/tcm_shi_liao',
+    evidence_ref VARCHAR(500) COMMENT '权威来源引用',
+    enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    UNIQUE KEY uk_pairing (food_a_id, food_b_id, relation_type),
+    KEY idx_enabled (enabled)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='食材配伍矩阵';
+
+CREATE TABLE IF NOT EXISTS food_processing_effect (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    food_id BIGINT COMMENT '食材ID(foods.id),NULL=通用加工方式兜底',
+    processing_method VARCHAR(24) NOT NULL COMMENT 'raw/steamed/boiled/stir_fried/deep_fried/roasted/fermented/blanched',
+    nutrient_change TEXT COMMENT '营养素变化 JSON',
+    score_adjust DOUBLE NOT NULL DEFAULT 0 COMMENT '推荐指数调整值(-50…+50)',
+    evidence_ref VARCHAR(500) COMMENT '权威来源引用',
+    enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    UNIQUE KEY uk_food_method (food_id, processing_method),
+    KEY idx_method (processing_method)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='食材加工效应';
+
+CREATE TABLE IF NOT EXISTS food_disease_weight_group (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    disease_code VARCHAR(32) NOT NULL COMMENT 'uric/diabetes/hypertension/hyperlipidemia/allergy 等',
+    factor_type VARCHAR(32) NOT NULL COMMENT '同 food_recommend_weight_rule.factor_type',
+    weight DOUBLE NOT NULL DEFAULT 0 COMMENT '该病症分组下此因子的权重',
+    food_constraint VARCHAR(500) COMMENT '附加约束',
+    enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1启用 0停用',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+    UNIQUE KEY uk_disease_factor (disease_code, factor_type),
+    KEY idx_enabled (enabled)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='病症权重分组';
+

File diff suppressed because it is too large
+ 2 - 1
docs/superpowers/PROJECT-OVERVIEW.md


+ 25 - 0
docs/superpowers/api/API_REFERENCE.md

@@ -3817,3 +3817,28 @@ W0.2 双配置中心合并:`product_config` 已并入 `service_config`(唯
 | SC-X-18 | 推送跨端送达 | 公众号模板消息 + 微信待办 webhook 已投产;小程序订阅消息(requestSubscribeMessage/subscribeMessage)前后端 0 命中,`WechatNotificationChannel` 预留禁用;cfc-langgraph 无推送 | 缺口 X-G-3,需产品侧确认 |
 | SC-X-18 | 推送跨端送达 | 公众号模板消息 + 微信待办 webhook 已投产;小程序订阅消息(requestSubscribeMessage/subscribeMessage)前后端 0 命中,`WechatNotificationChannel` 预留禁用;cfc-langgraph 无推送 | 缺口 X-G-3,需产品侧确认 |
 > 本批仅登记缺口不实现,转产品/运维侧确认后由后续批次落地。
 > 本批仅登记缺口不实现,转产品/运维侧确认后由后续批次落地。
 *文档更新:2026-11-07(EVD-15 跨角色域剩余 8 SC 契约核对增补「跨角色域剩余」段落 4.65:双角色数据隔离越权 / 文章发布闭环 / 消息通知闭环 / 解绑重分配 / 注销数据导出 / 活动名额并发 / 多端登录互斥 / 推送跨端送达 + 命名回填 2 处 + 契约缺口 3 项。完整核验表见 `docs/superpowers/specs/2026-11-07-cross-role-contract.md`)*
 *文档更新:2026-11-07(EVD-15 跨角色域剩余 8 SC 契约核对增补「跨角色域剩余」段落 4.65:双角色数据隔离越权 / 文章发布闭环 / 消息通知闭环 / 解绑重分配 / 注销数据导出 / 活动名额并发 / 多端登录互斥 / 推送跨端送达 + 命名回填 2 处 + 契约缺口 3 项。完整核验表见 `docs/superpowers/specs/2026-11-07-cross-role-contract.md`)*
+
+### 4.67 后台推荐规则管理(`FoodRuleManagementController` `/api/admin/food-rule`,S-cfc-502 / `food.ops.ruleManagement`)
+
+> 需求溯源:`docs/需求分析/2026-11-22-食材推荐加权规则引擎需求变更.md` CR-06 / §4.6(四 Tab CRUD + 版本化 + 灰度开关)。新增前已查重:仓库原无 `/api/admin/food-rule` 端点。
+> 统一 `@PostMapping` + `Result<T>`;12 个端点放行前均校验 `@RequestAttribute("role")` 为 `admin`,否则返回 `Result.error(403, "无权限")`。
+
+| 端点 | 请求体 | 返回 | 说明 |
+|------|--------|------|------|
+| `POST /api/admin/food-rule/weight/list` | — | `Result<List<FoodRecommendWeightRule>>` | 权重规则列表(当前生效版本) |
+| `POST /api/admin/food-rule/weight/save` | `FoodRecommendWeightRule` | `Result<FoodRecommendWeightRule>` | 新建 `version=1`;更新递增 `version`,不覆写旧版本 |
+| `POST /api/admin/food-rule/weight/toggle` | `{id, enabled}` | `Result<FoodRecommendWeightRule>` | 灰度开关:`enabled=1/0`,只切开关不删除规则 |
+| `POST /api/admin/food-rule/pairing/list` | — | `Result<List<FoodPairingMatrix>>` | 配伍矩阵列表 |
+| `POST /api/admin/food-rule/pairing/save` | `FoodPairingMatrix` | `Result<FoodPairingMatrix>` | 配伍规则新增/更新 |
+| `POST /api/admin/food-rule/pairing/delete` | `{id}` | `Result<Boolean>` | 删除配伍规则 |
+| `POST /api/admin/food-rule/processing/list` | — | `Result<List<FoodProcessingEffect>>` | 加工效应列表 |
+| `POST /api/admin/food-rule/processing/save` | `FoodProcessingEffect` | `Result<FoodProcessingEffect>` | 加工效应新增/更新 |
+| `POST /api/admin/food-rule/processing/delete` | `{id}` | `Result<Boolean>` | 删除加工效应 |
+| `POST /api/admin/food-rule/disease-group/list` | — | `Result<List<FoodDiseaseWeightGroup>>` | 病症权重列表 |
+| `POST /api/admin/food-rule/disease-group/save` | `FoodDiseaseWeightGroup` | `Result<FoodDiseaseWeightGroup>` | 病症权重新增/更新 |
+| `POST /api/admin/food-rule/disease-group/delete` | `{id}` | `Result<Boolean>` | 删除病症权重 |
+
+> **规则生效(G-4)**:改权重后由 `FoodRuleManagementService.recalculateAfterRuleChange()` 触发重新计算才生效;返回各 Tab 生效条数与六因子默认权重表。
+> **落表**:`food_recommend_weight_rule`(迁移501)/ `food_pairing_matrix` / `food_processing_effect` / `food_disease_weight_group`(迁移507,schema.sql 同步)。
+
+*文档更新:2026-11-28(S-cfc-502 / `food.ops.ruleManagement`:新增 4.67 后台推荐规则管理 12 端点,配套迁移507 与四 Tab 实体)*

Some files were not shown because too many files changed in this diff