package com.custom.webui.service.impl;
|
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
import com.custom.webui.dto.req.ChatCreateRequest;
|
import com.custom.webui.dto.req.ChatMetaRequest;
|
import com.custom.webui.dto.req.ChatUpdateRequest;
|
import com.custom.webui.dto.resp.ChatDTO;
|
import com.custom.webui.entity.Chat;
|
import com.custom.webui.entity.ChatCollection;
|
import com.custom.webui.entity.Message;
|
import com.custom.webui.entity.UploadFile;
|
import com.custom.webui.exception.BusinessException;
|
import com.custom.webui.mapper.ChatCollectionMapper;
|
import com.custom.webui.mapper.ChatMapper;
|
import com.custom.webui.mapper.MessageMapper;
|
import com.custom.webui.mapper.UploadFileMapper;
|
import com.custom.webui.service.ChatService;
|
import com.custom.webui.service.ChatGroupService;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
import lombok.RequiredArgsConstructor;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.stereotype.Service;
|
import org.springframework.transaction.annotation.Transactional;
|
|
import java.time.LocalDateTime;
|
import java.util.Set;
|
import java.util.Locale;
|
import java.util.LinkedHashSet;
|
import java.util.LinkedHashMap;
|
import java.util.ArrayList;
|
import java.util.Collections;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.stream.Collectors;
|
|
/** 会话服务实现。 */
|
@Slf4j
|
@Service
|
@RequiredArgsConstructor
|
public class ChatServiceImpl implements ChatService {
|
|
private static final String DEFAULT_TITLE = "新对话";
|
|
/** 搜索片段中关键词前后保留的字符数 */
|
private static final int CONTEXT_LENGTH = 40;
|
|
/** 无命中位置(理论上不会走到)时的片段长度 */
|
private static final int SNIPPET_LENGTH = 100;
|
|
private final ChatMapper chatMapper;
|
private final MessageMapper messageMapper;
|
private final UploadFileMapper uploadFileMapper;
|
private final ChatCollectionMapper chatCollectionMapper;
|
private final ChatGroupService chatGroupService;
|
private final ObjectMapper objectMapper;
|
|
@Override
|
public List<ChatDTO> listByUser(Long userId, boolean archived) {
|
List<Chat> chats = chatMapper.selectList(
|
Wrappers.<Chat>lambdaQuery()
|
.eq(Chat::getUserId, userId)
|
.eq(Chat::getArchived, archived)
|
// 置顶优先,其次置顶时间倒序,最后活跃时间倒序。
|
// 非置顶行的 pinned_at 全为 NULL,第二排序键等同无效,
|
// 于是自然退化成「按最近活跃倒序」。
|
.orderByDesc(Chat::getPinned)
|
.orderByDesc(Chat::getPinnedAt)
|
.orderByDesc(Chat::getUpdatedAt));
|
if (chats.isEmpty()) {
|
return Collections.emptyList();
|
}
|
|
// 一次性聚合消息数,避免在循环里对每个会话查一次(N+1 查询)
|
List<Long> chatIds = chats.stream().map(Chat::getId).toList();
|
Map<Long, Long> countByChat = messageMapper.selectList(
|
Wrappers.<Message>lambdaQuery()
|
.select(Message::getChatId)
|
.in(Message::getChatId, chatIds))
|
.stream()
|
.collect(Collectors.groupingBy(Message::getChatId, Collectors.counting()));
|
|
// 同样一次性取出所有会话的知识库绑定
|
Map<Long, List<String>> collectionsByChat = chatCollectionMapper.selectList(
|
Wrappers.<ChatCollection>lambdaQuery().in(ChatCollection::getChatId, chatIds))
|
.stream()
|
.collect(Collectors.groupingBy(ChatCollection::getChatId,
|
Collectors.mapping(ChatCollection::getCollectionName, Collectors.toList())));
|
|
return chats.stream()
|
.map(c -> toDto(c,
|
countByChat.getOrDefault(c.getId(), 0L),
|
collectionsByChat.getOrDefault(c.getId(), Collections.emptyList())))
|
.toList();
|
}
|
|
@Override
|
@Transactional(rollbackFor = Exception.class)
|
public ChatDTO create(Long userId, ChatCreateRequest request) {
|
Chat chat = new Chat();
|
chat.setUserId(userId);
|
chat.setTitle(request != null && request.getTitle() != null && !request.getTitle().isBlank()
|
? request.getTitle().trim()
|
: DEFAULT_TITLE);
|
chat.setMeta(writeMeta(request == null ? null : request.getMeta()));
|
chat.setCreatedAt(LocalDateTime.now());
|
chat.setUpdatedAt(LocalDateTime.now());
|
chatMapper.insert(chat);
|
|
log.info("新建会话 userId={} chatId={}", userId, chat.getId());
|
return toDto(chat, 0L, Collections.emptyList());
|
}
|
|
@Override
|
@Transactional(rollbackFor = Exception.class)
|
public ChatDTO update(Long userId, Long chatId, ChatUpdateRequest request) {
|
Chat existing = requireOwnedChat(userId, chatId);
|
|
/*
|
* 这里刻意用 UpdateWrapper 逐列显式 SET,而不是 updateById(entity):
|
*
|
* 1) updateById 默认**忽略 null 字段**,而「取消置顶」恰恰要把
|
* pinned_at 写回 NULL,用实体传 null 表达不了这个意图。
|
* 2) updated_at 这一列在 MySQL 里带 ON UPDATE CURRENT_TIMESTAMP,
|
* 只要 UPDATE 语句不显式提到它,它就会被数据库自动刷新。
|
* 而置顶/归档属于**视图整理**操作,不该被当成「刚刚活跃」——
|
* 否则置顶一下,会话就会在时间分组里从「更早」跳到「今天」。
|
* 显式 SET updated_at = 原值 是唯一能压住该自动行为的方式
|
* (MySQL 文档:被显式赋值的列不会再走 ON UPDATE)。
|
*/
|
LocalDateTime now = LocalDateTime.now();
|
var wrapper = Wrappers.<Chat>lambdaUpdate().eq(Chat::getId, chatId);
|
|
boolean contentChanged = false;
|
|
if (request.getTitle() != null) {
|
String title = request.getTitle().trim();
|
if (title.isEmpty()) {
|
throw BusinessException.badRequest("标题不能为空");
|
}
|
// 防御超长标题:列宽 255,超出部分直接截断而不是报数据库错误
|
wrapper.set(Chat::getTitle, title.length() > 255 ? title.substring(0, 255) : title);
|
contentChanged = true;
|
}
|
|
if (request.getMeta() != null) {
|
// meta 是整体覆盖语义:前端应提交完整的参数对象
|
wrapper.set(Chat::getMeta, writeMeta(request.getMeta()));
|
contentChanged = true;
|
}
|
|
// ---- 置顶 ----
|
// 置顶时记录 pinned_at,置顶区因此按「钉上去的先后」排序;
|
// 取消置顶则清回 NULL,不让旧时间残留下去影响后续排序。
|
if (request.getPinned() != null) {
|
boolean pinned = request.getPinned();
|
wrapper.set(Chat::getPinned, pinned);
|
wrapper.set(Chat::getPinnedAt, pinned ? now : null);
|
}
|
|
// ---- 归档 ----
|
if (request.getArchived() != null) {
|
boolean archived = request.getArchived();
|
wrapper.set(Chat::getArchived, archived);
|
wrapper.set(Chat::getArchivedAt, archived ? now : null);
|
}
|
|
wrapper.set(Chat::getUpdatedAt, contentChanged ? now : existing.getUpdatedAt());
|
chatMapper.update(null, wrapper);
|
|
Chat refreshed = chatMapper.selectById(chatId);
|
Long messageCount = messageMapper.selectCount(
|
Wrappers.<Message>lambdaQuery().eq(Message::getChatId, chatId));
|
List<String> collections = chatCollectionMapper.selectList(
|
Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
|
.stream().map(ChatCollection::getCollectionName).toList();
|
|
log.debug("更新会话 chatId={} 原meta={} 新meta={} pinned={} archived={}",
|
chatId, existing.getMeta(), refreshed.getMeta(),
|
refreshed.getPinned(), refreshed.getArchived());
|
return toDto(refreshed, messageCount, collections);
|
}
|
|
@Override
|
@Transactional(rollbackFor = Exception.class)
|
public void delete(Long userId, Long chatId) {
|
requireOwnedChat(userId, chatId);
|
|
// 显式级联:先删子表再删主表,避免留下孤儿数据。
|
// 不使用数据库外键是刻意选择 —— 便于分库分表和批量导入,代价是要自己保证一致性。
|
int msgDeleted = messageMapper.delete(
|
Wrappers.<Message>lambdaQuery().eq(Message::getChatId, chatId));
|
chatCollectionMapper.delete(
|
Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId));
|
|
// 会话绑定的文件解除会话绑定(文件本体与向量集合保留,用户可继续在别处使用)
|
List<UploadFile> boundFiles = uploadFileMapper.selectList(
|
Wrappers.<UploadFile>lambdaQuery().eq(UploadFile::getChatId, chatId));
|
for (UploadFile f : boundFiles) {
|
UploadFile patch = new UploadFile();
|
patch.setId(f.getId());
|
patch.setChatId(null);
|
uploadFileMapper.updateById(patch);
|
}
|
|
chatMapper.deleteById(chatId);
|
log.info("删除会话 userId={} chatId={} 连带删除消息 {} 条、解绑文件 {} 个",
|
userId, chatId, msgDeleted, boundFiles.size());
|
}
|
|
@Override
|
@Transactional(rollbackFor = Exception.class)
|
public ChatDTO moveToGroup(Long userId, Long chatId, Long groupId) {
|
Chat chat = requireOwnedChat(userId, chatId);
|
|
if (groupId != null) {
|
// 目标分组必须是自己的 —— 否则用户可以把会话「移进」别人的分组 id,
|
// 虽然看不到对方的内容,但会在对方的列表里凭空多出一条不属于他的会话
|
chatGroupService.requireOwnedGroup(userId, groupId);
|
}
|
|
// 一次 UPDATE 同时处理两件事:
|
// 1. group_id 要能写成 NULL(移出分组),所以用 UpdateWrapper 显式 SET,
|
// 实体里的 null 字段会被 MyBatis-Plus 忽略,表达不了「置空」
|
// 2. updated_at 显式写回原值 —— 整理动作不该被当成「刚刚活跃」,
|
// 否则会话会在时间分组里从「更早」跳到「今天」
|
chatMapper.update(null,
|
Wrappers.<Chat>lambdaUpdate()
|
.eq(Chat::getId, chatId)
|
.set(Chat::getGroupId, groupId)
|
.set(Chat::getUpdatedAt, chat.getUpdatedAt()));
|
|
Long messageCount = messageMapper.selectCount(
|
Wrappers.<Message>lambdaQuery().eq(Message::getChatId, chatId));
|
List<String> collections = chatCollectionMapper.selectList(
|
Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
|
.stream().map(ChatCollection::getCollectionName).toList();
|
|
log.info("会话移动分组 userId={} chatId={} groupId={}", userId, chatId, groupId);
|
return toDto(chatMapper.selectById(chatId), messageCount, collections);
|
}
|
|
@Override
|
public Chat requireOwnedChat(Long userId, Long chatId) {
|
if (chatId == null) {
|
throw BusinessException.badRequest("会话 id 不能为空");
|
}
|
Chat chat = chatMapper.selectById(chatId);
|
// 不存在与不属于当前用户统一返回 404:
|
// 若返回 403 就等于告诉攻击者「这个 id 是存在的」,属于信息泄露。
|
if (chat == null || !chat.getUserId().equals(userId)) {
|
throw BusinessException.notFound("会话不存在或无权访问");
|
}
|
return chat;
|
}
|
|
@Override
|
public ChatMetaRequest parseMeta(Chat chat) {
|
if (chat == null || chat.getMeta() == null || chat.getMeta().isBlank()) {
|
return new ChatMetaRequest();
|
}
|
try {
|
ChatMetaRequest meta = objectMapper.readValue(chat.getMeta(), ChatMetaRequest.class);
|
return meta == null ? new ChatMetaRequest() : meta;
|
} catch (Exception e) {
|
// 脏数据不应导致整个请求失败,降级为默认参数并留下告警
|
log.warn("会话 meta 解析失败 chatId={} raw={}", chat.getId(), chat.getMeta());
|
return new ChatMetaRequest();
|
}
|
}
|
|
@Override
|
@Transactional(rollbackFor = Exception.class)
|
public void updateTitle(Long chatId, String title) {
|
if (title == null || title.isBlank()) {
|
return;
|
}
|
String normalized = title.trim();
|
Chat update = new Chat();
|
update.setId(chatId);
|
update.setTitle(normalized.length() > 255 ? normalized.substring(0, 255) : normalized);
|
update.setUpdatedAt(LocalDateTime.now());
|
chatMapper.updateById(update);
|
}
|
|
@Override
|
public List<ChatDTO> search(Long userId, String keyword, int limit, boolean archived) {
|
if (keyword == null || keyword.isBlank()) {
|
// 空关键词直接返回空,而不是返回全部会话 ——
|
// 否则搜索框会退化成「无过滤列表」,和侧边栏本身重复
|
return Collections.emptyList();
|
}
|
String kw = keyword.trim();
|
int max = limit > 0 ? Math.min(limit, 100) : 30;
|
|
// 先取该用户全部会话(个人会话量级通常在数百,一次查完再做内存匹配,
|
// 比两次 LIKE 查询 + 合并更简单,也避免了 title/message 两次往返)。
|
//
|
// 搜索范围与当前视图一致:主列表搜索不把归档对话混进来,
|
// 在「归档对话」里搜索则只搜归档的 —— 否则用户会搜到一堆
|
// 自己刚归档起来、并不想看到的对话。
|
List<Chat> chats = chatMapper.selectList(
|
Wrappers.<Chat>lambdaQuery()
|
.eq(Chat::getUserId, userId)
|
.eq(Chat::getArchived, archived)
|
.orderByDesc(Chat::getUpdatedAt));
|
if (chats.isEmpty()) {
|
return Collections.emptyList();
|
}
|
|
Map<Long, Chat> chatById = new LinkedHashMap<>();
|
for (Chat c : chats) {
|
chatById.put(c.getId(), c);
|
}
|
|
// 命中标题的会话
|
Set<Long> titleHits = new LinkedHashSet<>();
|
String lowerKw = kw.toLowerCase(Locale.ROOT);
|
for (Chat c : chats) {
|
if (c.getTitle() != null && c.getTitle().toLowerCase(Locale.ROOT).contains(lowerKw)) {
|
titleHits.add(c.getId());
|
}
|
}
|
|
// 命中消息内容的会话:取每个命中会话的**最早一条**命中消息作为片段。
|
// 用 Map 去重,避免同一个会话因多条消息命中而重复出现。
|
Map<Long, Message> contentHits = new LinkedHashMap<>();
|
if (!chatById.isEmpty()) {
|
List<Message> hits = messageMapper.selectList(
|
Wrappers.<Message>lambdaQuery()
|
.in(Message::getChatId, chatById.keySet())
|
.like(Message::getContent, kw)
|
.orderByAsc(Message::getId));
|
for (Message m : hits) {
|
contentHits.putIfAbsent(m.getChatId(), m);
|
}
|
}
|
|
// 合并:按「会话最近活跃时间倒序」输出,标题命中优先于内容命中
|
List<ChatDTO> result = new ArrayList<>();
|
for (Chat c : chats) {
|
boolean byTitle = titleHits.contains(c.getId());
|
Message byContent = contentHits.get(c.getId());
|
if (!byTitle && byContent == null) {
|
continue;
|
}
|
|
ChatDTO dto = toDto(c, null, null);
|
dto.setMatchType(byTitle && byContent != null ? "both"
|
: byTitle ? "title" : "message");
|
if (byContent != null) {
|
dto.setMatchSnippet(buildSnippet(byContent.getContent(), kw));
|
}
|
result.add(dto);
|
|
if (result.size() >= max) {
|
break;
|
}
|
}
|
|
// 数量信息:会话数用轻量查询补齐,避免 N+1
|
if (!result.isEmpty()) {
|
List<Long> ids = result.stream().map(ChatDTO::getId).toList();
|
Map<Long, Long> counts = messageMapper.selectList(
|
Wrappers.<Message>lambdaQuery()
|
.select(Message::getChatId)
|
.in(Message::getChatId, ids))
|
.stream()
|
.collect(Collectors.groupingBy(Message::getChatId, Collectors.counting()));
|
for (ChatDTO dto : result) {
|
dto.setMessageCount(counts.getOrDefault(dto.getId(), 0L));
|
}
|
}
|
|
log.debug("会话搜索 userId={} 关键词={} 标题命中={} 内容命中={} 返回={}",
|
userId, kw, titleHits.size(), contentHits.size(), result.size());
|
return result;
|
}
|
|
/**
|
* 围绕关键词截取一段用于展示的片段。
|
*
|
* <p>把关键词居中,前后各留 {@code CONTEXT} 个字符,两侧加省略号。
|
* 命中位置在很长的消息里时,这比返回消息开头更有助于用户辨认。
|
*/
|
private String buildSnippet(String content, String keyword) {
|
if (content == null || content.isBlank()) {
|
return "";
|
}
|
String flat = content.replaceAll("\\s+", " ").trim();
|
int index = flat.toLowerCase(Locale.ROOT).indexOf(keyword.toLowerCase(Locale.ROOT));
|
if (index < 0) {
|
return abbreviate(flat, SNIPPET_LENGTH);
|
}
|
|
int start = Math.max(0, index - CONTEXT_LENGTH);
|
int end = Math.min(flat.length(), index + keyword.length() + CONTEXT_LENGTH);
|
String snippet = flat.substring(start, end);
|
return (start > 0 ? "…" : "") + snippet + (end < flat.length() ? "…" : "");
|
}
|
|
private String abbreviate(String text, int max) {
|
return text.length() <= max ? text : text.substring(0, max) + "…";
|
}
|
|
// ==================== 内部辅助 ====================
|
|
/** 序列化 meta;传入 null 时返回 null(列可为空) */
|
private String writeMeta(ChatMetaRequest meta) {
|
if (meta == null) {
|
return null;
|
}
|
try {
|
return objectMapper.writeValueAsString(meta);
|
} catch (Exception e) {
|
throw BusinessException.badRequest("模型参数格式不正确: " + e.getMessage());
|
}
|
}
|
|
private ChatDTO toDto(Chat chat, Long messageCount, List<String> collections) {
|
ChatDTO dto = new ChatDTO();
|
dto.setId(chat.getId());
|
dto.setTitle(chat.getTitle());
|
// meta 列可能为 NULL,而 @JsonRawValue 遇到 null 会输出字面量 null,
|
// 因此统一兜底成 {} 让前端可以无脑取字段
|
dto.setMeta(chat.getMeta() == null || chat.getMeta().isBlank() ? "{}" : chat.getMeta());
|
dto.setCreatedAt(chat.getCreatedAt());
|
dto.setUpdatedAt(chat.getUpdatedAt());
|
// 置顶/归档列可能为 NULL(例如迁移前的老数据被显式查出),统一兜底成 false,
|
// 免得前端拿到 null 还要到处判空
|
dto.setPinned(Boolean.TRUE.equals(chat.getPinned()));
|
dto.setPinnedAt(chat.getPinnedAt());
|
dto.setArchived(Boolean.TRUE.equals(chat.getArchived()));
|
dto.setArchivedAt(chat.getArchivedAt());
|
dto.setGroupId(chat.getGroupId());
|
dto.setMessageCount(messageCount == null ? 0L : messageCount);
|
dto.setCollectionNames(collections == null ? new ArrayList<>() : collections);
|
return dto;
|
}
|
}
|