|
|
@@ -0,0 +1,1101 @@
|
|
|
+package com.etotem.cfc.controller.ai;
|
|
|
+
|
|
|
+import com.etotem.cfc.common.Result;
|
|
|
+import com.etotem.cfc.dto.AiGateResult;
|
|
|
+import com.etotem.cfc.dto.HealthAnalysisResult;
|
|
|
+import com.etotem.cfc.dto.RecommendationQuery;
|
|
|
+import com.etotem.cfc.dto.RecommendationResult;
|
|
|
+import com.etotem.cfc.dto.TaskParseResult;
|
|
|
+import com.etotem.cfc.enums.AiGateStatus;
|
|
|
+import com.etotem.cfc.service.AIService;
|
|
|
+import com.etotem.cfc.service.AiGateway;
|
|
|
+import com.etotem.cfc.service.CoachSafetyGuardService;
|
|
|
+import com.etotem.cfc.service.FamilyContextService;
|
|
|
+import com.etotem.cfc.service.HealthAnalysisService;
|
|
|
+import com.etotem.cfc.service.RecommendationService;
|
|
|
+import com.etotem.cfc.service.SelfCheckAnalysisService;
|
|
|
+import com.etotem.cfc.service.TaskParseService;
|
|
|
+import com.etotem.cfc.service.UserService;
|
|
|
+import com.etotem.cfc.service.MembershipService;
|
|
|
+import io.swagger.v3.oas.annotations.Operation;
|
|
|
+import io.swagger.v3.oas.annotations.tags.Tag;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.data.redis.core.RedisTemplate;
|
|
|
+import org.springframework.web.bind.annotation.*;
|
|
|
+
|
|
|
+import javax.annotation.Resource;
|
|
|
+import java.time.Duration;
|
|
|
+import java.time.LocalDate;
|
|
|
+import java.util.*;
|
|
|
+import java.util.regex.Matcher;
|
|
|
+import java.util.regex.Pattern;
|
|
|
+
|
|
|
+/**
|
|
|
+ * AI 聊天接口
|
|
|
+ * 对接 LangGraph Chatbot API,自动注入家庭上下文
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Tag(name = "AI聊天", description = "AI家庭助手聊天接口")
|
|
|
+@RestController
|
|
|
+@RequestMapping("/api/ai")
|
|
|
+public class AIChatController {
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private AIService aiService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private FamilyContextService familyContextService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private HealthAnalysisService healthAnalysisService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private SelfCheckAnalysisService selfCheckAnalysisService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private RecommendationService recommendationService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private com.etotem.cfc.service.GrowthTaskService growthTaskService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private TaskParseService taskParseService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private UserService userService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private MembershipService membershipService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private com.etotem.cfc.service.ChatMirrorService chatMirrorService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private AiGateway aiGateway;
|
|
|
+
|
|
|
+ /** 内容安全过滤前置门禁(ai.coach.safetyGuard / SC-B-05)。 */
|
|
|
+ @Resource
|
|
|
+ private CoachSafetyGuardService coachSafetyGuardService;
|
|
|
+
|
|
|
+ /** 纯单测/离线环境未注入时的兜底实例(内置基础词库)。 */
|
|
|
+ private static final CoachSafetyGuardService DEFAULT_SAFETY_GUARD = new CoachSafetyGuardService();
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private com.etotem.cfc.service.PortraitService portraitService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private com.etotem.cfc.mapper.FiveDimensionSelfCheckMapper selfCheckMapper;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private com.fasterxml.jackson.databind.ObjectMapper objectMapper;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private RedisTemplate<String, Object> redisTemplate;
|
|
|
+
|
|
|
+ /** 会员专享业务错误码:前端据此展示会员开通付费墙(UPGRADE_REQUIRED) */
|
|
|
+ private static final int ERR_AI_COACH_MEMBER_ONLY = 46003;
|
|
|
+
|
|
|
+ /** 会员已过期业务错误码:前端据此展示续费引导(MEMBER_EXPIRED) */
|
|
|
+ private static final int ERR_AI_MEMBER_EXPIRED = 46004;
|
|
|
+
|
|
|
+ /** AI 教练对应的会员权益功能码 */
|
|
|
+ private static final String AI_COACH_FEATURE = "mascot_ai";
|
|
|
+
|
|
|
+ /** 内容安全命中拒答业务错误码(区别于会员门禁 46003/46004,不返回 500) */
|
|
|
+ private static final int ERR_CONTENT_SAFETY_BLOCKED = 46005;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 门禁拦截统一响应:过期 → 46004;从未付费 → 46003。
|
|
|
+ */
|
|
|
+ private <T> Result<T> gateError(AiGateResult gate) {
|
|
|
+ if (gate != null && gate.getStatus() == AiGateStatus.MEMBER_EXPIRED) {
|
|
|
+ return Result.error(ERR_AI_MEMBER_EXPIRED, "会员已过期,请续费后继续使用");
|
|
|
+ }
|
|
|
+ return Result.error(ERR_AI_COACH_MEMBER_ONLY, "该功能为会员专享,请先开通会员");
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 门禁校验:返回 null 表示放行,否则返回拦截响应。
|
|
|
+ * 原 canUseAiCoach()(仅 FAMILY/PREMIUM)已收敛到此处统一门禁(BASIC+ 且需在有效期内)。
|
|
|
+ */
|
|
|
+ private <T> Result<T> checkGate(Long userId) {
|
|
|
+ AiGateResult gate = membershipService.checkAiFeatureGate(userId);
|
|
|
+ if (gate == null || !gate.isCanUse()) {
|
|
|
+ return gateError(gate);
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 组装 /api/ai/gate 的 features 明细:
|
|
|
+ * 纳入门禁的 4 项同源同 status;不纳入门禁的 4 项固定放行。
|
|
|
+ */
|
|
|
+ private Map<String, AiGateResult.FeatureGate> buildGateFeatures(AiGateResult gate) {
|
|
|
+ boolean canUse = gate != null && gate.isCanUse();
|
|
|
+ String reason = gate != null ? gate.getReason() : AiGateStatus.UPGRADE_REQUIRED.name();
|
|
|
+ AiGateResult.FeatureGate gated = new AiGateResult.FeatureGate(canUse, canUse ? null : reason);
|
|
|
+
|
|
|
+ Map<String, AiGateResult.FeatureGate> features = new LinkedHashMap<>();
|
|
|
+ features.put("chat", gated);
|
|
|
+ features.put("nutrition", gated);
|
|
|
+ features.put("healthCoach", gated);
|
|
|
+ features.put("butler", gated);
|
|
|
+ features.put("reportAnalyze", AiGateResult.FeatureGate.allow());
|
|
|
+ features.put("emotion", AiGateResult.FeatureGate.allow());
|
|
|
+ features.put("tongue", AiGateResult.FeatureGate.allow());
|
|
|
+ features.put("diet", AiGateResult.FeatureGate.allow());
|
|
|
+ return features;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Operation(summary = "发送聊天消息(支持传入reportId以解读报告)")
|
|
|
+ @PostMapping("/chat/send")
|
|
|
+ public Result<Map<String, Object>> sendMessage(
|
|
|
+ @RequestAttribute("userId") Long userId,
|
|
|
+ @RequestBody Map<String, String> params) {
|
|
|
+ String query = params.get("query");
|
|
|
+ String conversationId = params.get("conversationId");
|
|
|
+
|
|
|
+ if (query == null || query.trim().isEmpty()) {
|
|
|
+ return Result.error("消息不能为空");
|
|
|
+ }
|
|
|
+
|
|
|
+ // 内容安全前置门禁(SC-B-05):命中敏感词/提示词注入即拒答 + 合规提示,
|
|
|
+ // 不透传 LangGraph、不泄露内部错误、不返回 500。
|
|
|
+ CoachSafetyGuardService guard = coachSafetyGuardService != null
|
|
|
+ ? coachSafetyGuardService : DEFAULT_SAFETY_GUARD;
|
|
|
+ String sensitiveCategory = guard.detectCategory(query);
|
|
|
+ if (sensitiveCategory != null) {
|
|
|
+ return Result.error(ERR_CONTENT_SAFETY_BLOCKED, guard.refuseNotice(sensitiveCategory));
|
|
|
+ }
|
|
|
+
|
|
|
+ // AI 使用会员门禁(前置;放行后仍走原配额链 AiGateway/consumeMemberQuota)
|
|
|
+ Result<Map<String, Object>> gateBlocked = checkGate(userId);
|
|
|
+ if (gateBlocked != null) {
|
|
|
+ return gateBlocked;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 复用上下文组装(mascot + 家庭/报告 + 画像 + 自检 + 记忆层)
|
|
|
+ Map<String, Object> inputs = buildChatInputs(userId, params);
|
|
|
+
|
|
|
+ Map<String, Object> difyResp = aiService.sendMessage(
|
|
|
+ query, String.valueOf(userId),
|
|
|
+ conversationId, inputs);
|
|
|
+
|
|
|
+ String answer = (String) difyResp.getOrDefault("answer", "");
|
|
|
+ Map<String, Object> result = new LinkedHashMap<>();
|
|
|
+ result.put("answer", answer);
|
|
|
+ result.put("conversationId", difyResp.getOrDefault("conversationId", ""));
|
|
|
+ // 降级态标记透传(SC-B-06 / e2e TC-B-06/2):供前端提示「AI 服务降级中」
|
|
|
+ if (Boolean.TRUE.equals(difyResp.get("degraded"))) {
|
|
|
+ result.put("degraded", Boolean.TRUE);
|
|
|
+ result.put("fallbackUsed", Boolean.TRUE);
|
|
|
+ }
|
|
|
+
|
|
|
+ // Parse [TASK] markers and create task records
|
|
|
+ List<Map<String, Object>> tasks = new ArrayList<>();
|
|
|
+ List<TaskParseResult> parsedTasks = taskParseService.parseTasks(answer);
|
|
|
+ String cleanAnswer = taskParseService.stripTaskMarkers(answer);
|
|
|
+
|
|
|
+ for (TaskParseResult taskResult : parsedTasks) {
|
|
|
+ com.etotem.cfc.entity.GrowthTask task = growthTaskService.createDynamicTask(
|
|
|
+ userId,
|
|
|
+ taskResult.getTitle(),
|
|
|
+ taskResult.getDescription(),
|
|
|
+ taskResult.getDimension(),
|
|
|
+ taskResult.getRewardPoints(),
|
|
|
+ (String) difyResp.getOrDefault("conversationId", "")
|
|
|
+ );
|
|
|
+ Map<String, Object> taskInfo = new LinkedHashMap<>();
|
|
|
+ taskInfo.put("id", task.getId());
|
|
|
+ taskInfo.put("title", task.getTitle());
|
|
|
+ taskInfo.put("description", task.getDescription());
|
|
|
+ taskInfo.put("dimension", task.getDimension());
|
|
|
+ taskInfo.put("rewardPoints", task.getRewardPoints());
|
|
|
+ tasks.add(taskInfo);
|
|
|
+ }
|
|
|
+
|
|
|
+ result.put("answer", cleanAnswer);
|
|
|
+ result.put("tasks", tasks);
|
|
|
+
|
|
|
+ try { growthTaskService.updateProgress(userId, "DAILY_AI", 1); } catch (Exception e) { log.warn("成长任务AI对话进度更新失败: userId={}, error={}", userId, e.getMessage()); }
|
|
|
+
|
|
|
+ return Result.success(result);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 组装 AI 对话上下文(mascot + 家庭/报告 + 画像 + 自检 + 记忆层)
|
|
|
+ * 供 /chat/send 和 /report/analyze 共用
|
|
|
+ */
|
|
|
+ private Map<String, Object> buildChatInputs(Long userId, Map<String, String> params) {
|
|
|
+ String conversationId = params.get("conversationId");
|
|
|
+ String reportIdStr = params.get("reportId");
|
|
|
+ String surveyIdStr = params.get("surveyId");
|
|
|
+ String selfCheckIdStr = params.get("selfCheckId");
|
|
|
+
|
|
|
+ // 获取用户mascot设置
|
|
|
+ com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
|
|
|
+ String mascotCode = user != null ? user.getMascot() : null;
|
|
|
+
|
|
|
+ // 组装家庭上下文(如果指定reportId/surveyId,注入报告+问卷数据)
|
|
|
+ Long reportId = null;
|
|
|
+ Long surveyId = null;
|
|
|
+ if (reportIdStr != null && !reportIdStr.trim().isEmpty()) {
|
|
|
+ reportId = Long.valueOf(reportIdStr);
|
|
|
+ }
|
|
|
+ if (surveyIdStr != null && !surveyIdStr.trim().isEmpty()) {
|
|
|
+ surveyId = Long.valueOf(surveyIdStr);
|
|
|
+ }
|
|
|
+ String draftIdStr = params.get("draftId");
|
|
|
+ Long draftId = null;
|
|
|
+ if (draftIdStr != null && !draftIdStr.trim().isEmpty()) {
|
|
|
+ draftId = Long.valueOf(draftIdStr);
|
|
|
+ }
|
|
|
+ Map<String, Object> inputs;
|
|
|
+ if (reportId != null && surveyId != null) {
|
|
|
+ inputs = familyContextService.buildContext(userId, reportId, surveyId);
|
|
|
+ } else if (reportId != null) {
|
|
|
+ inputs = familyContextService.buildContext(userId, reportId);
|
|
|
+ } else if (draftId != null) {
|
|
|
+ inputs = familyContextService.buildContextFromDraft(userId, draftId);
|
|
|
+ } else {
|
|
|
+ inputs = familyContextService.buildContext(userId);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 注入mascot信息到LangGraph inputs
|
|
|
+ if (mascotCode != null && !mascotCode.isEmpty()) {
|
|
|
+ com.etotem.cfc.enums.MascotEnum mascot = com.etotem.cfc.enums.MascotEnum.fromCode(mascotCode);
|
|
|
+ if (mascot != null) {
|
|
|
+ inputs.put("mascot_name", mascot.name());
|
|
|
+ inputs.put("mascot_gender", mascot.gender());
|
|
|
+ inputs.put("mascot_persona", mascot.persona());
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ inputs.put("mascot_name", "小助手");
|
|
|
+ inputs.put("mascot_gender", "");
|
|
|
+ inputs.put("mascot_persona", "");
|
|
|
+ }
|
|
|
+
|
|
|
+ // 画像注入
|
|
|
+ String chatMemberIdStr = params.get("memberId");
|
|
|
+ Long chatMemberId = chatMemberIdStr != null && !chatMemberIdStr.trim().isEmpty()
|
|
|
+ ? Long.valueOf(chatMemberIdStr) : null;
|
|
|
+ String chatPortrait = portraitService.buildPortraitPrompt(userId, chatMemberId);
|
|
|
+ if (chatPortrait != null) {
|
|
|
+ inputs.put("portrait_prompt", chatPortrait);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 注入自检上下文(P1-2):自动注入最近一次自检摘要(维度分 + 低分项),
|
|
|
+ // 使 /chat/send 无需前端额外传参即可针对自检结果连续对话;
|
|
|
+ // 指定 selfCheckId 时优先用该记录(服务内校验归属,无效静默跳过)
|
|
|
+ Long selfCheckId = null;
|
|
|
+ if (selfCheckIdStr != null && !selfCheckIdStr.trim().isEmpty()) {
|
|
|
+ try {
|
|
|
+ selfCheckId = Long.valueOf(selfCheckIdStr);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("selfCheckId 解析失败: {}", e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ java.util.Map<String, Object> selfCheckSummary = selfCheckAnalysisService.buildLatestSummary(userId, selfCheckId);
|
|
|
+ if (selfCheckSummary != null) {
|
|
|
+ try {
|
|
|
+ inputs.put("self_check_result", objectMapper.writeValueAsString(selfCheckSummary));
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("序列化自检上下文失败: {}", e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // AI记忆层注入(会话摘要+关键事实)
|
|
|
+ inputs = aiService.enrichInputsWithMemory(userId, conversationId, inputs);
|
|
|
+ return inputs;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Operation(summary = "报告快速分析(免费版每日1次,付费版多轮)")
|
|
|
+ @PostMapping("/report/analyze")
|
|
|
+ public Result<Map<String, Object>> reportAnalyze(
|
|
|
+ @RequestAttribute("userId") Long userId,
|
|
|
+ @RequestBody Map<String, String> params) {
|
|
|
+ String query = params.get("query");
|
|
|
+ String reportIdStr = params.get("reportId");
|
|
|
+ String draftIdStr = params.get("draftId");
|
|
|
+ if (query == null || query.trim().isEmpty()) {
|
|
|
+ return Result.error("消息不能为空");
|
|
|
+ }
|
|
|
+ if ((reportIdStr == null || reportIdStr.trim().isEmpty())
|
|
|
+ && (draftIdStr == null || draftIdStr.trim().isEmpty())) {
|
|
|
+ return Result.error("报告ID或草稿ID不能为空");
|
|
|
+ }
|
|
|
+
|
|
|
+ // 1. 会员级别检查
|
|
|
+ com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
|
|
|
+ String memberLevel = user != null ? user.getMemberLevel() : "FREE";
|
|
|
+ boolean isFree = memberLevel == null || "FREE".equals(memberLevel);
|
|
|
+
|
|
|
+ // 2. 免费版 Redis 计数(每日 1 次;Redis 异常时 fail-open 放行)
|
|
|
+ if (isFree) {
|
|
|
+ try {
|
|
|
+ String key = "report:analyze:free:" + userId + ":" + LocalDate.now();
|
|
|
+ Long count = redisTemplate.opsForValue().increment(key);
|
|
|
+ if (count != null && count == 1L) {
|
|
|
+ redisTemplate.expire(key, Duration.ofDays(1));
|
|
|
+ }
|
|
|
+ if (count != null && count > 1L) {
|
|
|
+ return Result.error("免费版每日仅限 1 次快速分析,升级会员解锁更多");
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("Redis 计数失败,放行: {}", e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 3. 组装上下文(免费版不带 conversationId → LangGraph 每次新建会话,锁死多轮)
|
|
|
+ if (isFree) {
|
|
|
+ params.remove("conversationId");
|
|
|
+ }
|
|
|
+ Map<String, Object> inputs = buildChatInputs(userId, params);
|
|
|
+
|
|
|
+ // 3.5 报告可用性门禁(S-cfc-350 / TC-B-04-E)
|
|
|
+ // - draftId 路径:草稿上下文必须已带解析后 payload(reportDetail),否则视为「报告解析中」
|
|
|
+ // - reportId 路径:上下文已带 reportDetail 时按归属校验;缺 reportDetail 视为无报告 → 提示上传
|
|
|
+ if (draftIdStr != null && !draftIdStr.trim().isEmpty()) {
|
|
|
+ Object draftDetail = inputs.get("reportDetail");
|
|
|
+ if (!(draftDetail instanceof Map) || ((Map<?, ?>) draftDetail).isEmpty()) {
|
|
|
+ return Result.error("报告解析中,请稍后重试");
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ Object detailObj = inputs.get("reportDetail");
|
|
|
+ if (detailObj instanceof Map) {
|
|
|
+ Object reportObj = ((Map<?, ?>) detailObj).get("report");
|
|
|
+ if (reportObj == null) {
|
|
|
+ return Result.error("尚未上传报告,请先上传报告后再发起解读");
|
|
|
+ }
|
|
|
+ Result<Void> accessDenied = checkReportAccess(user, reportObj);
|
|
|
+ if (accessDenied != null) {
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ Result<Map<String, Object>> denied = (Result<Map<String, Object>>) (Result<?>) accessDenied;
|
|
|
+ return denied;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // detailObj 缺失/非 Map(如上下文未注入 reportDetail):保持原有宽容行为,交由 AI 侧兜底回答
|
|
|
+ }
|
|
|
+
|
|
|
+ // 4. 调 LangGraph(经 aiService.sendMessage 含记忆层+镜像)
|
|
|
+ Map<String, Object> difyResp = aiService.sendMessage(
|
|
|
+ query, String.valueOf(userId),
|
|
|
+ params.get("conversationId"), inputs);
|
|
|
+
|
|
|
+ if (difyResp == null || difyResp.isEmpty()) {
|
|
|
+ return Result.error("AI 服务暂不可用,请稍后重试");
|
|
|
+ }
|
|
|
+ String answer = (String) difyResp.getOrDefault("answer", "");
|
|
|
+ String cleanAnswer = maskSensitiveInfo(taskParseService.stripTaskMarkers(answer));
|
|
|
+
|
|
|
+ // 5. 结构化三段输出(通俗解读 / 五维关联 / 行动建议)+ 类型一致性提示
|
|
|
+ Map<String, Object> result = new LinkedHashMap<>();
|
|
|
+ result.put("answer", cleanAnswer);
|
|
|
+ result.put("plainSummary", cleanAnswer);
|
|
|
+ result.put("fiveDimAssociations", buildFiveDimAssociations(cleanAnswer));
|
|
|
+ result.put("actionSuggestions", buildActionSuggestions(cleanAnswer));
|
|
|
+ result.put("typeWarning", buildTypeWarning(inputs));
|
|
|
+ result.put("conversationId", difyResp.getOrDefault("conversationId", ""));
|
|
|
+ return Result.success(result);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 报告归属校验(TC-B-04-P):报告已带 familyId 且与当前登录用户家庭不一致 → 拒绝。
|
|
|
+ * 报告缺 familyId(历史数据/未归属)时 fail-open 放行,由上游 family 上下文保证隔离。
|
|
|
+ */
|
|
|
+ private Result<Void> checkReportAccess(com.etotem.cfc.entity.User user, Object reportObj) {
|
|
|
+ if (!(reportObj instanceof com.etotem.cfc.entity.HealthReport)) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ com.etotem.cfc.entity.HealthReport report = (com.etotem.cfc.entity.HealthReport) reportObj;
|
|
|
+ Long reportFamilyId = report.getFamilyId();
|
|
|
+ if (reportFamilyId == null || user == null) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ Long userFamilyId = user.getFamilyId();
|
|
|
+ if (userFamilyId != null && !reportFamilyId.equals(userFamilyId)) {
|
|
|
+ return Result.forbidden("无权解读该报告,报告不属于当前家庭");
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 五维关键词表(身/心/智/行/富) */
|
|
|
+ private static final String[][] FIVE_DIM_KEYWORDS = {
|
|
|
+ // body 身
|
|
|
+ {"肠道", "菌群", "免疫", "营养", "代谢", "消化", "身体", "体质", "健康", "炎症", "睡眠", "体重"},
|
|
|
+ // mind 心
|
|
|
+ {"情绪", "压力", "焦虑", "心理", "心情", "情感", "抑郁", "心态"},
|
|
|
+ // intellect 智
|
|
|
+ {"认知", "学习", "记忆", "专注", "注意力", "智力", "思维", "大脑"},
|
|
|
+ // action 行
|
|
|
+ {"运动", "锻炼", "作息", "习惯", "行为", "活动", "执行", "坚持"},
|
|
|
+ // wealth 富
|
|
|
+ {"医疗", "保险", "费用", "花费", "支出", "财富", "理财", "预算", "经济"}
|
|
|
+ };
|
|
|
+
|
|
|
+ private static final String[] FIVE_DIM_FALLBACKS = {
|
|
|
+ "身体维度:建议结合本次报告关注身体基础指标,维持均衡饮食与规律作息。",
|
|
|
+ "心理维度:报告未直接覆盖情绪,可结合日常情绪变化观察身体状况对心理的影响。",
|
|
|
+ "智力维度:报告未直接覆盖认知,可关注营养与睡眠对学习专注度的间接支持。",
|
|
|
+ "行动维度:建议把报告中的改善建议转化为可执行的小步骤并持续跟进。",
|
|
|
+ "财富维度:报告未涉及财务信息,可在医疗/营养支出上做合理规划。"
|
|
|
+ };
|
|
|
+
|
|
|
+ private static final String[] ACTION_SUGGESTION_KEYWORDS = {
|
|
|
+ "建议", "应该", "可以", "需要", "推荐", "尽量", "注意", "不妨", "宜"
|
|
|
+ };
|
|
|
+
|
|
|
+ private static final List<String> DEFAULT_ACTION_SUGGESTIONS;
|
|
|
+
|
|
|
+ static {
|
|
|
+ List<String> defaults = new ArrayList<>();
|
|
|
+ defaults.add("建议结合报告结论,把改善动作拆成每天可完成的小步骤并记录执行情况。");
|
|
|
+ defaults.add("建议持续跟踪关键指标变化,必要时复检或咨询专业人士。");
|
|
|
+ DEFAULT_ACTION_SUGGESTIONS = Collections.unmodifiableList(defaults);
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 把解读文本按中文句读切分为句子 */
|
|
|
+ private List<String> splitSentences(String text) {
|
|
|
+ List<String> sentences = new ArrayList<>();
|
|
|
+ if (text == null || text.trim().isEmpty()) {
|
|
|
+ return sentences;
|
|
|
+ }
|
|
|
+ String[] parts = text.split("[。!?!?;;\n]+");
|
|
|
+ for (String part : parts) {
|
|
|
+ String trimmed = part == null ? "" : part.trim();
|
|
|
+ if (!trimmed.isEmpty()) {
|
|
|
+ sentences.add(trimmed);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return sentences;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 基于关键词把解读文本映射到身/心/智/行/富五维;命不中的维度用兜底文案,
|
|
|
+ * 保证输出恒定含 body/mind/intellect/action/wealth 五键。
|
|
|
+ */
|
|
|
+ private Map<String, Object> buildFiveDimAssociations(String text) {
|
|
|
+ List<String> sentences = splitSentences(text);
|
|
|
+ String[] dimKeys = {"body", "mind", "intellect", "action", "wealth"};
|
|
|
+ Map<String, Object> dims = new LinkedHashMap<>();
|
|
|
+ for (int i = 0; i < dimKeys.length; i++) {
|
|
|
+ String matched = null;
|
|
|
+ for (String sentence : sentences) {
|
|
|
+ for (String keyword : FIVE_DIM_KEYWORDS[i]) {
|
|
|
+ if (sentence.contains(keyword)) {
|
|
|
+ matched = sentence;
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (matched != null) break;
|
|
|
+ }
|
|
|
+ dims.put(dimKeys[i], matched != null ? matched : FIVE_DIM_FALLBACKS[i]);
|
|
|
+ }
|
|
|
+ return dims;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 抽取含建议类关键词的句子作为行动建议;无命中时返回兜底建议 */
|
|
|
+ private List<String> buildActionSuggestions(String text) {
|
|
|
+ List<String> suggestions = new ArrayList<>();
|
|
|
+ for (String sentence : splitSentences(text)) {
|
|
|
+ for (String keyword : ACTION_SUGGESTION_KEYWORDS) {
|
|
|
+ if (sentence.contains(keyword)) {
|
|
|
+ suggestions.add(sentence);
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (suggestions.isEmpty()) {
|
|
|
+ return new ArrayList<>(DEFAULT_ACTION_SUGGESTIONS);
|
|
|
+ }
|
|
|
+ return suggestions;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 报告类型一致性提示:类型集合为空 / 含未知类型 / 多于一种类型时视为不可横向比较。
|
|
|
+ */
|
|
|
+ private Map<String, Object> buildTypeWarning(Map<String, Object> inputs) {
|
|
|
+ Set<String> types = new LinkedHashSet<>();
|
|
|
+ Object detailObj = inputs.get("reportDetail");
|
|
|
+ if (detailObj instanceof Map) {
|
|
|
+ Object reportObj = ((Map<?, ?>) detailObj).get("report");
|
|
|
+ if (reportObj instanceof com.etotem.cfc.entity.HealthReport) {
|
|
|
+ String reportType = ((com.etotem.cfc.entity.HealthReport) reportObj).getReportType();
|
|
|
+ if (reportType != null && !reportType.trim().isEmpty()) {
|
|
|
+ types.add(reportType.trim());
|
|
|
+ } else {
|
|
|
+ types.add("");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ boolean mismatch = types.isEmpty() || types.contains("") || types.size() > 1;
|
|
|
+ Map<String, Object> warning = new LinkedHashMap<>();
|
|
|
+ warning.put("mismatch", mismatch);
|
|
|
+ if (mismatch) {
|
|
|
+ warning.put("message", "检测到不同类型的报告,数据口径不一致,不建议直接横向比较");
|
|
|
+ }
|
|
|
+ return warning;
|
|
|
+ }
|
|
|
+
|
|
|
+ // ── PII 脱敏(S-cfc-350 / TC-B-04-E 异常流-4) ──
|
|
|
+
|
|
|
+ /** 中国大陆手机号:1[3-9] 开头的 11 位数字,前后不接数字 */
|
|
|
+ private static final Pattern PII_PHONE_PATTERN =
|
|
|
+ Pattern.compile("(?<!\\d)1[3-9]\\d{9}(?!\\d)");
|
|
|
+
|
|
|
+ /** 长数字串(身份证/银行卡等 15-18 位)整体遮蔽 */
|
|
|
+ private static final Pattern PII_LONG_DIGIT_PATTERN =
|
|
|
+ Pattern.compile("(?<!\\d)\\d{15,18}(?!\\d)");
|
|
|
+
|
|
|
+ /** 中文姓名:2-3 个汉字后紧跟「的」或称谓类后缀 */
|
|
|
+ private static final Pattern PII_NAME_PATTERN =
|
|
|
+ Pattern.compile("[\\u4e00-\\u9fa5]{2,3}(?=的|先生|女士|小姐|老师|医生|大夫|教授|主任|同学|患者|受检人|受检者|本人)");
|
|
|
+
|
|
|
+ /** 姓名脱敏白名单:常见泛指/亲属/职业/部位词,命中后缀时不应被当成姓名遮蔽 */
|
|
|
+ private static final Set<String> NAME_STOPWORDS;
|
|
|
+
|
|
|
+ static {
|
|
|
+ Set<String> words = new HashSet<>();
|
|
|
+ String[] raw = {
|
|
|
+ "孩子", "家长", "小孩", "宝宝", "儿童", "学生", "大人", "父母", "爸爸", "妈妈",
|
|
|
+ "爷爷", "奶奶", "外公", "外婆", "哥哥", "姐姐", "弟弟", "妹妹", "儿子", "女儿",
|
|
|
+ "老师", "医生", "大夫", "护士", "教授", "主任", "同学", "朋友", "本人", "患者",
|
|
|
+ "受检人", "受检者", "用户", "我们", "他们", "大家", "建议", "关注", "注意",
|
|
|
+ "肠道", "菌群", "免疫", "营养", "代谢", "消化", "睡眠", "体重", "体质",
|
|
|
+ "情绪", "心理", "压力", "焦虑", "认知", "学习", "记忆", "专注", "大脑",
|
|
|
+ "运动", "锻炼", "作息", "习惯", "行为", "医疗", "保险", "费用", "花费",
|
|
|
+ "主治", "主治医生", "可联系主治", "联系", "可以联系", "报告", "数据", "结果",
|
|
|
+ "以上", "以下", "如下", "因此", "所以", "但是", "然而", "如果", "当", "其中",
|
|
|
+ "其他", "其它", "有些", "有的", "所有", "任何", "每个", "某些", "这种", "那种"
|
|
|
+ };
|
|
|
+ for (String w : raw) {
|
|
|
+ words.add(w);
|
|
|
+ }
|
|
|
+ NAME_STOPWORDS = Collections.unmodifiableSet(words);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 对解读输出做最小必要脱敏:手机号 → 前 3 + **** + 后 4;长数字串遮蔽;中文姓名 → ***。
|
|
|
+ */
|
|
|
+ private String maskSensitiveInfo(String text) {
|
|
|
+ if (text == null || text.isEmpty()) {
|
|
|
+ return text;
|
|
|
+ }
|
|
|
+ Matcher phoneMatcher = PII_PHONE_PATTERN.matcher(text);
|
|
|
+ StringBuffer phoneBuf = new StringBuffer();
|
|
|
+ while (phoneMatcher.find()) {
|
|
|
+ String full = phoneMatcher.group();
|
|
|
+ phoneMatcher.appendReplacement(phoneBuf,
|
|
|
+ Matcher.quoteReplacement(full.substring(0, 3) + "****" + full.substring(full.length() - 4)));
|
|
|
+ }
|
|
|
+ phoneMatcher.appendTail(phoneBuf);
|
|
|
+ String masked = PII_LONG_DIGIT_PATTERN.matcher(phoneBuf.toString()).replaceAll("********");
|
|
|
+ Matcher nameMatcher = PII_NAME_PATTERN.matcher(masked);
|
|
|
+ StringBuilder sb = new StringBuilder();
|
|
|
+ int lastEnd = 0;
|
|
|
+ while (nameMatcher.find()) {
|
|
|
+ String token = nameMatcher.group();
|
|
|
+ int start = nameMatcher.start();
|
|
|
+ sb.append(masked, lastEnd, start);
|
|
|
+ if (NAME_STOPWORDS.contains(token)) {
|
|
|
+ sb.append(token);
|
|
|
+ } else {
|
|
|
+ sb.append("***");
|
|
|
+ }
|
|
|
+ lastEnd = nameMatcher.end();
|
|
|
+ }
|
|
|
+ sb.append(masked.substring(lastEnd));
|
|
|
+ return sb.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ @Operation(summary = "获取会话列表")
|
|
|
+ @PostMapping("/chat/conversations")
|
|
|
+ public Result<List<Map<String, Object>>> getConversations(
|
|
|
+ @RequestAttribute("userId") Long userId) {
|
|
|
+ try {
|
|
|
+ List<Map<String, Object>> list = aiService.getConversations(String.valueOf(userId));
|
|
|
+ return Result.success(list);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("LangGraph获取会话列表失败,回退到本地: {}", e.getMessage());
|
|
|
+ List<com.etotem.cfc.entity.ChatConversation> local = chatMirrorService.getConversations(userId);
|
|
|
+ List<Map<String, Object>> fallback = new ArrayList<>();
|
|
|
+ for (com.etotem.cfc.entity.ChatConversation c : local) {
|
|
|
+ Map<String, Object> m = new LinkedHashMap<>();
|
|
|
+ m.put("id", c.getDifyConversationId());
|
|
|
+ m.put("name", c.getTitle());
|
|
|
+ m.put("last_message_at", c.getLastMessageAt());
|
|
|
+ fallback.add(m);
|
|
|
+ }
|
|
|
+ return Result.success(fallback);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Operation(summary = "获取消息历史")
|
|
|
+ @PostMapping("/chat/messages")
|
|
|
+ public Result<List<Map<String, Object>>> getMessages(
|
|
|
+ @RequestAttribute("userId") Long userId,
|
|
|
+ @RequestBody Map<String, String> params) {
|
|
|
+ String conversationId = params.get("conversationId");
|
|
|
+ if (conversationId == null || conversationId.trim().isEmpty()) {
|
|
|
+ return Result.error("conversationId 不能为空");
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ List<Map<String, Object>> list = aiService.getMessages(conversationId, String.valueOf(userId));
|
|
|
+ return Result.success(list);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("LangGraph获取消息历史失败,回退到本地: {}", e.getMessage());
|
|
|
+ List<com.etotem.cfc.entity.ChatConversation> conversations = chatMirrorService.getConversations(userId);
|
|
|
+ Long localConvId = null;
|
|
|
+ for (com.etotem.cfc.entity.ChatConversation c : conversations) {
|
|
|
+ if (conversationId.equals(c.getDifyConversationId())) {
|
|
|
+ localConvId = c.getId();
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (localConvId == null) {
|
|
|
+ return Result.success(Collections.emptyList());
|
|
|
+ }
|
|
|
+ List<com.etotem.cfc.entity.ChatMessage> messages = chatMirrorService.getMessages(localConvId);
|
|
|
+ List<Map<String, Object>> fallback = new ArrayList<>();
|
|
|
+ for (com.etotem.cfc.entity.ChatMessage msg : messages) {
|
|
|
+ Map<String, Object> m = new LinkedHashMap<>();
|
|
|
+ m.put("role", msg.getRole());
|
|
|
+ m.put("content", msg.getContent());
|
|
|
+ m.put("created_at", msg.getCreatedAt());
|
|
|
+ fallback.add(m);
|
|
|
+ }
|
|
|
+ return Result.success(fallback);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Operation(summary = "删除会话")
|
|
|
+ @PostMapping("/chat/conversations/{id}/delete")
|
|
|
+ public Result<Void> deleteConversation(
|
|
|
+ @RequestAttribute("userId") Long userId,
|
|
|
+ @PathVariable("id") String conversationId) {
|
|
|
+ aiService.deleteConversation(conversationId, String.valueOf(userId));
|
|
|
+ return Result.success(null);
|
|
|
+ }
|
|
|
+
|
|
|
+ // ── 精准营养助手 ──
|
|
|
+
|
|
|
+ private static final Pattern RECOMMEND_PATTERN =
|
|
|
+ Pattern.compile("\\[RECOMMEND:\\s*(\\{.*?\\})\\]", Pattern.DOTALL);
|
|
|
+
|
|
|
+ @Operation(summary = "发送营养分析消息(基于菌群报告)")
|
|
|
+ @PostMapping("/nutrition/send")
|
|
|
+ public Result<Map<String, Object>> sendNutritionMessage(
|
|
|
+ @RequestAttribute("userId") Long userId,
|
|
|
+ @RequestBody Map<String, String> params) {
|
|
|
+ String query = params.get("query");
|
|
|
+ String conversationId = params.get("conversationId");
|
|
|
+ String reportIdStr = params.get("reportId");
|
|
|
+
|
|
|
+ if (query == null || query.trim().isEmpty()) {
|
|
|
+ return Result.error("消息不能为空");
|
|
|
+ }
|
|
|
+ if (reportIdStr == null || reportIdStr.trim().isEmpty()) {
|
|
|
+ return Result.error("需要reportId进行营养分析");
|
|
|
+ }
|
|
|
+
|
|
|
+ // AI 使用会员门禁(参数校验后、分析前)
|
|
|
+ Result<Map<String, Object>> gateBlocked = checkGate(userId);
|
|
|
+ if (gateBlocked != null) {
|
|
|
+ return gateBlocked;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 获取用户mascot设置
|
|
|
+ com.etotem.cfc.entity.User user = userService.getUserInfo(userId);
|
|
|
+ String mascotCode = user != null ? user.getMascot() : null;
|
|
|
+
|
|
|
+ Long reportId = Long.valueOf(reportIdStr);
|
|
|
+
|
|
|
+ // 1. 菌群分析
|
|
|
+ HealthAnalysisResult analysis = healthAnalysisService.analyze(reportId);
|
|
|
+ if (analysis == null) {
|
|
|
+ return Result.error("报告不存在或分析失败: reportId=" + reportId);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 2. 构建 LangGraph inputs(菌群分析 + 家庭上下文)
|
|
|
+ Map<String, Object> inputs = familyContextService.buildContext(userId);
|
|
|
+ inputs.put("health_analysis", analysis);
|
|
|
+
|
|
|
+ // 注入mascot信息到LangGraph inputs
|
|
|
+ if (mascotCode != null && !mascotCode.isEmpty()) {
|
|
|
+ com.etotem.cfc.enums.MascotEnum mascot = com.etotem.cfc.enums.MascotEnum.fromCode(mascotCode);
|
|
|
+ if (mascot != null) {
|
|
|
+ inputs.put("mascot_name", mascot.name());
|
|
|
+ inputs.put("mascot_gender", mascot.gender());
|
|
|
+ inputs.put("mascot_persona", mascot.persona());
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ inputs.put("mascot_name", "小助手");
|
|
|
+ inputs.put("mascot_gender", "");
|
|
|
+ inputs.put("mascot_persona", "");
|
|
|
+ }
|
|
|
+
|
|
|
+ // 3. 注入用户画像
|
|
|
+ String memberIdStr = params.get("memberId");
|
|
|
+ Long memberId = memberIdStr != null && !memberIdStr.trim().isEmpty()
|
|
|
+ ? Long.valueOf(memberIdStr) : null;
|
|
|
+ String portraitPrompt = portraitService.buildPortraitPrompt(userId, memberId);
|
|
|
+ if (portraitPrompt != null) {
|
|
|
+ inputs.put("portrait_prompt", portraitPrompt);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 4. 调用营养助手(走 LangGraph)
|
|
|
+ // 契约 langgraph.intent.errorPropagate:上游 429/401 由 AiGateway.chat 直接抛出,
|
|
|
+ // 不在此处吞 null 伪装成「普通失败」;编排层(Controller)负责统一降级
|
|
|
+ Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
|
|
|
+
|
|
|
+ String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
|
|
|
+
|
|
|
+ // 4. 解析 [RECOMMEND] 标记
|
|
|
+ List<RecommendationResult> recommendations = null;
|
|
|
+ String cleanAnswer = answer;
|
|
|
+ Matcher matcher = RECOMMEND_PATTERN.matcher(answer);
|
|
|
+ if (matcher.find()) {
|
|
|
+ try {
|
|
|
+ String json = matcher.group(1);
|
|
|
+ // 简单 JSON 解析(不用 Jackson 避免异常链)
|
|
|
+ Map<String, Object> rec = parseSimpleJson(json);
|
|
|
+ if (rec != null) {
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ List<String> tags = (List<String>) rec.get("tags");
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ List<String> types = (List<String>) rec.get("types");
|
|
|
+ Object limitObj = rec.get("limit");
|
|
|
+ int limit = limitObj instanceof Number ? ((Number) limitObj).intValue() : 3;
|
|
|
+
|
|
|
+ if (tags != null && !tags.isEmpty()) {
|
|
|
+ RecommendationQuery rq = new RecommendationQuery();
|
|
|
+ rq.setNutritionTags(tags);
|
|
|
+ rq.setTypes(types != null && !types.isEmpty() ? types : null);
|
|
|
+ rq.setLimit(limit);
|
|
|
+ rq.setUserId(userId);
|
|
|
+ if (user != null) {
|
|
|
+ rq.setFamilyId(user.getFamilyId());
|
|
|
+ }
|
|
|
+ recommendations = recommendationService.search(rq);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("解析 [RECOMMEND] 标记失败, 忽略: {}", e.getMessage());
|
|
|
+ }
|
|
|
+ // 从回答中移除标记
|
|
|
+ cleanAnswer = matcher.replaceAll("").trim();
|
|
|
+ }
|
|
|
+
|
|
|
+ // Parse [TASK] markers and create task records
|
|
|
+ List<Map<String, Object>> tasks = new ArrayList<>();
|
|
|
+ List<TaskParseResult> parsedTasks = taskParseService.parseTasks(answer);
|
|
|
+ cleanAnswer = taskParseService.stripTaskMarkers(cleanAnswer);
|
|
|
+
|
|
|
+ for (TaskParseResult taskResult : parsedTasks) {
|
|
|
+ com.etotem.cfc.entity.GrowthTask task = growthTaskService.createDynamicTask(
|
|
|
+ userId,
|
|
|
+ taskResult.getTitle(),
|
|
|
+ taskResult.getDescription(),
|
|
|
+ taskResult.getDimension(),
|
|
|
+ taskResult.getRewardPoints(),
|
|
|
+ null
|
|
|
+ );
|
|
|
+ Map<String, Object> taskInfo = new LinkedHashMap<>();
|
|
|
+ taskInfo.put("id", task.getId());
|
|
|
+ taskInfo.put("title", task.getTitle());
|
|
|
+ taskInfo.put("description", task.getDescription());
|
|
|
+ taskInfo.put("dimension", task.getDimension());
|
|
|
+ taskInfo.put("rewardPoints", task.getRewardPoints());
|
|
|
+ tasks.add(taskInfo);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 5. 组装结果
|
|
|
+ Map<String, Object> result = new LinkedHashMap<>();
|
|
|
+ result.put("answer", cleanAnswer);
|
|
|
+ result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
|
|
|
+ result.put("recommendations", recommendations != null ? recommendations : Collections.emptyList());
|
|
|
+ result.put("tasks", tasks);
|
|
|
+ return Result.success(result);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 极简 JSON 解析(仅用于 [RECOMMEND] 标记中的简单对象)
|
|
|
+ * 避免引入 Jackson 依赖或抛异常
|
|
|
+ */
|
|
|
+ private Map<String, Object> parseSimpleJson(String json) {
|
|
|
+ json = json.trim();
|
|
|
+ if (!json.startsWith("{") || !json.endsWith("}")) return null;
|
|
|
+ json = json.substring(1, json.length() - 1).trim();
|
|
|
+
|
|
|
+ Map<String, Object> map = new LinkedHashMap<>();
|
|
|
+ // 按逗号分割顶层键值对(忽略引号内的逗号)
|
|
|
+ List<String> pairs = splitOutsideQuotes(json);
|
|
|
+ for (String pair : pairs) {
|
|
|
+ int colonIdx = pair.indexOf(':');
|
|
|
+ if (colonIdx < 0) continue;
|
|
|
+ String key = pair.substring(0, colonIdx).trim();
|
|
|
+ String value = pair.substring(colonIdx + 1).trim();
|
|
|
+ key = stripQuotes(key);
|
|
|
+ if (key.isEmpty()) continue;
|
|
|
+
|
|
|
+ if (value.startsWith("[") && value.endsWith("]")) {
|
|
|
+ // 解析数组
|
|
|
+ String inner = value.substring(1, value.length() - 1).trim();
|
|
|
+ List<String> items = new ArrayList<>();
|
|
|
+ for (String item : splitOutsideQuotes(inner)) {
|
|
|
+ items.add(stripQuotes(item.trim()));
|
|
|
+ }
|
|
|
+ map.put(key, items);
|
|
|
+ } else {
|
|
|
+ map.put(key, stripQuotes(value));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return map;
|
|
|
+ }
|
|
|
+
|
|
|
+ private List<String> splitOutsideQuotes(String s) {
|
|
|
+ List<String> parts = new ArrayList<>();
|
|
|
+ int depth = 0;
|
|
|
+ boolean inStr = false;
|
|
|
+ int start = 0;
|
|
|
+ for (int i = 0; i < s.length(); i++) {
|
|
|
+ char c = s.charAt(i);
|
|
|
+ if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) {
|
|
|
+ inStr = !inStr;
|
|
|
+ } else if (!inStr) {
|
|
|
+ if (c == '{' || c == '[') depth++;
|
|
|
+ else if (c == '}' || c == ']') depth--;
|
|
|
+ else if (c == ',' && depth == 0) {
|
|
|
+ parts.add(s.substring(start, i));
|
|
|
+ start = i + 1;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (start < s.length()) {
|
|
|
+ parts.add(s.substring(start));
|
|
|
+ }
|
|
|
+ return parts;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String stripQuotes(String s) {
|
|
|
+ if (s == null) return "";
|
|
|
+ s = s.trim();
|
|
|
+ if (s.startsWith("\"") && s.endsWith("\"") && s.length() >= 2) {
|
|
|
+ return s.substring(1, s.length() - 1);
|
|
|
+ }
|
|
|
+ return s;
|
|
|
+ }
|
|
|
+
|
|
|
+ // ── 健康教练 ──
|
|
|
+
|
|
|
+ @Operation(summary = "发送健康教练消息")
|
|
|
+ @PostMapping("/health-coach/send")
|
|
|
+ public Result<Map<String, Object>> sendHealthCoachMessage(
|
|
|
+ @RequestAttribute("userId") Long userId,
|
|
|
+ @RequestBody Map<String, Object> params) {
|
|
|
+ String query = (String) params.get("query");
|
|
|
+ String conversationId = (String) params.get("conversationId");
|
|
|
+ if (query == null || query.trim().isEmpty()) {
|
|
|
+ return Result.error("消息不能为空");
|
|
|
+ }
|
|
|
+ // 会员付费门禁:有效期内 BASIC 及以上会员可用(开关关闭时对所有登录用户放行)
|
|
|
+ Result<Map<String, Object>> gateBlocked = checkGate(userId);
|
|
|
+ if (gateBlocked != null) {
|
|
|
+ return gateBlocked;
|
|
|
+ }
|
|
|
+ Long memberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
|
|
|
+ Map<String, Object> inputs = new LinkedHashMap<>();
|
|
|
+ if (memberId != null) {
|
|
|
+ inputs.put("child_id", memberId);
|
|
|
+ }
|
|
|
+ // 注入教练人格(对齐 /chat/send 的 mascot 范式;coach_id 用于 LangGraph prompt 路由)
|
|
|
+ com.etotem.cfc.entity.User hcUser = userService.getUserInfo(userId);
|
|
|
+ String hcMascotCode = hcUser != null ? hcUser.getMascot() : null;
|
|
|
+ if (hcMascotCode != null && !hcMascotCode.isEmpty()) {
|
|
|
+ com.etotem.cfc.enums.MascotEnum hcMascot = com.etotem.cfc.enums.MascotEnum.fromCode(hcMascotCode);
|
|
|
+ if (hcMascot != null) {
|
|
|
+ inputs.put("coach_id", hcMascot.getCode());
|
|
|
+ inputs.put("mascot_name", hcMascot.name());
|
|
|
+ inputs.put("mascot_gender", hcMascot.gender());
|
|
|
+ inputs.put("mascot_persona", hcMascot.persona());
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ inputs.put("coach_id", "");
|
|
|
+ inputs.put("mascot_name", "健康教练");
|
|
|
+ inputs.put("mascot_gender", "");
|
|
|
+ inputs.put("mascot_persona", "");
|
|
|
+ }
|
|
|
+ // 画像注入
|
|
|
+ String coachPortrait = portraitService.buildPortraitPrompt(userId, memberId);
|
|
|
+ if (coachPortrait != null) {
|
|
|
+ inputs.put("portrait_prompt", coachPortrait);
|
|
|
+ }
|
|
|
+ Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
|
|
|
+ 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<>();
|
|
|
+ result.put("answer", answer);
|
|
|
+ result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
|
|
|
+ result.put("recommendations", Collections.emptyList());
|
|
|
+ result.put("tasks", Collections.emptyList());
|
|
|
+ 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 明细。
|
|
|
+ * 前端一次请求即可渲染会员状态条与功能锁。
|
|
|
+ */
|
|
|
+ @Operation(summary = "获取AI使用会员门禁状态(全量功能)")
|
|
|
+ @PostMapping("/gate")
|
|
|
+ public Result<AiGateResult> aiGateStatus(@RequestAttribute("userId") Long userId) {
|
|
|
+ AiGateResult gate = membershipService.checkAiFeatureGate(userId);
|
|
|
+ if (gate == null) {
|
|
|
+ gate = new AiGateResult();
|
|
|
+ gate.setStatus(AiGateStatus.ALLOW);
|
|
|
+ gate.setEnabled(true);
|
|
|
+ gate.setCanUse(true);
|
|
|
+ gate.setCanViewHistory(true);
|
|
|
+ gate.setMemberLevel("FREE");
|
|
|
+ gate.setIsActive(false);
|
|
|
+ gate.setDaysRemaining(0L);
|
|
|
+ }
|
|
|
+ gate.setFeatures(buildGateFeatures(gate));
|
|
|
+ return Result.success(gate);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * AI 教练会员付费开关状态(兼容保留,前端新代码统一改调 /api/ai/gate)。
|
|
|
+ * enabled=true 表示开关开启(会员门禁生效);canUse=false 表示当前用户被拦截。
|
|
|
+ */
|
|
|
+ @Operation(summary = "获取AI教练会员付费开关状态")
|
|
|
+ @PostMapping("/health-coach/gate")
|
|
|
+ public Result<Map<String, Object>> aiCoachGateStatus(@RequestAttribute("userId") Long userId) {
|
|
|
+ AiGateResult gate = membershipService.checkAiFeatureGate(userId);
|
|
|
+ boolean enabled = gate != null && gate.isEnabled();
|
|
|
+ boolean canUse = gate != null && gate.isCanUse();
|
|
|
+ Map<String, Object> result = new LinkedHashMap<>();
|
|
|
+ result.put("enabled", enabled);
|
|
|
+ result.put("canUse", canUse);
|
|
|
+ result.put("memberOnly", enabled);
|
|
|
+ result.put("feature", AI_COACH_FEATURE);
|
|
|
+ result.put("status", gate != null ? gate.getStatus() : AiGateStatus.UPGRADE_REQUIRED);
|
|
|
+ result.put("canViewHistory", gate != null && gate.isCanViewHistory());
|
|
|
+ result.put("memberLevel", gate != null && gate.getMemberLevel() != null ? gate.getMemberLevel() : "FREE");
|
|
|
+ result.put("memberExpireTime", gate != null ? gate.getMemberExpireTime() : null);
|
|
|
+ return Result.success(result);
|
|
|
+ }
|
|
|
+
|
|
|
+ // ── 健康管家 ──
|
|
|
+
|
|
|
+ @Operation(summary = "发送健康管家消息")
|
|
|
+ @PostMapping("/butler/send")
|
|
|
+ public Result<Map<String, Object>> sendHealthButlerMessage(
|
|
|
+ @RequestAttribute("userId") Long userId,
|
|
|
+ @RequestBody Map<String, Object> params) {
|
|
|
+ String query = (String) params.get("query");
|
|
|
+ String conversationId = (String) params.get("conversationId");
|
|
|
+ if (query == null || query.trim().isEmpty()) {
|
|
|
+ return Result.error("消息不能为空");
|
|
|
+ }
|
|
|
+ // AI 使用会员门禁
|
|
|
+ Result<Map<String, Object>> gateBlocked = checkGate(userId);
|
|
|
+ if (gateBlocked != null) {
|
|
|
+ return gateBlocked;
|
|
|
+ }
|
|
|
+ Map<String, Object> inputs = new LinkedHashMap<>();
|
|
|
+ if (params.get("memberId") != null) {
|
|
|
+ inputs.put("child_id", Long.valueOf(params.get("memberId").toString()));
|
|
|
+ }
|
|
|
+ if (params.get("reportId") != null) {
|
|
|
+ inputs.put("report_id", Long.valueOf(params.get("reportId").toString()));
|
|
|
+ }
|
|
|
+ if (params.get("focus") != null) {
|
|
|
+ inputs.put("focus", params.get("focus").toString());
|
|
|
+ }
|
|
|
+ // 画像注入
|
|
|
+ Long butlerMemberId = params.get("memberId") != null ? Long.valueOf(params.get("memberId").toString()) : null;
|
|
|
+ String butlerPortrait = portraitService.buildPortraitPrompt(userId, butlerMemberId);
|
|
|
+ if (butlerPortrait != null) {
|
|
|
+ inputs.put("portrait_prompt", butlerPortrait);
|
|
|
+ }
|
|
|
+ Map<String, Object> resp = aiGateway.chat(query, userId, conversationId, inputs);
|
|
|
+ String answer = resp != null ? (String) resp.getOrDefault("answer", "") : "";
|
|
|
+ Map<String, Object> result = new LinkedHashMap<>();
|
|
|
+ result.put("answer", answer);
|
|
|
+ result.put("conversationId", resp != null ? resp.getOrDefault("conversationId", "") : "");
|
|
|
+ result.put("recommendations", Collections.emptyList());
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ List<Object> tasks = resp != null && resp.get("tasks") instanceof List
|
|
|
+ ? (List<Object>) resp.get("tasks") : Collections.emptyList();
|
|
|
+ result.put("tasks", tasks);
|
|
|
+ return Result.success(result);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Operation(summary = "语音转文字")
|
|
|
+ @PostMapping("/transcribe")
|
|
|
+ public Result<Map<String, Object>> transcribe(
|
|
|
+ @RequestAttribute("userId") Long userId,
|
|
|
+ @RequestParam("file") org.springframework.web.multipart.MultipartFile file) {
|
|
|
+ if (file == null || file.isEmpty()) {
|
|
|
+ return Result.error(400, "音频文件为空");
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ Map<String, Object> result = aiGateway.transcribe(file.getBytes(), file.getOriginalFilename());
|
|
|
+ if (result != null) {
|
|
|
+ return Result.success(result);
|
|
|
+ }
|
|
|
+ return Result.error(500, "语音转写失败");
|
|
|
+ } catch (java.io.IOException e) {
|
|
|
+ return Result.error(500, "读取音频文件失败");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+}
|