Răsfoiți Sursa

merge(task/S-cfc-365): 整合远端保留实现,Service 采用对齐设计版(degraded 注入 generateRecommendation + 逐餐复用 + 忌口过滤),13/13 契约测试绿(S-cfc-365 diet.mealPlan.generate)

- 保留远端 1dde9fb27 历史(Agnes 实现 + 0a40359c7 实测绿版)
- 冲突解析:Service 取远端对齐版(基于 cfclub 同源基底、纯增量 +368);Controller 路由与文档恢复 cfclub 版(本任务仅服务层契约范围)
- 终态相对 origin/cfclub 仅 1 个文件变更(DietRecommendationService.java +368)
Sisyphus Agent 2 zile în urmă
părinte
comite
0aaa44721e

+ 305 - 333
cfc-backend/src/main/java/com/etotem/cfc/service/DietRecommendationService.java

@@ -14,8 +14,6 @@ import com.etotem.cfc.mapper.MealConfigMapper;
 import com.etotem.cfc.util.ParamUtils;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 
@@ -89,6 +87,7 @@ public class DietRecommendationService {
     @Resource
     private FamilyMemberMapper familyMemberMapper;
 
+    /** 参与者忌口 / 过敏偏好(diet.mealPlan.generate 的排除项唯一数据源,SC-P-27 / SC-P-28)。 */
     @Resource
     private DietPreferencesMapper dietPreferencesMapper;
 
@@ -213,8 +212,11 @@ public class DietRecommendationService {
 
         // 4. AI 失败 / 熔断 / 超时 → 规则降级(同菜数规则造 D(N)+1 道)
         List<String> ingredientNames = availableIngredientNames(familyId, date);
+        // degraded:该餐是否走「规则降级通用食谱」,供一日三餐聚合(diet.mealPlan.generate)透出降级标志
+        boolean degraded = false;
         if (menuJson == null || menuJson.trim().isEmpty() || "{}".equals(menuJson.trim())) {
             menuJson = buildFallbackMenu(familyId, date, participantCount, ingredientNames);
+            degraded = true;
         }
 
         // 5. 归一化(唯一硬保证点)+ 聚合营养
@@ -229,6 +231,7 @@ public class DietRecommendationService {
             normalized = normalizeMenu(
                     buildFallbackMenu(familyId, date, participantCount, ingredientNames),
                     participantCount, ingredientNames);
+            degraded = true;
         }
         String normalizedMenuJson = safeWrite(normalized);
         Map<String, Object> nutritionSummary = aggregateNutrition(normalized);
@@ -261,6 +264,7 @@ public class DietRecommendationService {
             result.put("nutritionSummary", existRecord.getNutritionSummary());
             result.put("participantCount", participantCount);
             result.put("dishCount", dishCount);
+            result.put("degraded", degraded);
             result.put("message", "食谱推荐已更新");
             return result;
         }
@@ -382,392 +386,151 @@ public class DietRecommendationService {
     }
 
     // ============================================================
-    // 家庭食谱·一日三餐聚合生成([diet.mealPlan.generate] SC-P-27 / SC-P-28)
+    // 一日三餐聚合生成(diet.mealPlan.generate / SC-P-27 / SC-P-28)
     // ============================================================
 
     /**
-     * 一日三餐聚合生成(SC-P-27 家庭食谱生成)。
+     * 一日三餐聚合生成(diet.mealPlan.generate / SC-P-27 家庭食谱生成)。
      *
-     * <p>request 与 {@code /api/diet/recommendation/generate} 同载荷:
-     * {@code date / participant_member_ids / nutrition_goals / view_key}。</p>
+     * <p>一次生成早 / 午 / 晚三餐:逐餐复用 {@link #generateRecommendation} 全链路
+     * (AI → 规则降级 → 归一化 → 幂等落库),再按共餐人忌口/过敏并集
+     * {@link #resolveParticipantExclusions} 统一重算排除项 {@link #excludeRestrictedFromMenu},
+     * 三餐共用同一排除集,避免逐餐口径漂移。</p>
      *
-     * <p>返回 Map 契约字段:</p>
-     * <ul>
-     *   <li>{@code meals} —— Map(键 {@code breakfast / lunch / dinner} 三顿,各含 dishes 等菜单结构)</li>
-     *   <li>{@code nutritionSummary} —— 三餐聚合营养汇总</li>
-     *   <li>{@code degraded} —— Boolean:无 AI / 无报告时降级通用食谱的标志(任一顿降级即 true)</li>
-     *   <li>{@code excludedItems} —— List&lt;String&gt;:参与者忌口/过敏自动排除项清单(SC-P-27「忌口/过敏自动排除」)</li>
-     * </ul>
+     * <p><b>边界(SC-P-27)</b>:AI 不可用 / 无菌群报告数据 → 规则降级通用食谱,
+     * 以 {@code degraded=true} 透出;忌口/过敏命中的菜品自动剔除并以 {@code excludedItems}
+     * 清单透出(SC-P-27「忌口/过敏自动排除」+ SC-P-28「设忌口 → 食谱重算排除项」)。</p>
      *
      * @param familyId 家庭 ID
-     * @param request  生成载荷
+     * @param request  {@code date / participant_member_ids / selected_foods / nutrition_goals / view_key},
+     *                 载荷口径同 §4.11 {@code /api/diet/recommendation/generate}
+     * @return {@code meals(breakfast/lunch/dinner) + nutritionSummary + degraded + excludedItems};
+     *         发生忌口冲突时另附 {@code conflictPrompt}
      */
     public Map<String, Object> generateDailyMealPlan(Long familyId, Map<String, Object> request) {
-        if (request == null) {
-            request = new HashMap<>();
-        }
-        // 营养目标校验与单餐次生成同规则(teacher.nutrition.plan / SC-T-26)
-        validateNutritionGoals(request.get("nutrition_goals"));
+        Map<String, Object> source = request == null ? Collections.<String, Object>emptyMap() : request;
 
-        String dateStr = asString(request.get("date"));
+        String dateStr = asString(source.get("date"));
         if (!hasText(dateStr)) {
             dateStr = LocalDate.now().toString();
         }
         LocalDate date = LocalDate.parse(dateStr);
+        String viewKey = asString(source.get("view_key"));
 
-        List<Long> participantIds = resolveParticipantIds(request, familyId, date);
-        int participantCount = participantIds.isEmpty() ? 1 : participantIds.size();
-        List<String> ingredientNames = availableIngredientNames(familyId, date);
+        // 共餐人:优先载荷 participant_member_ids(字符串 / 数组双形态),为空才回落 meal_config / 家庭成员
+        List<Long> participantIds = asIds(source.get("participant_member_ids"));
+        if (participantIds.isEmpty()) {
+            participantIds = resolveParticipantIds(source, familyId, date);
+        }
+        Collections.sort(participantIds);
+        String participantsJson = safeWrite(participantIds);
 
-        // 忌口/过敏自动排除(SC-P-27 / SC-P-28):各参与者 allergies / absoluteAvoid 关键词并集
+        // 忌口/过敏并集(SC-P-27「忌口/过敏自动排除」+ SC-P-28)
         List<String> exclusions = resolveParticipantExclusions(participantIds);
 
         Map<String, Object> meals = new LinkedHashMap<>();
+        Map<String, Object> nutritionSummary = new LinkedHashMap<>();
+        nutritionSummary.put("calories", 0);
+        nutritionSummary.put("protein", 0);
+        nutritionSummary.put("carbs", 0);
+        nutritionSummary.put("fat", 0);
         boolean degraded = false;
+        String conflictPrompt = "";
+
         for (String mealType : Arrays.asList("breakfast", "lunch", "dinner")) {
-            Map<String, Object> meal = generateDailyMeal(mealType, familyId, date, participantIds,
-                    ingredientNames, participantCount);
-            boolean mealDegraded = Boolean.TRUE.equals(meal.remove("_degraded"));
-            degraded |= mealDegraded;
-            meals.put(mealType, meal);
+            Map<String, Object> single = new HashMap<>();
+            single.put("date", dateStr);
+            single.put("meal_type", mealType);
+            single.put("selected_foods", source.get("selected_foods"));
+            single.put("participant_member_ids", participantsJson);
+            single.put("nutrition_goals", source.get("nutrition_goals"));
+            single.put("view_key", viewKey);
+
+            Map<String, Object> generated = generateRecommendation(familyId, single);
+            degraded = degraded || Boolean.TRUE.equals(generated.get("degraded"));
+
+            Map<String, Object> filtered =
+                    excludeRestrictedFromMenu(asString(generated.get("menu")), exclusions);
+            meals.put(mealType, filtered.get("menu"));
+            collectNutrition(filtered.get("menu"), nutritionSummary, 0);
+
+            Object prompt = filtered.get("conflictPrompt");
+            String text = prompt == null ? "" : String.valueOf(prompt);
+            if (hasText(text)) {
+                conflictPrompt = text;
+            }
         }
 
-        Map<String, Object> summaryInput = new LinkedHashMap<>();
-        List<Map<String, Object>> summaryMeals = new ArrayList<>();
-        summaryMeals.add((Map<String, Object>) meals.get("breakfast"));
-        summaryMeals.add((Map<String, Object>) meals.get("lunch"));
-        summaryMeals.add((Map<String, Object>) meals.get("dinner"));
-        summaryInput.put("meals", summaryMeals);
-
         Map<String, Object> result = new LinkedHashMap<>();
         result.put("meals", meals);
-        result.put("nutritionSummary", aggregateNutrition(summaryInput));
+        result.put("nutritionSummary", nutritionSummary);
         result.put("degraded", degraded);
         result.put("excludedItems", exclusions);
+        if (hasText(conflictPrompt)) {
+            result.put("conflictPrompt", conflictPrompt);
+        }
+        result.put("participantCount", participantIds.isEmpty() ? 1 : participantIds.size());
+        result.put("date", dateStr);
         return result;
     }
 
     /**
-     * 参与者忌口/过敏关键词并集(SC-P-28「设忌口/过敏」数据源)。
+     * 参与者忌口 / 过敏关键词并集(diet.mealPlan.generate / SC-P-27 + SC-P-28)。
      *
-     * <p>来源 {@code diet_preferences.allergies / absoluteAvoid}(实体 {@link DietPreferences}),
-     * 兼容 JSON 数组(生产存量)与逗号/顿号分隔字符串(历史录入)两种形态,结果去重保序。</p>
+     * <p>来源 {@code diet_preferences.allergies / absoluteAvoid}:共餐人里任一成员有忌口,
+     * 全员食谱都要排除(过敏不过「只有一人不吃」的折中)。关键词按分隔符切分去空、保持首次出现顺序。</p>
      *
-     * @param participantMemberIds 共餐人成员 ID 列表
-     * @return 关键词并集(空列表=无忌口/过敏)
+     * @param participantMemberIds 共餐成员 ID(family_members.id)
+     * @return 忌口/过敏关键词并集;无成员或无记录时返回空列表(不抛异常)
      */
     public List<String> resolveParticipantExclusions(List<Long> participantMemberIds) {
         Set<String> union = new LinkedHashSet<>();
         if (participantMemberIds == null || participantMemberIds.isEmpty()) {
             return new ArrayList<>(union);
         }
-        // 单元测试无 Spring / MyBatis-Plus 运行时元数据,Lambda SFunction 无法解析列名 →
-        // 用字符串列名 QueryWrapper(列名与 schema.sql 的 diet_preferences 保持一致)
-        QueryWrapper<DietPreferences> wrapper = new QueryWrapper<>();
-        wrapper.in("family_member_id", participantMemberIds);
-        List<DietPreferences> prefsList = null;
         try {
-            prefsList = dietPreferencesMapper.selectList(wrapper);
-        } catch (Exception e) {
-            log.warn("查询参与者饮食偏好失败: {}", e.getMessage());
-        }
-        if (prefsList != null) {
-            for (DietPreferences prefs : prefsList) {
-                if (prefs == null) {
-                    continue;
+            // 用列名 QueryWrapper 而非 LambdaQueryWrapper:SFunction 依赖 MyBatis-Plus 的
+            // Lambda 缓存,脱离 Spring/MP 容器(纯契约单测)时无法解析列名;此处列名稳定,代价可控。
+            QueryWrapper<DietPreferences> wrapper = new QueryWrapper<>();
+            wrapper.in("family_member_id", participantMemberIds);
+            List<DietPreferences> prefs = dietPreferencesMapper.selectList(wrapper);
+            if (prefs != null) {
+                for (DietPreferences pref : prefs) {
+                    if (pref == null) {
+                        continue;
+                    }
+                    union.addAll(splitKeywords(pref.getAllergies()));
+                    union.addAll(splitKeywords(pref.getAbsoluteAvoid()));
                 }
-                union.addAll(parsePreferenceKeywords(prefs.getAllergies()));
-                union.addAll(parsePreferenceKeywords(prefs.getAbsoluteAvoid()));
             }
+        } catch (Exception e) {
+            log.warn("读取参与者忌口/过敏失败,按无排除项处理: {}", e.getMessage());
         }
         return new ArrayList<>(union);
     }
 
     /**
-     * 按忌口重算排除项(SC-P-28 主流程)。
+     * 按忌口重算排除项(diet.mealPlan.generate / SC-P-28「设忌口/过敏 → 食谱重算排除项」)。
      *
-     * <p>对现有菜单(JSON 字符串或 Map)逐菜校验:菜名或任一生鲜食材命中忌口关键词即剔除,
-     * 并透出剔除清单。菜单形如 {@code {meals:[...]}},兼容两层结构:meals 元素即菜
-     * ({@code name/ingredients}),或 meals 元素为餐次组(内含 {@code dishes} 数组)。</p>
+     * <p>兼容两种菜单形态:{@code {"meals":[{name, ingredients}]}}(meals 元素即单道菜,前端直传)
+     * 与 {@code {"meals":[{type, dishes:[...]}]}}(归一化后落库形态,逐道过滤 dishes)。
+     * 忌口命中按「菜品名 + 食材名」子串匹配,命中的忌口关键词写入 {@code excludedItems}。</p>
      *
-     * @param menuJson   现有菜单(JSON 字符串或 Map)
-     * @param exclusions 忌口/过敏关键词
-     * @return Map 含 {@code menu}(过滤后菜单 JSON)、{@code excludedItems}(命中剔除清单)、
-     *         {@code conflictPrompt}(全部菜品均命中忌口时给出提示,无冲突为空串)
+     * @param menuJson 菜单(JSON 字符串 / 已解析 Map),null / 非法 JSON 视为空菜单
+     * @param exclusions 忌口/过敏关键词({@link #resolveParticipantExclusions} 的并集)
+     * @return {@code {menu, excludedItems, conflictPrompt}};无冲突时 conflictPrompt 为空串
      */
     public Map<String, Object> excludeRestrictedFromMenu(Object menuJson, List<String> exclusions) {
-        Map<String, Object> result = new LinkedHashMap<>();
-        List<String> hitExclusions = new ArrayList<>();
-        List<String> cleanExclusions = new ArrayList<>();
-        if (exclusions != null) {
-            for (String e : exclusions) {
-                if (hasText(e) && !cleanExclusions.contains(e.trim())) {
-                    cleanExclusions.add(e.trim());
-                }
-            }
-        }
-        if (cleanExclusions.isEmpty()) {
-            result.put("menu", menuJson);
-            result.put("excludedItems", hitExclusions);
-            result.put("conflictPrompt", "");
-            return result;
-        }
-
-        try {
-            JsonNode root = toJsonNode(menuJson);
-            if (root == null || !root.isObject()) {
-                throw new IllegalArgumentException("menu格式非法");
-            }
-            ObjectNode out = (ObjectNode) root.deepCopy();
-            JsonNode mealsNode = root.get("meals");
-            if (mealsNode != null && mealsNode.isArray()) {
-                // 形状判定:任一元素含非空 dishes 数组 → 餐次组结构;否则元素本身即菜
-                boolean groupShape = false;
-                for (JsonNode meal : mealsNode) {
-                    JsonNode dishes = meal.get("dishes");
-                    if (dishes != null && dishes.isArray() && dishes.size() > 0) {
-                        groupShape = true;
-                        break;
-                    }
-                }
-                if (groupShape) {
-                    filterMealGroups(mealsNode, out, cleanExclusions, hitExclusions);
-                } else {
-                    filterDishList(mealsNode, out, cleanExclusions, hitExclusions);
-                }
-            }
-            boolean allRemoved = mealsNode != null && mealsNode.isArray()
-                    && mealsNode.size() > 0 && out.get("meals").size() == 0;
-            if (allRemoved && !hitExclusions.isEmpty()) {
-                result.put("conflictPrompt", "忌口冲突:全部菜品均命中忌口("
-                        + String.join("、", hitExclusions) + "),请调整忌口或更换菜单");
-            } else {
-                result.put("conflictPrompt", "");
-            }
-            result.put("menu", safeWrite(out));
-            result.put("excludedItems", hitExclusions);
-        } catch (Exception e) {
-            log.warn("按忌口重算排除项失败: {}", e.getMessage());
-            result.put("menu", menuJson);
-            result.put("excludedItems", hitExclusions);
-            result.put("conflictPrompt", "");
-        }
-        return result;
-    }
+        Set<String> hitKeywords = new LinkedHashSet<>();
+        Object filtered = filterRestrictedMenu(menuJson, exclusions, hitKeywords);
 
-    /**
-     * 餐次组结构(meals[].dishes[])过滤:剔除命中忌口的菜,保留其它字段与未命中菜。
-     */
-    private void filterMealGroups(JsonNode mealsNode, ObjectNode out, List<String> exclusions,
-                                  List<String> hitExclusions) {
-        ArrayNode filteredMeals = OBJECT_MAPPER.createArrayNode();
-        for (JsonNode mealNode : mealsNode) {
-            JsonNode dishesNode = mealNode.get("dishes");
-            ObjectNode mealCopy = mealNode.isObject()
-                    ? (ObjectNode) mealNode.deepCopy() : OBJECT_MAPPER.createObjectNode();
-            if (dishesNode != null && dishesNode.isArray()) {
-                ArrayNode filteredDishes = OBJECT_MAPPER.createArrayNode();
-                for (JsonNode dish : dishesNode) {
-                    String hit = matchExclusion(dish, exclusions);
-                    if (hit != null) {
-                        if (!hitExclusions.contains(hit)) {
-                            hitExclusions.add(hit);
-                        }
-                    } else {
-                        filteredDishes.add(dish);
-                    }
-                }
-                mealCopy.set("dishes", filteredDishes);
-            }
-            filteredMeals.add(mealCopy);
-        }
-        out.set("meals", filteredMeals);
-    }
-
-    /**
-     * 菜平铺结构(meals[] 即菜)过滤:剔除命中忌口的菜。
-     */
-    private void filterDishList(JsonNode mealsNode, ObjectNode out, List<String> exclusions,
-                                List<String> hitExclusions) {
-        ArrayNode filteredMeals = OBJECT_MAPPER.createArrayNode();
-        for (JsonNode dish : mealsNode) {
-            String hit = matchExclusion(dish, exclusions);
-            if (hit != null) {
-                if (!hitExclusions.contains(hit)) {
-                    hitExclusions.add(hit);
-                }
-            } else {
-                filteredMeals.add(dish);
-            }
-        }
-        out.set("meals", filteredMeals);
-    }
-
-    /**
-     * 单菜忌口命中判定:命中面 = 菜名 + 各食材名(字符串或 {@code {name}} 对象)。
-     *
-     * @return 命中的忌口关键词;未命中返回 null
-     */
-    private static String matchExclusion(JsonNode dish, List<String> exclusions) {
-        List<String> haystacks = new ArrayList<>();
-        if (dish.has("name")) {
-            haystacks.add(dish.get("name").asText());
-        }
-        JsonNode ingredients = dish.get("ingredients");
-        if (ingredients != null && ingredients.isArray()) {
-            for (JsonNode ing : ingredients) {
-                if (ing.isTextual()) {
-                    haystacks.add(ing.asText());
-                } else if (ing.has("name")) {
-                    haystacks.add(ing.get("name").asText());
-                }
-            }
-        }
-        for (String exclusion : exclusions) {
-            for (String haystack : haystacks) {
-                if (exclusionMatches(haystack, exclusion)) {
-                    return exclusion;
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * 忌口关键词 vs 食材命中规则(SC-P-28):
-     * <ol>
-     *   <li>子串命中(双向):食材含忌口词(如 羊肉串 含 羊肉),或忌口词含食材(宽口径);</li>
-     *   <li>中文食材类目兜底:同「类目首字」视为同类命中(如 忌口 羊肉 → 羊肉串/羊排 均剔除),
-     *       仅长度≥2 的实义词生效,避免单字过度命中(如「花」)。</li>
-     * </ol>
-     */
-    private static boolean exclusionMatches(String haystack, String exclusion) {
-        if (haystack == null || exclusion == null) {
-            return false;
-        }
-        String h = haystack.trim();
-        String e = exclusion.trim();
-        if (h.isEmpty() || e.isEmpty()) {
-            return false;
-        }
-        if (h.contains(e) || e.contains(h)) {
-            return true;
-        }
-        return h.length() >= 2 && e.length() >= 2 && h.charAt(0) == e.charAt(0);
-    }
-
-    /**
-     * 菜单入参归一:JSON 字符串 → JsonNode;Map/List → valueToTree。
-     */
-    private static JsonNode toJsonNode(Object obj) throws Exception {
-        if (obj == null) {
-            return null;
-        }
-        if (obj instanceof String) {
-            String s = ((String) obj).trim();
-            return hasText(s) ? OBJECT_MAPPER.readTree(s) : null;
-        }
-        return OBJECT_MAPPER.valueToTree(obj);
-    }
-
-    /**
-     * 偏好关键词解析(兼容 JSON 数组与逗号/顿号分隔字符串双形态)。
-     */
-    private static List<String> parsePreferenceKeywords(String raw) {
-        List<String> result = new ArrayList<>();
-        if (!hasText(raw)) {
-            return result;
-        }
-        try {
-            JsonNode node = OBJECT_MAPPER.readTree(raw.trim());
-            if (node != null && node.isArray()) {
-                for (JsonNode item : node) {
-                    String t = item.isTextual() ? item.asText().trim() : "";
-                    if (!t.isEmpty() && !result.contains(t)) {
-                        result.add(t);
-                    }
-                }
-                return result;
-            }
-        } catch (Exception ignore) {
-            // 非 JSON 数组(如逗号分隔 "花生,海鲜")→ 走分隔符拆分
-        }
-        for (String t : raw.split("[,,、/\\s]+")) {
-            String s = t.trim();
-            if (!s.isEmpty() && !result.contains(s)) {
-                result.add(s);
-            }
-        }
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("menu", filtered);
+        result.put("excludedItems", new ArrayList<>(hitKeywords));
+        result.put("conflictPrompt", buildConflictPrompt(filtered, hitKeywords));
         return result;
     }
 
-    /**
-     * 生成单顿餐(AI 正常 → 失败/空输出降级通用 → 归一化),内部以 {@code _degraded} 键透出降级标志。
-     */
-    private Map<String, Object> generateDailyMeal(String mealType, Long familyId, LocalDate date,
-                                                  List<Long> participantIds, List<String> ingredientNames, int n) {
-        int dishCount = DishCountRule.dishCount(n);
-        String participantsJson = safeWrite(participantIds);
-        boolean degraded = false;
-
-        // 优先 AI:失败 / 熔断 / 空输出 → 规则降级(与单餐次 generateRecommendation 同约束,绝不整份重试 AI)
-        String menuJson = aiGateway.generateMenu("[]", participantsJson, date.toString(), dishCount);
-        if (menuJson == null || menuJson.trim().isEmpty() || "{}".equals(menuJson.trim())) {
-            degraded = true;
-            menuJson = buildFallbackMenu(familyId, date, n, ingredientNames);
-        }
-
-        Map<String, Object> normalized = normalizeMenu(menuJson, n, ingredientNames);
-        Map<String, Object> meal = extractMeal(normalized, mealType);
-        if (!hasAnyDish(meal)) {
-            // AI 给了可用 JSON 但缺本餐次菜(如 {"meals":[]})→ 复用规则降级
-            degraded = true;
-            normalized = normalizeMenu(buildFallbackMenu(familyId, date, n, ingredientNames), n, ingredientNames);
-            meal = extractMeal(normalized, mealType);
-        }
-        if (meal == null) {
-            Map<String, Object> empty = new LinkedHashMap<>();
-            empty.put("type", mealType);
-            empty.put("name", "");
-            empty.put("participants", n);
-            empty.put("dishes", new ArrayList<Object>());
-            empty.put("_degraded", degraded);
-            return empty;
-        }
-        meal.put("_degraded", degraded);
-        return meal;
-    }
-
-    /** 从归一化菜单中按 type 抽取指定餐次(未命中返回 null)。 */
-    private static Map<String, Object> extractMeal(Map<String, Object> normalized, String mealType) {
-        Object mealsObj = normalized.get("meals");
-        if (mealsObj instanceof List) {
-            for (Object item : (List<?>) mealsObj) {
-                if (item instanceof Map) {
-                    Map<?, ?> m = (Map<?, ?>) item;
-                    if (mealType.equals(m.get("type"))) {
-                        Map<String, Object> copy = new LinkedHashMap<>();
-                        copy.put("type", m.get("type"));
-                        copy.put("name", m.get("name"));
-                        copy.put("participants", m.get("participants"));
-                        copy.put("dishes", m.get("dishes"));
-                        return copy;
-                    }
-                }
-            }
-        }
-        return null;
-    }
-
-    /** 餐次是否至少含 1 道菜(null / 空 dishes 视为不可用)。 */
-    private static boolean hasAnyDish(Map<String, Object> meal) {
-        if (meal == null) {
-            return false;
-        }
-        Object dishes = meal.get("dishes");
-        return dishes instanceof List && !((List<?>) dishes).isEmpty();
-    }
-
     // ============================================================
     // 内部辅助:view_key / 参数归一
     // ============================================================
@@ -1306,6 +1069,215 @@ public class DietRecommendationService {
         }
     }
 
+    // ============================================================
+    // 内部辅助:忌口过滤 / 排除清单(diet.mealPlan.generate)
+    // ============================================================
+
+    /** 忌口 / 过敏关键词切分:兼容中英文逗号、顿号、分号、斜杠与空白分隔。 */
+    private static List<String> splitKeywords(String raw) {
+        List<String> keys = new ArrayList<>();
+        if (!hasText(raw)) {
+            return keys;
+        }
+        for (String part : raw.split("[,,、;;/\\s]+")) {
+            if (hasText(part) && !keys.contains(part.trim())) {
+                keys.add(part.trim());
+            }
+        }
+        return keys;
+    }
+
+    /**
+     * 忌口命中判定:菜品名 + 食材名任一包含忌口关键词即命中(子串匹配,中文无需大小写归一)。
+     * 命中的忌口关键词写入 {@code hitKeywords}(供 excludedItems 透出)。
+     */
+    private static boolean isRestricted(Map<?, ?> dish, List<String> exclusions, Set<String> hitKeywords) {
+        if (exclusions == null || exclusions.isEmpty()) {
+            return false;
+        }
+        List<String> texts = collectTexts(dish);
+        for (String keyword : exclusions) {
+            if (!hasText(keyword)) {
+                continue;
+            }
+            String key = keyword.trim();
+            for (String text : texts) {
+                if (text.contains(key)) {
+                    hitKeywords.add(key);
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    /** 收集菜品的可匹配文本:菜名 + 各食材名(兼容 Map 形态与字符串数组形态的 ingredients)。 */
+    private static List<String> collectTexts(Map<?, ?> dish) {
+        List<String> texts = new ArrayList<>();
+        Object name = dish.get("name");
+        if (name != null && hasText(String.valueOf(name))) {
+            texts.add(String.valueOf(name));
+        }
+        Object ingredients = dish.get("ingredients");
+        if (ingredients instanceof List) {
+            for (Object item : (List<?>) ingredients) {
+                String value;
+                if (item instanceof Map) {
+                    Object ingName = ((Map<?, ?>) item).get("name");
+                    value = ingName == null ? "" : String.valueOf(ingName);
+                } else {
+                    value = item == null ? "" : String.valueOf(item);
+                }
+                if (hasText(value) && !texts.contains(value)) {
+                    texts.add(value);
+                }
+            }
+        }
+        return texts;
+    }
+
+    /**
+     * 忌口过滤(两种菜单形态同收口):
+     * {@code {"meals":[{type,dishes:[...]}]}} 归一化落库形态逐道过滤 dishes 并保留餐结构;
+     * {@code {"meals":[{name,ingredients}]}} 前端直传形态下 meals 元素即单道菜,整条剔除。
+     * 菜单为 null / 非法 JSON 时返回空菜单 —— 保守起见不把未过滤原文透出(忌口菜可能就在其中)。
+     */
+    private Object filterRestrictedMenu(Object menuJson, List<String> exclusions, Set<String> hitKeywords) {
+        Map<String, Object> root;
+        if (menuJson == null) {
+            return emptyMenu();
+        }
+        if (menuJson instanceof Map) {
+            root = copyMap((Map<?, ?>) menuJson);
+        } else {
+            try {
+                JsonNode node = OBJECT_MAPPER.readTree(String.valueOf(menuJson));
+                root = toMap(node);
+            } catch (Exception e) {
+                return emptyMenu();
+            }
+        }
+
+        Object mealsObj = root.get("meals");
+        if (!(mealsObj instanceof List)) {
+            return root;
+        }
+        List<Object> keptMeals = new ArrayList<>();
+        for (Object item : (List<?>) mealsObj) {
+            if (!(item instanceof Map)) {
+                continue;
+            }
+            Map<?, ?> meal = (Map<?, ?>) item;
+            if (meal.get("dishes") instanceof List) {
+                Map<String, Object> keptMeal = copyMap(meal);
+                List<Object> keptDishes = new ArrayList<>();
+                for (Object dish : (List<?>) meal.get("dishes")) {
+                    if (dish instanceof Map && !isRestricted((Map<?, ?>) dish, exclusions, hitKeywords)) {
+                        keptDishes.add(dish);
+                    }
+                }
+                keptMeal.put("dishes", keptDishes);
+                keptMeals.add(keptMeal);
+            } else if (!isRestricted(meal, exclusions, hitKeywords)) {
+                keptMeals.add(meal);
+            }
+        }
+        Map<String, Object> out = new LinkedHashMap<>(root);
+        out.put("meals", keptMeals);
+        return out;
+    }
+
+    /** 忌口冲突提示(SC-P-28 边界):无冲突空串;全被剔除给出强提示;部分剔除告知已排除项。 */
+    private static String buildConflictPrompt(Object filtered, Set<String> hitKeywords) {
+        if (hitKeywords.isEmpty()) {
+            return "";
+        }
+        String keys = String.join("、", hitKeywords);
+        if (isMenuEmpty(filtered)) {
+            return "全部菜品均命中忌口(" + keys + "),暂无可选菜品,请调整忌口设置或更换食材后重新生成";
+        }
+        return "已按忌口自动剔除(" + keys + "),相关菜品已从菜单移除,请确认剩余菜品是否满足全家需求";
+    }
+
+    /** 菜单是否已无可食菜品:meals 为空,或所有餐的 dishes 为空且无「元素即菜」的保留项。 */
+    private static boolean isMenuEmpty(Object filtered) {
+        if (!(filtered instanceof Map)) {
+            return true;
+        }
+        Object mealsObj = ((Map<?, ?>) filtered).get("meals");
+        if (!(mealsObj instanceof List) || ((List<?>) mealsObj).isEmpty()) {
+            return true;
+        }
+        for (Object item : (List<?>) mealsObj) {
+            if (!(item instanceof Map)) {
+                continue;
+            }
+            Map<?, ?> meal = (Map<?, ?>) item;
+            Object dishes = meal.get("dishes");
+            if (dishes instanceof List && !((List<?>) dishes).isEmpty()) {
+                return false;
+            }
+            Object name = meal.get("name");
+            if (name != null && hasText(String.valueOf(name))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /** 空菜单骨架(与归一化输出同构,前端可直接渲染空态)。 */
+    private static Map<String, Object> emptyMenu() {
+        Map<String, Object> empty = new LinkedHashMap<>();
+        empty.put("meals", new ArrayList<Object>());
+        return empty;
+    }
+
+    /** Map 浅拷贝并统一 key 为 String(JsonNode / 泛型 Map 转换后保持可写结构)。 */
+    private static Map<String, Object> copyMap(Map<?, ?> source) {
+        Map<String, Object> copy = new LinkedHashMap<>();
+        if (source != null) {
+            for (Map.Entry<?, ?> entry : source.entrySet()) {
+                copy.put(String.valueOf(entry.getKey()), entry.getValue());
+            }
+        }
+        return copy;
+    }
+
+    /** JsonNode → Map(Jackson 自带转换,保持字段原值,无需二次归一化)。 */
+    @SuppressWarnings("unchecked")
+    private static Map<String, Object> toMap(JsonNode node) {
+        Map<String, Object> map = OBJECT_MAPPER.convertValue(node, Map.class);
+        return map == null ? new LinkedHashMap<>() : map;
+    }
+
+    /**
+     * 三餐营养汇总:递归收集菜品级 calories / 宏量营养素,兼容「meals→dishes」与「meals 元素即菜」两形态。
+     * 深度上限 6,避免异常自引用结构导致死循环。
+     */
+    private static void collectNutrition(Object node, Map<String, Object> summary, int depth) {
+        if (node == null || depth > 6) {
+            return;
+        }
+        if (node instanceof List) {
+            for (Object item : (List<?>) node) {
+                collectNutrition(item, summary, depth + 1);
+            }
+            return;
+        }
+        if (!(node instanceof Map)) {
+            return;
+        }
+        Map<?, ?> map = (Map<?, ?>) node;
+        if (map.containsKey("calories") || map.containsKey("protein")
+                || map.containsKey("carbs") || map.containsKey("fat")) {
+            for (String key : Arrays.asList("calories", "protein", "carbs", "fat")) {
+                summary.put(key, asInt(summary.get(key)) + asInt(map.get(key)));
+            }
+        }
+        collectNutrition(map.get("dishes"), summary, depth + 1);
+        collectNutrition(map.get("meals"), summary, depth + 1);
+    }
+
     /**
      * 菜数规则唯一常量源(CR-C / D3·D4)。
      * 仅 lunch/dinner 适用;N<=0 兜底 1;D(N)=4+max(0,N-3);汤恒 1 且不计入菜数。