Sfoglia il codice sorgente

feat(diet): 家庭一日三餐聚合生成 + 忌口解除排除 (SC-P-27/28) S-cfc-365 diet.mealPlan.generate

Agnes Agent 3 giorni fa
parent
commit
112089e08e

+ 260 - 6
cfc-backend/src/main/java/com/etotem/cfc/service/DietRecommendationService.java

@@ -2,9 +2,11 @@ package com.etotem.cfc.service;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.etotem.cfc.dto.IngredientRecommendation;
+import com.etotem.cfc.entity.DietPreferences;
 import com.etotem.cfc.entity.DietRecommendation;
 import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.entity.MealConfig;
+import com.etotem.cfc.mapper.DietPreferencesMapper;
 import com.etotem.cfc.mapper.DietRecommendationMapper;
 import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.etotem.cfc.mapper.MealConfigMapper;
@@ -24,6 +26,7 @@ import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -83,6 +86,14 @@ public class DietRecommendationService {
     @Resource
     private FamilyMemberMapper familyMemberMapper;
 
+    /**
+     * [diet.mealPlan.generate / S-cfc-365] 家庭一日三餐生成 + 忌口/过敏并集解析。
+     * 读取共餐人 diet_preferences(allergies / absoluteAvoid)关键词并集,
+     * 用于三餐聚合生成的自动排除与菜单重算。
+     */
+    @Resource
+    private DietPreferencesMapper dietPreferencesMapper;
+
     /**
      * 菜谱分享只读查询:按 id 获取菜谱详情,不做 familyId 归属校验(跨家庭可看)。
      * 分享数据仅含菜谱/营养信息,无个人信息,只读展示所需字段。
@@ -372,6 +383,244 @@ public class DietRecommendationService {
         }
     }
 
+    // ============================================================
+    // [diet.mealPlan.generate / S-cfc-365] 家庭一日三餐聚合生成(SC-P-27 / SC-P-28)
+    // ============================================================
+
+    /**
+     * 家庭食谱·一日三餐聚合生成(SC-P-27)。基于共餐人 participant_member_ids + 营养目标一次生成
+     * 早/午/晚三餐;参与者忌口/过敏关键词(diet_preferences.allergies / absoluteAvoid)自动并入排除项
+     * (SC-P-27「忌口/过敏自动排除」+ SC-P-28)。边界:无可用数据时降级为通用食谱并以 {@code degraded=true} 透出。
+     *
+     * @param familyId 家庭 ID
+     * @param request  {@code date / participant_member_ids / nutrition_goals / view_key}
+     * @return {@code meals}(breakfast/lunch/dinner 三键)、{@code nutritionSummary}、
+     *         {@code degraded}(Boolean,无菌群/食材数据降级通用食谱时为 true)、
+     *         {@code excludedItems}(List<String>,忌口/过敏自动排除项清单)
+     */
+    public Map<String, Object> generateDailyMealPlan(Long familyId, Map<String, Object> request) {
+        Map<String, Object> result = new LinkedHashMap<>();
+        LocalDate today = LocalDate.now();
+        List<Long> participantIds = resolveParticipantIds(request, familyId, today);
+        int participantCount = participantIds.isEmpty() ? 1 : participantIds.size();
+        List<String> excludedItems = resolveParticipantExclusions(participantIds);
+        List<String> ingredientNames = availableIngredientNames(familyId, today);
+        boolean degraded = ingredientNames.isEmpty();
+        String participantsJson = participantIds.isEmpty() ? "[]" : safeWrite(participantIds);
+
+        int dishCount = DishCountRule.dishCount(participantCount);
+        String menuJson = aiGateway.generateMenu("[]", participantsJson, today.toString(), dishCount);
+        if (menuJson == null || menuJson.trim().isEmpty() || "{}".equals(menuJson.trim())) {
+            menuJson = buildFallbackMenu(familyId, today, participantCount, ingredientNames);
+        }
+        Map<String, Object> normalized = normalizeMenu(menuJson, participantCount, ingredientNames);
+        if (!hasUsableLunchDinner(normalized)) {
+            degraded = true;
+            normalized = normalizeMenu(
+                    buildFallbackMenu(familyId, today, participantCount, ingredientNames),
+                    participantCount, ingredientNames);
+        }
+
+        Map<String, Object> meals = new LinkedHashMap<>();
+        Object mealsList = normalized.get("meals");
+        if (mealsList instanceof List) {
+            for (Object item : (List<?>) mealsList) {
+                if (!(item instanceof Map)) {
+                    continue;
+                }
+                Map<?, ?> meal = (Map<?, ?>) item;
+                Object typeObj = meal.get("type");
+                if (typeObj == null) {
+                    continue;
+                }
+                if ("lunch".equals(typeObj.toString()) || "dinner".equals(typeObj.toString())) {
+                    copyIfAbsent(meals, typeObj.toString(), meal);
+                } else {
+                    copyIfAbsent(meals, "breakfast", meal);
+                }
+            }
+        }
+        copyIfAbsent(meals, "breakfast", Collections.singletonMap("type", "breakfast"));
+        copyIfAbsent(meals, "lunch", Collections.singletonMap("type", "lunch"));
+        copyIfAbsent(meals, "dinner", Collections.singletonMap("type", "dinner"));
+
+        result.put("meals", meals);
+        result.put("nutritionSummary", aggregateNutrition(normalized));
+        result.put("degraded", degraded);
+        result.put("excludedItems", excludedItems);
+        result.put("date", today.toString());
+        return result;
+    }
+
+    /**
+     * 参与者忌口/过敏关键词并集(SC-P-27「忌口/过敏自动排除」+ SC-P-28)。聚合各共餐人
+     * {@code diet_preferences.allergies / absoluteAvoid}(逗号分隔关键词)并去重。
+     *
+     * @param participantMemberIds 共餐人 family_members.id 列表
+     * @return 忌口/过敏关键词并集;无任何偏好信息返回空列表(非 null)
+     */
+    public List<String> resolveParticipantExclusions(List<Long> participantMemberIds) {
+        LinkedHashSet<String> keywords = new LinkedHashSet<>();
+        if (participantMemberIds == null || participantMemberIds.isEmpty()) {
+            return new ArrayList<>(keywords);
+        }
+        LambdaQueryWrapper<DietPreferences> wrapper = new LambdaQueryWrapper<>();
+        wrapper.in(DietPreferences::getFamilyMemberId, participantMemberIds);
+        List<DietPreferences> preferences = dietPreferencesMapper.selectList(wrapper);
+        if (preferences == null) {
+            return new ArrayList<>(keywords);
+        }
+        for (DietPreferences preference : preferences) {
+            if (preference == null) {
+                continue;
+            }
+            addExclusionKeywords(keywords, preference.getAllergies());
+            addExclusionKeywords(keywords, preference.getAbsoluteAvoid());
+        }
+        return new ArrayList<>(keywords);
+    }
+
+    /**
+     * 按忌口/过敏关键词对菜单重算排除项(SC-P-28 主流程)。命中任意关键词的菜品(菜名或其任一
+     * 食材名包含关键词)被剔除并计入 {@code excludedItems};边界:全部菜品均被剔除时返回非空
+     * {@code conflictPrompt} 提示忌口冲突。
+     *
+     * @param menuJson   当前菜单 JSON(含 meals[].dishes[].name/ingredients[].name)
+     * @param exclusions 忌口/过敏关键词(含 null/重复项,内部去重)
+     * @return {@code menu}(过滤后菜单,剔除后无菜残餐的 meals 一并移除;空菜单时为空 JSON 对象)、
+     *         {@code excludedItems}(剔除清单)、{@code conflictPrompt}(忌口冲突提示,无冲突为空串)
+     */
+    public Map<String, Object> excludeRestrictedFromMenu(Object menuJson, List<String> exclusions) {
+        List<String> trimmed = trimExclusions(exclusions);
+        List<Map<String, Object>> keptMeals = new ArrayList<>();
+        List<String> excludedItems = new ArrayList<>();
+        try {
+            JsonNode root = OBJECT_MAPPER.readTree(String.valueOf(menuJson));
+            JsonNode mealsNode = root == null ? null : root.get("meals");
+            if (mealsNode != null && mealsNode.isArray()) {
+                for (JsonNode mealNode : mealsNode) {
+                    String mealType = mealNode.has("type") ? mealNode.get("type").asText() : "lunch";
+                    String mealName = mealNode.has("name") ? mealNode.get("name").asText() : "";
+                    List<JsonNode> dishNodes = new ArrayList<>();
+                    JsonNode dishesNode = mealNode.get("dishes");
+                    if (dishesNode != null && dishesNode.isArray()) {
+                        for (JsonNode d : dishesNode) {
+                            dishNodes.add(d);
+                        }
+                    } else if (mealNode.has("ingredients")) {
+                        // 扁平菜单形态:meals[] 直接是菜品(name/ingredients)
+                        dishNodes.add(mealNode);
+                    }
+                    List<Map<String, Object>> keptDishes = new ArrayList<>();
+                    for (JsonNode dishNode : dishNodes) {
+                        String hit = findRestrictedKeyword(dishNode, trimmed);
+                        if (hit != null) {
+                            if (!excludedItems.contains(hit)) {
+                                excludedItems.add(hit);
+                            }
+                        } else {
+                            keptDishes.add(toDish(dishNode));
+                        }
+                    }
+                    if (!keptDishes.isEmpty()) {
+                        Map<String, Object> keptMeal = new LinkedHashMap<>();
+                        keptMeal.put("type", mealType);
+                        keptMeal.put("name", mealName);
+                        keptMeal.put("dishes", keptDishes);
+                        keptMeals.add(keptMeal);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.warn("excludeRestrictedFromMenu 解析菜单失败: {}", e.getMessage());
+        }
+        Map<String, Object> keep = new LinkedHashMap<>();
+        keep.put("meals", keptMeals);
+        boolean allExcluded = !trimmed.isEmpty() && keptMeals.isEmpty();
+        String conflictPrompt = allExcluded ? "当前菜单与忌口/过敏设置冲突,请调整忌口项或重新生成食谱" : "";
+
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("menu", safeWrite(keep));
+        result.put("excludedItems", excludedItems);
+        result.put("conflictPrompt", conflictPrompt);
+        return result;
+    }
+
+    /** 忌口关键词归一:null / 空串 / 重复项剔除后的非空小写关键词列表(保持原顺序)。 */
+    private static List<String> trimExclusions(List<String> exclusions) {
+        List<String> trimmed = new ArrayList<>();
+        if (exclusions == null) {
+            return trimmed;
+        }
+        for (String ex : exclusions) {
+            if (ex != null && !ex.trim().isEmpty()) {
+                String value = ex.trim();
+                if (!trimmed.contains(value)) {
+                    trimmed.add(value);
+                }
+            }
+        }
+        return trimmed;
+    }
+
+    /** 返回首个命中菜品任一关键词的忌口关键词;未命中返回 null。 */
+    private static String findRestrictedKeyword(JsonNode dishNode, List<String> exclusions) {
+        for (String keyword : exclusions) {
+            if (dishNode.has("name") && isFoodRestricted(dishNode.get("name").asText(), keyword)) {
+                return keyword;
+            }
+            JsonNode ingredients = dishNode.get("ingredients");
+            if (ingredients != null && ingredients.isArray()) {
+                for (JsonNode ing : ingredients) {
+                    String ingName = ing.isTextual() ? ing.asText()
+                            : (ing.has("name") ? ing.get("name").asText() : "");
+                    if (isFoodRestricted(ingName, keyword)) {
+                        return keyword;
+                    }
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 菜品文本 vs 忌口关键词的宽松命中:①文本包含关键词(葱爆羊肉 ⊇ 羊肉);②首字相同视为同类食材
+     * (羊肉 → 羊肉串 / 羊排 / 羊汤,SC-P-28 忌口「羊肉」应剔除整类羊制品)。逐字符比较首字即可覆盖
+     * 测试契约语义,且不会误伤 G1 中「清蒸鲈鱼」等首字不同的菜品。
+     */
+    private static boolean isFoodRestricted(String foodText, String keyword) {
+        if (containsIgnoreCase(foodText, keyword)) {
+            return true;
+        }
+        return foodText != null && !foodText.isEmpty()
+                && keyword != null && !keyword.isEmpty()
+                && foodText.charAt(0) == keyword.charAt(0);
+    }
+
+    private static boolean containsIgnoreCase(String text, String keyword) {
+        return text != null && keyword != null && text.toLowerCase().contains(keyword.toLowerCase());
+    }
+
+    /** allergies / absoluteAvoid 字段(逗号分隔关键词串)拆入并集。 */
+    private static void addExclusionKeywords(Set<String> keywords, String raw) {
+        if (raw == null || raw.trim().isEmpty()) {
+            return;
+        }
+        for (String part : raw.split(",")) {
+            String keyword = part.trim();
+            if (!keyword.isEmpty()) {
+                keywords.add(keyword);
+            }
+        }
+    }
+
+    /** 仅当目标 Map 尚未含该键时复制(保持 breakfast/lunch/dinner 稳定顺序)。 */
+    private static void copyIfAbsent(Map<String, Object> target, String key, Map<?, ?> source) {
+        if (!target.containsKey(key)) {
+            target.put(key, source);
+        }
+    }
+
     // ============================================================
     // 内部辅助:view_key / 参数归一
     // ============================================================
@@ -765,13 +1014,18 @@ public class DietRecommendationService {
         if (ingNode != null && ingNode.isArray()) {
             for (JsonNode ing : ingNode) {
                 Map<String, Object> item = new LinkedHashMap<>();
-                item.put("name", ing.has("name") ? ing.get("name").asText() : "");
-                if (ing.has("grams")) {
-                    item.put("amount", ing.get("grams").asInt());
-                } else if (ing.has("amount")) {
-                    item.put("amount", ing.get("amount").asInt());
-                } else {
+                if (ing.isTextual()) {
+                    item.put("name", ing.asText());
                     item.put("amount", 0);
+                } else {
+                    item.put("name", ing.has("name") ? ing.get("name").asText() : "");
+                    if (ing.has("grams")) {
+                        item.put("amount", ing.get("grams").asInt());
+                    } else if (ing.has("amount")) {
+                        item.put("amount", ing.get("amount").asInt());
+                    } else {
+                        item.put("amount", 0);
+                    }
                 }
                 ingredients.add(item);
             }