Преглед изворни кода

feat(workbench): 家庭聊天接口(会话列表+消息,归属校验)

Xiaogang Liao пре 1 недеља
родитељ
комит
25912b96f4

+ 34 - 1
cfc-backend/src/main/java/com/etotem/cfc/controller/admin/AdminFamilyWorkbenchController.java

@@ -1,8 +1,12 @@
 package com.etotem.cfc.controller.admin;
 
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.FamilyConversationVO;
+import com.etotem.cfc.dto.FamilyMessageVO;
 import com.etotem.cfc.dto.FamilyWorkbenchDTO;
 import com.etotem.cfc.service.FamilyWorkbenchService;
+import java.util.Map;
 import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import org.springframework.security.access.prepost.PreAuthorize;
@@ -20,7 +24,7 @@ public class AdminFamilyWorkbenchController {
 
     @Operation(summary = "单家庭工作台聚合(6 卡:总额 + 近 30 天逐日序列)")
     @PostMapping("/families/{id}/workbench")
-    @PreAuthorize("hasRole(admin)")
+    @PreAuthorize("hasRole('admin')")
     public Result<FamilyWorkbenchDTO> workbench(@PathVariable Long id) {
         try {
             return Result.success(service.aggregate(id));
@@ -28,4 +32,33 @@ public class AdminFamilyWorkbenchController {
             return Result.error(e.getMessage());
         }
     }
+
+    @Operation(summary = "家庭聊天会话列表")
+    @PostMapping("/families/{id}/messages")
+    @PreAuthorize("hasRole('admin')")
+    public Result<Page<FamilyConversationVO>> messages(@PathVariable Long id,
+                                                       @RequestBody(required = false) Map<String, Object> params) {
+        long page = params != null && params.get("page") != null ? ((Number) params.get("page")).longValue() : 1L;
+        long size = params != null && params.get("size") != null ? ((Number) params.get("size")).longValue() : 20L;
+        return Result.success(service.pageConversations(id, page, size));
+    }
+
+    @Operation(summary = "家庭聊天-会话消息")
+    @PostMapping("/families/{id}/messages/items")
+    @PreAuthorize("hasRole('admin')")
+    public Result<Page<FamilyMessageVO>> messageItems(@PathVariable Long id,
+                                                      @RequestBody Map<String, Object> params) {
+        Long conversationId = params.get("conversationId") != null
+                ? ((Number) params.get("conversationId")).longValue() : null;
+        if (conversationId == null) {
+            return Result.error("conversationId不能为空");
+        }
+        long page = params.get("page") != null ? ((Number) params.get("page")).longValue() : 1L;
+        long size = params.get("size") != null ? ((Number) params.get("size")).longValue() : 20L;
+        try {
+            return Result.success(service.pageConversationMessages(id, conversationId, page, size));
+        } catch (RuntimeException e) {
+            return Result.error(e.getMessage());
+        }
+    }
 }

+ 16 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/FamilyConversationVO.java

@@ -0,0 +1,16 @@
+package com.etotem.cfc.dto;
+
+import lombok.Data;
+
+import java.util.Date;
+
+/** 单家庭工作台-聊天会话项(家庭与老师/AI) */
+@Data
+public class FamilyConversationVO {
+    private Long id;
+    private String title;
+    private String assistantType;
+    private Date lastMessageAt;
+    private Long messageCount;
+    private String lastMessagePreview;
+}

+ 14 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/FamilyMessageVO.java

@@ -0,0 +1,14 @@
+package com.etotem.cfc.dto;
+
+import lombok.Data;
+
+import java.util.Date;
+
+/** 单家庭工作台-会话消息项(content 裁剪 2000 字) */
+@Data
+public class FamilyMessageVO {
+    private Long id;
+    private String role;
+    private String content;
+    private Date createdAt;
+}

+ 26 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/FamilyWorkbenchMapper.java

@@ -10,6 +10,7 @@ import java.util.Map;
 /**
  * 单家庭运营工作台-聚合查询(纯只读 @Select)。
  * 序列统一按 DATE(created_at) 分桶,供 FamilyWorkbenchSeriesBuilder 0 填充。
+ * 聊天无 family_id,经 family_members(user_id) 关联;所有列 alias 到无下划线的驼峰名,规避 map key 转换歧义。
  */
 @Mapper
 public interface FamilyWorkbenchMapper {
@@ -49,4 +50,29 @@ public interface FamilyWorkbenchMapper {
 
     @Select("SELECT DATE(created_at) AS d, SUM(amount) AS c FROM cf_balance_log WHERE family_id = #{familyId} AND created_at >= #{from} GROUP BY DATE(created_at)")
     List<Map<String, Object>> cfDailySeries(@Param("familyId") Long familyId, @Param("from") String from);
+
+    // ---------------- 家庭聊天(只读,经 family_members 归属) ----------------
+
+    @Select("SELECT c.id AS id, c.title AS title, c.assistant_type AS assistantType, "
+            + "c.last_message_at AS lastMessageAt, c.created_at AS createdAt, fm.user_id AS userId "
+            + "FROM chat_conversations c JOIN family_members fm ON fm.user_id = c.user_id "
+            + "WHERE fm.family_id = #{familyId} ORDER BY c.last_message_at DESC, c.id DESC")
+    List<Map<String, Object>> conversationsByFamily(@Param("familyId") Long familyId);
+
+    @Select("SELECT COUNT(*) FROM chat_messages WHERE conversation_id = #{conversationId}")
+    long conversationMessageCount(@Param("conversationId") Long conversationId);
+
+    @Select("SELECT content FROM chat_messages WHERE conversation_id = #{conversationId} ORDER BY created_at DESC, id DESC LIMIT 1")
+    String conversationLastMessage(@Param("conversationId") Long conversationId);
+
+    @Select("SELECT id AS id, role AS role, content AS content, created_at AS createdAt "
+            + "FROM chat_messages WHERE conversation_id = #{conversationId} "
+            + "ORDER BY created_at ASC, id ASC LIMIT #{size} OFFSET #{offset}")
+    List<Map<String, Object>> messagesOfConversation(@Param("conversationId") Long conversationId,
+                                                    @Param("offset") long offset,
+                                                    @Param("size") long size);
+
+    @Select("SELECT COUNT(*) FROM chat_conversations c JOIN family_members fm ON fm.user_id = c.user_id "
+            + "WHERE c.id = #{conversationId} AND fm.family_id = #{familyId}")
+    long conversationInFamily(@Param("conversationId") Long conversationId, @Param("familyId") Long familyId);
 }

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/FamilyWorkbenchService.java

@@ -1,5 +1,8 @@
 package com.etotem.cfc.service;
 
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.dto.FamilyConversationVO;
+import com.etotem.cfc.dto.FamilyMessageVO;
 import com.etotem.cfc.dto.FamilyWorkbenchDTO;
 
 /** 单家庭运营工作台-聚合与家庭模块只读查询 */
@@ -7,4 +10,10 @@ public interface FamilyWorkbenchService {
 
     /** 家庭不存在抛 RuntimeException("家庭不存在");返回 family + 6 张指标卡(总额+近30天序列) */
     FamilyWorkbenchDTO aggregate(Long familyId);
+
+    /** 该家庭成员的聊天会话(分页);会话经 family_members 归属 */
+    Page<FamilyConversationVO> pageConversations(Long familyId, long page, long size);
+
+    /** 会话消息(分页);会话不属于该家庭抛 RuntimeException("会话不属于该家庭") */
+    Page<FamilyMessageVO> pageConversationMessages(Long familyId, Long conversationId, long page, long size);
 }

+ 74 - 1
cfc-backend/src/main/java/com/etotem/cfc/service/impl/FamilyWorkbenchServiceImpl.java

@@ -1,8 +1,10 @@
 package com.etotem.cfc.service.impl;
 
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.dto.FamilyConversationVO;
+import com.etotem.cfc.dto.FamilyMessageVO;
 import com.etotem.cfc.dto.FamilyWorkbenchCard;
 import com.etotem.cfc.dto.FamilyWorkbenchDTO;
-import com.etotem.cfc.dto.FamilyWorkbenchSeriesPoint;
 import com.etotem.cfc.entity.Family;
 import com.etotem.cfc.mapper.FamilyMapper;
 import com.etotem.cfc.mapper.FamilyWorkbenchMapper;
@@ -13,6 +15,7 @@ import org.springframework.stereotype.Service;
 import javax.annotation.Resource;
 import java.time.LocalDate;
 import java.util.ArrayList;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -20,6 +23,9 @@ import java.util.Map;
 @Service
 public class FamilyWorkbenchServiceImpl implements FamilyWorkbenchService {
 
+    private static final int CONVERSATION_PREVIEW_MAX = 50;
+    private static final int MESSAGE_CONTENT_MAX = 2000;
+
     @Resource
     private FamilyMapper familyMapper;
 
@@ -55,6 +61,56 @@ public class FamilyWorkbenchServiceImpl implements FamilyWorkbenchService {
         return dto;
     }
 
+    @Override
+    public Page<FamilyConversationVO> pageConversations(Long familyId, long page, long size) {
+        long safePage = Math.max(page, 1);
+        long safeSize = Math.min(Math.max(size, 1), 100);
+        List<Map<String, Object>> rows = workbenchMapper.conversationsByFamily(familyId);
+        long total = rows.size();
+        int fromIdx = (int) Math.min((safePage - 1) * safeSize, total);
+        int toIdx = (int) Math.min(fromIdx + safeSize, total);
+
+        List<FamilyConversationVO> records = new ArrayList<>();
+        for (Map<String, Object> r : rows.subList(fromIdx, toIdx)) {
+            FamilyConversationVO vo = new FamilyConversationVO();
+            vo.setId(asLong(r.get("id")));
+            vo.setTitle(asString(r.get("title")));
+            vo.setAssistantType(asString(r.get("assistantType")));
+            vo.setLastMessageAt(asDate(r.get("lastMessageAt")));
+            vo.setMessageCount(workbenchMapper.conversationMessageCount(vo.getId()));
+            vo.setLastMessagePreview(trim(workbenchMapper.conversationLastMessage(vo.getId()), CONVERSATION_PREVIEW_MAX));
+            records.add(vo);
+        }
+        Page<FamilyConversationVO> out = new Page<>(safePage, safeSize, total);
+        out.setRecords(records);
+        return out;
+    }
+
+    @Override
+    public Page<FamilyMessageVO> pageConversationMessages(Long familyId, Long conversationId, long page, long size) {
+        long safePage = Math.max(page, 1);
+        long safeSize = Math.min(Math.max(size, 1), 200);
+        if (workbenchMapper.conversationInFamily(conversationId, familyId) <= 0) {
+            throw new RuntimeException("会话不属于该家庭");
+        }
+        long total = workbenchMapper.conversationMessageCount(conversationId);
+        long offset = (safePage - 1) * safeSize;
+        List<Map<String, Object>> rows = workbenchMapper.messagesOfConversation(conversationId, offset, safeSize);
+
+        List<FamilyMessageVO> records = new ArrayList<>();
+        for (Map<String, Object> r : rows) {
+            FamilyMessageVO vo = new FamilyMessageVO();
+            vo.setId(asLong(r.get("id")));
+            vo.setRole(asString(r.get("role")));
+            vo.setContent(trim(asString(r.get("content")), MESSAGE_CONTENT_MAX));
+            vo.setCreatedAt(asDate(r.get("createdAt")));
+            records.add(vo);
+        }
+        Page<FamilyMessageVO> out = new Page<>(safePage, safeSize, total);
+        out.setRecords(records);
+        return out;
+    }
+
     private FamilyWorkbenchCard card(String key, String label, Long total,
                                      List<Map<String, Object>> rows, LocalDate from, LocalDate to) {
         FamilyWorkbenchCard c = new FamilyWorkbenchCard();
@@ -77,4 +133,21 @@ public class FamilyWorkbenchServiceImpl implements FamilyWorkbenchService {
         f.put("createdAt", family.getCreatedAt());
         return f;
     }
+
+    private static String trim(String s, int max) {
+        if (s == null) return null;
+        return s.length() > max ? s.substring(0, max) + "…" : s;
+    }
+
+    private static Long asLong(Object o) {
+        return o == null ? null : ((Number) o).longValue();
+    }
+
+    private static String asString(Object o) {
+        return o == null ? null : o.toString();
+    }
+
+    private static Date asDate(Object o) {
+        return o instanceof Date ? (Date) o : null;
+    }
 }

+ 102 - 0
cfc-backend/src/test/java/com/etotem/cfc/service/FamilyWorkbenchMessageServiceTest.java

@@ -0,0 +1,102 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.dto.FamilyConversationVO;
+import com.etotem.cfc.dto.FamilyMessageVO;
+import com.etotem.cfc.mapper.FamilyWorkbenchMapper;
+import com.etotem.cfc.service.impl.FamilyWorkbenchServiceImpl;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.when;
+
+/**
+ * 家庭聊天接口契约:会话列表映射/预览截断、会话归属校验(防越权)、消息分页内容裁剪。
+ */
+class FamilyWorkbenchMessageServiceTest {
+
+    @Mock private FamilyWorkbenchMapper mapper;
+    @InjectMocks private FamilyWorkbenchServiceImpl service;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+    }
+
+    private Map<String, Object> convRow(Long id, String title, String assistantType) {
+        Map<String, Object> m = new HashMap<>();
+        m.put("id", id);
+        m.put("title", title);
+        m.put("assistantType", assistantType);
+        m.put("lastMessageAt", new Date());
+        m.put("createdAt", new Date());
+        m.put("userId", 100L);
+        return m;
+    }
+
+    private String longText(int n) {
+        return "x".repeat(n);
+    }
+
+    @Test
+    void 家庭会话列表_映射与预览截断50字() {
+        when(mapper.conversationsByFamily(5L)).thenReturn(List.of(convRow(11L, "测试会话", "family")));
+        when(mapper.conversationMessageCount(11L)).thenReturn(3L);
+        when(mapper.conversationLastMessage(11L)).thenReturn(longText(120));
+
+        Page<FamilyConversationVO> page = service.pageConversations(5L, 1, 20);
+
+        assertEquals(1, page.getRecords().size());
+        FamilyConversationVO vo = page.getRecords().get(0);
+        assertEquals(11L, vo.getId());
+        assertEquals("测试会话", vo.getTitle());
+        assertEquals("family", vo.getAssistantType());
+        assertEquals(3L, vo.getMessageCount());
+        assertTrue(vo.getLastMessagePreview().endsWith("…"));
+        assertEquals(51, vo.getLastMessagePreview().length(), "预览=50字+省略号");
+    }
+
+    @Test
+    void 会话不属于该家庭_拒绝() {
+        when(mapper.conversationInFamily(99L, 5L)).thenReturn(0L);
+        RuntimeException e = assertThrows(RuntimeException.class,
+                () -> service.pageConversationMessages(5L, 99L, 1, 20));
+        assertTrue(e.getMessage().contains("会话不属于该家庭"));
+    }
+
+    @Test
+    void 会话消息分页_内容裁剪2000字() {
+        when(mapper.conversationInFamily(11L, 5L)).thenReturn(1L);
+        when(mapper.conversationMessageCount(11L)).thenReturn(2L);
+        Map<String, Object> m1 = new HashMap<>();
+        m1.put("id", 1L);
+        m1.put("role", "user");
+        m1.put("content", longText(3000));
+        m1.put("createdAt", new Date());
+        Map<String, Object> m2 = new HashMap<>();
+        m2.put("id", 2L);
+        m2.put("role", "assistant");
+        m2.put("content", "短内容");
+        m2.put("createdAt", new Date());
+        when(mapper.messagesOfConversation(11L, 0L, 20L)).thenReturn(List.of(m1, m2));
+
+        Page<FamilyMessageVO> page = service.pageConversationMessages(5L, 11L, 1, 20);
+
+        assertEquals(2L, page.getTotal());
+        assertEquals("user", page.getRecords().get(0).getRole());
+        assertTrue(page.getRecords().get(0).getContent().endsWith("…"));
+        assertEquals(2001, page.getRecords().get(0).getContent().length(), "裁剪=2000字+省略号");
+        assertEquals("短内容", page.getRecords().get(1).getContent());
+    }
+}