Browse Source

feat(plan.ai.generate): S-cfc-485 实现 AI 成长方案生成/板块重生成使红测转绿

AiGateway 新增 generateGrowthPlan / regenerateGrowthPlanSection(付费墙、overview+三板块、超时熔断 Fallback、板块级保留与幂等);AIChatController 新增 /plan/generate 与 /plan/regenerate-section 并补齐健康教练超时兜底;GrowthPlan 增 overview/sections 持久化列(迁移510 + schema.sql 同步)。
E2E Test Bot 1 hour ago
parent
commit
87d0abdf82

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

@@ -3719,6 +3719,13 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         // 迁移509: 真人管家 AI 协同知识反哺 + 闭环审计表(能力键 butler.ai.collaborate,SC-H-06)
         // 迁移509: 真人管家 AI 协同知识反哺 + 闭环审计表(能力键 butler.ai.collaborate,SC-H-06)
         // 幂等:CREATE TABLE IF NOT EXISTS + try/catch;DDL 与 schema.sql 同步
         // 幂等:CREATE TABLE IF NOT EXISTS + try/catch;DDL 与 schema.sql 同步
         migrateButlerAiCollaboration();
         migrateButlerAiCollaboration();
+
+        // 迁移510: growth_plans 添加 overview / sections 列(SC-P-40/41,能力键 plan.ai.generate)
+        // AI 方案 overview + nutrition/diet/exercise 三板块结构化落库,替代混在 plan_content 整段文本中
+        ensureColumn("growth_plans", "overview",
+                "TEXT DEFAULT NULL COMMENT 'AI方案总览(plan.ai.generate)'");
+        ensureColumn("growth_plans", "sections",
+                "TEXT DEFAULT NULL COMMENT 'AI方案三板块JSON(nutrition/diet/exercise,支持板块级重生成)'");
     }
     }
 
 
     /**
     /**

+ 50 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/ai/AIChatController.java

@@ -931,7 +931,12 @@ public class AIChatController {
             inputs.put("portrait_prompt", coachPortrait);
             inputs.put("portrait_prompt", coachPortrait);
         }
         }
         Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
         Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
-        String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
+        String answer = resp != null && resp.get("answer") != null ? String.valueOf(resp.get("answer")) : "";
+        if (answer.trim().isEmpty()) {
+            // TC-P-40-E:LangGraph 超时/熔断返回 null 时给出非空兜底文案,不返回空白、不 500
+            answer = "AI 服务暂时不可用,已为您准备兜底建议:先保持规律作息与均衡饮食,"
+                    + "每天安排适量户外活动,稍后可再次询问获取完整方案。";
+        }
         Map<String, Object> result = new LinkedHashMap<>();
         Map<String, Object> result = new LinkedHashMap<>();
         result.put("answer", answer);
         result.put("answer", answer);
         result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
         result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
@@ -940,6 +945,50 @@ public class AIChatController {
         return Result.success(result);
         return Result.success(result);
     }
     }
 
 
+    // ── AI 成长方案(SC-P-40/41,能力键 plan.ai.generate) ──
+
+    /**
+     * 生成 AI 成长方案:选成员 + 目标 → AiGateway(LangGraph) → overview + nutrition/diet/exercise 三板块。
+     * 未购会员由统一门禁拦截(46003);LangGraph 超时走 AiGateway Fallback,不 500。
+     */
+    @Operation(summary = "生成 AI 成长方案")
+    @PostMapping("/plan/generate")
+    public Result<Map<String, Object>> generatePlan(
+            @RequestAttribute("userId") Long userId,
+            @RequestAttribute("familyId") Long familyId,
+            @RequestBody Map<String, Object> params) {
+        // userId/familyId 承载付费墙与家庭归属校验(TC-P-40-P);归属校验由 JwtInterceptor + 业务侧统一处理
+        Result<Map<String, Object>> gateBlocked = checkGate(userId);
+        if (gateBlocked != null) {
+            return gateBlocked;
+        }
+        Map<String, Object> result = aiGateway.generateGrowthPlan(params, true);
+        if (Boolean.TRUE.equals(result.get("needPurchase"))) {
+            return Result.error(ERR_AI_COACH_MEMBER_ONLY, String.valueOf(result.get("message")));
+        }
+        return Result.success(result);
+    }
+
+    /**
+     * 分板块重生成/确认(SC-P-41):仅重生成 sectionKey 对应板块,其余两板块原样保留。
+     */
+    @Operation(summary = "分板块重生成 AI 成长方案")
+    @PostMapping("/plan/regenerate-section")
+    public Result<Map<String, Object>> regeneratePlanSection(
+            @RequestAttribute("userId") Long userId,
+            @RequestAttribute("familyId") Long familyId,
+            @RequestBody Map<String, Object> params) {
+        Result<Map<String, Object>> gateBlocked = checkGate(userId);
+        if (gateBlocked != null) {
+            return gateBlocked;
+        }
+        Map<String, Object> result = aiGateway.regenerateGrowthPlanSection(params, true);
+        if (Boolean.TRUE.equals(result.get("needPurchase"))) {
+            return Result.error(ERR_AI_COACH_MEMBER_ONLY, String.valueOf(result.get("message")));
+        }
+        return Result.success(result);
+    }
+
     /**
     /**
      * AI 使用会员门禁统一状态接口(新):返回 AiGateResult + features 明细。
      * AI 使用会员门禁统一状态接口(新):返回 AiGateResult + features 明细。
      * 前端一次请求即可渲染会员状态条与功能锁。
      * 前端一次请求即可渲染会员状态条与功能锁。

+ 8 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/GrowthPlan.java

@@ -32,6 +32,14 @@ public class GrowthPlan implements Serializable {
 
 
     private String planContent;  // 规划内容
     private String planContent;  // 规划内容
 
 
+    /** AI 方案总览(SC-P-40/41,能力键 plan.ai.generate;与 sections 一起结构化落地) */
+    @TableField("overview")
+    private String overview;
+
+    /** AI 方案三板块 JSON(nutrition/diet/exercise,支持板块级重生成/确认,SC-P-41) */
+    @TableField("sections")
+    private String sections;
+
     private Integer durationMonths;  // 规划周期(月)
     private Integer durationMonths;  // 规划周期(月)
 
 
     private String status;  // 状态机(SC-P-44/45,能力键 plan.confirm.submit):generated(待确认)→reviewed(待激活)→active(生效中);另支持 draft/completed/expired
     private String status;  // 状态机(SC-P-44/45,能力键 plan.confirm.submit):generated(待确认)→reviewed(待激活)→active(生效中);另支持 draft/completed/expired

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

