Browse Source

feat(recipe): 食谱生成改用用户当前食材推荐 + 换花样

按需求变更 docs/superpowers/specs/2026-11-26-personalized-recipe-generation-design.md 实现:

- 迁移504 + schema.sql: user_current_food_recommend(报告基线+问卷重算,原始分保留在 food_recommend_idx)
- UserCurrentFoodService: rebuildForUser(报告/健康现状/饮食偏好/健康阅卷/报告问卷 5处钩子)+ buildGenerationContext(逐成员归属、硬禁忌并集、软偏好、缺食材提示)
- AiGateway: generateMenu 新增 constraints/exclude_dish_names/variation_seed 透传,保留旧4参重载
- DietRecommendationService: 逐成员取个人食材;显式成员缺食材则400提示;近30天3份 completed 菜单菜名作为换花样排除;兜底用个人食材按 seed 轮换;regenerate 不再传空食材
- langgraph meal.py: 合并个人约束、换花样排除、变化种子进 prompt(模型/温度不变)

编译通过;相关测试74项中仅 byReport 7条存量RED失败(本需求明确不做)
Xiaogang Liao 1 hour ago
parent
commit
c9a89a1ced

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

@@ -3687,6 +3687,10 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         // 迁移503: 谷禾新版物种功能库 health_species_library + 异常菌派生视图 health_abnormal_species
         // (能力键 health.report.abnormalSpecies,P0-6 异常菌清单接口 ▲ 直出;设计 §三 P0-4 + §五 DDL④⑤)
         createHealthSpeciesLibraryTable();
+
+        // 迁移504: 用户当前食材推荐表 user_current_food_recommend(个性化食谱生成)
+        // 报告基线之上按问卷重算出的当前可用食材清单;食谱生成只读此表,报告原始分不被问卷覆盖。
+        createUserCurrentFoodRecommendTable();
     }
 
     /**
@@ -17067,4 +17071,36 @@ log.info("迁移298: 已为无 openid 的 child 账号补齐 family_members 记
         }
         log.info("迁移503: 异常菌清单数据源已就绪(health_species_library + health_abnormal_species 视图/表)");
     }
+
+    /**
+     * 迁移504: 用户当前食材推荐表 {@code user_current_food_recommend}(spec 2026-11-26 个性化食谱生成)。
+     *
+     * <p>报告基线({@code food_recommend_idx})之上按健康问卷/偏好重算出的「当前可用食材清单」;
+     * 食谱生成只读本表,{@code base_score} 复制报告原始分且永不被问卷覆盖。</p>
+     *
+     * <p>MySQL 8.0 兼容:索引内不使用函数表达式(314 号迁移踩坑);
+     * 幂等:CREATE TABLE IF NOT EXISTS + try/catch,可重复执行。</p>
+     */
+    void createUserCurrentFoodRecommendTable() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS user_current_food_recommend ("
+                    + "id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID', "
+                    + "user_id BIGINT NOT NULL COMMENT '归一后的 users.id(与 food_recommend_idx.user_id 同口径)', "
+                    + "food_id BIGINT NOT NULL COMMENT '食材ID', "
+                    + "food_name VARCHAR(100) COMMENT '食材名称', "
+                    + "category VARCHAR(50) COMMENT '食材分类', "
+                    + "base_score INT NOT NULL COMMENT '报告原始分(复制自 index_score,永不被问卷覆盖)', "
+                    + "source_report_id BIGINT COMMENT '来源健康报告ID', "
+                    + "adjustment VARCHAR(16) NOT NULL DEFAULT 'normal' COMMENT 'normal/boost/warning/blocked', "
+                    + "adjustment_reason VARCHAR(500) COMMENT '调整命中原因', "
+                    + "current_score INT NOT NULL COMMENT 'base_score + 权重(adjustment),clamp 到 [-100,100]', "
+                    + "rebuilt_at DATETIME NOT NULL COMMENT '最近重建时间', "
+                    + "UNIQUE KEY uk_user_food (user_id, food_id), "
+                    + "KEY idx_user_score (user_id, current_score)"
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户当前食材推荐(报告基线+问卷重算,食谱生成只读此表)'");
+            log.info("迁移504: 已创建/确认 user_current_food_recommend 表");
+        } catch (Exception e) {
+            log.warn("迁移504: user_current_food_recommend 表创建失败(忽略): {}", e.getMessage());
+        }
+    }
 }

+ 41 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/UserCurrentFoodRecommend.java

