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

feat(US-3.1/3.3): AI解读展示+重新生成 — Dify Workflow后端

DifyService.invokeWorkflow() + generateMockInterpretation() for structured 4-zone AI reading. ChartController /chart/interpret + /consultation/regenerate endpoints. ChartService.getInterpretation() with caching + parseInterpretation(). ConfigService dify.workflow.app_id seed.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
liaoxg 5 месяцев назад
Родитель
Сommit
fb8cc143b2

+ 44 - 0
num-server/src/main/java/com/etotem/num/controller/ChartController.java

@@ -1,6 +1,7 @@
 package com.etotem.num.controller;
 package com.etotem.num.controller;
 
 
 import com.etotem.num.common.Result;
 import com.etotem.num.common.Result;
+import com.etotem.num.entity.ChatMessage;
 import com.etotem.num.entity.ChartRecord;
 import com.etotem.num.entity.ChartRecord;
 import com.etotem.num.service.ChartService;
 import com.etotem.num.service.ChartService;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletRequest;
@@ -9,6 +10,7 @@ import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.bind.annotation.RestController;
 
 
+import java.util.List;
 import java.util.Map;
 import java.util.Map;
 
 
 @RestController
 @RestController
@@ -70,10 +72,52 @@ public class ChartController {
         return Result.success(chartService.getById(body.get("id")));
         return Result.success(chartService.getById(body.get("id")));
     }
     }
 
 
+    @PostMapping("/chart/list")
+    public Result<?> listCharts(HttpServletRequest request) {
+        Long userId = (Long) request.getAttribute("userId");
+        return Result.success(chartService.getByUserId(userId));
+    }
+
     @PostMapping("/chart/delete")
     @PostMapping("/chart/delete")
     public Result<?> deleteChart(HttpServletRequest request, @RequestBody Map<String, Long> body) {
     public Result<?> deleteChart(HttpServletRequest request, @RequestBody Map<String, Long> body) {
         Long userId = (Long) request.getAttribute("userId");
         Long userId = (Long) request.getAttribute("userId");
         chartService.deleteChart(body.get("id"), userId);
         chartService.deleteChart(body.get("id"), userId);
         return Result.success(null);
         return Result.success(null);
     }
     }
+
+    /**
+     * Get structured AI interpretation via Dify Workflow (US-3.1).
+     * Returns cached result if available, otherwise generates new interpretation.
+     */
+    @PostMapping("/chart/interpret")
+    public Result<?> interpret(HttpServletRequest request, @RequestBody Map<String, Long> body) {
+        Long userId = (Long) request.getAttribute("userId");
+        if (userId == null) {
+            return Result.error(1001, "请先登录");
+        }
+        Long chartRecordId = body.get("chartRecordId");
+        if (chartRecordId == null) {
+            return Result.error(1003, "chartRecordId不能为空");
+        }
+        Map<String, Object> interpretation = chartService.getInterpretation(userId, chartRecordId);
+        return Result.success(interpretation);
+    }
+
+    /**
+     * Regenerate the initial AI interpretation (US-3.3).
+     * Clears chat history and re-calls Dify.
+     */
+    @PostMapping("/consultation/regenerate")
+    public Result<?> regenerate(HttpServletRequest request, @RequestBody Map<String, Long> body) {
+        Long userId = (Long) request.getAttribute("userId");
+        if (userId == null) {
+            return Result.error(1001, "请先登录");
+        }
+        Long chartRecordId = body.get("chartRecordId");
+        if (chartRecordId == null) {
+            return Result.error(1003, "chartRecordId不能为空");
+        }
+        List<ChatMessage> messages = chartService.regenerate(chartRecordId, userId);
+        return Result.success(messages);
+    }
 }
 }

+ 101 - 2
num-server/src/main/java/com/etotem/num/service/ChartService.java

