fix(service): 仅返回活跃会话中的聊天角色列表

This commit is contained in:
2026-01-28 20:53:47 +08:00
parent 408d4d4bc1
commit 7d23b6be0f

View File

@@ -79,14 +79,31 @@ public class KeyboardAiChatMessageServiceImpl extends ServiceImpl<KeyboardAiChat
@Override @Override
public List<Long> getChattedCompanionIds(Long userId) { public List<Long> getChattedCompanionIds(Long userId) {
// 使用原生SQL查询用户聊过天的所有角色ID按最近聊天时间倒序 // 1. 查询用户所有活跃会话
LambdaQueryWrapper<KeyboardAiChatSession> sessionWrapper = new LambdaQueryWrapper<>();
sessionWrapper.eq(KeyboardAiChatSession::getUserId, userId)
.eq(KeyboardAiChatSession::getIsActive, true);
List<KeyboardAiChatSession> activeSessions = sessionService.list(sessionWrapper);
// 2. 如果没有活跃会话,返回空列表
if (activeSessions == null || activeSessions.isEmpty()) {
return Collections.emptyList();
}
// 3. 提取活跃会话的 sessionId 列表
List<Long> activeSessionIds = activeSessions.stream()
.map(KeyboardAiChatSession::getId)
.collect(java.util.stream.Collectors.toList());
// 4. 查询这些会话中的消息,获取 companionId按最近聊天时间倒序
LambdaQueryWrapper<KeyboardAiChatMessage> queryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<KeyboardAiChatMessage> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(KeyboardAiChatMessage::getUserId, userId) queryWrapper.eq(KeyboardAiChatMessage::getUserId, userId)
.select(KeyboardAiChatMessage::getCompanionId) .in(KeyboardAiChatMessage::getSessionId, activeSessionIds)
.groupBy(KeyboardAiChatMessage::getCompanionId) .orderByDesc(KeyboardAiChatMessage::getCreatedAt);
.orderByDesc(KeyboardAiChatMessage::getCompanionId);
List<KeyboardAiChatMessage> messages = this.list(queryWrapper); List<KeyboardAiChatMessage> messages = this.list(queryWrapper);
// 5. 去重并保持顺序(按最近聊天时间)
return messages.stream() return messages.stream()
.map(KeyboardAiChatMessage::getCompanionId) .map(KeyboardAiChatMessage::getCompanionId)
.distinct() .distinct()