@@ -0,0 +1,41 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 用户当前食材推荐(迁移504)。
+ *
+ * <p>报告基线({@code food_recommend_idx})之上按健康问卷/偏好重算出的「当前可用食材清单」,
+ * 食谱生成只读本表;报告原始分存 {@link #baseScore},永不被问卷覆盖。</p>
+ */
+@Data
+@TableName("user_current_food_recommend")
+public class UserCurrentFoodRecommend implements Serializable {
+    @TableId(type = IdType.AUTO)
+    private Long id;
+    /** 归一后的用户ID(food_recommend_idx.user_id 同口径) */
+    private Long userId;
+    /** 食材ID */
+    private Long foodId;
+    /** 食材名称 */
+    private String foodName;
+    /** 食材分类 */
+    private String category;
+    /** 报告原始分(复制自 food_recommend_idx.index_score,不被问卷覆盖) */
+    private Integer baseScore;
+    /** 来源健康报告ID */
+    private Long sourceReportId;
+    /** 调整标记:normal/boost/warning/blocked */
+    private String adjustment;
+    /** 调整命中原因 */
+    private String adjustmentReason;
+    /** base_score + healthAdjustScore(adjustment),clamp 到 [-100,100] */
+    private Integer currentScore;
+    /** 最近重建时间 */
+    private Date rebuiltAt;
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/UserCurrentFoodRecommendMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.UserCurrentFoodRecommend;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface UserCurrentFoodRecommendMapper extends BaseMapper<UserCurrentFoodRecommend> {
+}

+ 18 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/AiGateway.java

@@ -634,6 +634,15 @@ public class AiGateway {
      * 不加重试、不改熔断 / 超时逻辑;菜数正确性由 Java 侧 normalizeMenu 硬保证。
      */
     public String generateMenu(String selectedFoodsJson, String participantsJson, String date, Integer dishCount) {
+        return generateMenu(selectedFoodsJson, participantsJson, date, dishCount, null, null, null);
+    }
+
+    /**
+     * 个性化菜单生成:在原有 4 字段之外,透传逐用户当前食材解析出的约束、
+     * 最近已采用菜名(换花样)与变化种子。
+     */
+    public String generateMenu(String selectedFoodsJson, String participantsJson, String date, Integer dishCount,
+                               Map<String, Object> constraints, List<String> excludeDishNames, Long variationSeed) {
         if (!enabled || isCircuitOpen()) return null;
 
         try {
@@ -650,6 +659,15 @@ public class AiGateway {
             } else {
                 body.putNull("dish_count");
             }
+            if (constraints != null && !constraints.isEmpty()) {
+                body.set("constraints", objectMapper.valueToTree(constraints));
+            }
+            if (excludeDishNames != null && !excludeDishNames.isEmpty()) {
+                body.set("exclude_dish_names", objectMapper.valueToTree(excludeDishNames));
+            }
+            if (variationSeed != null) {
+                body.put("variation_seed", variationSeed.longValue());
+            }
             
             HttpEntity<String> entity = new HttpEntity<>(body.toString(), createJsonHeaders());
             String url = baseUrl + "/api/v1/menu/generate";

+ 18 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/DietPreferencesService.java

@@ -3,7 +3,9 @@ package com.etotem.cfc.service;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.etotem.cfc.dto.DietPreferencesDTO;
 import com.etotem.cfc.entity.DietPreferences;
+import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.mapper.DietPreferencesMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
@@ -22,6 +24,13 @@ public class DietPreferencesService {
     @Resource
     private ObjectMapper objectMapper;
 
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    /** 迁移504:饮食偏好保存成功后重建用户当前食材推荐 */
+    @Resource
+    private UserCurrentFoodService userCurrentFoodService;
+
     public DietPreferencesDTO getCurrentMemberPreferences(Long familyMemberId) {
         LambdaQueryWrapper<DietPreferences> wrapper = new LambdaQueryWrapper<>();
         wrapper.eq(DietPreferences::getFamilyMemberId, familyMemberId);
@@ -72,6 +81,15 @@ public class DietPreferencesService {
         } else {
             dietPreferencesMapper.updateById(entity);
         }
+
+        // 迁移504:问卷偏好变化后同步重算当前食材推荐(幂等,失败不影响偏好保存)
+        try {
+            FamilyMember member = familyMemberMapper.selectById(familyMemberId);
+            Long uid = (member != null && member.getUserId() != null) ? member.getUserId() : familyMemberId;
+            userCurrentFoodService.rebuildForUser(uid, familyMemberId);
+        } catch (Exception e) {
+            log.warn("饮食偏好保存后当前食材推荐重建失败 memberId={}: {}", familyMemberId, e.getMessage());
+        }
     }
 
     private String toJSON(Object obj) {

+ 100 - 4
cfc-backend/src/main/java/com/etotem/cfc/service/DietRecommendationService.java

@@ -23,6 +23,7 @@ import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.LinkedHashSet;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -83,6 +84,9 @@ public class DietRecommendationService {
     @Resource
     private FamilyMemberMapper familyMemberMapper;
 
+    @Resource
+    private UserCurrentFoodService userCurrentFoodService;
+
     /**
      * 菜谱分享只读查询:按 id 获取菜谱详情,不做 familyId 归属校验(跨家庭可看)。
      * 分享数据仅含菜谱/营养信息,无个人信息,只读展示所需字段。
@@ -198,14 +202,42 @@ public class DietRecommendationService {
         String participantsJson = participantIds.isEmpty() ? "[]" : safeWrite(participantIds);
         String participantIdsJson = safeWrite(participantIds);
 
+        // 2.1 逐成员取「用户当前食材推荐」:报告基线 + 问卷规则,生成只读该表。
+        //     只有显式传了 participant_member_ids 才对缺数据成员硬阻断;隐式兜底成员只提示不阻断。
+        boolean explicitParticipants = hasText(asString(request.get("participant_member_ids")));
+        Map<String, Object> foodContext = userCurrentFoodService.buildGenerationContext(participantIds, explicitParticipants);
+        if (foodContext == null) {
+            foodContext = Collections.emptyMap();
+        }
+        List<String> missingMemberNames = (List<String>) foodContext.get("missingMemberNames");
+        if (explicitParticipants && Boolean.TRUE.equals(foodContext.get("hasMissing"))) {
+            throw new IllegalArgumentException("以下成员尚无食材推荐,请先上传报告或填写问卷:" + String.join("、", missingMemberNames == null ? Collections.<String>emptyList() : missingMemberNames));
+        }
+        String personalFoodsJson = asString(foodContext.get("selectedFoodsJson"));
+        if (hasText(personalFoodsJson)) {
+            selectedFoodsJson = personalFoodsJson;
+        }
+        List<String> personalFoodNames = parseSelectedFoodNames(selectedFoodsJson);
+        Map<String, Object> generationConstraints = (Map<String, Object>) foodContext.get("constraints");
+        List<String> excludeDishNames = recentCompletedDishNames(familyId, viewKey, hasViewKey);
+        Long seedParam = request == null ? null : ParamUtils.getLong(request.get("_variation_seed"));
+        long variationSeed = seedParam != null ? seedParam : System.currentTimeMillis();
+
         // 3. 菜数规则(K4):D(N) 仅作为 AI 的软引导;硬保证在 normalizeMenu
         int dishCount = DishCountRule.dishCount(participantCount);
-        String menuJson = aiGateway.generateMenu(selectedFoodsJson, participantsJson, dateStr, dishCount);
+        // 拿到个人食材才走个性化重载;没有个人数据时保留旧 4 参调用(兼容存量契约测试与旧调用方)。
+        String menuJson;
+        if (hasText(personalFoodsJson) && !"[]".equals(personalFoodsJson.trim())) {
+            menuJson = aiGateway.generateMenu(selectedFoodsJson, participantsJson, dateStr, dishCount,
+                    generationConstraints, excludeDishNames, variationSeed);
+        } else {
+            menuJson = aiGateway.generateMenu(selectedFoodsJson, participantsJson, dateStr, dishCount);
+        }
 
         // 4. AI 失败 / 熔断 / 超时 → 规则降级(同菜数规则造 D(N)+1 道)
         List<String> ingredientNames = availableIngredientNames(familyId, date);
         if (menuJson == null || menuJson.trim().isEmpty() || "{}".equals(menuJson.trim())) {
-            menuJson = buildFallbackMenu(familyId, date, participantCount, ingredientNames);
+            menuJson = buildFallbackMenu(familyId, date, participantCount, ingredientNames, personalFoodNames, variationSeed);
         }
 
         // 5. 归一化(唯一硬保证点)+ 聚合营养
@@ -218,7 +250,7 @@ public class DietRecommendationService {
         // regenerate 复用本方法(L283),同样受保护。
         if (!hasUsableLunchDinner(normalized)) {
             normalized = normalizeMenu(
-                    buildFallbackMenu(familyId, date, participantCount, ingredientNames),
+                    buildFallbackMenu(familyId, date, participantCount, ingredientNames, personalFoodNames, variationSeed),
                     participantCount, ingredientNames);
         }
         String normalizedMenuJson = safeWrite(normalized);
@@ -332,7 +364,8 @@ public class DietRecommendationService {
         Map<String, Object> genRequest = new HashMap<>();
         genRequest.put("date", dateStr);
         genRequest.put("meal_type", record.getMealType() != null ? record.getMealType() : "all");
-        genRequest.put("selected_foods", "[]");
+        // 个性化食材由 generateRecommendation 内部逐成员解析;这里只传变化种子实现"换花样"
+        genRequest.put("_variation_seed", oldVersion + 1);
         // 原记录共餐人(字符串或紧凑 JSON)→ resolveParticipantIds 复用 parseMemberIds 解析
         genRequest.put("participant_member_ids", record.getParticipantMemberIds());
         genRequest.put("view_key", record.getViewKey());
@@ -873,6 +906,69 @@ public class DietRecommendationService {
      * AI 不可用时的规则降级(K4 / AC-24):lunch/dinner 造 D(N) 道菜 + 1 道汤(带 type),
      * 早餐维持现状 1 道「营养餐」。输出仍经 normalizeMenu 归一化,保证三条路径同规则。
      */
+    /**
+     * 兜底菜单:优先使用「用户当前食材推荐」的高分食材名,按本次变化种子轮换起点,
+     * 保证重新生成不会得到逐字节相同的菜单;个人数据缺失时退回家庭食材列表。
+     */
+    private String buildFallbackMenu(Long familyId, LocalDate date, int participantCount, List<String> ingredientNames,
+                                     List<String> personalFoodNames, long variationSeed) {
+        List<String> names = (personalFoodNames != null && !personalFoodNames.isEmpty()) ? personalFoodNames : ingredientNames;
+        if (names != null && names.size() > 1) {
+            int offset = (int) (Math.abs(variationSeed) % names.size());
+            List<String> rotated = new ArrayList<>();
+            for (int i = 0; i < names.size(); i++) {
+                rotated.add(names.get((i + offset) % names.size()));
+            }
+            names = rotated;
+        }
+        return buildFallbackMenu(familyId, date, participantCount, names);
+    }
+
+    /** 从 selected_foods JSON 中抽出食材名(兼容异常 JSON,静默降级为空) */
+    private List<String> parseSelectedFoodNames(String selectedFoodsJson) {
+        List<String> names = new ArrayList<>();
+        if (!hasText(selectedFoodsJson)) return names;
+        try {
+            JsonNode arr = new ObjectMapper().readTree(selectedFoodsJson);
+            if (arr != null && arr.isArray()) {
+                for (JsonNode node : arr) {
+                    String n = node.path("name").asText(null);
+                    if (n != null && n.trim().length() > 0) names.add(n.trim());
+                }
+            }
+        } catch (Exception ignore) {
+        }
+        return names;
+    }
+
+    /** 近 30 天、同 view_key 的 3 份已完成菜单里的菜名,用于「换花样」排除 */
+    private List<String> recentCompletedDishNames(Long familyId, String viewKey, boolean hasViewKey) {
+        LambdaQueryWrapper<DietRecommendation> wrapper = new LambdaQueryWrapper<>();
+        wrapper.eq(DietRecommendation::getFamilyId, familyId)
+               .eq(DietRecommendation::getStatus, "completed")
+               .ge(DietRecommendation::getUpdatedAt, new Date(System.currentTimeMillis() - 30L * 24 * 3600 * 1000))
+               .orderByDesc(DietRecommendation::getUpdatedAt)
+               .last("LIMIT 3");
+        if (hasViewKey) wrapper.eq(DietRecommendation::getViewKey, viewKey);
+        List< DietRecommendation > rows = dietRecommendationMapper.selectList(wrapper);
+        Set<String> names = new LinkedHashSet<>();
+        for (DietRecommendation row : rows) {
+            String menuJson = row.getMenuJson();
+            if (!hasText(menuJson)) continue;
+            try {
+                JsonNode root = new ObjectMapper().readTree(menuJson);
+                for (JsonNode meal : root.path("meals")) {
+                    for (JsonNode dish : meal.path("dishes")) {
+                        String n = dish.path("name").asText(null);
+                        if (n != null && n.trim().length() > 0) names.add(n.trim());
+                    }
+                }
+            } catch (Exception ignore) {
+            }
+        }
+        return new ArrayList<>(names);
+    }
+
     private String buildFallbackMenu(Long familyId, LocalDate date, int participantCount, List<String> ingredientNames) {
         int n = DishCountRule.normalizeN(participantCount);
         List<String> names = ingredientNames == null ? Collections.<String>emptyList() : ingredientNames;

+ 29 - 2
cfc-backend/src/main/java/com/etotem/cfc/service/FoodRecommendService.java

@@ -55,6 +55,10 @@ public class FoodRecommendService {
     @Resource
     private HealthFilterService healthFilterService;
 
+    /** 迁移504:报告基线刷新后重建用户当前食材推荐(本服务注入它,反向依赖禁止) */
+    @Resource
+    private UserCurrentFoodService userCurrentFoodService;
+
     /**
      * 把外部传入的 subjectId 归一为 food_recommend_idx 的统一写入/读取键(T28 方向1:写侧统一为 users.id)。
      * <p>
@@ -149,15 +153,23 @@ public class FoodRecommendService {
                     .eq(FoodRecommendIndex::getUserId, writeKey));
             log.info("用户{}无最新健康报告,已清除推荐指数", userId);
             refreshFamilyOverviews(writeKey);
+            // 报告基线已清空 → 同步清空当前食材推荐(幂等,不阻断主流程)
+            try {
+                userCurrentFoodService.rebuildForUser(writeKey, null);
+            } catch (Exception e) {
+                log.warn("用户当前食材推荐重建失败 writeKey={}: {}", writeKey, e.getMessage());
+            }
             return;
         }
+        // 报告被检测成员(family_members.id 口径);无绑定成员时为 null,问卷画像按 userId 回退
+        Long subjectMemberId = report.getSubjectId();
         // 写键权威化:报告已绑定成员(subject_id 非空 = family_members.id 口径)时,以成员视角解析写入键,
         // 规避 users 与 family_members.id 数值重叠时 resolveFoodIndexUserId 的 users 优先启发式误判。
         // 如家庭72 报告63:subject_id=84(CF 成员卡, user_id=27),而 users.id=84 是无关用户"用户1905",
         // resolveFoodIndexUserId(84) 会把食材错写到 user_id=84;成员视角解析得真实登录用户 27。
         // subject_id 为空(历史数据/无绑定)时保持原 writeKey 不变,兼容既有行为与单测。
-        if (report.getSubjectId() != null) {
-            Long memberViewKey = resolveMemberViewToUserId(report.getSubjectId());
+        if (subjectMemberId != null) {
+            Long memberViewKey = resolveMemberViewToUserId(subjectMemberId);
             if (memberViewKey != null) {
                 writeKey = memberViewKey;
             }
@@ -175,6 +187,13 @@ public class FoodRecommendService {
                         .eq(FoodRecommendIndex::getUserId, writeKey));
                 log.info("报告{}无食材推荐数据,已清除用户{}的推荐指数", report.getId(), userId);
                 refreshFamilyOverviews(writeKey);
+                // 报告基线已清空 → 同步清空当前食材推荐(幂等,不阻断主流程)
+                try {
+                    userCurrentFoodService.rebuildForUser(writeKey, subjectMemberId);
+                } catch (Exception e) {
+                    log.warn("用户当前食材推荐重建失败 writeKey={} memberId={}: {}",
+                            writeKey, subjectMemberId, e.getMessage());
+                }
                 return;
             }
             // 回退:将 report_food_suitability 映射为 Food 列表后继续处理
@@ -295,6 +314,14 @@ public class FoodRecommendService {
         // 家庭食材总览重算(T28):最新指数已全量覆盖写入,刷新所属家庭的持久化最小值总览。
         // try/catch + 只 warn,绝不因总览重算失败让报告确认入库主流程回滚(与归一化管道处理方式一致)
         refreshFamilyOverviews(writeKey);
+
+        // 迁移504:报告基线刷新成功后同步重建用户当前食材推荐;只读报告基线,绝不回写 food_recommend_idx.index_score
+        try {
+            userCurrentFoodService.rebuildForUser(writeKey, subjectMemberId);
+        } catch (Exception e) {
+            log.warn("用户当前食材推荐重建失败 writeKey={} memberId={}: {}",
+                    writeKey, subjectMemberId, e.getMessage());
+        }
     }
 
     /**

+ 18 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/ReportSurveyService.java

@@ -2,8 +2,10 @@ package com.etotem.cfc.service;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.etotem.cfc.entity.DietPreferences;
+import com.etotem.cfc.entity.FamilyMember;
 import com.etotem.cfc.entity.ReportSurvey;
 import com.etotem.cfc.mapper.DietPreferencesMapper;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.etotem.cfc.mapper.ReportSurveyMapper;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -28,6 +30,13 @@ public class ReportSurveyService {
     @Resource
     private DietPreferencesMapper dietPreferencesMapper;
 
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    /** 迁移504:报告调研问卷写入饮食偏好后重建用户当前食材推荐 */
+    @Resource
+    private UserCurrentFoodService userCurrentFoodService;
+
     private final ObjectMapper objectMapper = new ObjectMapper();
 
     /**
@@ -114,6 +123,15 @@ public class ReportSurveyService {
         }
         log.info("饮食偏好已同步: memberId={}, absoluteAvoid={}, mustEat={}, religiousDiet={}",
                 memberId, absoluteAvoid, mustEat, religiousDiet);
+
+        // 迁移504:报告问卷偏好变化后同步重算当前食材推荐(幂等,失败不影响问卷提交)
+        try {
+            FamilyMember member = familyMemberMapper.selectById(memberId);
+            Long uid = (member != null && member.getUserId() != null) ? member.getUserId() : memberId;
+            userCurrentFoodService.rebuildForUser(uid, memberId);
+        } catch (Exception e) {
+            log.warn("报告问卷保存后当前食材推荐重建失败 memberId={}: {}", memberId, e.getMessage());
+        }
     }
 
     private String toJSON(Object obj) {

+ 480 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/UserCurrentFoodService.java

@@ -0,0 +1,480 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.DietPreferences;
+import com.etotem.cfc.entity.FamilyMember;
+import com.etotem.cfc.entity.Food;
+import com.etotem.cfc.entity.FoodRecommendIndex;
+import com.etotem.cfc.entity.UserCurrentFoodRecommend;
+import com.etotem.cfc.mapper.FamilyMemberMapper;
+import com.etotem.cfc.mapper.FoodRecommendIndexMapper;
+import com.etotem.cfc.mapper.UserCurrentFoodRecommendMapper;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * 用户当前食材推荐(迁移504 / 个性化食谱生成)。
+ *
+ * <p>报告基线({@code food_recommend_idx})之上按问卷/偏好重算出「当前可用食材清单」,
+ * 食谱生成只读这份清单;重建只写 {@code user_current_food_recommend},绝不回写报告原始分。</p>
+ *
+ * <p>刻意不注入 {@link FoodRecommendService}(后者将注入本服务,避免循环依赖);
+ * 成员 → users.id 的归一在本服务内直接用 {@link FamilyMemberMapper} 完成。</p>
+ */
+@Slf4j
+@Service
+public class UserCurrentFoodService {
+
+    private static final int SELECTED_FOODS_LIMIT = 30;
+    private static final int ADJUSTMENT_REASON_MAX_LEN = 500;
+
+    @Resource
+    private UserCurrentFoodRecommendMapper userCurrentFoodRecommendMapper;
+
+    @Resource
+    private FoodRecommendIndexMapper foodRecommendIndexMapper;
+
+    @Resource
+    private HealthFilterService healthFilterService;
+
+    @Resource
+    private FamilyMemberMapper familyMemberMapper;
+
+    /** 仅用于补齐食材 category / allergens / dietType,使问卷判定口径与食材页一致 */
+    @Resource
+    private FoodService foodService;
+
+    private final ObjectMapper objectMapper = new ObjectMapper();
+
+    /**
+     * 重建指定用户的当前食材推荐。
+     *
+     * @param userId   归一后的 users.id(调用方负责归一;与 food_recommend_idx.user_id 同口径)
+     * @param memberId 原始成员卡 id(family_members.id),仅用于加载问卷画像/偏好;可为 null
+     */
+    @Transactional
+    public void rebuildForUser(Long userId, Long memberId) {
+        if (userId == null) {
+            return;
+        }
+        List<FoodRecommendIndex> indices = foodRecommendIndexMapper.selectList(
+                new LambdaQueryWrapper<FoodRecommendIndex>()
+                        .eq(FoodRecommendIndex::getUserId, userId));
+        if (indices == null || indices.isEmpty()) {
+            // 无报告基线 → 清空当前表,生成侧 hasData=false
+            userCurrentFoodRecommendMapper.delete(new LambdaQueryWrapper<UserCurrentFoodRecommend>()
+                    .eq(UserCurrentFoodRecommend::getUserId, userId));
+            return;
+        }
+
+        // 问卷画像/偏好按原始成员 id 加载,避免一个 users.id 对应多张成员卡时取错问卷
+        HealthFilterService.HealthProfile profile = null;
+        DietPreferences prefs = null;
+        try {
+            profile = healthFilterService.loadProfile(memberId, userId, null);
+            prefs = healthFilterService.loadDietPreferences(memberId);
+        } catch (Exception e) {
+            log.warn("加载用户{}当前食材问卷画像失败 memberId={}: {}", userId, memberId, e.getMessage());
+        }
+
+        Map<Long, Food> foodMap = loadFoods(indices);
+        Date now = new Date();
+        List<UserCurrentFoodRecommend> targetRows = new ArrayList<>();
+        Set<Long> baselineFoodIds = new HashSet<>();
+
+        for (FoodRecommendIndex idx : indices) {
+            Long foodId = idx.getFoodId();
+            if (foodId == null) {
+                // 唯一键 (user_id, food_id) 需要确定 food_id,跳过脏数据
+                continue;
+            }
+            baselineFoodIds.add(foodId);
+
+            Food food = buildFood(idx, foodMap.get(foodId));
+            String adjustment = "normal";
+            String reason = "";
+            if (profile != null) {
+                try {
+                    HealthFilterService.FoodAdjustmentResult adj =
+                            healthFilterService.assessFoodAdjustment(profile, prefs, food);
+                    if (adj != null) {
+                        adjustment = adj.adjustment != null ? adj.adjustment : "normal";
+                        reason = adj.reason != null ? adj.reason : "";
+                    }
+                } catch (Exception e) {
+                    log.warn("食材{}问卷调整判定失败 userId={}: {}", food.getName(), userId, e.getMessage());
+                }
+            }
+
+            int baseScore = idx.getIndexScore() != null ? idx.getIndexScore() : 0;
+            int currentScore = (int) Math.round(FoodRecommendWeightEngine.clamp(
+                    baseScore + FoodRecommendWeightEngine.healthAdjustScore(adjustment)));
+
+            UserCurrentFoodRecommend row = new UserCurrentFoodRecommend();
+            row.setUserId(userId);
+            row.setFoodId(foodId);
+            row.setFoodName(idx.getFoodName() != null ? idx.getFoodName() : food.getName());
+            row.setCategory(food.getCategory());
+            row.setBaseScore(baseScore);
+            row.setSourceReportId(idx.getHealthReportId());
+            row.setAdjustment(adjustment);
+            row.setAdjustmentReason(truncate(reason, ADJUSTMENT_REASON_MAX_LEN));
+            row.setCurrentScore(currentScore);
+            row.setRebuiltAt(now);
+            targetRows.add(row);
+        }
+
+        // 删除基线中已不存在的行;空基线时全删(notIn 空集合的 SQL 语义不可靠)
+        LambdaQueryWrapper<UserCurrentFoodRecommend> staleWrapper =
+                new LambdaQueryWrapper<UserCurrentFoodRecommend>().eq(UserCurrentFoodRecommend::getUserId, userId);
+        if (baselineFoodIds.isEmpty()) {
+            userCurrentFoodRecommendMapper.delete(staleWrapper);
+        } else {
+            userCurrentFoodRecommendMapper.delete(staleWrapper.notIn(UserCurrentFoodRecommend::getFoodId, baselineFoodIds));
+        }
+
+        Map<Long, UserCurrentFoodRecommend> existingMap = new HashMap<>();
+        List<UserCurrentFoodRecommend> existingRows = userCurrentFoodRecommendMapper.selectList(
+                new LambdaQueryWrapper<UserCurrentFoodRecommend>()
+                        .eq(UserCurrentFoodRecommend::getUserId, userId));
+        if (existingRows != null) {
+            for (UserCurrentFoodRecommend row : existingRows) {
+                if (row != null && row.getFoodId() != null) {
+                    existingMap.put(row.getFoodId(), row);
+                }
+            }
+        }
+
+        for (UserCurrentFoodRecommend row : targetRows) {
+            UserCurrentFoodRecommend old = existingMap.get(row.getFoodId());
+            if (old == null) {
+                userCurrentFoodRecommendMapper.insert(row);
+            } else if (changed(old, row)) {
+                row.setId(old.getId());
+                userCurrentFoodRecommendMapper.updateById(row);
+            }
+        }
+    }
+
+    /** 用户当前食材全量列表,按当前分降序 */
+    public List<UserCurrentFoodRecommend> getCurrentFoods(Long userId) {
+        if (userId == null) {
+            return new ArrayList<>();
+        }
+        return userCurrentFoodRecommendMapper.selectList(
+                new LambdaQueryWrapper<UserCurrentFoodRecommend>()
+                        .eq(UserCurrentFoodRecommend::getUserId, userId)
+                        .orderByDesc(UserCurrentFoodRecommend::getCurrentScore));
+    }
+
+    /** 是否已有当前食材数据 */
+    public boolean hasData(Long userId) {
+        if (userId == null) {
+            return false;
+        }
+        Long count = userCurrentFoodRecommendMapper.selectCount(
+                new LambdaQueryWrapper<UserCurrentFoodRecommend>()
+                        .eq(UserCurrentFoodRecommend::getUserId, userId));
+        return count != null && count > 0;
+    }
+
+    /**
+     * 为食谱生成构建逐成员上下文(个人食材 + 合并约束 + 缺食材成员)。
+     *
+     * <p>{@code strictAllExplicit} 只影响 {@code hasMissing} 语义:显式传入参与成员时为 true——任一成员
+     * 缺食材即由调用方阻断;隐式兜底成员时为 false——缺食材仅通过 {@code missingMemberNames} 提示,
+     * 由调用方决定是否继续生成。</p>
+     */
+    public Map<String, Object> buildGenerationContext(List<Long> participantMemberIds, boolean strictAllExplicit) {
+        Map<String, List<String>> constraints = new LinkedHashMap<String, List<String>>();
+        constraints.put("allergies", new ArrayList<String>());
+        constraints.put("diseases", new ArrayList<String>());
+        constraints.put("medications", new ArrayList<String>());
+        constraints.put("healthGoals", new ArrayList<String>());
+        constraints.put("cuisinePrefs", new ArrayList<String>());
+        constraints.put("flavorPrefs", new ArrayList<String>());
+        constraints.put("spiceLevels", new ArrayList<String>());
+        constraints.put("mustEat", new ArrayList<String>());
+
+        List<String> missingMemberNames = new ArrayList<String>();
+        List<Map<String, Object>> candidates = new ArrayList<Map<String, Object>>();
+
+        if (participantMemberIds != null) {
+            for (Long memberId : participantMemberIds) {
+                if (memberId == null) {
+                    continue;
+                }
+                try {
+                    FamilyMember fm = familyMemberMapper.selectById(memberId);
+                    Long uid = (fm != null && fm.getUserId() != null) ? fm.getUserId() : memberId;
+                    String memberName = (fm != null && fm.getNickname() != null && !fm.getNickname().trim().isEmpty())
+                            ? fm.getNickname() : String.valueOf(memberId);
+
+                    List<UserCurrentFoodRecommend> foods = getCurrentFoods(uid);
+                    boolean hasAvailableFood = false;
+                    if (foods != null) {
+                        for (UserCurrentFoodRecommend row : foods) {
+                            if (row == null || "blocked".equalsIgnoreCase(row.getAdjustment())) {
+                                continue;
+                            }
+                            hasAvailableFood = true;
+                            Map<String, Object> item = new LinkedHashMap<String, Object>();
+                            item.put("memberId", memberId);
+                            item.put("memberName", memberName);
+                            item.put("name", row.getFoodName());
+                            item.put("score", row.getCurrentScore());
+                            item.put("adjustment", row.getAdjustment() != null ? row.getAdjustment() : "normal");
+                            candidates.add(item);
+                        }
+                    }
+                    if (!hasAvailableFood) {
+                        missingMemberNames.add(memberName);
+                    }
+
+                    // 硬禁忌取并集(安全优先);软偏好逐成员收集后交由 prompt 使用
+                    try {
+                        HealthFilterService.HealthProfile profile =
+                                healthFilterService.loadProfile(memberId, uid, null);
+                        if (profile != null) {
+                            addAll(constraints.get("allergies"), profile.allergies);
+                            addAll(constraints.get("diseases"), profile.diseases);
+                            addAll(constraints.get("medications"), profile.medications);
+                        }
+                    } catch (Exception e) {
+                        log.warn("成员{}健康画像合并失败: {}", memberId, e.getMessage());
+                    }
+                    try {
+                        DietPreferences prefs = healthFilterService.loadDietPreferences(memberId);
+                        if (prefs != null) {
+                            addAll(constraints.get("healthGoals"), parseValues(prefs.getHealthGoals()));
+                            addAll(constraints.get("cuisinePrefs"), parseValues(prefs.getCuisinePref()));
+                            addAll(constraints.get("flavorPrefs"), parseValues(prefs.getFlavorPref()));
+                            addAll(constraints.get("mustEat"), parseValues(prefs.getMustEat()));
+                            if (prefs.getSpiceLevel() != null) {
+                                constraints.get("spiceLevels").add(String.valueOf(prefs.getSpiceLevel()));
+                            }
+                        }
+                    } catch (Exception e) {
+                        log.warn("成员{}饮食偏好合并失败: {}", memberId, e.getMessage());
+                    }
+                } catch (Exception e) {
+                    log.warn("成员{}当前食材解析失败,已跳过: {}", memberId, e.getMessage());
+                }
+            }
+        }
+
+        // 按食材名去重:保留最大分数,任一人 boost 即标 boost;按分数降序取 Top 30
+        Map<String, Map<String, Object>> dedup = new LinkedHashMap<String, Map<String, Object>>();
+        Map<String, Boolean> boostSeen = new HashMap<String, Boolean>();
+        for (Map<String, Object> item : candidates) {
+            String name = (String) item.get("name");
+            if (name == null || name.trim().isEmpty()) {
+                continue;
+            }
+            boolean boost = "boost".equalsIgnoreCase((String) item.get("adjustment"));
+            Map<String, Object> prev = dedup.get(name);
+            if (prev == null) {
+                dedup.put(name, new LinkedHashMap<String, Object>(item));
+                boostSeen.put(name, Boolean.valueOf(boost));
+                continue;
+            }
+            boostSeen.put(name, Boolean.valueOf(Boolean.TRUE.equals(boostSeen.get(name)) || boost));
+            if (intValue(item.get("score")) > intValue(prev.get("score"))) {
+                dedup.put(name, new LinkedHashMap<String, Object>(item));
+            }
+        }
+        List<Map<String, Object>> selected = new ArrayList<Map<String, Object>>(dedup.values());
+        for (Map<String, Object> item : selected) {
+            if (Boolean.TRUE.equals(boostSeen.get((String) item.get("name")))) {
+                item.put("adjustment", "boost");
+            }
+        }
+        selected.sort((a, b) -> Integer.compare(intValue(b.get("score")), intValue(a.get("score"))));
+        if (selected.size() > SELECTED_FOODS_LIMIT) {
+            selected = new ArrayList<Map<String, Object>>(selected.subList(0, SELECTED_FOODS_LIMIT));
+        }
+
+        String selectedFoodsJson;
+        try {
+            selectedFoodsJson = objectMapper.writeValueAsString(selected);
+        } catch (Exception e) {
+            log.warn("selected_foods 序列化失败: {}", e.getMessage());
+            selectedFoodsJson = "[]";
+        }
+
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+        result.put("selectedFoodsJson", selectedFoodsJson);
+        result.put("constraints", constraints);
+        result.put("missingMemberNames", missingMemberNames);
+        result.put("hasMissing", Boolean.valueOf(!missingMemberNames.isEmpty() && strictAllExplicit));
+        return result;
+    }
+
+    // ---------------------------------------------------------------- helpers
+
+    private Map<Long, Food> loadFoods(List<FoodRecommendIndex> indices) {
+        Map<Long, Food> map = new HashMap<Long, Food>();
+        Set<Long> foodIds = new HashSet<Long>();
+        for (FoodRecommendIndex idx : indices) {
+            if (idx != null && idx.getFoodId() != null) {
+                foodIds.add(idx.getFoodId());
+            }
+        }
+        if (foodIds.isEmpty()) {
+            return map;
+        }
+        try {
+            List<Food> foods = foodService.listByIds(new ArrayList<Long>(foodIds));
+            if (foods != null) {
+                for (Food f : foods) {
+                    if (f != null && f.getId() != null) {
+                        map.put(f.getId(), f);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.warn("当前食材分类/禁忌补齐失败: {}", e.getMessage());
+        }
+        return map;
+    }
+
+    /** 由报告基线行构造 Food:报告分/食材名来自 index,分类与禁忌来自 foods 表(存在时) */
+    private Food buildFood(FoodRecommendIndex idx, Food persisted) {
+        Food food = new Food();
+        if (persisted != null) {
+            food.setName(persisted.getName() != null ? persisted.getName() : idx.getFoodName());
+            food.setCategory(persisted.getCategory());
+            food.setAllergens(persisted.getAllergens());
+            food.setDietType(persisted.getDietType());
+        } else {
+            food.setName(idx.getFoodName());
+        }
+        food.setScore(idx.getIndexScore());
+        return food;
+    }
+
+    private boolean changed(UserCurrentFoodRecommend old, UserCurrentFoodRecommend row) {
+        return !Objects.equals(old.getFoodName(), row.getFoodName())
+                || !Objects.equals(old.getCategory(), row.getCategory())
+                || !Objects.equals(old.getBaseScore(), row.getBaseScore())
+                || !Objects.equals(old.getSourceReportId(), row.getSourceReportId())
+                || !Objects.equals(old.getAdjustment(), row.getAdjustment())
+                || !Objects.equals(old.getAdjustmentReason(), row.getAdjustmentReason())
+                || !Objects.equals(old.getCurrentScore(), row.getCurrentScore());
+    }
+
+    private String truncate(String text, int maxLen) {
+        if (text == null) {
+            return "";
+        }
+        return text.length() <= maxLen ? text : text.substring(0, maxLen);
+    }
+
+    private void addAll(List<String> target, Set<String> values) {
+        if (target == null || values == null) {
+            return;
+        }
+        for (String v : values) {
+            if (v != null && !v.trim().isEmpty()) {
+                target.add(v.trim());
+            }
+        }
+    }
+
+    private void addAll(List<String> target, List<String> values) {
+        if (target == null || values == null) {
+            return;
+        }
+        for (String v : values) {
+            if (v != null && !v.trim().isEmpty()) {
+                target.add(v.trim());
+            }
+        }
+    }
+
+    /** 兼容 JSON 数组/单值与逗号分隔字符串,解析异常时退化为分隔符切分 */
+    private List<String> parseValues(String raw) {
+        List<String> values = new ArrayList<String>();
+        if (raw == null || raw.trim().isEmpty()) {
+            return values;
+        }
+        String text = raw.trim();
+        try {
+            JsonNode node = objectMapper.readTree(text);
+            if (node != null) {
+                if (node.isArray()) {
+                    for (JsonNode child : node) {
+                        appendNodeValue(values, child);
+                    }
+                    return values;
+                }
+                if (node.isValueNode()) {
+                    String v = node.asText();
+                    if (!v.trim().isEmpty()) {
+                        values.add(v.trim());
+                    }
+                    return values;
+                }
+                if (node.isObject()) {
+                    java.util.Iterator<JsonNode> it = node.elements();
+                    while (it.hasNext()) {
+                        appendNodeValue(values, it.next());
+                    }
+                    return values;
+                }
+            }
+        } catch (Exception e) {
+            // 非 JSON → 按分隔符切分
+        }
+        for (String part : text.split("[,,、\\s]+")) {
+            if (!part.trim().isEmpty()) {
+                values.add(part.trim());
+            }
+        }
+        return values;
+    }
+
+    private void appendNodeValue(List<String> values, JsonNode node) {
+        if (node == null || node.isNull()) {
+            return;
+        }
+        if (node.isArray()) {
+            for (JsonNode child : node) {
+                appendNodeValue(values, child);
+            }
+        } else if (node.isValueNode()) {
+            String v = node.asText();
+            if (!v.trim().isEmpty()) {
+                values.add(v.trim());
+            }
+        }
+    }
+
+    private int intValue(Object value) {
+        if (value instanceof Number) {
+            return ((Number) value).intValue();
+        }
+        if (value instanceof String) {
+            try {
+                return Integer.parseInt((String) value);
+            } catch (NumberFormatException e) {
+                return 0;
+            }
+        }
+        return 0;
+    }
+}

+ 13 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/impl/HealthStatusServiceImpl.java

@@ -5,17 +5,24 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
 import com.etotem.cfc.entity.HealthStatus;
 import com.etotem.cfc.mapper.HealthStatusMapper;
 import com.etotem.cfc.service.HealthStatusService;
+import com.etotem.cfc.service.UserCurrentFoodService;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
 import java.util.Date;
 
+@Slf4j
 @Service
 public class HealthStatusServiceImpl implements HealthStatusService {
 
     @Resource
     private HealthStatusMapper healthStatusMapper;
 
+    /** 迁移504:健康问卷保存成功后重建用户当前食材推荐 */
+    @Resource
+    private UserCurrentFoodService userCurrentFoodService;
+
     @Override
     public HealthStatus getByUserId(Long userId) {
         if (userId == null) return null;
@@ -75,6 +82,12 @@ public class HealthStatusServiceImpl implements HealthStatusService {
                     .set(HealthStatus::getSignature, null)
                     .set(HealthStatus::getSignedAt, null));
         }
+        // 迁移504:问卷变化后同步重算当前食材推荐(幂等,失败不影响问卷保存)
+        try {
+            userCurrentFoodService.rebuildForUser(userId, memberId);
+        } catch (Exception e) {
+            log.warn("健康问卷保存后当前食材推荐重建失败 userId={} memberId={}: {}", userId, memberId, e.getMessage());
+        }
         return getByMemberId(userId, memberId);
     }
 

+ 11 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/impl/SurveyServiceImpl.java

@@ -11,6 +11,7 @@ import com.etotem.cfc.mapper.FamilyMemberMapper;
 import com.etotem.cfc.service.AiGateway;
 import com.etotem.cfc.service.HealthStatusService;
 import com.etotem.cfc.service.SurveyService;
+import com.etotem.cfc.service.UserCurrentFoodService;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -48,6 +49,10 @@ public class SurveyServiceImpl implements SurveyService {
     @Resource
     private HealthStatusService healthStatusService;
 
+    /** 迁移504:健康阅卷同步后重建用户当前食材推荐 */
+    @Resource
+    private UserCurrentFoodService userCurrentFoodService;
+
     @Override
     public SurveyTemplate saveTemplate(SurveyTemplate template, Long adminId) {
         if (template.getId() != null) {
@@ -249,6 +254,12 @@ public class SurveyServiceImpl implements SurveyService {
         status.setLifestyle(text(form, "lifestyle"));
         status.setNotes(text(form, "notes"));
         healthStatusService.saveForMember(member.getUserId(), member.getId(), status);
+        // 迁移504:健康问卷已同步,重建当前食材推荐(幂等,失败不影响阅卷提交)
+        try {
+            userCurrentFoodService.rebuildForUser(member.getUserId(), member.getId());
+        } catch (Exception e) {
+            log.warn("健康阅卷同步后当前食材推荐重建失败 memberId={}: {}", member.getId(), e.getMessage());
+        }
     }
 
     private java.math.BigDecimal dec(com.fasterxml.jackson.databind.JsonNode node, String key) {

+ 21 - 0
cfc-backend/src/main/resources/schema.sql

@@ -7754,3 +7754,24 @@ CREATE TABLE IF NOT EXISTS food_recommend_weight_rule (
     KEY idx_enabled (enabled)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='食材推荐加权规则表';
 
+-- ============================================================
+-- 用户当前食材推荐表(迁移504 / 个性化食谱生成,spec 2026-11-26)
+-- 报告基线之上按问卷重算出的当前可用食材清单;食谱生成只读此表,
+-- 报告原始分存 base_score 且永不被问卷覆盖。MySQL 8.0 兼容:索引内无函数表达式。
+-- ============================================================
+CREATE TABLE IF NOT EXISTS user_current_food_recommend (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
+    user_id BIGINT NOT NULL COMMENT '归一后的 users.id(与 food_recommend_idx.user_id 同口径)',
+    food_id BIGINT NOT NULL COMMENT '食材ID',
+    food_name VARCHAR(100) COMMENT '食材名称',
+    category VARCHAR(50) COMMENT '食材分类',
+    base_score INT NOT NULL COMMENT '报告原始分(复制自 index_score,永不被问卷覆盖)',
+    source_report_id BIGINT COMMENT '来源健康报告ID(food_recommend_idx.health_report_id)',
+    adjustment VARCHAR(16) NOT NULL DEFAULT 'normal' COMMENT 'normal/boost/warning/blocked',
+    adjustment_reason VARCHAR(500) COMMENT '调整命中原因',
+    current_score INT NOT NULL COMMENT 'base_score + 权重(adjustment),clamp 到 [-100,100]',
+    rebuilt_at DATETIME NOT NULL COMMENT '最近重建时间',
+    UNIQUE KEY uk_user_food (user_id, food_id),
+    KEY idx_user_score (user_id, current_score)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户当前食材推荐(报告基线+问卷重算,食谱生成只读此表)';
+

+ 111 - 0
cfc-langgraph/app/api/meal.py

@@ -41,6 +41,106 @@ MENU_GENERATE_TEMPLATE = """请为{participant_count}人生成{date}的一日三
 6. 只返回 JSON,不要其他文字"""
 
 
+# Java 侧个性化画像字段 -> prompt 约束标签。同一标签可有多个别名(驼峰 / 下划线)。
+_CONSTRAINT_ALIASES = (
+    (("allergies",), "禁忌"),
+    (("diseases",), "疾病禁忌"),
+    (("medications",), "用药禁忌"),
+    (("healthGoals", "health_goals"), "健康目标"),
+    (("cuisinePrefs", "cuisine_pref"), "菜系偏好"),
+    (("flavorPrefs", "flavor_pref"), "口味偏好"),
+    (("spiceLevels", "spice_level"), "辣度偏好"),
+    (("mustEat", "must_eat"), "优先食材(用户喜好,优先安排)"),
+)
+_TOKEN_SEPARATORS = re.compile(r"[,,、;;]+")
+
+
+def _as_text(value):
+    """把约束值安全转成文本;列表/字典取元素;空值返回空串;任何异常都不外抛。"""
+    if value is None:
+        return ""
+    if isinstance(value, str):
+        return value.strip()
+    if isinstance(value, (list, tuple, set)):
+        items = value
+    elif isinstance(value, dict):
+        items = value.values()
+    else:
+        items = (value,)
+    parts = []
+    for item in items:
+        try:
+            text = str(item).strip()
+        except Exception:
+            continue
+        if text:
+            parts.append(text)
+    return ", ".join(parts)
+
+
+def _split_tokens(text):
+    """把一行约束值切成去重用的 token(兼容中英文逗号/顿号/分号)。"""
+    tokens = []
+    for token in _TOKEN_SEPARATORS.split(text):
+        token = token.strip()
+        if token and token not in tokens:
+            tokens.append(token)
+    return tokens
+
+
+def _merge_constraints(constraints, raw):
+    """把 req.constraints 增量合并进现有 constraints:按标签去重、忽略空值。"""
+    if not isinstance(raw, dict):
+        return
+    for keys, label in _CONSTRAINT_ALIASES:
+        values = []
+        for key in keys:
+            text = _as_text(raw.get(key))
+            if text and text not in values:
+                values.append(text)
+        if not values:
+            continue
+        prefix = label + ": "
+        covered = set()
+        for line in constraints:
+            if isinstance(line, str) and line.startswith(prefix):
+                covered.update(_split_tokens(line[len(prefix):]))
+        fresh = []
+        for value in values:
+            for token in _split_tokens(value):
+                if token and token not in covered and token not in fresh:
+                    fresh.append(token)
+        if fresh:
+            constraints.append(prefix + ", ".join(fresh))
+
+
+def _append_variation_constraints(constraints, req):
+    """追加「换花样」相关约束:最近已用菜名 + 变化种子。"""
+    names = getattr(req, "exclude_dish_names", None)
+    if isinstance(names, str):
+        names = [names]
+    elif isinstance(names, (list, tuple, set)):
+        names = list(names)
+    else:
+        names = []
+    cleaned = []
+    for name in names:
+        try:
+            text = str(name).strip()
+        except Exception:
+            continue
+        if text and text not in cleaned:
+            cleaned.append(text)
+        if len(cleaned) >= 20:
+            break
+    if cleaned:
+        constraints.append("换花样:避免使用最近已采用的菜名:" + "、".join(cleaned))
+
+    seed = getattr(req, "variation_seed", None)
+    if seed is not None:
+        constraints.append(f"本次生成变化种子:{seed},请让菜品搭配与上次不同")
+
+
 @router.post("/food/recognize", response_model=FoodRecognizeResponse)
 async def recognize_food(req: FoodRecognizeRequest):
     """食材识别: 上传图片 URL, 返回识别食材列表"""
@@ -122,6 +222,17 @@ async def generate_menu(req: MenuGenerateRequest):
         if req.spice_level is not None:
             constraints.append(f"辣度: {req.spice_level}/5")
 
+        # 个性化画像:把 Java 下发的 constraints 字典增量合并进同一份 constraints,
+        # 不新增占位符、不改动 prompt 模板,旧调用方不传该字段时行为完全不变。
+        try:
+            _merge_constraints(constraints, getattr(req, "constraints", None))
+        except Exception as e:
+            logger.warning("合并用户个性化约束失败,忽略该字段: %s", e)
+        try:
+            _append_variation_constraints(constraints, req)
+        except Exception as e:
+            logger.warning("合并换花样约束失败,忽略该字段: %s", e)
+
         # 菜数要求(CR-C / R-05):注入既有 {constraints_text} 占位符,不新增占位符(F-18),
         # 因此 DB 模板(get_prompt)与本地模板两个来源同时生效;不依赖 prompt 的正确性,
         # 菜数硬保证由 Java DietRecommendationService.normalizeMenu 兜底。

+ 5 - 0
cfc-langgraph/app/models/meal.py

@@ -31,6 +31,11 @@ class MenuGenerateRequest(BaseModel):
     # CR-C / AC-23:Java AiGateway 下发的午/晚餐标准菜数 D(N)。
     # 默认 None 让旧调用方 100% 兼容;菜数硬保证在 Java normalizeMenu,此处仅软引导 prompt。
     dish_count: Optional[int] = None
+    # 个性化食谱生成(Java 侧下发的饮食画像 / 换花样参数)。
+    # 均为可选且默认 None,旧调用方不传时行为完全不变。
+    constraints: Optional[dict] = None
+    exclude_dish_names: Optional[List[str]] = None
+    variation_seed: Optional[int] = None
 
 
 class MenuIngredient(BaseModel):