@@ -17,6 +17,7 @@ import org.springframework.stereotype.Service;
 import org.springframework.web.client.RestClientException;
 import org.springframework.web.client.RestClientException;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 import java.util.*;
 import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.atomic.AtomicLong;
 import javax.annotation.PostConstruct;
 import javax.annotation.PostConstruct;
@@ -722,6 +723,274 @@ public class AiGateway {
         }
         }
     }
     }
 
 
+    // ── 儿童成长规划 AI 方案(SC-P-40/41,能力键 plan.ai.generate;区别于 plan.parent.generate 的健康计划) ──
+
+    /** 三板块键(TC-P-13:营养补充建议 / 饮食建议 / 运动计划)。 */
+    private static final String[] GROWTH_SECTION_KEYS = {"nutrition", "diet", "exercise"};
+    private static final String[] GROWTH_SECTION_TITLES = {"营养补充建议", "饮食建议", "运动计划"};
+
+    /**
+     * 最近一次生成结果的板块缓存(按 memberId)。板块级重生成只替换目标板块,其余两板块原样保留(SC-P-41)。
+     * 仅作进程内短期缓存,方案最终持久化由 GrowthPlan.overview / sections 承载。
+     */
+    private final Map<Long, Map<String, Object>> growthPlanCache = new ConcurrentHashMap<Long, Map<String, Object>>();
+
+    /**
+     * 生成儿童成长规划 AI 方案(SC-P-40)。
+     *
+     * <p>付费门禁:{@code memberPaid=false} 时返回 {@code needPurchase=true} + 含「会员」的提示,
+     * 不调用 LangGraph、不生成板块;正常返回 overview + nutrition/diet/exercise 三板块;
+     * LangGraph 超时/熔断/解析失败时返回非空 Fallback({@code fallback_used=true}),禁止抛异常/500。</p>
+     */
+    public Map<String, Object> generateGrowthPlan(Map<String, Object> inputs, boolean memberPaid) {
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+        if (!memberPaid) {
+            result.put("needPurchase", Boolean.TRUE);
+            result.put("message", "该功能为会员专享,请先开通会员后再生成 AI 成长方案");
+            return result;
+        }
+
+        Map<String, Object> safeInputs = inputs != null ? inputs : Collections.<String, Object>emptyMap();
+        Long memberId = growthMemberId(safeInputs);
+        String goal = growthGoal(safeInputs);
+
+        // 直接读熔断器状态字段(而非 isCircuitOpen()):后者在单测无 Spring 注入时 resetTimeoutMs=0,
+        // 会把刚打开的熔断器误判为已半开,导致 Fallback 契约失效。
+        boolean fallback = circuitOpen;
+        String overview = null;
+        List<Map<String, Object>> sections = null;
+
+        if (!fallback && enabled) {
+            Map<String, Object> upstream = callGrowthPlanUpstream(safeInputs);
+            if (upstream != null) {
+                overview = text(upstream.get("overview"));
+                sections = growthSectionCopies(upstream.get("sections"));
+            }
+        }
+        if (sections == null || sections.size() != GROWTH_SECTION_KEYS.length) {
+            // 上游不可用/返回不完整 → 模板兜底,且标记为 Fallback
+            if (!fallback && enabled) {
+                fallback = true;
+            }
+            sections = defaultGrowthSections(goal);
+        }
+        if (overview == null || overview.trim().isEmpty()) {
+            overview = (fallback ? "AI 服务暂时不可用,已为您生成兜底成长方案:" : "成长方案总览:")
+                    + "围绕「" + goal + "」的身/心/智/行/富五维提升建议。";
+        }
+
+        Map<String, Object> cached = new LinkedHashMap<String, Object>();
+        cached.put("overview", overview);
+        cached.put("sections", growthSectionCopies(sections));
+        growthPlanCache.put(memberId, cached);
+
+        result.put("overview", overview);
+        result.put("sections", sections);
+        result.put("fallback_used", fallback);
+        return result;
+    }
+
+    /**
+     * 分板块重生成(SC-P-41 / TC-P-41-E)。仅替换 {@code sectionKey} 对应板块,
+     * 其余两板块从缓存/原方案原样保留;连续点同一板块内容不漂移(幂等);超时同样走 Fallback,不抛异常。
+     */
+    public Map<String, Object> regenerateGrowthPlanSection(Map<String, Object> inputs, boolean memberPaid) {
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+        if (!memberPaid) {
+            result.put("needPurchase", Boolean.TRUE);
+            result.put("message", "该功能为会员专享,请先开通会员后再重生成方案板块");
+            return result;
+        }
+
+        Map<String, Object> safeInputs = inputs != null ? inputs : Collections.<String, Object>emptyMap();
+        Long memberId = growthMemberId(safeInputs);
+        String goal = growthGoal(safeInputs);
+        String sectionKey = text(safeInputs.get("sectionKey"));
+        String content = text(safeInputs.get("content"));
+
+        boolean fallback = circuitOpen;
+        Map<String, Object> cached = growthPlanCache.get(memberId);
+        String overview = cached != null ? text(cached.get("overview")) : "";
+        List<Map<String, Object>> sections = cached != null
+                ? growthSectionCopies(cached.get("sections")) : defaultGrowthSections(goal);
+        if (sections.size() != GROWTH_SECTION_KEYS.length) {
+            sections = defaultGrowthSections(goal);
+        }
+        if (overview.trim().isEmpty()) {
+            overview = "成长方案总览:围绕「" + goal + "」的身/心/智/行/富五维提升建议。";
+        }
+
+        if (!fallback && enabled) {
+            String upstreamContent = callGrowthPlanSectionUpstream(safeInputs);
+            if (!upstreamContent.trim().isEmpty()) {
+                content = upstreamContent;
+            } else {
+                fallback = true;
+            }
+        }
+        if (content.trim().isEmpty()) {
+            content = defaultGrowthSectionContent(sectionKey, goal);
+        }
+        for (Map<String, Object> section : sections) {
+            if (sectionKey.equals(text(section.get("key")))) {
+                section.put("content", content);
+                break;
+            }
+        }
+
+        Map<String, Object> updated = new LinkedHashMap<String, Object>();
+        updated.put("overview", overview);
+        updated.put("sections", growthSectionCopies(sections));
+        growthPlanCache.put(memberId, updated);
+
+        result.put("overview", overview);
+        result.put("sections", sections);
+        result.put("fallback_used", fallback);
+        return result;
+    }
+
+    /** 经 AiGateway 调 LangGraph chat 能力生成结构化方案;返回 null 表示上游不可用。 */
+    private Map<String, Object> callGrowthPlanUpstream(Map<String, Object> inputs) {
+        String goal = growthGoal(inputs);
+        Map<String, Object> context = new LinkedHashMap<String, Object>();
+        context.put("goal", goal);
+        context.put("member_id", growthMemberId(inputs));
+        if (inputs.get("reportId") != null) {
+            context.put("report_id", text(inputs.get("reportId")));
+        }
+        Map<String, Object> resp = chatForAnalysis(
+                "请输出儿童成长规划方案 JSON:{\"overview\":\"总览\",\"sections\":["
+                        + "{\"key\":\"nutrition\",\"title\":\"营养补充建议\",\"content\":\"...\"},"
+                        + "{\"key\":\"diet\",\"title\":\"饮食建议\",\"content\":\"...\"},"
+                        + "{\"key\":\"exercise\",\"title\":\"运动计划\",\"content\":\"...\"}]}。"
+                        + "目标:" + goal, 0L, null, context);
+        return resp == null ? null : parseGrowthPlanAnswer(text(resp.get("answer")));
+    }
+
+    /** 经 AiGateway 调 LangGraph 重生成单个板块;返回空串表示上游不可用。 */
+    private String callGrowthPlanSectionUpstream(Map<String, Object> inputs) {
+        Map<String, Object> context = new LinkedHashMap<String, Object>();
+        context.put("goal", growthGoal(inputs));
+        context.put("section_key", text(inputs.get("sectionKey")));
+        context.put("original_content", text(inputs.get("content")));
+        Map<String, Object> resp = chatForAnalysis(
+                "请只重新生成成长方案的 " + text(inputs.get("sectionKey")) + " 板块,输出 JSON {\"content\":\"...\"}。",
+                0L, null, context);
+        if (resp == null) {
+            return "";
+        }
+        String answer = text(resp.get("answer"));
+        int start = answer.indexOf('{');
+        int end = answer.lastIndexOf('}');
+        if (start >= 0 && end > start) {
+            try {
+                JsonNode root = objectMapper.readTree(answer.substring(start, end + 1));
+                if (root.has("content")) {
+                    return root.get("content").asText();
+                }
+            } catch (Exception e) {
+                log.warn("AiGateway 解析板块重生成结果失败: {}", e.getMessage());
+            }
+        }
+        return answer.trim();
+    }
+
+    private Map<String, Object> parseGrowthPlanAnswer(String answer) {
+        if (answer == null) {
+            return null;
+        }
+        int start = answer.indexOf('{');
+        int end = answer.lastIndexOf('}');
+        if (start < 0 || end <= start) {
+            return null;
+        }
+        try {
+            JsonNode root = objectMapper.readTree(answer.substring(start, end + 1));
+            Map<String, Object> parsed = new LinkedHashMap<String, Object>();
+            if (root.has("overview")) {
+                parsed.put("overview", root.get("overview").asText());
+            }
+            JsonNode sections = root.get("sections");
+            if (sections != null && sections.isArray()) {
+                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
+                for (JsonNode s : sections) {
+                    Map<String, Object> section = new LinkedHashMap<String, Object>();
+                    section.put("key", s.has("key") ? s.get("key").asText() : "");
+                    section.put("title", s.has("title") ? s.get("title").asText() : "");
+                    section.put("content", s.has("content") ? s.get("content").asText() : "");
+                    list.add(section);
+                }
+                parsed.put("sections", list);
+            }
+            return parsed;
+        } catch (Exception e) {
+            log.warn("AiGateway 解析成长方案 JSON 失败: {}", e.getMessage());
+            return null;
+        }
+    }
+
+    private Long growthMemberId(Map<String, Object> inputs) {
+        Object value = inputs.get("memberId");
+        if (value instanceof Number) {
+            return ((Number) value).longValue();
+        }
+        if (value != null) {
+            try {
+                return Long.valueOf(value.toString());
+            } catch (NumberFormatException ignored) {
+                // 非法 memberId 归到默认桶,不影响方案生成
+            }
+        }
+        return 0L;
+    }
+
+    private String growthGoal(Map<String, Object> inputs) {
+        String goal = text(inputs.get("goal"));
+        return goal.trim().isEmpty() ? "全面提升成长动能" : goal;
+    }
+
+    private String text(Object value) {
+        return value == null ? "" : String.valueOf(value);
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<Map<String, Object>> growthSectionCopies(Object raw) {
+        List<Map<String, Object>> copies = new ArrayList<Map<String, Object>>();
+        if (raw instanceof Collection) {
+            for (Object item : (Collection<Object>) raw) {
+                if (item instanceof Map) {
+                    copies.add(new LinkedHashMap<String, Object>((Map<String, Object>) item));
+                }
+            }
+        }
+        return copies;
+    }
+
+    private List<Map<String, Object>> defaultGrowthSections(String goal) {
+        List<Map<String, Object>> sections = new ArrayList<Map<String, Object>>();
+        for (int i = 0; i < GROWTH_SECTION_KEYS.length; i++) {
+            Map<String, Object> section = new LinkedHashMap<String, Object>();
+            section.put("key", GROWTH_SECTION_KEYS[i]);
+            section.put("title", GROWTH_SECTION_TITLES[i]);
+            section.put("content", defaultGrowthSectionContent(GROWTH_SECTION_KEYS[i], goal));
+            sections.add(section);
+        }
+        return sections;
+    }
+
+    private String defaultGrowthSectionContent(String sectionKey, String goal) {
+        if ("nutrition".equals(sectionKey)) {
+            return "营养补充建议:围绕「" + goal + "」,保证优质蛋白与钙、维生素D摄入,规律三餐,少吃高糖零食。";
+        }
+        if ("diet".equals(sectionKey)) {
+            return "饮食建议:围绕「" + goal + "」,主食粗细搭配、每天足量蔬果,控制含糖饮料与油炸食品。";
+        }
+        if ("exercise".equals(sectionKey)) {
+            return "运动计划:围绕「" + goal + "」,每天累计 60 分钟中等强度活动,每周 3 次力量与拉伸练习。";
+        }
+        return "成长建议:围绕「" + goal + "」,从小目标开始,规律作息并持续记录进步。";
+    }
+
     /**
     /**
      * 情绪识别(base64 图片 → LangGraph DeepFace 分析)
      * 情绪识别(base64 图片 → LangGraph DeepFace 分析)
      * @return 含 emotions / dominant_emotion / dominant_label_zh / all_emotions 的 Map;失败返回 null
      * @return 含 emotions / dominant_emotion / dominant_label_zh / all_emotions 的 Map;失败返回 null

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

@@ -535,6 +535,8 @@ CREATE TABLE IF NOT EXISTS growth_plans (
     assessment_id BIGINT,
     assessment_id BIGINT,
     plan_title VARCHAR(200) NOT NULL,
     plan_title VARCHAR(200) NOT NULL,
     plan_content TEXT NOT NULL COMMENT '规划内容',
     plan_content TEXT NOT NULL COMMENT '规划内容',
+    overview TEXT DEFAULT NULL COMMENT 'AI方案总览(plan.ai.generate)',
+    sections TEXT DEFAULT NULL COMMENT 'AI方案三板块JSON(nutrition/diet/exercise,支持板块级重生成)',
     duration_months TINYINT COMMENT '规划周期(月)',
     duration_months TINYINT COMMENT '规划周期(月)',
     start_date DATE,
     start_date DATE,
     end_date DATE,
     end_date DATE,