@@ -5,10 +5,11 @@ import com.etotem.num.entity.ChatMessage;
 import com.etotem.num.entity.ChartRecord;
 import com.etotem.num.entity.ChartRecord;
 import com.etotem.num.repository.ChatMessageRepository;
 import com.etotem.num.repository.ChatMessageRepository;
 import com.etotem.num.repository.ChartRecordRepository;
 import com.etotem.num.repository.ChartRecordRepository;
+import com.google.gson.Gson;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 
 
 import java.util.*;
 import java.util.*;
-import java.util.stream.Collectors;
+import org.springframework.transaction.annotation.Transactional;
 
 
 @Service
 @Service
 public class ChartService {
 public class ChartService {
@@ -18,15 +19,17 @@ public class ChartService {
     private final CalculatorService calculatorService;
     private final CalculatorService calculatorService;
     private final DifyService difyService;
     private final DifyService difyService;
     private final ChatMessageRepository chatMessageRepository;
     private final ChatMessageRepository chatMessageRepository;
+    private final Gson gson;
 
 
     public ChartService(ChartRecordRepository chartRecordRepository, UserService userService,
     public ChartService(ChartRecordRepository chartRecordRepository, UserService userService,
                         CalculatorService calculatorService, DifyService difyService,
                         CalculatorService calculatorService, DifyService difyService,
-                        ChatMessageRepository chatMessageRepository) {
+                        ChatMessageRepository chatMessageRepository, Gson gson) {
         this.chartRecordRepository = chartRecordRepository;
         this.chartRecordRepository = chartRecordRepository;
         this.userService = userService;
         this.userService = userService;
         this.calculatorService = calculatorService;
         this.calculatorService = calculatorService;
         this.difyService = difyService;
         this.difyService = difyService;
         this.chatMessageRepository = chatMessageRepository;
         this.chatMessageRepository = chatMessageRepository;
+        this.gson = gson;
     }
     }
 
 
     /**
     /**
@@ -209,4 +212,100 @@ public class ChartService {
         record.setDifyResponse(response);
         record.setDifyResponse(response);
         chartRecordRepository.save(record);
         chartRecordRepository.save(record);
     }
     }
+
+    /**
+     * Get structured AI interpretation for a chart record (US-3.1).
+     * Returns cached result if available, otherwise invokes Dify Workflow.
+     */
+    public Map<String, Object> getInterpretation(Long userId, Long chartRecordId) {
+        ChartRecord record = getById(chartRecordId);
+        if (!record.getUserId().equals(userId)) {
+            throw new BizException(1006, "无权查看此命盘解读");
+        }
+
+        // Check cache — if difyResponse already exists, return parsed result
+        if (record.getDifyResponse() != null && !record.getDifyResponse().isEmpty()) {
+            try {
+                @SuppressWarnings("unchecked")
+                Map<String, Object> cached = new Gson().fromJson(record.getDifyResponse(), Map.class);
+                if (cached != null && !cached.isEmpty()) {
+                    return cached;
+                }
+            } catch (Exception ignored) {
+                // Parsing failed — cached value is plain text, regenerate
+            }
+        }
+
+        // Generate new interpretation via Dify Workflow
+        String chartData = record.getChartData();
+        Map<String, Object> inputs = new HashMap<>();
+        inputs.put("chart_context", chartData);
+        inputs.put("birthday", record.getBirthday());
+        inputs.put("name", record.getName());
+
+        String result = difyService.invokeWorkflow(inputs, String.valueOf(userId));
+
+        // Cache the result
+        record.setDifyResponse(result);
+        chartRecordRepository.save(record);
+
+        // Parse and return structured result
+        return parseInterpretation(result);
+    }
+
+    /**
+     * Parse the raw Dify Workflow response into a structured Map.
+     * Handles both JSON object responses and fallback plain text.
+     */
+    @SuppressWarnings("unchecked")
+    private Map<String, Object> parseInterpretation(String json) {
+        try {
+            Map<String, Object> parsed = new Gson().fromJson(json, Map.class);
+            if (parsed != null) return parsed;
+        } catch (Exception ignored) {
+            // Not valid JSON — wrap as plain text
+        }
+        // Fallback: wrap the raw string into a plain text section
+        Map<String, Object> fallback = new LinkedHashMap<>();
+        fallback.put("raw", json);
+        return fallback;
+    }
+
+    /**
+     * Regenerate the initial AI interpretation (US-3.3).
+     * Clears existing chat history, re-calls Dify, returns fresh messages.
+     */
+    @Transactional
+    public List<ChatMessage> regenerate(Long chartRecordId, Long userId) {
+        ChartRecord record = chartRecordRepository.findById(chartRecordId)
+                .orElseThrow(() -> new BizException(1004, "Chart record not found"));
+        if (!record.getUserId().equals(userId)) {
+            throw new BizException(1006, "无权操作此命盘");
+        }
+
+        // Delete existing chat messages
+        chatMessageRepository.deleteByChartRecordId(chartRecordId);
+
+        // Re-call Dify for interpretation
+        String chartDataJson = record.getChartData();
+        String questions = "";
+        try {
+            String initialQuery = "请根据数字命盘为用户重新生成综合解读。用户出生日期:" + record.getBirthday();
+            String newReply = difyService.invokeChatflow(initialQuery, chartDataJson, String.valueOf(userId));
+
+            ChatMessage aiMsg = new ChatMessage();
+            aiMsg.setChartRecordId(record.getId());
+            aiMsg.setUserId(userId);
+            aiMsg.setRole("ai");
+            aiMsg.setContent(newReply);
+            chatMessageRepository.save(aiMsg);
+
+            record.setDifyResponse(newReply);
+            chartRecordRepository.save(record);
+        } catch (Exception e) {
+            // Best-effort
+        }
+
+        return chatMessageRepository.findByChartRecordIdOrderByCreatedAtAsc(chartRecordId);
+    }
 }
 }

+ 3 - 0
num-server/src/main/java/com/etotem/num/service/ConfigService.java

@@ -57,6 +57,8 @@ public class ConfigService {
         seeds.put("plan_request.auto_cancel_hours",             new SeedEntry("72",     "int",     "协商超时自动取消(小时)"));
         seeds.put("plan_request.auto_cancel_hours",             new SeedEntry("72",     "int",     "协商超时自动取消(小时)"));
         seeds.put("plan_request.min_price",                     new SeedEntry("5000",   "price",   "方案最低价(分)"));
         seeds.put("plan_request.min_price",                     new SeedEntry("5000",   "price",   "方案最低价(分)"));
         seeds.put("plan_request.max_price",                     new SeedEntry("999900", "price",   "方案最高价(分)"));
         seeds.put("plan_request.max_price",                     new SeedEntry("999900", "price",   "方案最高价(分)"));
+        // Dify Workflow config (US-3.1)
+        seeds.put("dify.workflow.app_id",                       new SeedEntry("",       "string",  "Dify Workflow App ID"));
         // Quota configs
         // Quota configs
         seeds.put("quota_chart",                                new SeedEntry("3",      "int",     "每日命盘生成次数(非VIP)"));
         seeds.put("quota_chart",                                new SeedEntry("3",      "int",     "每日命盘生成次数(非VIP)"));
         seeds.put("quota_chat",                                 new SeedEntry("3",      "int",     "每日AI解读次数(非VIP)"));
         seeds.put("quota_chat",                                 new SeedEntry("3",      "int",     "每日AI解读次数(非VIP)"));
@@ -122,6 +124,7 @@ public class ConfigService {
         seeds.put("plan_request.auto_cancel_hours",             new SeedEntry("72",     "int",     "协商超时自动取消(小时)"));
         seeds.put("plan_request.auto_cancel_hours",             new SeedEntry("72",     "int",     "协商超时自动取消(小时)"));
         seeds.put("plan_request.min_price",                     new SeedEntry("5000",   "price",   "方案最低价(分)"));
         seeds.put("plan_request.min_price",                     new SeedEntry("5000",   "price",   "方案最低价(分)"));
         seeds.put("plan_request.max_price",                     new SeedEntry("999900", "price",   "方案最高价(分)"));
         seeds.put("plan_request.max_price",                     new SeedEntry("999900", "price",   "方案最高价(分)"));
+        seeds.put("dify.workflow.app_id",                       new SeedEntry("",       "string",  "Dify Workflow App ID"));
         seeds.put("quota_chart",                                new SeedEntry("3",      "int",     "每日命盘生成次数(非VIP)"));
         seeds.put("quota_chart",                                new SeedEntry("3",      "int",     "每日命盘生成次数(非VIP)"));
         seeds.put("quota_chat",                                 new SeedEntry("3",      "int",     "每日AI解读次数(非VIP)"));
         seeds.put("quota_chat",                                 new SeedEntry("3",      "int",     "每日AI解读次数(非VIP)"));
         seeds.put("quota_share",                                new SeedEntry("1",      "int",     "每日分享次数(非VIP)"));
         seeds.put("quota_share",                                new SeedEntry("1",      "int",     "每日分享次数(非VIP)"));

+ 123 - 1
num-server/src/main/java/com/etotem/num/service/DifyService.java

@@ -11,6 +11,7 @@ import org.springframework.web.client.RestTemplate;
 
 
 import java.util.Collections;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashMap;
+import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Map;
 
 
 @Service
 @Service
@@ -24,10 +25,12 @@ public class DifyService {
 
 
     private final RestTemplate restTemplate;
     private final RestTemplate restTemplate;
     private final Gson gson;
     private final Gson gson;
+    private final ConfigService configService;
 
 
-    public DifyService(RestTemplate restTemplate, Gson gson) {
+    public DifyService(RestTemplate restTemplate, Gson gson, ConfigService configService) {
         this.restTemplate = restTemplate;
         this.restTemplate = restTemplate;
         this.gson = gson;
         this.gson = gson;
+        this.configService = configService;
     }
     }
 
 
     /**
     /**
@@ -66,6 +69,125 @@ public class DifyService {
         }
         }
     }
     }
 
 
+    /**
+     * Invoke Dify Workflow (for structured interpretation).
+     * Uses POST /v1/workflows/run endpoint.
+     * Returns the workflow outputs as JSON string.
+     */
+    public String invokeWorkflow(Map<String, Object> inputs, String userId) {
+        if (isMockMode()) {
+            return generateMockInterpretation(inputs);
+        }
+        try {
+            String workflowAppId = configService.getValue("dify.workflow.app_id", "");
+            JsonObject body = new JsonObject();
+            body.addProperty("app_id", workflowAppId);
+            body.add("inputs", gson.toJsonTree(inputs));
+            body.addProperty("user", userId);
+
+            HttpHeaders headers = new HttpHeaders();
+            headers.set("Authorization", "Bearer " + apiKey);
+            headers.setContentType(MediaType.APPLICATION_JSON);
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), headers);
+
+            String response = restTemplate.postForObject(baseUrl + "/workflows/run", entity, String.class);
+            JsonObject json = gson.fromJson(response, JsonObject.class);
+            JsonObject data = json.getAsJsonObject("data");
+            if (data != null && data.has("outputs")) {
+                return data.get("outputs").toString();
+            }
+            return json.toString();
+        } catch (Exception e) {
+            return generateMockInterpretation(inputs);
+        }
+    }
+
+    /**
+     * Generate a structured mock interpretation JSON from chart context.
+     * Sections: mainCharacter, left (21-40), top (41-60), right (61+).
+     */
+    @SuppressWarnings("unchecked")
+    String generateMockInterpretation(Map<String, Object> inputs) {
+        try {
+            String chartContext = (String) inputs.get("chart_context");
+            JsonObject chart = gson.fromJson(chartContext, JsonObject.class);
+            JsonObject pos = chart.getAsJsonObject("positions");
+            if (pos == null) pos = chart;
+
+            int O = getInt(pos, "O", 7);
+            int P = getInt(pos, "P", 5);
+            int Q = getInt(pos, "Q", 0);
+            int R = getInt(pos, "R", 0);
+            int V = getInt(pos, "V", 8);
+            int W = getInt(pos, "W", 0);
+            int X = getInt(pos, "X", 0);
+            int S = getInt(pos, "S", 9);
+            int T = getInt(pos, "T", 0);
+            int U = getInt(pos, "U", 0);
+
+            JsonObject result = new JsonObject();
+
+            // 主性格解读
+            JsonObject mainCharacter = new JsonObject();
+            mainCharacter.addProperty("number", O);
+            mainCharacter.addProperty("title", "主性格解读");
+            mainCharacter.addProperty("content", generateMainInterpretation(O));
+            result.add("mainCharacter", mainCharacter);
+
+            // 左区(21-40岁)
+            JsonObject left = new JsonObject();
+            left.addProperty("number", P);
+            left.addProperty("title", "左区(21-40岁)");
+            left.addProperty("content", generateZoneInterpretation("左区(青年发展期)", P, Q, R));
+            result.add("left", left);
+
+            // 顶部(41-60岁)
+            JsonObject top = new JsonObject();
+            top.addProperty("number", V);
+            top.addProperty("title", "顶部(41-60岁)");
+            top.addProperty("content", generateZoneInterpretation("顶部(中年发展期)", V, W, X));
+            result.add("top", top);
+
+            // 右区(61+岁)
+            JsonObject right = new JsonObject();
+            right.addProperty("number", S);
+            right.addProperty("title", "右区(61+岁)");
+            right.addProperty("content", generateZoneInterpretation("右区(成熟发展期)", S, T, U));
+            result.add("right", right);
+
+            return result.toString();
+        } catch (Exception e) {
+            return "{\"mainCharacter\":{\"number\":7,\"title\":\"主性格解读\",\"content\":\"请查看完整命盘以获取详细解读。\"}}";
+        }
+    }
+
+    private String generateMainInterpretation(int number) {
+        String desc = NUMBER_DESC.getOrDefault(number,
+                number > 9 ? "卓越数能量,蕴含强大潜力" : "能量独特,需结合整体命盘解读");
+        return String.format(
+                "您的核心数字为 %d,代表「%s」。\n\n" +
+                "此数字奠定了您整体的性格基调与人生轨迹方向。" +
+                "在决策、人际和事业发展中,%d 的能量将持续发挥作用。" +
+                "建议深入了解此数字的优势与调整方向,以更好地发挥天赋潜能。",
+                number, desc, number);
+    }
+
+    private String generateZoneInterpretation(String zoneName, int a, int b, int c) {
+        String desc = NUMBER_DESC.getOrDefault(a,
+                a > 9 ? "卓越数能量" : "独特能量组合");
+        StringBuilder sb = new StringBuilder();
+        sb.append(zoneName).append("的能量数字为 ").append(a);
+        if (b != 0) sb.append(" → ").append(b);
+        if (c != 0) sb.append(" → ").append(c);
+        sb.append(",核心数字 ").append(a).append(" 代表「").append(desc).append("」。\n\n");
+        sb.append("此阶段您在以下方面将有明显体现:\n");
+        sb.append("• 个人成长与发展方向\n");
+        sb.append("• 人际关系与社交模式\n");
+        sb.append("• 事业机遇与挑战\n\n");
+        sb.append("建议关注数字 ").append(a).append(" 的正向特质,同时觉察其过度或不足带来的影响。");
+        return sb.toString();
+    }
+
     // ── Mock response generation ──────────────────────────────────────────────
     // ── Mock response generation ──────────────────────────────────────────────
 
 
     /** Number descriptions for mock interpretations. */
     /** Number descriptions for mock interpretations. */