实现知识库两级分类树与完整 CRUD
支持父子分类、展开侧栏与改删校验;选中父分类可筛子级条目;对齐左右顶栏并更新种子树形数据。
This commit is contained in:
@@ -2,6 +2,9 @@ package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"kefu-sys/server/internal/middleware"
|
||||
@@ -44,7 +47,13 @@ func hasKnowledgeCapacity(tenantID uint) (bool, error) {
|
||||
|
||||
type CategoryListItem struct {
|
||||
model.Category
|
||||
EntryCount int64 `json:"entry_count"`
|
||||
EntryCount int64 `json:"entry_count"` // 本分类直属条目数
|
||||
TotalCount int64 `json:"total_count"` // 含子分类汇总
|
||||
}
|
||||
|
||||
type CategoryReq struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
ParentID *uint `json:"parent_id"`
|
||||
}
|
||||
|
||||
func (h *KnowledgeHandler) ListCategories(c *gin.Context) {
|
||||
@@ -63,40 +72,223 @@ func (h *KnowledgeHandler) ListCategories(c *gin.Context) {
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Group("category_id").
|
||||
Scan(&rows)
|
||||
countMap := map[uint]int64{}
|
||||
var total int64
|
||||
directMap := map[uint]int64{}
|
||||
for _, r := range rows {
|
||||
countMap[r.CategoryID] = r.Cnt
|
||||
total += r.Cnt
|
||||
directMap[r.CategoryID] = r.Cnt
|
||||
}
|
||||
// 子分类映射 parent -> children
|
||||
childrenMap := map[uint][]uint{}
|
||||
for _, cat := range categories {
|
||||
if cat.ParentID != nil {
|
||||
childrenMap[*cat.ParentID] = append(childrenMap[*cat.ParentID], cat.ID)
|
||||
}
|
||||
}
|
||||
var rollup func(id uint) int64
|
||||
rollup = func(id uint) int64 {
|
||||
sum := directMap[id]
|
||||
for _, child := range childrenMap[id] {
|
||||
sum += rollup(child)
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
var total int64
|
||||
model.DB.Model(&model.KnowledgeEntry{}).Where("tenant_id = ?", tenantID).Count(&total)
|
||||
|
||||
items := make([]CategoryListItem, 0, len(categories))
|
||||
for _, cat := range categories {
|
||||
items = append(items, CategoryListItem{Category: cat, EntryCount: countMap[cat.ID]})
|
||||
items = append(items, CategoryListItem{
|
||||
Category: cat,
|
||||
EntryCount: directMap[cat.ID],
|
||||
TotalCount: rollup(cat.ID),
|
||||
})
|
||||
}
|
||||
// total 放在额外字段便于侧栏「全部知识库」
|
||||
middleware.JSON(c, gin.H{"list": items, "total_entries": total})
|
||||
}
|
||||
|
||||
func validateCategoryName(name string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
n := utf8.RuneCountInString(name)
|
||||
if n < 2 || n > 30 {
|
||||
return ""
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// 校验父分类:最多两级(父分类自身 parent_id 必须为空)
|
||||
func validateCategoryParent(tenantID uint, parentID *uint) error {
|
||||
if parentID == nil {
|
||||
return nil
|
||||
}
|
||||
var parent model.Category
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ?", *parentID, tenantID).First(&parent).Error; err != nil {
|
||||
return errParentNotFound
|
||||
}
|
||||
if parent.ParentID != nil {
|
||||
return errCategoryDepth
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
errParentNotFound = errCat("父分类不存在")
|
||||
errCategoryDepth = errCat("仅支持两级分类,不能挂到子分类下")
|
||||
errCategoryName = errCat("分类名称需 2-30 个字符")
|
||||
errCategoryDup = errCat("同级下分类名称已存在")
|
||||
)
|
||||
|
||||
type catError string
|
||||
|
||||
func errCat(s string) catError { return catError(s) }
|
||||
func (e catError) Error() string { return string(e) }
|
||||
|
||||
func isCategoryNameTaken(tenantID uint, name string, parentID *uint, excludeID uint) bool {
|
||||
q := model.DB.Model(&model.Category{}).Where("tenant_id = ? AND name = ?", tenantID, name)
|
||||
if parentID == nil {
|
||||
q = q.Where("parent_id IS NULL")
|
||||
} else {
|
||||
q = q.Where("parent_id = ?", *parentID)
|
||||
}
|
||||
if excludeID > 0 {
|
||||
q = q.Where("id <> ?", excludeID)
|
||||
}
|
||||
var n int64
|
||||
q.Count(&n)
|
||||
return n > 0
|
||||
}
|
||||
|
||||
func (h *KnowledgeHandler) CreateCategory(c *gin.Context) {
|
||||
if !requireKnowledgeManager(c) {
|
||||
return
|
||||
}
|
||||
var category model.Category
|
||||
if err := c.ShouldBindJSON(&category); err != nil {
|
||||
var req CategoryReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
category.TenantID = middleware.GetTenantID(c)
|
||||
|
||||
name := validateCategoryName(req.Name)
|
||||
if name == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": errCategoryName.Error()})
|
||||
return
|
||||
}
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
if err := validateCategoryParent(tenantID, req.ParentID); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
if isCategoryNameTaken(tenantID, name, req.ParentID, 0) {
|
||||
c.JSON(http.StatusConflict, gin.H{"code": 409, "message": errCategoryDup.Error()})
|
||||
return
|
||||
}
|
||||
category := model.Category{
|
||||
TenantID: tenantID,
|
||||
Name: name,
|
||||
ParentID: req.ParentID,
|
||||
}
|
||||
if err := model.DB.Create(&category).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "创建失败"})
|
||||
return
|
||||
}
|
||||
|
||||
middleware.JSON(c, category)
|
||||
}
|
||||
|
||||
func (h *KnowledgeHandler) UpdateCategory(c *gin.Context) {
|
||||
if !requireKnowledgeManager(c) {
|
||||
return
|
||||
}
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
var category model.Category
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ?", id, tenantID).First(&category).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "分类不存在"})
|
||||
return
|
||||
}
|
||||
var req CategoryReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "参数错误"})
|
||||
return
|
||||
}
|
||||
name := validateCategoryName(req.Name)
|
||||
if name == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": errCategoryName.Error()})
|
||||
return
|
||||
}
|
||||
// 禁止把自己设为自己的子级;改父级时校验
|
||||
if req.ParentID != nil && *req.ParentID == category.ID {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "不能将分类设为自己的子分类"})
|
||||
return
|
||||
}
|
||||
// 若本分类已有子分类,则不能再挂到其它父级下(保持最多两级)
|
||||
if req.ParentID != nil {
|
||||
var childCnt int64
|
||||
model.DB.Model(&model.Category{}).Where("parent_id = ? AND tenant_id = ?", category.ID, tenantID).Count(&childCnt)
|
||||
if childCnt > 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "已有子分类的节点不能改为子分类"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := validateCategoryParent(tenantID, req.ParentID); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
if isCategoryNameTaken(tenantID, name, req.ParentID, category.ID) {
|
||||
c.JSON(http.StatusConflict, gin.H{"code": 409, "message": errCategoryDup.Error()})
|
||||
return
|
||||
}
|
||||
updates := map[string]interface{}{
|
||||
"name": name,
|
||||
"parent_id": req.ParentID,
|
||||
}
|
||||
if err := model.DB.Model(&category).Updates(updates).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "更新失败"})
|
||||
return
|
||||
}
|
||||
model.DB.First(&category, category.ID)
|
||||
middleware.JSON(c, category)
|
||||
}
|
||||
|
||||
func (h *KnowledgeHandler) DeleteCategory(c *gin.Context) {
|
||||
if !requireKnowledgeManager(c) {
|
||||
return
|
||||
}
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
var category model.Category
|
||||
if err := model.DB.Where("id = ? AND tenant_id = ?", id, tenantID).First(&category).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"code": 404, "message": "分类不存在"})
|
||||
return
|
||||
}
|
||||
var childCnt int64
|
||||
model.DB.Model(&model.Category{}).Where("parent_id = ? AND tenant_id = ?", category.ID, tenantID).Count(&childCnt)
|
||||
if childCnt > 0 {
|
||||
c.JSON(http.StatusConflict, gin.H{"code": 409, "message": "请先删除或移走子分类"})
|
||||
return
|
||||
}
|
||||
// 本分类及不应有子分类后,检查条目
|
||||
var entryCnt int64
|
||||
model.DB.Model(&model.KnowledgeEntry{}).Where("category_id = ? AND tenant_id = ?", category.ID, tenantID).Count(&entryCnt)
|
||||
if entryCnt > 0 {
|
||||
c.JSON(http.StatusConflict, gin.H{"code": 409, "message": "分类下仍有知识条目,请先删除或迁移条目"})
|
||||
return
|
||||
}
|
||||
if err := model.DB.Delete(&category).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "删除失败"})
|
||||
return
|
||||
}
|
||||
middleware.JSON(c, gin.H{"message": "已删除"})
|
||||
}
|
||||
|
||||
// categoryScopeIDs 选中分类时包含自身与所有直接子分类(两级树)
|
||||
func categoryScopeIDs(tenantID, categoryID uint) []uint {
|
||||
ids := []uint{categoryID}
|
||||
var children []model.Category
|
||||
model.DB.Where("tenant_id = ? AND parent_id = ?", tenantID, categoryID).Find(&children)
|
||||
for _, ch := range children {
|
||||
ids = append(ids, ch.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
type EntryListItem struct {
|
||||
model.KnowledgeEntry
|
||||
CategoryName string `json:"category_name"`
|
||||
@@ -115,7 +307,12 @@ func (h *KnowledgeHandler) ListEntries(c *gin.Context) {
|
||||
|
||||
query := model.DB.Where("tenant_id = ?", tenantID)
|
||||
if categoryID != "" {
|
||||
query = query.Where("category_id = ?", categoryID)
|
||||
if id64, err := strconv.ParseUint(categoryID, 10, 64); err == nil && id64 > 0 {
|
||||
ids := categoryScopeIDs(tenantID, uint(id64))
|
||||
query = query.Where("category_id IN ?", ids)
|
||||
} else {
|
||||
query = query.Where("category_id = ?", categoryID)
|
||||
}
|
||||
}
|
||||
if search != "" {
|
||||
query = query.Where("title LIKE ? OR content LIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
|
||||
Reference in New Issue
Block a user