kongdeqiang
2026-10-14 9f9e043849b6f497e00399900ff234cf097eba82
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
package com.custom.webui.service.impl;
 
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.custom.webui.dto.req.ChatGroupRequest;
import com.custom.webui.dto.resp.ChatGroupDTO;
import com.custom.webui.entity.Chat;
import com.custom.webui.entity.ChatGroup;
import com.custom.webui.exception.BusinessException;
import com.custom.webui.mapper.ChatGroupMapper;
import com.custom.webui.mapper.ChatMapper;
import com.custom.webui.service.ChatGroupService;
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.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/** 对话分组服务实现。 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatGroupServiceImpl implements ChatGroupService {
 
    private final ChatGroupMapper chatGroupMapper;
    private final ChatMapper chatMapper;
 
    @Override
    public List<ChatGroupDTO> listByUser(Long userId) {
        List<ChatGroup> groups = chatGroupMapper.selectList(
                Wrappers.<ChatGroup>lambdaQuery()
                        .eq(ChatGroup::getUserId, userId)
                        .orderByAsc(ChatGroup::getId));
        if (groups.isEmpty()) {
            return Collections.emptyList();
        }
 
        // 一次聚合出每个分组的会话数,避免逐个分组查一次(N+1)
        Map<Long, Long> countByGroup = chatMapper.selectList(
                        Wrappers.<Chat>lambdaQuery()
                                .select(Chat::getGroupId)
                                .eq(Chat::getUserId, userId)
                                .eq(Chat::getArchived, false)
                                .isNotNull(Chat::getGroupId))
                .stream()
                .collect(Collectors.groupingBy(Chat::getGroupId, Collectors.counting()));
 
        return groups.stream().map(g -> toDto(g, countByGroup.getOrDefault(g.getId(), 0L))).toList();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChatGroupDTO create(Long userId, ChatGroupRequest request) {
        String name = normalizeName(request.getName());
        requireNameAvailable(userId, name, null);
 
        ChatGroup group = new ChatGroup();
        group.setUserId(userId);
        group.setName(name);
        group.setCreatedAt(LocalDateTime.now());
        chatGroupMapper.insert(group);
 
        log.info("新建对话分组 userId={} groupId={} name={}", userId, group.getId(), name);
        return toDto(group, 0L);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChatGroupDTO rename(Long userId, Long groupId, ChatGroupRequest request) {
        requireOwnedGroup(userId, groupId);
        String name = normalizeName(request.getName());
        requireNameAvailable(userId, name, groupId);
 
        ChatGroup update = new ChatGroup();
        update.setId(groupId);
        update.setName(name);
        chatGroupMapper.updateById(update);
 
        Long count = chatMapper.selectCount(
                Wrappers.<Chat>lambdaQuery()
                        .eq(Chat::getGroupId, groupId)
                        .eq(Chat::getArchived, false));
        return toDto(chatGroupMapper.selectById(groupId), count);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long userId, Long groupId) {
        requireOwnedGroup(userId, groupId);
 
        // 只解除关联,**不删会话**:删文件夹不该毁掉里面的东西。
        // 把 group_id 显式置 NULL 用 UpdateWrapper —— 实体的 null 字段
        // 会被 MyBatis-Plus 忽略,表达不了「置空」这个意图。
        int moved = chatMapper.update(null,
                Wrappers.<Chat>lambdaUpdate()
                        .eq(Chat::getGroupId, groupId)
                        .eq(Chat::getUserId, userId)
                        .set(Chat::getGroupId, null));
 
        chatGroupMapper.deleteById(groupId);
        log.info("删除对话分组 userId={} groupId={},{} 条会话回到未分组", userId, groupId, moved);
        return moved;
    }
 
    @Override
    public ChatGroup requireOwnedGroup(Long userId, Long groupId) {
        if (groupId == null) {
            throw BusinessException.badRequest("分组 id 不能为空");
        }
        ChatGroup group = chatGroupMapper.selectById(groupId);
        // 不存在与不属于当前用户统一 404:返回 403 等于确认「这个 id 存在」
        if (group == null || !group.getUserId().equals(userId)) {
            throw BusinessException.notFound("分组不存在或无权访问");
        }
        return group;
    }
 
    // ==================== 内部辅助 ====================
 
    private String normalizeName(String raw) {
        String name = raw == null ? "" : raw.trim();
        if (name.isEmpty()) {
            throw BusinessException.badRequest("分组名不能为空");
        }
        // 列宽 64,超长直接截断而不是抛数据库异常
        return name.length() > 64 ? name.substring(0, 64) : name;
    }
 
    /**
     * 检查重名。
     *
     * <p>先查一次是为了给用户一句「已有同名分组」的人话提示;
     * 数据库上的唯一键仍然保留,用于兜住并发插入(两个请求同时通过检查)。
     */
    private void requireNameAvailable(Long userId, String name, Long excludeId) {
        ChatGroup exists = chatGroupMapper.selectOne(
                Wrappers.<ChatGroup>lambdaQuery()
                        .eq(ChatGroup::getUserId, userId)
                        .eq(ChatGroup::getName, name)
                        .last("LIMIT 1"));
        if (exists != null && !exists.getId().equals(excludeId)) {
            throw BusinessException.badRequest("已有同名分组:" + name);
        }
    }
 
    private ChatGroupDTO toDto(ChatGroup group, Long chatCount) {
        ChatGroupDTO dto = new ChatGroupDTO();
        dto.setId(group.getId());
        dto.setName(group.getName());
        dto.setChatCount(chatCount == null ? 0L : chatCount);
        return dto;
    }
}