Browse Source

feat(food.rule.processingEffect): 落地加工效应查询服务与分层Mapper,S-cfc-465 红单测转绿

E2E Test Bot 2 hours ago
parent
commit
8a839bd121

+ 15 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/FoodProcessingEffectMapper.java

@@ -0,0 +1,15 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.FoodProcessingEffect;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 食材加工效应 Mapper(能力键 {@code food.rule.processingEffect},CR-04 / §4.4)。
+ *
+ * <p>对应表 {@code food_processing_effect}:按「食材 × 加工方式」细化营养素变化与
+ * 推荐指数调整;{@code food_id=NULL} 行为通用加工方式兜底规则。</p>
+ */
+@Mapper
+public interface FoodProcessingEffectMapper extends BaseMapper<FoodProcessingEffect> {
+}

+ 304 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/FoodProcessingEffectService.java

@@ -0,0 +1,304 @@
+package com.etotem.cfc.service;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.FoodProcessingEffect;
+import com.etotem.cfc.mapper.FoodProcessingEffectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 食材加工效应查询/计算服务(能力键 {@code food.rule.processingEffect},CR-04 / §4.4 / §8)。
+ *
+ * <p>规则口径:具体到「食材 × 加工方式」;通用加工方式规则({@code food_id=NULL} 行)作为兜底默认值,
+ * 食材级覆盖通用级;未配置的食材 × 方式 → 无调整({@code score_adjust=0})。</p>
+ *
+ * <p>下游集成(§4.7-2 / G-3):{@code dish.type} 推断加工方式 → 查 {@code food_processing_effect}
+ * → 返回体加 {@code processingWarning}。</p>
+ *
+ * <p>权限流:本服务为后端内部查询/计算服务,无用户侧鉴权分支;后台 CRUD 由
+ * {@code ops.foodRuleManagement}(CR-06)承载,食谱集成由 {@code diet.menu.pairingConstraint}(CR-07)承载。</p>
+ */
+@Slf4j
+@Service
+public class FoodProcessingEffectService {
+
+    /** §4.4 processing_method 的 8 个合法枚举值 */
+    private static final String[] METHODS = {
+            "raw", "steamed", "boiled", "stir_fried",
+            "deep_fried", "roasted", "fermented", "blanched"
+    };
+
+    private static final Set<String> METHOD_SET =
+            Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(METHODS)));
+
+    /** score_adjust 取值域(§4.4) */
+    private static final double SCORE_MIN = -50.0;
+    private static final double SCORE_MAX = 50.0;
+
+    private static final Map<String, String> METHOD_LABELS = new HashMap<String, String>();
+    private static final Map<String, String> METHOD_SUGGESTIONS = new HashMap<String, String>();
+    private static final Map<String, String> NUTRIENT_NAMES = new HashMap<String, String>();
+
+    static {
+        METHOD_LABELS.put("raw", "生食");
+        METHOD_LABELS.put("steamed", "蒸制");
+        METHOD_LABELS.put("boiled", "水煮");
+        METHOD_LABELS.put("stir_fried", "炒制");
+        METHOD_LABELS.put("deep_fried", "油炸");
+        METHOD_LABELS.put("roasted", "烘烤");
+        METHOD_LABELS.put("fermented", "发酵");
+        METHOD_LABELS.put("blanched", "焯水");
+
+        METHOD_SUGGESTIONS.put("raw", "建议充分加热后食用");
+        METHOD_SUGGESTIONS.put("steamed", "蒸制能较好保留营养");
+        METHOD_SUGGESTIONS.put("boiled", "建议连汤食用以保留水溶性营养");
+        METHOD_SUGGESTIONS.put("stir_fried", "建议少油快炒");
+        METHOD_SUGGESTIONS.put("deep_fried", "建议改蒸煮");
+        METHOD_SUGGESTIONS.put("roasted", "建议改蒸煮");
+        METHOD_SUGGESTIONS.put("fermented", "建议控制摄入量");
+        METHOD_SUGGESTIONS.put("blanched", "建议焯水后弃汤");
+
+        NUTRIENT_NAMES.put("vitamin_c", "维生素 C");
+        NUTRIENT_NAMES.put("oxalic_acid", "草酸");
+        NUTRIENT_NAMES.put("protein", "蛋白质");
+        NUTRIENT_NAMES.put("fat", "脂肪");
+        NUTRIENT_NAMES.put("fiber", "膳食纤维");
+        NUTRIENT_NAMES.put("calcium", "钙");
+        NUTRIENT_NAMES.put("iron", "铁");
+    }
+
+    /** 加工效应查询走分层 Mapper(§4.4);纯内存契约方法不依赖 DB,反射实例化时该字段为 null。 */
+    @Resource
+    private FoodProcessingEffectMapper foodProcessingEffectMapper;
+
+    // ==================== 加工方式值域(§4.4) ====================
+
+    /** 8 种合法加工方式(§4.4)。 */
+    public List<String> supportedProcessingMethods() {
+        return new ArrayList<String>(Arrays.asList(METHODS));
+    }
+
+    /** 加工方式值域校验:仅接受 8 种合法值,null / 空串 / 未知值一律拒绝。 */
+    public boolean isValidProcessingMethod(String method) {
+        return method != null && METHOD_SET.contains(method);
+    }
+
+    // ==================== 推荐指数调整(§4.4 / §8) ====================
+
+    /**
+     * 解析「食材 × 加工方式」的推荐指数调整。
+     *
+     * <ul>
+     *   <li>食材级命中优先(foodId 相等);</li>
+     *   <li>食材级未命中该方式 → 回落通用级(foodId=NULL 行);</li>
+     *   <li>foodId=null 时只取通用级;规则集为空/null 或方式未配置 → 无调整 0;</li>
+     *   <li>结果恒截断在 [-50, +50]。</li>
+     * </ul>
+     *
+     * @param effects 纯内存规则集,每项含 foodId(Long 或 null) / processingMethod / scoreAdjust(Number)
+     */
+    public double resolveScoreAdjust(Long foodId, String method, List<Map<String, Object>> effects) {
+        if (effects == null || effects.isEmpty() || !isValidProcessingMethod(method)) {
+            return 0.0;
+        }
+        Map<String, Object> generic = null;
+        for (Map<String, Object> effect : effects) {
+            if (effect == null || !method.equals(effect.get("processingMethod"))) {
+                continue;
+            }
+            Object ruleFoodId = effect.get("foodId");
+            if (foodId != null && foodId.equals(ruleFoodId)) {
+                return clampScoreAdjust(readAdjust(effect.get("scoreAdjust")));
+            }
+            if (ruleFoodId == null && generic == null) {
+                generic = effect;
+            }
+        }
+        if (generic != null) {
+            return clampScoreAdjust(readAdjust(generic.get("scoreAdjust")));
+        }
+        return 0.0;
+    }
+
+    /** 截断到 [-50, +50](§4.4 score_adjust 取值域)。 */
+    public double clampScoreAdjust(double value) {
+        if (Double.isNaN(value)) {
+            return 0.0;
+        }
+        if (value > SCORE_MAX) {
+            return SCORE_MAX;
+        }
+        if (value < SCORE_MIN) {
+            return SCORE_MIN;
+        }
+        return value;
+    }
+
+    private double readAdjust(Object value) {
+        if (value instanceof Number) {
+            return ((Number) value).doubleValue();
+        }
+        if (value instanceof String) {
+            try {
+                return Double.parseDouble(((String) value).trim());
+            } catch (NumberFormatException ignored) {
+                // 非法配置视为无调整
+            }
+        }
+        return 0.0;
+    }
+
+    // ==================== nutrient_change 解析(§4.4) ====================
+
+    /** 解析 nutrient_change JSON;null / 空串 / 非法 JSON 容错返回空映射,不抛异常。 */
+    public Map<String, String> parseNutrientChange(String json) {
+        Map<String, String> result = new HashMap<String, String>();
+        if (json == null || json.trim().isEmpty()) {
+            return result;
+        }
+        try {
+            JSONObject node = JSON.parseObject(json);
+            if (node == null) {
+                return result;
+            }
+            for (Map.Entry<String, Object> entry : node.entrySet()) {
+                Object value = entry.getValue();
+                result.put(entry.getKey(), value == null ? "" : String.valueOf(value));
+            }
+        } catch (Exception e) {
+            log.warn("解析 nutrient_change 失败,按空映射处理 json={}: {}", json, e.getMessage());
+        }
+        return result;
+    }
+
+    // ==================== 加工建议 + dish.type 推断(§4.7-2 / G-3) ====================
+
+    /**
+     * 生成 processingWarning(§4.7-2 示例:deep_fried + vitamin_c=-50%
+     * →「油炸降低维生素 C 50%,建议改蒸煮」)。
+     */
+    public String processingWarning(String method, Map<String, String> nutrientChange) {
+        String label = METHOD_LABELS.get(method);
+        if (label == null) {
+            label = "该加工方式";
+        }
+        StringBuilder sb = new StringBuilder(label);
+        if (nutrientChange != null && !nutrientChange.isEmpty()) {
+            StringBuilder changes = new StringBuilder();
+            for (Map.Entry<String, String> entry : nutrientChange.entrySet()) {
+                if (changes.length() > 0) {
+                    changes.append("、");
+                }
+                String value = entry.getValue() == null ? "" : entry.getValue().trim();
+                String verb;
+                String magnitude;
+                if (value.startsWith("-")) {
+                    verb = "降低";
+                    magnitude = value.substring(1);
+                } else if (value.startsWith("+")) {
+                    verb = "提升";
+                    magnitude = value.substring(1);
+                } else {
+                    verb = "改变";
+                    magnitude = value;
+                }
+                String name = NUTRIENT_NAMES.get(entry.getKey());
+                if (name == null) {
+                    name = entry.getKey();
+                }
+                changes.append(verb).append(name).append(" ").append(magnitude);
+            }
+            sb.append(changes);
+        }
+        String suggestion = METHOD_SUGGESTIONS.get(method);
+        if (suggestion == null) {
+            suggestion = "建议优先选择蒸煮等清淡加工方式";
+        }
+        sb.append(",").append(suggestion);
+        return sb.toString();
+    }
+
+    /** 由 dish.type 推断加工方式(§4.7-2);未知类型返回 null,不抛异常。 */
+    public String inferProcessingMethod(String dishType) {
+        if (dishType == null || dishType.trim().isEmpty()) {
+            return null;
+        }
+        String type = dishType.trim();
+        if (type.contains("炸")) {
+            return "deep_fried";
+        }
+        if (type.contains("蒸")) {
+            return "steamed";
+        }
+        if (type.contains("焯")) {
+            return "blanched";
+        }
+        if (type.contains("煮") || type.contains("白灼")) {
+            return "boiled";
+        }
+        if (type.contains("炒")) {
+            return "stir_fried";
+        }
+        if (type.contains("烤") || type.contains("烘焙")) {
+            return "roasted";
+        }
+        if (type.contains("发酵") || type.contains("腌") || type.contains("酱")) {
+            return "fermented";
+        }
+        if (type.contains("生") || type.contains("凉拌")) {
+            return "raw";
+        }
+        return null;
+    }
+
+    // ==================== DB 查询(分层 Mapper) ====================
+
+    /**
+     * 从 {@code food_processing_effect} 读取启用中的规则,转换为契约内存规则集。
+     *
+     * <p>同时返回通用级(food_id=NULL)与指定食材级规则,供
+     * {@link #resolveScoreAdjust(Long, String, List)} 按「食材级优先 / 通用级兜底」解析。</p>
+     */
+    public List<Map<String, Object>> loadEffects(Long foodId, String method) {
+        List<Map<String, Object>> effects = new ArrayList<Map<String, Object>>();
+        if (foodProcessingEffectMapper == null) {
+            return effects;
+        }
+        LambdaQueryWrapper<FoodProcessingEffect> query = new LambdaQueryWrapper<FoodProcessingEffect>();
+        query.eq(FoodProcessingEffect::getEnabled, 1);
+        if (method != null) {
+            query.eq(FoodProcessingEffect::getProcessingMethod, method);
+        }
+        if (foodId != null) {
+            query.and(w -> w.isNull(FoodProcessingEffect::getFoodId)
+                    .or().eq(FoodProcessingEffect::getFoodId, foodId));
+        } else {
+            query.isNull(FoodProcessingEffect::getFoodId);
+        }
+        List<FoodProcessingEffect> rows = foodProcessingEffectMapper.selectList(query);
+        if (rows == null) {
+            return effects;
+        }
+        for (FoodProcessingEffect row : rows) {
+            Map<String, Object> effect = new HashMap<String, Object>();
+            effect.put("foodId", row.getFoodId());
+            effect.put("processingMethod", row.getProcessingMethod());
+            effect.put("scoreAdjust", row.getScoreAdjust());
+            effect.put("nutrientChange", row.getNutrientChange());
+            effects.add(effect);
+        }
+        return effects;
+    }
+}