细节优化
This commit is contained in:
@@ -52,10 +52,13 @@ def get_category_tree(
|
||||
"""获取完整目录树(含文档数量)。"""
|
||||
_check_kb_owner(kb_id, user, db)
|
||||
|
||||
# 获取所有分类
|
||||
# 获取所有未删除的分类
|
||||
stmt = (
|
||||
select(DocumentCategory)
|
||||
.where(DocumentCategory.knowledge_base_id == kb_id)
|
||||
.where(
|
||||
DocumentCategory.knowledge_base_id == kb_id,
|
||||
DocumentCategory.deleted_at.is_(None),
|
||||
)
|
||||
.order_by(DocumentCategory.sort_order, DocumentCategory.name)
|
||||
)
|
||||
all_cats = list(db.scalars(stmt).all())
|
||||
@@ -110,7 +113,10 @@ def list_categories_flat(
|
||||
|
||||
stmt = (
|
||||
select(DocumentCategory)
|
||||
.where(DocumentCategory.knowledge_base_id == kb_id)
|
||||
.where(
|
||||
DocumentCategory.knowledge_base_id == kb_id,
|
||||
DocumentCategory.deleted_at.is_(None),
|
||||
)
|
||||
.order_by(DocumentCategory.path, DocumentCategory.sort_order)
|
||||
)
|
||||
cats = list(db.scalars(stmt).all())
|
||||
@@ -236,32 +242,44 @@ def delete_category(
|
||||
user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> None:
|
||||
"""删除分类(同时删除子分类,关联文档的 category_id 置 NULL)。"""
|
||||
"""删除分类 → 进回收站(含全部子分类及其下文档,3 天后自动彻底删除)。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app.models.document import Document
|
||||
|
||||
_check_kb_owner(kb_id, user, db)
|
||||
cat = db.get(DocumentCategory, cat_id)
|
||||
if cat is None or cat.knowledge_base_id != kb_id:
|
||||
if cat is None or cat.knowledge_base_id != kb_id or cat.deleted_at:
|
||||
raise NotFoundError("分类不存在。")
|
||||
|
||||
# 删除所有子分类
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# 收集本分类 + 所有存活的后代分类
|
||||
target_ids = [cat_id]
|
||||
if cat.path:
|
||||
stmt = select(DocumentCategory).where(
|
||||
DocumentCategory.knowledge_base_id == kb_id,
|
||||
DocumentCategory.path.startswith(cat.path),
|
||||
DocumentCategory.id != cat_id,
|
||||
DocumentCategory.deleted_at.is_(None),
|
||||
)
|
||||
children = list(db.scalars(stmt).all())
|
||||
for child in children:
|
||||
db.delete(child)
|
||||
for c in db.scalars(stmt).all():
|
||||
if c.id != cat_id:
|
||||
target_ids.append(c.id)
|
||||
|
||||
# 关联文档的 category_id 置 NULL
|
||||
from app.models.document import Document
|
||||
# 软删除分类树
|
||||
for cid in target_ids:
|
||||
c = db.get(DocumentCategory, cid)
|
||||
c.deleted_at = now
|
||||
|
||||
doc_stmt = select(Document).where(Document.category_id == cat_id)
|
||||
docs = list(db.scalars(doc_stmt).all())
|
||||
for doc in docs:
|
||||
doc.category_id = None
|
||||
# 软删除目录下的文档(同一批次时间戳,便于整组恢复)
|
||||
doc_stmt = select(Document).where(
|
||||
Document.category_id.in_(target_ids),
|
||||
Document.status != "DELETED",
|
||||
)
|
||||
for doc in db.scalars(doc_stmt).all():
|
||||
doc.status = "DELETED"
|
||||
doc.deleted_at = now
|
||||
|
||||
db.delete(cat)
|
||||
db.commit()
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user