kongdeqiang
2026-10-12 ccf1a44c001e233c158bd168dc2d0d96721af929
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
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;
    }
}