Ver código fonte

feat(S-cfc-365): diet.mealPlan.generate contract — generateDailyMealPlan / resolveParticipantExclusions / excludeRestrictedFromMenu

Sisyphus Agent 1 dia atrás
pai
commit
47a8bc30a6

+ 396 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/DietRecommendationService.java

@@ -1,16 +1,21 @@
 package com.etotem.cfc.service;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 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;
 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;
 
@@ -24,6 +29,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 +89,9 @@ public class DietRecommendationService {
     @Resource
     private FamilyMemberMapper familyMemberMapper;
 
+    @Resource
+    private DietPreferencesMapper dietPreferencesMapper;
+
     /**
      * 菜谱分享只读查询:按 id 获取菜谱详情,不做 familyId 归属校验(跨家庭可看)。
      * 分享数据仅含菜谱/营养信息,无个人信息,只读展示所需字段。
@@ -372,6 +381,393 @@ public class DietRecommendationService {
         }
     }
 
+    // ============================================================
+    // 家庭食谱·一日三餐聚合生成([diet.mealPlan.generate] SC-P-27 / SC-P-28)
+    // ============================================================
+
+    /**
+     * 一日三餐聚合生成(SC-P-27 家庭食谱生成)。
+     *
+     * <p>request 与 {@code /api/diet/recommendation/generate} 同载荷:
+     * {@code date / participant_member_ids / nutrition_goals / view_key}。</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>
+     *
+     * @param familyId 家庭 ID
+     * @param request  生成载荷
+     */
+    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"));
+
+        String dateStr = asString(request.get("date"));
+        if (!hasText(dateStr)) {
+            dateStr = LocalDate.now().toString();
+        }
+        LocalDate date = LocalDate.parse(dateStr);
+
+        List<Long> participantIds = resolveParticipantIds(request, familyId, date);
+        int participantCount = participantIds.isEmpty() ? 1 : participantIds.size();
+        List<String> ingredientNames = availableIngredientNames(familyId, date);
+
+        // 忌口/过敏自动排除(SC-P-27 / SC-P-28):各参与者 allergies / absoluteAvoid 关键词并集
+        List<String> exclusions = resolveParticipantExclusions(participantIds);
+
+        Map<String, Object> meals = new LinkedHashMap<>();
+        boolean degraded = false;
+        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> 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("degraded", degraded);
+        result.put("excludedItems", exclusions);
+        return result;
+    }
+
+    /**
+     * 参与者忌口/过敏关键词并集(SC-P-28「设忌口/过敏」数据源)。
+     *
+     * <p>来源 {@code diet_preferences.allergies / absoluteAvoid}(实体 {@link DietPreferences}),
+     * 兼容 JSON 数组(生产存量)与逗号/顿号分隔字符串(历史录入)两种形态,结果去重保序。</p>
+     *
+     * @param participantMemberIds 共餐人成员 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;
+                }
+                union.addAll(parsePreferenceKeywords(prefs.getAllergies()));
+                union.addAll(parsePreferenceKeywords(prefs.getAbsoluteAvoid()));
+            }
+        }
+        return new ArrayList<>(union);
+    }
+
+    /**
+     * 按忌口重算排除项(SC-P-28 主流程)。
+     *
+     * <p>对现有菜单(JSON 字符串或 Map)逐菜校验:菜名或任一生鲜食材命中忌口关键词即剔除,
+     * 并透出剔除清单。菜单形如 {@code {meals:[...]}},兼容两层结构:meals 元素即菜
+     * ({@code name/ingredients}),或 meals 元素为餐次组(内含 {@code dishes} 数组)。</p>
+     *
+     * @param menuJson   现有菜单(JSON 字符串或 Map)
+     * @param exclusions 忌口/过敏关键词
+     * @return Map 含 {@code menu}(过滤后菜单 JSON)、{@code excludedItems}(命中剔除清单)、
+     *         {@code 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;
+    }
+
+    /**
+     * 餐次组结构(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);
+            }
+        }
+        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 / 参数归一
     // ============================================================