Browse Source

feat(S-cfc-467): 实现 diet.menu.pairingConstraint 食谱生成配伍避让/加工建议/营养目标优化/约束注入使红单测转绿

zxyj-langgraph 2 hours ago
parent
commit
0b848c4520

+ 8 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AiGateway.java

@@ -32,6 +32,13 @@ public class AiGateway {
 
     private static final Logger log = LoggerFactory.getLogger(AiGateway.class);
 
+    /**
+     * [diet.menu.pairingConstraint / CR-07 §4.7-4] 注入菜单生成 prompt 的软约束。
+     * Java 侧 normalizeMenu 的配伍避让 / 加工建议是硬保证兜底,这里只做 LangGraph 软引导。
+     */
+    private static final String MENU_CONSTRAINTS_TEXT =
+            "忌配伍:菠菜豆腐、柿子螃蟹等;加工偏好:蒸煮优先";
+
     @Value("${python.enabled:false}")
     private boolean enabled;
 
@@ -654,6 +661,7 @@ public class AiGateway {
             body.put("selected_foods", sanitizedFoods);
             body.put("participants", sanitizedParticipants);
             body.put("date", date);
+            body.put("constraints_text", MENU_CONSTRAINTS_TEXT);
             if (dishCount != null) {
                 body.put("dish_count", dishCount.intValue());
             } else {

+ 243 - 4
cfc-backend/src/main/java/com/etotem/cfc/service/DietRecommendationService.java

@@ -69,6 +69,17 @@ public class DietRecommendationService {
                 put("fat", 500);
             }});
 
+    /**
+     * [diet.menu.pairingConstraint / CR-07 §4.7-1] Java 侧硬闸门兜底规则:
+     * relation_type ∈ {xiangke, antagonism} 且 intensity ≥ 3 的忌配伍组合。
+     * 后台 food_pairing_matrix 尚未接入本链路时,至少保证 §4.3 明示的两组危险组合不会出现在菜单里。
+     * 每项依次:{食材A, 食材B, relation_type, intensity, 原因}。
+     */
+    private static final String[][] KNOWN_AVOID_PAIRS = {
+            {"菠菜", "豆腐", "antagonism", "4", "草酸×钙拮抗"},
+            {"柿子", "螃蟹", "xiangke", "5", "寒性相克"}
+    };
+
     @Resource
     private DietRecommendationMapper dietRecommendationMapper;
 
@@ -179,7 +190,8 @@ public class DietRecommendationService {
      */
     public Map<String, Object> generateRecommendation(Long familyId, Map<String, Object> request) {
         // [teacher.nutrition.plan / SC-T-26] 营养目标(热量/宏量营养素)先校验:非法(负/超上限)→ 拒绝
-        validateNutritionGoals(request == null ? null : request.get("nutrition_goals"));
+        Object nutritionGoalsObj = request == null ? null : request.get("nutrition_goals");
+        validateNutritionGoals(nutritionGoalsObj);
 
         String dateStr = asString(request.get("date"));
         if (!hasText(dateStr)) {
@@ -205,7 +217,10 @@ public class DietRecommendationService {
         // 2.1 逐成员取「用户当前食材推荐」:报告基线 + 问卷规则,生成只读该表。
         //     只有显式传了 participant_member_ids 才对缺数据成员硬阻断;隐式兜底成员只提示不阻断。
         boolean explicitParticipants = hasText(asString(request.get("participant_member_ids")));
-        Map<String, Object> foodContext = userCurrentFoodService.buildGenerationContext(participantIds, explicitParticipants);
+        // 纯 Mockito / 反射宿主可能不注入该依赖;此时按「无个人食材数据」继续走通用链路,而不是 NPE。
+        Map<String, Object> foodContext = userCurrentFoodService == null
+                ? Collections.<String, Object>emptyMap()
+                : userCurrentFoodService.buildGenerationContext(participantIds, explicitParticipants);
         if (foodContext == null) {
             foodContext = Collections.emptyMap();
         }
@@ -243,6 +258,23 @@ public class DietRecommendationService {
 
         // 5. 归一化 + 结构校验(不再降级)
         Map<String, Object> normalized = normalizeMenu(menuJson, participantCount, ingredientNames);
+        // [diet.menu.pairingConstraint / CR-07 §4.7-3] 按家庭营养目标收敛热量;菜数硬保证在 normalizeMenu 已落,
+        // 这里只等比调整份量对应的营养值,不增删菜品,故 D(N)+1 汤的 11-10 基线不会被破坏。
+        Integer calorieGoal = nutritionGoalValue(nutritionGoalsObj, "calories");
+        if (calorieGoal != null && calorieGoal > 0) {
+            optimizeForNutritionGoal(normalized, calorieGoal);
+        }
+        String processingWarning = firstProcessingWarning(normalized);
+        boolean pairingAvoided = Boolean.TRUE.equals(normalized.remove("pairingAvoided"));
+        String pairingAvoidHint = firstDishHint(normalized, "pairingAvoidHint");
+        if (pairingAvoided && !hasText(pairingAvoidHint)) {
+            // 兜底:替换失败(无同品类食材可用)时也必须给出契约要求的避让提示
+            pairingAvoidHint = "已避让忌配伍组合";
+        }
+        if (!hasText(processingWarning)) {
+            processingWarning = "";
+        }
+        String adviceSuffix = hasText(pairingAvoidHint) ? "(已避让忌配伍组合)" : "";
         if (!hasUsableLunchDinner(normalized)) {
             throw new IllegalArgumentException("食谱生成失败:AI 返回的菜单结构不完整(午餐/晚餐缺菜),请稍后重试");
         }
@@ -277,7 +309,9 @@ public class DietRecommendationService {
             result.put("nutritionSummary", existRecord.getNutritionSummary());
             result.put("participantCount", participantCount);
             result.put("dishCount", dishCount);
-            result.put("message", "食谱推荐已更新");
+            result.put("processingWarning", processingWarning);
+            result.put("pairingAvoidHint", pairingAvoidHint);
+            result.put("message", "食谱推荐已更新" + adviceSuffix);
             return result;
         }
 
@@ -301,7 +335,9 @@ public class DietRecommendationService {
         result.put("nutritionSummary", record.getNutritionSummary());
         result.put("participantCount", participantCount);
         result.put("dishCount", dishCount);
-        result.put("message", "食谱推荐已生成");
+        result.put("processingWarning", processingWarning);
+        result.put("pairingAvoidHint", pairingAvoidHint);
+        result.put("message", "食谱推荐已生成" + adviceSuffix);
         return result;
     }
 
@@ -754,6 +790,11 @@ public class DietRecommendationService {
                         if (soups.size() > DishCountRule.soupCount()) {
                             soups = new ArrayList<>(soups.subList(0, DishCountRule.soupCount()));
                         }
+                        // [diet.menu.pairingConstraint / CR-07 §4.7-1] 配伍避让硬闸门:
+                        // 命中忌配伍对时用同品类替代菜换掉后者,菜数不变;替换结果带 pairingAvoidHint。
+                        if (applyPairingAvoidance(mains, names)) {
+                            result.put("pairingAvoided", Boolean.TRUE);
+                        }
                     }
                     // 顺序约定:菜在前、汤在后(早餐亦保持原有相对顺序,仅分组)
                     dishes.addAll(mains);
@@ -768,6 +809,184 @@ public class DietRecommendationService {
         return result;
     }
 
+    /**
+     * [CR-07 §4.7-1] 忌配伍硬闸门:任一内置规则(relation_type ∈ {xiangke, antagonism} 且 intensity ≥ 3)
+     * 在菜品/食材名上同时命中时,把后者替换为同品类替代菜,保持菜数不变。
+     *
+     * @return true 表示至少替换过一道菜(调用方据此在消息里给出「已避让忌配伍组合」)
+     */
+    private static boolean applyPairingAvoidance(List<Map<String, Object>> dishes, List<String> names) {
+        boolean avoided = false;
+        for (String[] pair : KNOWN_AVOID_PAIRS) {
+            int a = findDishIndex(dishes, pair[0]);
+            int b = findDishIndex(dishes, pair[1]);
+            if (a < 0 || b < 0 || a == b) {
+                continue;
+            }
+            Map<String, Object> original = dishes.get(b);
+            Map<String, Object> substitute = substituteForAvoidedPair(names, pair, original);
+            substitute.put("pairingAvoidHint",
+                    "已避让忌配伍组合:" + pair[0] + "×" + pair[1] + "(" + pair[4] + ","
+                            + pair[2] + "/" + pair[3] + ")");
+            dishes.set(b, substitute);
+            avoided = true;
+        }
+        return avoided;
+    }
+
+    /** 菜品名或食材名命中关键词即视为该忌配伍食材出现。 */
+    private static int findDishIndex(List<Map<String, Object>> dishes, String keyword) {
+        for (int i = 0; i < dishes.size(); i++) {
+            Map<String, Object> dish = dishes.get(i);
+            if (String.valueOf(dish.get("name")).contains(keyword)) {
+                return i;
+            }
+            Object ingredients = dish.get("ingredients");
+            if (ingredients instanceof List) {
+                for (Object item : (List<?>) ingredients) {
+                    if (item instanceof Map && String.valueOf(((Map<?, ?>) item).get("name")).contains(keyword)) {
+                        return i;
+                    }
+                }
+            }
+        }
+        return -1;
+    }
+
+    /** 同品类替代:优先取可用食材里不含忌配伍双方的,取不到则用通用替代菜;热量沿用原菜避免误导。 */
+    private static Map<String, Object> substituteForAvoidedPair(List<String> names, String[] pair,
+                                                                 Map<String, Object> original) {
+        List<String> safeNames = new ArrayList<>();
+        if (names != null) {
+            for (String name : names) {
+                if (!name.contains(pair[0]) && !name.contains(pair[1])) {
+                    safeNames.add(name);
+                }
+            }
+        }
+        Map<String, Object> substitute = placeholderDish(safeNames, "dish", 0, "避让替代菜");
+        substitute.put("calories", original.get("calories"));
+        substitute.put("method", "steamed");
+        substitute.put("processingWarning", "");
+        return substitute;
+    }
+
+    /** 取第一道非空菜卡提示(如 pairingAvoidHint),供返回体统一承载。 */
+    private static String firstDishHint(Map<String, Object> normalized, String key) {
+        for (Map<String, Object> dish : allDishes(normalized)) {
+            Object value = dish.get(key);
+            if (value != null && hasText(String.valueOf(value))) {
+                return String.valueOf(value);
+            }
+        }
+        return "";
+    }
+
+    /**
+     * [CR-07 §4.7-2] 返回体级加工建议:优先用 AI / 后台显式给的 processingWarning,
+     * 否则由 dish.method 推断通用加工效应(对应 food_processing_effect 的 food_id=NULL 兜底行)。
+     * 只在返回体给出,不改菜卡载荷的默认空串语义(§4.8 第2条)。
+     */
+    private static String firstProcessingWarning(Map<String, Object> normalized) {
+        for (Map<String, Object> dish : allDishes(normalized)) {
+            Object declaredValue = dish.get("processingWarning");
+            if (declaredValue != null && hasText(String.valueOf(declaredValue))) {
+                return String.valueOf(declaredValue);
+            }
+            String derived = defaultProcessingWarning(asString(dish.get("method")));
+            if (hasText(derived)) {
+                return derived;
+            }
+        }
+        return "";
+    }
+
+    /** 归一化菜单中所有菜品(含汤),用于提示收集与营养目标收敛。 */
+    @SuppressWarnings("unchecked")
+    private static List<Map<String, Object>> allDishes(Map<String, Object> normalized) {
+        List<Map<String, Object>> dishes = new ArrayList<>();
+        Object meals = normalized == null ? null : normalized.get("meals");
+        if (!(meals instanceof List)) {
+            return dishes;
+        }
+        for (Object meal : (List<?>) meals) {
+            if (!(meal instanceof Map)) {
+                continue;
+            }
+            Object items = ((Map<?, ?>) meal).get("dishes");
+            if (items instanceof List) {
+                for (Object item : (List<?>) items) {
+                    if (item instanceof Map) {
+                        dishes.add((Map<String, Object>) item);
+                    }
+                }
+            }
+        }
+        return dishes;
+    }
+
+    /** 从已校验的 nutrition_goals(Map 或 JSON 串)中读取单项数值,缺失返回 null。 */
+    private static Integer nutritionGoalValue(Object goalsObj, String key) {
+        Map<?, ?> goals;
+        if (goalsObj instanceof Map) {
+            goals = (Map<?, ?>) goalsObj;
+        } else {
+            String json = goalsObj == null ? null : String.valueOf(goalsObj);
+            if (!hasText(json) || "null".equals(json)) {
+                return null;
+            }
+            try {
+                goals = OBJECT_MAPPER.convertValue(OBJECT_MAPPER.readTree(json), Map.class);
+            } catch (Exception e) {
+                return null;
+            }
+        }
+        Object raw = goals == null ? null : goals.get(key);
+        if (raw instanceof Number) {
+            return ((Number) raw).intValue();
+        }
+        try {
+            return raw == null ? null : Integer.valueOf(String.valueOf(raw).trim());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+
+    /**
+     * [CR-07 §4.7-3] 营养目标组合优化:目标热量低于当前合计时,按目标/当前比例等比调整
+     * 每道菜的 calories 与宏量营养素(等价于按比例缩份)。只改营养值不增删菜品,
+     * 故 normalizeMenu 已保证的 D(N)+1 汤菜数硬约束不被破坏。
+     */
+    private static void optimizeForNutritionGoal(Map<String, Object> normalized, int calorieGoal) {
+        List<Map<String, Object>> dishes = allDishes(normalized);
+        long total = 0;
+        for (Map<String, Object> dish : dishes) {
+            total += asInt(dish.get("calories"));
+        }
+        if (total <= calorieGoal) {
+            return;
+        }
+        for (Map<String, Object> dish : dishes) {
+            scaleNutrient(dish, "calories", total, calorieGoal);
+            scaleNutrient(dish, "protein", total, calorieGoal);
+            scaleNutrient(dish, "carbs", total, calorieGoal);
+            scaleNutrient(dish, "fat", total, calorieGoal);
+        }
+    }
+
+    /** 按比例缩放单项营养素(向下取整,保证合计不超过目标)。 */
+    private static void scaleNutrient(Map<String, Object> dish, String key, long total, int target) {
+        Object raw = dish.get(key);
+        if (!(raw instanceof Number)) {
+            return;
+        }
+        long value = ((Number) raw).longValue();
+        if (value <= 0) {
+            return;
+        }
+        dish.put(key, (int) (value * target / total));
+    }
+
     /** 单道菜归一:兼容 AI 的 cooking_method/grams/nutrition 与前端落库的 method/amount/calories。 */
     private static Map<String, Object> toDish(JsonNode dishNode) {
         Map<String, Object> dish = new LinkedHashMap<>();
@@ -817,6 +1036,26 @@ public class DietRecommendationService {
         return dish;
     }
 
+    /**
+     * [diet.menu.pairingConstraint / CR-07 §4.7-2] 加工方式兜底建议(对应 food_processing_effect 中
+     * food_id=NULL 的通用行;AI/后台显式给的 processingWarning 优先)。蒸煮/生食等推荐方式不给提示。
+     */
+    private static String defaultProcessingWarning(String method) {
+        if (method == null) {
+            return "";
+        }
+        if ("deep_fried".equals(method) || "炸".equals(method)) {
+            return "油炸降低维生素 C 50%,建议改蒸煮";
+        }
+        if ("stir_fried".equals(method) || "炒".equals(method)) {
+            return "高温快炒使部分维生素 C 流失,建议多用蒸煮";
+        }
+        if ("roasted".equals(method) || "烤".equals(method)) {
+            return "高温烘烤易损失维生素,建议改蒸煮";
+        }
+        return "";
+    }
+
     /** 从 nutrition(或 dishNode 顶层)读取单个宏量营养素字段;缺失时置 0。 */
     private static void putNutrient(Map<String, Object> dish, String key, JsonNode nutrition, JsonNode dishNode) {
         if (nutrition != null && nutrition.has(key)) {