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
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
package com.custom.webui.service.impl;
 
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.custom.webui.dto.resp.CategoryDTO;
import com.custom.webui.entity.ChatCollection;
import com.custom.webui.entity.KbCategory;
import com.custom.webui.entity.RagCollection;
import com.custom.webui.entity.UploadFile;
import com.custom.webui.exception.BusinessException;
import com.custom.webui.mapper.ChatCollectionMapper;
import com.custom.webui.mapper.KbCategoryMapper;
import com.custom.webui.mapper.RagCollectionMapper;
import com.custom.webui.mapper.UploadFileMapper;
import com.custom.webui.security.CurrentUser;
import com.custom.webui.service.CategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
 
/**
 * 知识库分类服务实现。
 *
 * <p>关键实现考量:{@link #listVisible} 会为每个分类算出「已入库集合名」,
 * 用于整类绑定。这里刻意用**两次批量查询**(分类 → 文件 → 集合)后在内存聚合,
 * 而不是对每个分类各查一遍 —— 后者在分类变多时是典型的 N+1。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {
 
    private static final int MAX_NAME_LENGTH = 64;
    private static final int MAX_DESCRIPTION_LENGTH = 255;
 
    private final KbCategoryMapper kbCategoryMapper;
    private final UploadFileMapper uploadFileMapper;
    private final RagCollectionMapper ragCollectionMapper;
    private final ChatCollectionMapper chatCollectionMapper;
 
    // ============================================================
    // 查询
    // ============================================================
 
    @Override
    public List<CategoryDTO> listVisible(Long userId, Long chatId) {
        // 可见 = 自己创建的 + 全局的
        List<KbCategory> categories = kbCategoryMapper.selectList(
                Wrappers.<KbCategory>lambdaQuery()
                        .and(w -> w.eq(KbCategory::getCreatedBy, userId)
                                .or()
                                .eq(KbCategory::getIsGlobal, true))
                        .orderByAsc(KbCategory::getSortOrder)
                        .orderByAsc(KbCategory::getId));
 
        // 一次取回这些分类下的全部文件,避免逐个分类查
        List<Long> categoryIds = categories.stream().map(KbCategory::getId).toList();
        Map<Long, List<UploadFile>> filesByCategory = new HashMap<>();
        if (!categoryIds.isEmpty()) {
            List<UploadFile> files = uploadFileMapper.selectList(
                    Wrappers.<UploadFile>lambdaQuery().in(UploadFile::getCategoryId, categoryIds));
            filesByCategory = files.stream()
                    .collect(Collectors.groupingBy(UploadFile::getCategoryId));
        }
 
        // 一次取回这些文件对应的集合记录
        List<Long> fileIds = filesByCategory.values().stream()
                .flatMap(List::stream)
                .map(UploadFile::getId)
                .toList();
        Map<Long, RagCollection> collectionByFileId = new HashMap<>();
        if (!fileIds.isEmpty()) {
            for (RagCollection rc : ragCollectionMapper.selectList(
                    Wrappers.<RagCollection>lambdaQuery().in(RagCollection::getFileId, fileIds))) {
                collectionByFileId.put(rc.getFileId(), rc);
            }
        }
 
        // 该会话已绑定的集合(用于标记选中态)
        List<String> bound = chatId == null ? Collections.emptyList()
                : chatCollectionMapper.selectList(
                                Wrappers.<ChatCollection>lambdaQuery()
                                        .eq(ChatCollection::getChatId, chatId))
                        .stream().map(ChatCollection::getCollectionName).toList();
 
        boolean admin = CurrentUser.isAdmin();
 
        List<CategoryDTO> result = new ArrayList<>(categories.size());
        for (KbCategory category : categories) {
            List<UploadFile> files = filesByCategory.getOrDefault(category.getId(), Collections.emptyList());
 
            CategoryDTO dto = new CategoryDTO();
            dto.setId(category.getId());
            dto.setName(category.getName());
            dto.setDescription(category.getDescription());
            dto.setIsGlobal(Boolean.TRUE.equals(category.getIsGlobal()));
            dto.setCreatedAt(category.getCreatedAt());
            dto.setCanManage(admin || Objects.equals(category.getCreatedBy(), userId));
            dto.setFileCount(files.size());
 
            List<String> collections = new ArrayList<>();
            int ingestedCount = 0;
            for (UploadFile file : files) {
                RagCollection rc = collectionByFileId.get(file.getId());
                if (rc != null && RagCollection.STATUS_READY.equals(rc.getStatus())) {
                    ingestedCount++;
                    if (!collections.contains(rc.getCollectionName())) {
                        collections.add(rc.getCollectionName());
                    }
                }
            }
            dto.setIngestedCount(ingestedCount);
            dto.setCollectionNames(collections);
 
            result.add(dto);
        }
 
        // 已绑定的分类排前面,方便用户看到当前生效的是哪些
        if (!bound.isEmpty()) {
            result.sort((a, b) -> {
                boolean aBound = !a.getCollectionNames().isEmpty()
                        && bound.containsAll(a.getCollectionNames());
                boolean bBound = !b.getCollectionNames().isEmpty()
                        && bound.containsAll(b.getCollectionNames());
                if (aBound == bBound) {
                    return 0;
                }
                return aBound ? -1 : 1;
            });
        }
 
        log.debug("分类列表 userId={} 可见 {} 个", userId, result.size());
        return result;
    }
 
    @Override
    public List<String> collectionsOfCategory(Long userId, Long categoryId) {
        // 先做可见性校验,避免通过 categoryId 探测他人分类
        requireVisible(userId, categoryId);
 
        List<UploadFile> files = uploadFileMapper.selectList(
                Wrappers.<UploadFile>lambdaQuery().eq(UploadFile::getCategoryId, categoryId));
        if (files.isEmpty()) {
            return Collections.emptyList();
        }
 
        List<Long> fileIds = files.stream().map(UploadFile::getId).toList();
        return ragCollectionMapper.selectList(
                        Wrappers.<RagCollection>lambdaQuery()
                                .in(RagCollection::getFileId, fileIds)
                                .eq(RagCollection::getStatus, RagCollection.STATUS_READY))
                .stream().map(RagCollection::getCollectionName).distinct().toList();
    }
 
    // ============================================================
    // 写操作
    // ============================================================
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CategoryDTO create(Long userId, String name, String description, boolean global) {
        String normalized = normalizeName(name);
        if (global && !CurrentUser.isAdmin()) {
            throw BusinessException.forbidden("只有管理员可以创建全局分类");
        }
 
        // 同名检查:唯一索引是 (created_by, name),但全局分类由不同管理员创建时
        // 会出现两个同名全局分类,用户面对两个「产品文档」无从选择,这里额外拦一下
        // 全局分类:同名即冲突(不分创建者,否则用户会看到两个「产品文档」)
        // 私有分类:只看自己名下的,别人叫什么都与我无关
        var duplicateQuery = Wrappers.<KbCategory>lambdaQuery()
                .eq(KbCategory::getName, normalized)
                .eq(KbCategory::getIsGlobal, global);
        if (!global) {
            duplicateQuery.eq(KbCategory::getCreatedBy, userId);
        }
        Long duplicated = kbCategoryMapper.selectCount(duplicateQuery);
        if (duplicated != null && duplicated > 0) {
            throw BusinessException.badRequest("已存在同名分类:" + normalized);
        }
 
        KbCategory category = new KbCategory();
        category.setName(normalized);
        category.setDescription(abbreviate(description, MAX_DESCRIPTION_LENGTH));
        category.setCreatedBy(userId);
        category.setIsGlobal(global);
        category.setSortOrder(0);
        category.setCreatedAt(LocalDateTime.now());
 
        try {
            kbCategoryMapper.insert(category);
        } catch (DuplicateKeyException e) {
            throw BusinessException.badRequest("已存在同名分类:" + normalized);
        }
 
        log.info("创建分类 userId={} categoryId={} name={} 全局={}",
                userId, category.getId(), normalized, global);
        return toBasicDto(category, userId);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CategoryDTO update(Long userId, Long categoryId, String name, String description) {
        KbCategory existing = requireManageable(userId, categoryId);
 
        KbCategory patch = new KbCategory();
        patch.setId(categoryId);
        if (name != null && !name.isBlank()) {
            String normalized = normalizeName(name);
            Long duplicated = kbCategoryMapper.selectCount(
                    Wrappers.<KbCategory>lambdaQuery()
                            .eq(KbCategory::getName, normalized)
                            .eq(KbCategory::getIsGlobal, Boolean.TRUE.equals(existing.getIsGlobal()))
                            .ne(KbCategory::getId, categoryId));
            if (duplicated != null && duplicated > 0) {
                throw BusinessException.badRequest("已存在同名分类:" + normalized);
            }
            patch.setName(normalized);
        }
        if (description != null) {
            patch.setDescription(abbreviate(description, MAX_DESCRIPTION_LENGTH));
        }
        kbCategoryMapper.updateById(patch);
 
        KbCategory refreshed = kbCategoryMapper.selectById(categoryId);
        return listVisible(userId, null).stream()
                .filter(d -> Objects.equals(d.getId(), categoryId))
                .findFirst()
                .orElse(toBasicDto(refreshed == null ? existing : refreshed, userId));
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long userId, Long categoryId) {
        KbCategory category = requireManageable(userId, categoryId);
 
        // 先把分类内的文档置为「未分类」,**不删文档**。
        // 用户想删的是分类,不是里面的资料;静默删文件是不可接受的。
        List<UploadFile> files = uploadFileMapper.selectList(
                Wrappers.<UploadFile>lambdaQuery().eq(UploadFile::getCategoryId, categoryId));
        // MyBatis-Plus 默认忽略实体里的 null 字段,无法把列更新成 NULL,
        // 因此这里用 UpdateWrapper 一条语句批量置空,而不是逐个 update。
        if (!files.isEmpty()) {
            uploadFileMapper.update(null,
                    Wrappers.<UploadFile>lambdaUpdate()
                            .set(UploadFile::getCategoryId, null)
                            .eq(UploadFile::getCategoryId, categoryId));
        }
 
        kbCategoryMapper.deleteById(categoryId);
        log.info("删除分类 userId={} categoryId={} name={},其中 {} 个文档已置为未分类",
                userId, categoryId, category.getName(), files.size());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignFile(Long userId, Long fileId, Long categoryId) {
        UploadFile file = uploadFileMapper.selectById(fileId);
        if (file == null) {
            throw BusinessException.notFound("文件不存在或无权访问");
        }
        boolean isOwner = file.getUserId() != null && file.getUserId().equals(userId);
        if (!isOwner && !CurrentUser.isAdmin()) {
            throw BusinessException.notFound("文件不存在或无权访问");
        }
 
        if (categoryId != null) {
            // 权限粒度要分清:
            //   私有分类 -> 需要**管理**权限(自己的分类,或本人是管理员),
            //               否则任何人都能往别人的分类里塞文档,等于篡改他人数据
            //   全局分类 -> 只需**可见**权限。全局分类本就是给全员用的容器,
            //               下属文档的归属由 upload_file.user_id 单独判定,
            //               要求管理权限会把「普通用户把自己的全局文档归类」也挡掉
            KbCategory category = requireVisible(userId, categoryId);
            if (!Boolean.TRUE.equals(category.getIsGlobal())) {
                // 私有分类必须是自己可管理的
                requireManageable(userId, categoryId);
            }
 
            // 范围一致性:全局分类只装全局文档,私有分类只装自己的文档。
            // 否则会出现「私有分类里塞了别人的全局文档」这种越权组合。
            boolean fileGlobal = Boolean.TRUE.equals(file.getIsGlobal());
            boolean categoryGlobal = Boolean.TRUE.equals(category.getIsGlobal());
            if (categoryGlobal != fileGlobal) {
                throw BusinessException.badRequest(
                        categoryGlobal
                                ? "全局分类只能存放全局文档;请先把该文档设为全局知识库"
                                : "私有分类只能存放自己的文档;全局文档请放入全局分类");
            }
        }
 
        // MyBatis-Plus 默认忽略 null,移出分类必须用 UpdateWrapper 显式 set null
        uploadFileMapper.update(null,
                Wrappers.<UploadFile>lambdaUpdate()
                        .set(UploadFile::getCategoryId, categoryId)
                        .eq(UploadFile::getId, fileId));
 
        log.info("文件归类 userId={} fileId={} categoryId={}", userId, fileId, categoryId);
    }
 
    // ============================================================
    // 校验
    // ============================================================
 
    @Override
    public KbCategory requireManageable(Long userId, Long categoryId) {
        KbCategory category = kbCategoryMapper.selectById(categoryId);
        if (category == null) {
            throw BusinessException.notFound("分类不存在或无权访问");
        }
        boolean owner = Objects.equals(category.getCreatedBy(), userId);
        if (!owner && !CurrentUser.isAdmin()) {
            throw BusinessException.notFound("分类不存在或无权访问");
        }
        return category;
    }
 
    @Override
    public KbCategory requireVisibleForUser(Long userId, Long categoryId) {
        return requireVisible(userId, categoryId);
    }
 
    /** 可见即可用:自己创建的或全局的 */
    private KbCategory requireVisible(Long userId, Long categoryId) {
        KbCategory category = kbCategoryMapper.selectById(categoryId);
        if (category == null) {
            throw BusinessException.notFound("分类不存在或无权访问");
        }
        boolean owner = Objects.equals(category.getCreatedBy(), userId);
        if (!owner && !Boolean.TRUE.equals(category.getIsGlobal())) {
            throw BusinessException.notFound("分类不存在或无权访问");
        }
        return category;
    }
 
    // ============================================================
    // 工具
    // ============================================================
 
    private String normalizeName(String name) {
        if (name == null || name.isBlank()) {
            throw BusinessException.badRequest("分类名称不能为空");
        }
        String normalized = name.trim();
        if (normalized.length() > MAX_NAME_LENGTH) {
            throw BusinessException.badRequest("分类名称不能超过 " + MAX_NAME_LENGTH + " 个字符");
        }
        return normalized;
    }
 
    private String abbreviate(String text, int max) {
        if (text == null) {
            return null;
        }
        String trimmed = text.trim();
        if (trimmed.isEmpty()) {
            return null;
        }
        return trimmed.length() <= max ? trimmed : trimmed.substring(0, max);
    }
 
    private CategoryDTO toBasicDto(KbCategory category, Long userId) {
        CategoryDTO dto = new CategoryDTO();
        dto.setId(category.getId());
        dto.setName(category.getName());
        dto.setDescription(category.getDescription());
        dto.setIsGlobal(Boolean.TRUE.equals(category.getIsGlobal()));
        dto.setCreatedAt(category.getCreatedAt());
        dto.setCanManage(CurrentUser.isAdmin() || Objects.equals(category.getCreatedBy(), userId));
        return dto;
    }
}