kongdeqiang
2026-10-12 ccf1a44c001e233c158bd168dc2d0d96721af929
src/main/java/com/custom/webui/service/impl/ChatServiceImpl.java
@@ -15,6 +15,7 @@
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;
@@ -50,13 +51,20 @@
    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) {
    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();
@@ -107,8 +115,22 @@
    public ChatDTO update(Long userId, Long chatId, ChatUpdateRequest request) {
        Chat existing = requireOwnedChat(userId, chatId);
        Chat update = new Chat();
        update.setId(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();
@@ -116,16 +138,34 @@
                throw BusinessException.badRequest("标题不能为空");
            }
            // 防御超长标题:列宽 255,超出部分直接截断而不是报数据库错误
            update.setTitle(title.length() > 255 ? title.substring(0, 255) : title);
            wrapper.set(Chat::getTitle, title.length() > 255 ? title.substring(0, 255) : title);
            contentChanged = true;
        }
        if (request.getMeta() != null) {
            // meta 是整体覆盖语义:前端应提交完整的参数对象
            update.setMeta(writeMeta(request.getMeta()));
            wrapper.set(Chat::getMeta, writeMeta(request.getMeta()));
            contentChanged = true;
        }
        update.setUpdatedAt(LocalDateTime.now());
        chatMapper.updateById(update);
        // ---- 置顶 ----
        // 置顶时记录 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(
@@ -134,7 +174,9 @@
                        Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
                .stream().map(ChatCollection::getCollectionName).toList();
        log.debug("更新会话 chatId={} 原meta={} 新meta={}", chatId, existing.getMeta(), refreshed.getMeta());
        log.debug("更新会话 chatId={} 原meta={} 新meta={} pinned={} archived={}",
                chatId, existing.getMeta(), refreshed.getMeta(),
                refreshed.getPinned(), refreshed.getArchived());
        return toDto(refreshed, messageCount, collections);
    }
@@ -163,6 +205,38 @@
        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
@@ -209,7 +283,7 @@
    }
    @Override
    public List<ChatDTO> search(Long userId, String keyword, int limit) {
    public List<ChatDTO> search(Long userId, String keyword, int limit, boolean archived) {
        if (keyword == null || keyword.isBlank()) {
            // 空关键词直接返回空,而不是返回全部会话 ——
            // 否则搜索框会退化成「无过滤列表」,和侧边栏本身重复
@@ -220,9 +294,14 @@
        // 先取该用户全部会话(个人会话量级通常在数百,一次查完再做内存匹配,
        // 比两次 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();
@@ -346,6 +425,13 @@
        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;