Преглед изворни кода

feat(diet.mealPlan.adjust): S-cfc-366 实现 MealPlanService 契约宿主使红转绿

- favorite/unfavorite/getFavoriteList:内存态收藏集合,(mealPlanId,memberId) 幂等仅 1 条,
  按 memberId 维度隔离防横向越权(TC-P-29 / TC-P-29-E / TC-P-29-P)
- adjustDish:按 mealIndex/dishIndex 替换食材并重算聚合 nutritionSummary,
  非法载荷返回 status='ERROR' 可读信息(TC-P-29 调整不破坏营养目标)
- alignNutrition:对比营养合计 vs 目标,返回 {status,percent,message},
  NO_TARGET 分支 percent 恒为合法 Number 不除零(TC-P-30 / TC-P-30-E)
zxyj-langgraph пре 5 дана
родитељ
комит
9c8647200f
1 измењених фајлова са 255 додато и 0 уклоњено
  1. 255 0
      cfc-backend/src/main/java/com/etotem/cfc/service/MealPlanService.java

+ 255 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/MealPlanService.java

@@ -0,0 +1,255 @@
+package com.etotem.cfc.service;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 食谱收藏 / 手动微调替换食材 / 营养对齐(能力键 {@code diet.mealPlan.adjust})。
+ *
+ * <p><b>契约锚点</b>:{@code DietMealPlanAdjustContractTest}(SC-P-29 食谱收藏/调整、SC-P-30 食谱与营养目标对齐)。</p>
+ *
+ * <p><b>实现口径</b>:纯内存态(收藏集合 + adjustDish 纯函数 + alignNutrition 纯函数),无 Spring / 无 DB,
+ * 契约级单测通过无参构造直接实例化({@code getDeclaredConstructor().newInstance()})。</p>
+ *
+ * <ul>
+ *   <li>{@link #favorite(Long, Long)} —— 收藏食谱;新增成功返回 true;已存在(幂等仅 1 条)返回 false。</li>
+ *   <li>{@link #unfavorite(Long, Long)} —— 取消收藏;存在且移除成功返回 true;不存在返回 false。</li>
+ *   <li>{@link #getFavoriteList(Long)} —— 该成员收藏列表,按 memberId 维度隔离(防横向越权)。</li>
+ *   <li>{@link #adjustDish(Map)} —— 以新旧食材替换后重算聚合营养合计(nutritionSummary)。</li>
+ *   <li>{@link #alignNutrition(Map, Map)} —— 营养合计 vs 目标;返回 {status, percent, message},不除零。</li>
+ * </ul>
+ */
+public class MealPlanService {
+
+    /** 收藏记录:key = memberId + ":" + mealPlanId(同一 (mealPlanId, memberId) 幂等仅 1 条)。 */
+    private final Set<String> favorites = ConcurrentHashMap.newKeySet();
+
+    /**
+     * 收藏食谱。
+     *
+     * @return 新增成功返回 true;已存在(幂等仅 1 条)返回 false,不抛异常。
+     */
+    public boolean favorite(Long mealPlanId, Long memberId) {
+        if (mealPlanId == null || memberId == null) {
+            return false;
+        }
+        return favorites.add(key(memberId, mealPlanId));
+    }
+
+    /**
+     * 取消收藏。
+     *
+     * @return 存在且移除成功返回 true;不存在返回 false(不抛异常、不产生副作用)。
+     */
+    public boolean unfavorite(Long mealPlanId, Long memberId) {
+        if (mealPlanId == null || memberId == null) {
+            return false;
+        }
+        return favorites.remove(key(memberId, mealPlanId));
+    }
+
+    /**
+     * 该成员收藏列表,每项 Map 至少含 {@code mealPlanId};按 memberId 维度隔离。
+     *
+     * @param memberId 成员 ID
+     * @return 该成员收藏列表(不得为 null)
+     */
+    public List<Map<String, Object>> getFavoriteList(Long memberId) {
+        List<Map<String, Object>> list = new ArrayList<>();
+        if (memberId == null) {
+            return list;
+        }
+        String prefix = memberId + ":";
+        for (String k : favorites) {
+            if (k.startsWith(prefix)) {
+                Map<String, Object> item = new HashMap<>();
+                item.put("mealPlanId", Long.valueOf(k.substring(prefix.length())));
+                item.put("memberId", memberId);
+                list.add(item);
+            }
+        }
+        list.sort(Comparator.comparing(m -> ((Number) m.get("mealPlanId")).longValue()));
+        return list;
+    }
+
+    /**
+     * 手动微调替换食材:按 {@code mealIndex}/{@code dishIndex} 定位菜品,以 {@code replacementFood} 替换,
+     * 重算聚合营养合计 {@code nutritionSummary},返回 {@code {status:"OK", menu(替换后), nutritionSummary}}。
+     *
+     * <p>非法载荷(缺 {@code replacementFood}/{@code replacementFoodId} 或索引越界)→ 返回
+     * {@code {status:"ERROR", message}}(可读信息),不允许静默以原食材被 null 顶替(破坏营养目标)。</p>
+     *
+     * @param request 键:{@code mealPlanId / mealIndex / dishIndex / replacementFoodId / replacementFood / menu}
+     * @return 替换结果(非法载荷返回 status != "OK")
+     */
+    @SuppressWarnings("unchecked")
+    public Map<String, Object> adjustDish(Map<String, Object> request) {
+        if (request == null) {
+            return errorResult("adjustDish 请求体不得为 null");
+        }
+        Object replacementFood = request.get("replacementFood");
+        Object replacementFoodId = request.get("replacementFoodId");
+        Object menuObj = request.get("menu");
+        if (replacementFood == null || !(replacementFood instanceof Map)
+                || replacementFoodId == null || menuObj == null) {
+            return errorResult("adjustDish 缺少必需参数:replacementFood / replacementFoodId / menu");
+        }
+        Map<String, Object> food = (Map<String, Object>) replacementFood;
+
+        Object mealIndexObj = request.get("mealIndex");
+        Object dishIndexObj = request.get("dishIndex");
+        if (!(mealIndexObj instanceof Number) || !(dishIndexObj instanceof Number)) {
+            return errorResult("adjustDish 缺少 mealIndex / dishIndex(数字)");
+        }
+        int mealIndex = ((Number) mealIndexObj).intValue();
+        int dishIndex = ((Number) dishIndexObj).intValue();
+
+        Map<String, Object> menu = (Map<String, Object>) menuObj;
+        List<Map<String, Object>> meals = (List<Map<String, Object>>) menu.get("meals");
+        if (meals == null || mealIndex < 0 || mealIndex >= meals.size()) {
+            return errorResult("adjustDish mealIndex 越界:" + mealIndex);
+        }
+        Map<String, Object> meal = meals.get(mealIndex);
+        List<Map<String, Object>> dishes = meal == null ? null : (List<Map<String, Object>>) meal.get("dishes");
+        if (dishes == null || dishIndex < 0 || dishIndex >= dishes.size()) {
+            return errorResult("adjustDish dishIndex 越界:" + dishIndex);
+        }
+
+        // 构造替换后的新菜品:保留原菜品 name/type,营养字段来自 replacementFood
+        Map<String, Object> replacementDish = new HashMap<>();
+        replacementDish.put("name", food.get("name") != null
+                ? food.get("name") : ("替换食材" + replacementFoodId));
+        replacementDish.put("type", "dish");
+        if (food.get("foodId") != null) {
+            replacementDish.put("foodId", food.get("foodId"));
+        }
+        copyNutrition(food, replacementDish);
+        dishes.set(dishIndex, replacementDish);
+
+        // 基于替换后菜品集合重算聚合营养合计(不允许静默丢失营养键)
+        Map<String, Object> nutritionSummary = aggregateNutrition(menu);
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("status", "OK");
+        result.put("menu", menu);
+        result.put("nutritionSummary", nutritionSummary);
+        return result;
+    }
+
+    /**
+     * 营养合计 vs 目标。返回 {@code {status:"ALIGNED"/"OVER"/"UNDER"/"NO_TARGET", percent:Number, message:String}}。
+     *
+     * <p>{@code percent = (actual-target)/target×100}(取整);{@code target == null} 或空 →
+     * {@code status="NO_TARGET"} + 提示「请先设置营养目标」,percent 仍为合法 Number(非 NaN,不除零红线)。</p>
+     *
+     * @param nutritionActual 实际营养合计(nutritionSummary 口径:calories/protein/fat/carbs…)
+     * @param target          目标营养
+     * @return 对齐评估结果
+     */
+    public Map<String, Object> alignNutrition(Map<String, Number> nutritionActual, Map<String, Number> target) {
+        Map<String, Object> result = new HashMap<>();
+        if (target == null || target.isEmpty()) {
+            result.put("status", "NO_TARGET");
+            result.put("percent", 0); // 合法 Number,不参与计算、不除零
+            result.put("message", "请先设置营养目标");
+            return result;
+        }
+        // 主营养键:优先 calories,否则取 target 首个键
+        String primaryKey = target.containsKey("calories") ? "calories" : target.keySet().iterator().next();
+        double targetVal = target.get(primaryKey) != null ? target.get(primaryKey).doubleValue() : 0;
+        if (targetVal == 0) {
+            result.put("status", "NO_TARGET");
+            result.put("percent", 0);
+            result.put("message", "请先设置营养目标");
+            return result;
+        }
+        double actualVal = nutritionActual != null && nutritionActual.get(primaryKey) != null
+                ? nutritionActual.get(primaryKey).doubleValue() : 0;
+        long percent = Math.round((actualVal - targetVal) / targetVal * 100);
+
+        String status;
+        String message;
+        if (actualVal > targetVal) {
+            status = "OVER";
+            message = "营养超出目标 " + Math.abs(percent) + "%";
+        } else if (actualVal < targetVal) {
+            status = "UNDER";
+            message = "营养低于目标 " + Math.abs(percent) + "%";
+        } else {
+            status = "ALIGNED";
+            message = "营养与目标一致";
+        }
+        result.put("status", status);
+        result.put("percent", percent);
+        result.put("message", message);
+        return result;
+    }
+
+    // ==================== helpers ====================
+
+    /** 非法载荷的失败返回:status != "OK",带可读 message。 */
+    private static Map<String, Object> errorResult(String message) {
+        Map<String, Object> result = new HashMap<>();
+        result.put("status", "ERROR");
+        result.put("message", message);
+        return result;
+    }
+
+    private static String key(Long memberId, Long mealPlanId) {
+        return memberId + ":" + mealPlanId;
+    }
+
+    /** 从 replacementFood 拷贝营养字段到新菜品(calories/protein/fat/carbs/sugar/fiber)。 */
+    private static void copyNutrition(Map<String, Object> food, Map<String, Object> dish) {
+        String[] keys = {"calories", "protein", "fat", "carbs", "sugar", "fiber"};
+        for (String k : keys) {
+            if (food.get(k) != null) {
+                dish.put(k, food.get(k));
+            }
+        }
+    }
+
+    /** 聚合菜单所有菜品的营养合计(营养键稳定存在,不静默丢失)。 */
+    @SuppressWarnings("unchecked")
+    private static Map<String, Object> aggregateNutrition(Map<String, Object> menu) {
+        double calories = 0, protein = 0, fat = 0, carbs = 0, sugar = 0, fiber = 0;
+        List<Map<String, Object>> meals = menu == null ? null : (List<Map<String, Object>>) menu.get("meals");
+        if (meals != null) {
+            for (Map<String, Object> meal : meals) {
+                List<Map<String, Object>> dishes = meal == null ? null
+                        : (List<Map<String, Object>>) meal.get("dishes");
+                if (dishes == null) {
+                    continue;
+                }
+                for (Map<String, Object> dish : dishes) {
+                    if (dish == null) {
+                        continue;
+                    }
+                    calories += num(dish.get("calories"));
+                    protein += num(dish.get("protein"));
+                    fat += num(dish.get("fat"));
+                    carbs += num(dish.get("carbs"));
+                    sugar += num(dish.get("sugar"));
+                    fiber += num(dish.get("fiber"));
+                }
+            }
+        }
+        Map<String, Object> summary = new HashMap<>();
+        summary.put("calories", calories);
+        summary.put("protein", protein);
+        summary.put("fat", fat);
+        summary.put("carbs", carbs);
+        summary.put("sugar", sugar);
+        summary.put("fiber", fiber);
+        return summary;
+    }
+
+    private static double num(Object o) {
+        return o instanceof Number ? ((Number) o).doubleValue() : 0;
+    }
+}