Просмотр исходного кода

feat(diet): S-cfc-461 diet.nutrition.target 营养目标设定与食谱推荐集成 (SC-P-69)

Agnes Agent 5 часов назад
Родитель
Сommit
19f5a46499

+ 6 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java

@@ -6812,6 +6812,12 @@ sqls.add("INSERT IGNORE INTO health_norm_reference (dimension, gender, age_min,
         ensureColumn("user_nutrition_profile", "cuisine_style", "VARCHAR(100) COMMENT '偏好菜系'");
         ensureColumn("user_nutrition_profile", "cuisine_style", "VARCHAR(100) COMMENT '偏好菜系'");
         ensureColumn("user_nutrition_profile", "meal_count", "INT DEFAULT 3 COMMENT '每日餐数'");
         ensureColumn("user_nutrition_profile", "meal_count", "INT DEFAULT 3 COMMENT '每日餐数'");
         ensureColumn("user_nutrition_profile", "cooking_ability", "VARCHAR(20) DEFAULT 'simple' COMMENT '烹饪能力: simple/medium/advanced'");
         ensureColumn("user_nutrition_profile", "cooking_ability", "VARCHAR(20) DEFAULT 'simple' COMMENT '烹饪能力: simple/medium/advanced'");
+        // S-cfc-461 / diet.nutrition.target(SC-P-69):每日营养/热量目标列,供食谱推荐读取
+        ensureColumn("user_nutrition_profile", "calorie_target", "INT DEFAULT 2000 COMMENT '每日热量目标(kcal)'");
+        ensureColumn("user_nutrition_profile", "protein_target", "INT DEFAULT 60 COMMENT '每日蛋白质目标(g)'");
+        ensureColumn("user_nutrition_profile", "fat_target", "INT DEFAULT 50 COMMENT '每日脂肪目标(g)'");
+        ensureColumn("user_nutrition_profile", "carb_target", "INT DEFAULT 200 COMMENT '每日碳水目标(g)'");
+        ensureColumn("user_nutrition_profile", "fiber_target", "INT DEFAULT 25 COMMENT '每日膳食纤维目标(g)'");
 
 
         log.info("食品相关表初始化完成");
         log.info("食品相关表初始化完成");
     }
     }

+ 117 - 2
cfc-backend/src/main/java/com/etotem/cfc/controller/UserNutritionProfileController.java

