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;
/**
* 知识库分类服务实现。
*
*
关键实现考量:{@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 listVisible(Long userId, Long chatId) {
// 可见 = 自己创建的 + 全局的
List categories = kbCategoryMapper.selectList(
Wrappers.lambdaQuery()
.and(w -> w.eq(KbCategory::getCreatedBy, userId)
.or()
.eq(KbCategory::getIsGlobal, true))
.orderByAsc(KbCategory::getSortOrder)
.orderByAsc(KbCategory::getId));
// 一次取回这些分类下的全部文件,避免逐个分类查
List categoryIds = categories.stream().map(KbCategory::getId).toList();
Map> filesByCategory = new HashMap<>();
if (!categoryIds.isEmpty()) {
List files = uploadFileMapper.selectList(
Wrappers.lambdaQuery().in(UploadFile::getCategoryId, categoryIds));
filesByCategory = files.stream()
.collect(Collectors.groupingBy(UploadFile::getCategoryId));
}
// 一次取回这些文件对应的集合记录
List fileIds = filesByCategory.values().stream()
.flatMap(List::stream)
.map(UploadFile::getId)
.toList();
Map collectionByFileId = new HashMap<>();
if (!fileIds.isEmpty()) {
for (RagCollection rc : ragCollectionMapper.selectList(
Wrappers.lambdaQuery().in(RagCollection::getFileId, fileIds))) {
collectionByFileId.put(rc.getFileId(), rc);
}
}
// 该会话已绑定的集合(用于标记选中态)
List bound = chatId == null ? Collections.emptyList()
: chatCollectionMapper.selectList(
Wrappers.lambdaQuery()
.eq(ChatCollection::getChatId, chatId))
.stream().map(ChatCollection::getCollectionName).toList();
boolean admin = CurrentUser.isAdmin();
List result = new ArrayList<>(categories.size());
for (KbCategory category : categories) {
List 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 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 collectionsOfCategory(Long userId, Long categoryId) {
// 先做可见性校验,避免通过 categoryId 探测他人分类
requireVisible(userId, categoryId);
List files = uploadFileMapper.selectList(
Wrappers.lambdaQuery().eq(UploadFile::getCategoryId, categoryId));
if (files.isEmpty()) {
return Collections.emptyList();
}
List fileIds = files.stream().map(UploadFile::getId).toList();
return ragCollectionMapper.selectList(
Wrappers.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.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.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 files = uploadFileMapper.selectList(
Wrappers.lambdaQuery().eq(UploadFile::getCategoryId, categoryId));
// MyBatis-Plus 默认忽略实体里的 null 字段,无法把列更新成 NULL,
// 因此这里用 UpdateWrapper 一条语句批量置空,而不是逐个 update。
if (!files.isEmpty()) {
uploadFileMapper.update(null,
Wrappers.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.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;
}
}