@@ -15,19 +15,40 @@ import java.util.Map;
 @RequestMapping("/api/nutrition/profile")
 @RequestMapping("/api/nutrition/profile")
 public class UserNutritionProfileController {
 public class UserNutritionProfileController {
 
 
+    /** 未显式设定目标时的默认日目标(SC-P-69:食谱推荐侧始终有目标可用)。 */
+    private static final int DEFAULT_CALORIE_TARGET = 2000;
+    private static final int DEFAULT_PROTEIN_TARGET = 60;
+    private static final int DEFAULT_FAT_TARGET = 50;
+    private static final int DEFAULT_CARB_TARGET = 200;
+    private static final int DEFAULT_FIBER_TARGET = 25;
+
+    /** 热量合理区间上限(TC-P-69-E:超上限返回 400『热量需在合理区间』)。 */
+    private static final int CALORIE_TARGET_MAX = 5000;
+    /** 结构性不可能值闸门:超出该量级属于非法入参,直接由守卫抛异常拦截,不落库。 */
+    private static final int CALORIE_TARGET_HARD_MAX = 500000;
+
     @Resource
     @Resource
     private UserNutritionProfileService service;
     private UserNutritionProfileService service;
 
 
     @Operation(summary = "获取当前用户营养偏好")
     @Operation(summary = "获取当前用户营养偏好")
     @PostMapping("/get")
     @PostMapping("/get")
     public Result<UserNutritionProfile> get(@RequestAttribute("userId") Long userId) {
     public Result<UserNutritionProfile> get(@RequestAttribute("userId") Long userId) {
-        return Result.success(service.getByUserId(userId));
+        UserNutritionProfile profile = service.getByUserId(userId);
+        if (profile != null) {
+            applyDefaultTargets(profile);
+        }
+        return Result.success(profile);
     }
     }
 
 
-    @Operation(summary = "保存营养偏好")
+    @Operation(summary = "保存营养偏好(含每日营养/热量目标)")
     @PostMapping("/save")
     @PostMapping("/save")
     public Result<String> save(@RequestAttribute("userId") Long userId,
     public Result<String> save(@RequestAttribute("userId") Long userId,
                                @RequestBody Map<String, Object> params) {
                                @RequestBody Map<String, Object> params) {
+        Result<String> invalid = validateNutritionTargets(params);
+        if (invalid != null) {
+            return invalid;
+        }
+
         UserNutritionProfile profile = service.getByUserId(userId);
         UserNutritionProfile profile = service.getByUserId(userId);
         if (profile == null) {
         if (profile == null) {
             profile = new UserNutritionProfile();
             profile = new UserNutritionProfile();
@@ -48,7 +69,101 @@ public class UserNutritionProfileController {
         if (params.get("cookingAbility") != null) {
         if (params.get("cookingAbility") != null) {
             profile.setCookingAbility((String) params.get("cookingAbility"));
             profile.setCookingAbility((String) params.get("cookingAbility"));
         }
         }
+
+        applyDefaultTargets(profile);
+        applyNutritionTargets(profile, params);
         service.save(profile);
         service.save(profile);
         return Result.success("ok");
         return Result.success("ok");
     }
     }
+
+    /**
+     * 营养目标合法性守卫(SC-P-69 / TC-P-69-E 边界)。
+     * 返回 null 表示合法;返回 400 Result 表示普通越界,抛 IllegalArgumentException 表示结构性非法入参。
+     * 两条路径均在落库之前拦截。
+     */
+    private Result<String> validateNutritionTargets(Map<String, Object> params) {
+        Integer calorie = null;
+        try {
+            calorie = parseTargetValue(params.get("calorieTarget"));
+        } catch (RuntimeException e) {
+            return Result.badRequest("热量需在合理区间");
+        }
+        if (calorie != null) {
+            // -1「取消/无限目标」哨兵与不可能量级值视为结构性非法,硬拦截。
+            if (calorie == -1 || calorie > CALORIE_TARGET_HARD_MAX) {
+                throw new IllegalArgumentException("目标热量非法:" + calorie);
+            }
+            if (calorie < 0 || calorie > CALORIE_TARGET_MAX) {
+                return Result.badRequest("热量需在合理区间");
+            }
+        }
+
+        String[] macroNames = {"proteinTarget", "fatTarget", "carbTarget", "fiberTarget"};
+        int[] macroMax = {300, 200, 800, 100};
+        for (int i = 0; i < macroNames.length; i++) {
+            Integer value;
+            try {
+                value = parseTargetValue(params.get(macroNames[i]));
+            } catch (RuntimeException e) {
+                return Result.badRequest("营养目标需在合理区间");
+            }
+            if (value != null && (value < 0 || value > macroMax[i])) {
+                return Result.badRequest("营养目标需在合理区间");
+            }
+        }
+        return null;
+    }
+
+    /** 将合法目标写入档案字段,供食谱推荐侧读取(只读取本能力产出)。 */
+    private void applyNutritionTargets(UserNutritionProfile profile, Map<String, Object> params) {
+        Integer calorie = parseTargetValue(params.get("calorieTarget"));
+        if (calorie != null) {
+            profile.setCalorieTarget(calorie);
+        }
+        String[] macroNames = {"proteinTarget", "fatTarget", "carbTarget", "fiberTarget"};
+        for (String name : macroNames) {
+            Integer value = parseTargetValue(params.get(name));
+            if (value != null) {
+                if ("proteinTarget".equals(name)) {
+                    profile.setProteinTarget(value);
+                } else if ("fatTarget".equals(name)) {
+                    profile.setFatTarget(value);
+                } else if ("carbTarget".equals(name)) {
+                    profile.setCarbTarget(value);
+                } else {
+                    profile.setFiberTarget(value);
+                }
+            }
+        }
+    }
+
+    /** 存量档案缺失目标时回填默认值,保证食谱推荐始终有目标可用。 */
+    private void applyDefaultTargets(UserNutritionProfile profile) {
+        if (profile.getCalorieTarget() == null) {
+            profile.setCalorieTarget(DEFAULT_CALORIE_TARGET);
+        }
+        if (profile.getProteinTarget() == null) {
+            profile.setProteinTarget(DEFAULT_PROTEIN_TARGET);
+        }
+        if (profile.getFatTarget() == null) {
+            profile.setFatTarget(DEFAULT_FAT_TARGET);
+        }
+        if (profile.getCarbTarget() == null) {
+            profile.setCarbTarget(DEFAULT_CARB_TARGET);
+        }
+        if (profile.getFiberTarget() == null) {
+            profile.setFiberTarget(DEFAULT_FIBER_TARGET);
+        }
+    }
+
+    /** 兼容 Integer / Long / 字符串数字;格式错误交由守卫转成 400,不抛原始异常。 */
+    private Integer parseTargetValue(Object raw) {
+        if (raw == null) {
+            return null;
+        }
+        if (raw instanceof Number) {
+            return ((Number) raw).intValue();
+        }
+        return Integer.valueOf(raw.toString().trim());
+    }
 }
 }

+ 6 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/RecommendationContext.java

@@ -17,6 +17,12 @@ public class RecommendationContext {
     private Integer cookingAbility;
     private Integer cookingAbility;
     private String familyTastePreferences;
     private String familyTastePreferences;
     private Map<String, Object> nutritionSummary;
     private Map<String, Object> nutritionSummary;
+    /** 每日营养目标(diet.nutrition.target / SC-P-69),来自 UserNutritionProfile,供食谱推荐读取。 */
+    private Integer calorieTarget;
+    private Integer proteinTarget;
+    private Integer fatTarget;
+    private Integer carbTarget;
+    private Integer fiberTarget;
     private List<Food> candidateFoods;
     private List<Food> candidateFoods;
     private List<Recipe> candidateRecipes;
     private List<Recipe> candidateRecipes;
 }
 }

+ 15 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/UserNutritionProfile.java

@@ -33,6 +33,21 @@ public class UserNutritionProfile implements Serializable {
 
 
     private String cookingAbility;
     private String cookingAbility;
 
 
+    /** 每日热量目标(kcal),SC-P-69 精准营养目标设定;未设定时使用默认值。 */
+    private Integer calorieTarget = 2000;
+
+    /** 每日蛋白质目标(g)。 */
+    private Integer proteinTarget = 60;
+
+    /** 每日脂肪目标(g)。 */
+    private Integer fatTarget = 50;
+
+    /** 每日碳水化合物目标(g)。 */
+    private Integer carbTarget = 200;
+
+    /** 每日膳食纤维目标(g)。 */
+    private Integer fiberTarget = 25;
+
     private Date createdAt;
     private Date createdAt;
 
 
     private Date updatedAt;
     private Date updatedAt;

+ 20 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/MealRecommendService.java

@@ -60,6 +60,18 @@ public class MealRecommendService {
         ctx.setDietaryRestrictions("\u65e0");
         ctx.setDietaryRestrictions("\u65e0");
         ctx.setCuisineStyle(profile != null && profile.getCuisineStyle() != null ? profile.getCuisineStyle() : "\u4e2d\u5f0f");
         ctx.setCuisineStyle(profile != null && profile.getCuisineStyle() != null ? profile.getCuisineStyle() : "\u4e2d\u5f0f");
 
 
+        // 营养目标由 diet.nutrition.target 产出:食谱推荐只读取本能力写入的档案字段(需求变更 §4.7)。
+        ctx.setCalorieTarget(profile != null && profile.getCalorieTarget() != null
+                ? profile.getCalorieTarget() : 2000);
+        ctx.setProteinTarget(profile != null && profile.getProteinTarget() != null
+                ? profile.getProteinTarget() : 60);
+        ctx.setFatTarget(profile != null && profile.getFatTarget() != null
+                ? profile.getFatTarget() : 50);
+        ctx.setCarbTarget(profile != null && profile.getCarbTarget() != null
+                ? profile.getCarbTarget() : 200);
+        ctx.setFiberTarget(profile != null && profile.getFiberTarget() != null
+                ? profile.getFiberTarget() : 25);
+
         ctx.setNutritionSummary(mealLogService.getNutritionSummary(userId, 7));
         ctx.setNutritionSummary(mealLogService.getNutritionSummary(userId, 7));
         filterCandidates(ctx);
         filterCandidates(ctx);
 
 
@@ -118,6 +130,14 @@ public class MealRecommendService {
         userProfile.put("dietaryRestrictions", ctx.getDietaryRestrictions());
         userProfile.put("dietaryRestrictions", ctx.getDietaryRestrictions());
         inputs.put("user_profile", userProfile);
         inputs.put("user_profile", userProfile);
 
 
+        Map<String, Object> nutritionTarget = new LinkedHashMap<>();
+        nutritionTarget.put("calorie", ctx.getCalorieTarget());
+        nutritionTarget.put("protein", ctx.getProteinTarget());
+        nutritionTarget.put("fat", ctx.getFatTarget());
+        nutritionTarget.put("carb", ctx.getCarbTarget());
+        nutritionTarget.put("fiber", ctx.getFiberTarget());
+        inputs.put("nutrition_target", nutritionTarget);
+
         if (ctx.getLatestReport() != null) {
         if (ctx.getLatestReport() != null) {
             Map<String, Object> healthSummary = new LinkedHashMap<>();
             Map<String, Object> healthSummary = new LinkedHashMap<>();
             HealthReport r = ctx.getLatestReport();
             HealthReport r = ctx.getLatestReport();

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

@@ -31,4 +31,12 @@ public class UserNutritionProfileService {
             mapper.updateById(profile);
             mapper.updateById(profile);
         }
         }
     }
     }
+
+    /**
+     * 营养目标设定/保存入口(SC-P-69 / diet.nutrition.target)。
+     * 目标字段随 {@link UserNutritionProfile} 按 userId 归属,透传通用保存逻辑。
+     */
+    public void saveNutritionTargets(UserNutritionProfile profile) {
+        save(profile);
+    }
 }
 }