kb.py
22.1 KB
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
"""知识库管理路由(前缀 /kb,不放在 /oa 下)。
- 列表/初始化/新建/改名停用:知识库配置页(系统管理)使用,需 kb:* 权限。
- 可读库 /kb/readable:任意登录用户,供「Wiki 原始文件 / Wiki 知识库 / Copilot」的库下拉。
- 授权/撤销:把某库读权限手工授予 user/dept/post/role(预留:让员工能读非本部门库)。
"""
from __future__ import annotations
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
from src.database.models import WikiFile, WikiKbGrant, WikiKbInfo, WikiOaDept, WikiOaRole, WikiOaUser, uuid_str
from src.database.session import AsyncSessionLocal
from src.services.identity.tokens import get_current_user
from src.services.oa import enums
from src.services.oa.audit import log_oper
from src.services.oa.deps import require_perm
from src.services.oa.kb_provision import ensure_base_kb, is_builtin_kb
from src.services.oa.kb_paths import ensure_kb_dirs, kb_root_rel, kb_wiki_dir
from src.services.oa.perms import resolve_readable_kbs_with_access
from src.tools.wiki_tools import rebuild_index
from sqlalchemy import func, or_, select
router = APIRouter(tags=["kb"])
_SORTABLE_COL = {
"kbName": WikiKbInfo.kb_name,
"kbType": WikiKbInfo.kb_type,
"status": WikiKbInfo.status,
"createdAt": WikiKbInfo.created_at,
}
def _dept_chain(dept_id: str | None, idx: dict[str, WikiOaDept]) -> list[WikiOaDept]:
"""据 ancestors 返回该部门的组织链(根在前,含自身)。"""
if not dept_id or dept_id not in idx:
return []
d = idx[dept_id]
parts = [p for p in (d.ancestors or "").split(",") if p]
return [idx[p] for p in parts if p in idx] + [d]
def _dept_meta(dept_id: str | None, idx: dict[str, WikiOaDept]) -> dict:
"""返回部门库的层级元数据:展示路径 / id 链 / 可排序键(供前端建组织树+排序)。
sortKey 逐级用 (order_num 零填充 + 名称) 拼成,字典序即"架构<中心<部门、父在子前"。
"""
chain = _dept_chain(dept_id, idx)
if not chain:
return {"deptPath": None, "deptIdPath": [], "sortKey": ""}
return {
"deptPath": " / ".join(x.dept_name for x in chain),
"deptIdPath": [x.id for x in chain],
"sortKey": "/".join(f"{(x.order_num or 0):06d}-{x.dept_name}" for x in chain),
}
def _serialize(
kb: WikiKbInfo, idx: dict[str, WikiOaDept],
granted: dict[str, list[str]] | None = None, access: str | None = None,
) -> dict:
meta = _dept_meta(kb.dept_id, idx) if kb.kb_type == enums.KB_DEPT else {"deptPath": None, "deptIdPath": [], "sortKey": ""}
return {
"id": kb.id,
"kbType": kb.kb_type,
"kbName": kb.kb_name,
"deptId": kb.dept_id,
"deptPath": meta["deptPath"],
"deptIdPath": meta["deptIdPath"], # 组织链 id(根在前含自身),前端建树用
"sortKey": meta["sortKey"], # 可排序键(架构<中心<部门、父在子前)
"ownerUserId": kb.owner_user_id,
"rootDir": kb.root_dir,
"status": kb.status,
# 内置公共库:前端据此禁用「改类型 / 停用 / 删除」,见 is_builtin_kb 的职责说明
"isBuiltin": is_builtin_kb(kb),
"createdAt": kb.created_at.isoformat() if kb.created_at else None,
# 已授权对象名称列表(当前均为部门/中心,完整路径),供配置页“已授权部门”列展示
"grantedLabels": (granted or {}).get(kb.id, []),
# 当前用户对本库的有效级别 owner/guest(供 Wiki 原始页库下拉打标记);配置页列表不传
"access": access,
}
async def _assert_valid_owner_dept(session, dept_id: str, exclude_kb_id: str | None = None) -> None:
"""校验部门库的 Owner 绑定部门:存在、是**叶子节点**、且未被其它部门库**占用(1:1)**。不满足抛 400。"""
dept = await session.get(WikiOaDept, dept_id)
if dept is None or dept.del_flag != enums.DEL_NORMAL:
raise HTTPException(status_code=400, detail="绑定部门不存在")
# 叶子=无下属部门(有子部门的中心/架构不能作 Owner)
child = (
await session.execute(
select(func.count(WikiOaDept.id)).where(
WikiOaDept.parent_id == dept_id,
WikiOaDept.del_flag == enums.DEL_NORMAL,
)
)
).scalar() or 0
if child > 0:
raise HTTPException(status_code=400, detail="Owner 只能绑定叶子部门(不能是含下属部门的中心/架构)")
# 1:1 唯一:该部门未被其它有效部门库绑定
stmt = select(func.count(WikiKbInfo.id)).where(
WikiKbInfo.dept_id == dept_id,
WikiKbInfo.del_flag == enums.DEL_NORMAL,
)
if exclude_kb_id:
stmt = stmt.where(WikiKbInfo.id != exclude_kb_id)
taken = (await session.execute(stmt)).scalar() or 0
if taken > 0:
raise HTTPException(status_code=409, detail="该部门已绑定其它部门库(一个部门只能绑定一个库)")
@router.get("/kb")
async def list_kbs(
keyword: str = Query(default=""),
kbType: str = Query(default=""),
status_: str = Query(default="", alias="status"),
sortBy: str = Query(default="createdAt"),
sortOrder: str = Query(default="asc"),
limit: int = Query(default=20, ge=1, le=500),
offset: int = Query(default=0, ge=0),
me: WikiOaUser = Depends(require_perm("kb:list")),
):
"""全部知识库列表:关键字/类型/状态筛选 + 排序 + 分页(配置页用,看全量)。"""
async with AsyncSessionLocal() as session:
depts = (
await session.execute(
select(WikiOaDept).where(WikiOaDept.del_flag == enums.DEL_NORMAL)
)
).scalars().all()
idx = {d.id: d for d in depts}
stmt = select(WikiKbInfo).where(WikiKbInfo.del_flag == enums.DEL_NORMAL)
count_stmt = select(func.count(WikiKbInfo.id)).where(
WikiKbInfo.del_flag == enums.DEL_NORMAL
)
kw = keyword.strip()
if kw:
cond = WikiKbInfo.kb_name.like(f"%{kw}%")
stmt = stmt.where(cond)
count_stmt = count_stmt.where(cond)
if kbType.strip() in enums.KB_TYPES:
stmt = stmt.where(WikiKbInfo.kb_type == kbType.strip())
count_stmt = count_stmt.where(WikiKbInfo.kb_type == kbType.strip())
if status_.strip() in enums.STATUSES:
stmt = stmt.where(WikiKbInfo.status == status_.strip())
count_stmt = count_stmt.where(WikiKbInfo.status == status_.strip())
total = (await session.execute(count_stmt)).scalar() or 0
col = _SORTABLE_COL.get(sortBy, WikiKbInfo.created_at)
col = col.desc() if sortOrder.lower() == "desc" else col.asc()
rows = (
await session.execute(stmt.order_by(col).limit(limit).offset(offset))
).scalars().all()
# 汇总本页各库的授权对象名称(一次查询避免 N+1)
granted: dict[str, list[str]] = {}
kb_ids = [r.id for r in rows]
kb_owner_dept = {r.id: r.dept_id for r in rows} # 各库 Owner 部门,用于从 Editor/Reader 列表剔除
if kb_ids:
grants = (
await session.execute(
select(WikiKbGrant).where(
WikiKbGrant.kb_id.in_(kb_ids),
WikiKbGrant.del_flag == enums.DEL_NORMAL,
WikiKbGrant.status == enums.GRANT_ACTIVE,
)
)
).scalars().all()
role_ids = {g.grantee_id for g in grants if g.grantee_type == enums.GRANTEE_ROLE}
role_map = {}
if role_ids:
role_map = {
r.id: r.role_name
for r in (
await session.execute(select(WikiOaRole).where(WikiOaRole.id.in_(role_ids)))
).scalars().all()
}
for g in grants:
# Owner 部门(kb.dept_id)恒有读写,是最高权限,不在「已授权 Editor/Reader」里重复展示
if g.grantee_type == enums.GRANTEE_DEPT and g.grantee_id == kb_owner_dept.get(g.kb_id):
continue
if g.grantee_type == enums.GRANTEE_DEPT:
dept = idx.get(g.grantee_id)
label = dept.dept_name if dept else "部门"
elif g.grantee_type == enums.GRANTEE_ROLE:
label = role_map.get(g.grantee_id, "角色")
elif g.grantee_type == enums.GRANTEE_USER:
label = "用户"
else:
label = "岗位"
granted.setdefault(g.kb_id, [])
if label not in granted[g.kb_id]:
granted[g.kb_id].append(label)
return {"success": True, "total": total, "items": [_serialize(r, idx, granted) for r in rows]}
@router.get("/kb/readable")
async def list_readable_kbs(me: WikiOaUser = Depends(get_current_user)):
"""当前用户可读的知识库(base ∪ 部门库(继承+管辖) ∪ 被授权库),带 owner/guest 级别。
级别用于 Wiki 原始页库下拉打「Owner/Guest」标记,让用户区分读写权限。
"""
pairs = await resolve_readable_kbs_with_access(me)
async with AsyncSessionLocal() as session:
depts = (
await session.execute(
select(WikiOaDept).where(WikiOaDept.del_flag == enums.DEL_NORMAL)
)
).scalars().all()
idx = {d.id: d for d in depts}
# base 排最前,其余按组织树顺序(架构<中心<部门、父在子前)
items = [_serialize(k, idx, access=acc) for k, acc in pairs]
items.sort(key=lambda it: (0 if it["kbType"] == enums.KB_BASE else 1, it["sortKey"]))
return {"success": True, "items": items}
@router.get("/kb/org-tree")
async def kb_org_tree(me: WikiOaUser = Depends(require_perm("kb:list"))):
"""返回完整部门组织树(供知识库配置页的授权组织树多选)。
与 /oa/depts 同构,但按 kb:list 授权——让有知识库管理权的中心/部门负责人也能选授权目标,
无需额外授予 oa:dept:list(避免暴露部门管理菜单)。
"""
async with AsyncSessionLocal() as session:
rows = (
await session.execute(
select(WikiOaDept)
.where(WikiOaDept.del_flag == enums.DEL_NORMAL)
.order_by(WikiOaDept.order_num, WikiOaDept.dept_name)
)
).scalars().all()
nodes = {
d.id: {
"id": d.id, "parentId": d.parent_id, "deptName": d.dept_name,
"deptCategory": d.dept_category, "duty": d.duty,
"orderNum": d.order_num,
"status": d.status, "children": [],
}
for d in rows
}
roots: list[dict] = []
for node in nodes.values():
parent = nodes.get(node["parentId"])
(parent["children"] if parent else roots).append(node)
return {"success": True, "items": roots}
@router.post("/kb")
async def create_kb(
request: Request,
kbName: str = Body(..., embed=True),
kbType: str = Body(default=enums.KB_DEPT, embed=True),
deptId: str = Body(default=None, embed=True),
me: WikiOaUser = Depends(require_perm("kb:create")),
):
"""新建知识库:库名 + 类型(+ 部门库的 Owner 绑定部门)。
- dept(部门库):必须绑定唯一的 Owner 部门(叶子节点、1:1),该部门成员隐式读写;额外的
Editor/Reader 授权在配置页详情按需分配。
- base(公共库):不绑定部门(无 Owner);默认全员只读,可按需授 Editor(写)/Reader(读)。
物理存储恒按库 UUID 落 ware/kb/base|dept/<id>,与绑定部门无关。
"""
await ensure_base_kb()
if kbType not in (enums.KB_DEPT, enums.KB_BASE):
raise HTTPException(status_code=400, detail="知识库类型不合法")
name = (kbName or "").strip()
if not name:
raise HTTPException(status_code=400, detail="知识库名称不能为空")
owner_dept = (deptId or "").strip() or None
if kbType == enums.KB_DEPT and not owner_dept:
raise HTTPException(status_code=400, detail="部门库必须绑定一个 Owner 部门")
if kbType == enums.KB_BASE:
owner_dept = None # 公共库不绑定部门
async with AsyncSessionLocal() as session:
dup = (
await session.execute(
select(WikiKbInfo).where(
WikiKbInfo.kb_name == name,
WikiKbInfo.del_flag == enums.DEL_NORMAL,
)
)
).scalars().first()
if dup is not None:
raise HTTPException(status_code=409, detail="同名知识库已存在")
if owner_dept:
await _assert_valid_owner_dept(session, owner_dept)
new_id = uuid_str()
kb = WikiKbInfo(
id=new_id,
kb_type=kbType,
kb_name=name,
dept_id=owner_dept,
root_dir=kb_root_rel(new_id, kbType), # 按类型落 ware/kb/base|dept/<id>
status=enums.STATUS_ACTIVE,
)
session.add(kb)
await session.commit()
try:
ensure_kb_dirs(kb)
rebuild_index(kb_wiki_dir(kb))
except Exception:
pass
kb_id = kb.id
await log_oper(
operator=me, request=request, module="kb", action="create",
target_type="kb", target_id=kb_id, target_name=name,
)
return {"success": True, "id": kb_id}
@router.patch("/kb/{kb_id}")
async def update_kb(
kb_id: str,
request: Request,
kbName: str = Body(default=None, embed=True),
kbType: str = Body(default=None, embed=True),
deptId: str = Body(default=None, embed=True),
status_: str = Body(default=None, embed=True, alias="status"),
me: WikiOaUser = Depends(require_perm("kb:create")),
):
"""改名 / 重绑 Owner 部门 / 启停知识库。
知识库类型创建后不可修改(类型决定物理目录 ware/kb/base|dept/<id> 与权限语义,
落盘后再改会导致目录与类型不一致)。唯独内置基础库是系统兜底库,停用/删除一律锁死。
重绑 Owner(deptId)仅部门库允许,且新部门须为叶子、未被占用(1:1)。
"""
async with AsyncSessionLocal() as session:
kb = await session.get(WikiKbInfo, kb_id)
if kb is None or kb.del_flag != enums.DEL_NORMAL:
raise HTTPException(status_code=404, detail="知识库不存在")
builtin = is_builtin_kb(kb)
if kbName is not None and kbName.strip():
kb.kb_name = kbName.strip()
if kbType is not None and kbType != kb.kb_type:
raise HTTPException(status_code=400, detail="知识库类型创建后不可修改")
if deptId is not None:
new_dept = (deptId or "").strip() or None
if kb.kb_type != enums.KB_DEPT:
raise HTTPException(status_code=400, detail="仅部门库可绑定 Owner 部门")
if not new_dept:
raise HTTPException(status_code=400, detail="部门库必须绑定一个 Owner 部门")
if new_dept != kb.dept_id:
await _assert_valid_owner_dept(session, new_dept, exclude_kb_id=kb_id)
kb.dept_id = new_dept
if status_ is not None and status_ in enums.STATUSES:
if builtin and status_ == enums.STATUS_DISABLED:
raise HTTPException(status_code=400, detail="内置基础库不可停用")
kb.status = status_
await session.commit()
await log_oper(
operator=me, request=request, module="kb", action="update",
target_type="kb", target_id=kb_id,
)
return {"success": True}
@router.delete("/kb/{kb_id}")
async def remove_kb(
kb_id: str, request: Request,
me: WikiOaUser = Depends(require_perm("kb:remove")),
):
"""删除知识库(逻辑删除)。内置公共库不可删;库内仍有文件则安全拦截,避免误删已摄入数据。"""
async with AsyncSessionLocal() as session:
kb = await session.get(WikiKbInfo, kb_id)
if kb is None or kb.del_flag != enums.DEL_NORMAL:
raise HTTPException(status_code=404, detail="知识库不存在")
if is_builtin_kb(kb):
raise HTTPException(status_code=400, detail="内置公共库不可删除")
# wiki_files 为硬删除表,存在即有内容
cnt = (
await session.execute(
select(func.count(WikiFile.id)).where(WikiFile.kb_id == kb_id)
)
).scalar() or 0
if cnt > 0:
raise HTTPException(status_code=400, detail=f"该库下还有 {cnt} 个文件,请先清空后再删除")
kb.del_flag = enums.DEL_DELETED
kb.status = enums.STATUS_DISABLED
name = kb.kb_name
# 连带撤销该库的所有授权
grants = (
await session.execute(
select(WikiKbGrant).where(
WikiKbGrant.kb_id == kb_id, WikiKbGrant.del_flag == enums.DEL_NORMAL
)
)
).scalars().all()
for g in grants:
g.del_flag = enums.DEL_DELETED
g.status = enums.GRANT_REVOKED
await session.commit()
await log_oper(
operator=me, request=request, module="kb", action="remove",
target_type="kb", target_id=kb_id, target_name=name,
)
return {"success": True}
@router.get("/kb/{kb_id}/grants")
async def list_grants(kb_id: str, me: WikiOaUser = Depends(require_perm("kb:list"))):
"""列出某库的授权记录(供授权管理弹窗展示,带组织节点完整路径 + owner/guest 级别)。"""
async with AsyncSessionLocal() as session:
depts = (
await session.execute(
select(WikiOaDept).where(WikiOaDept.del_flag == enums.DEL_NORMAL)
)
).scalars().all()
idx = {d.id: d for d in depts}
rows = (
await session.execute(
select(WikiKbGrant).where(
WikiKbGrant.kb_id == kb_id,
WikiKbGrant.del_flag == enums.DEL_NORMAL,
WikiKbGrant.status == enums.GRANT_ACTIVE,
)
)
).scalars().all()
return {
"success": True,
"items": [
{
"id": g.id,
"granteeType": g.grantee_type,
"granteeId": g.grantee_id,
"granteeLabel": (
_dept_meta(g.grantee_id, idx)["deptPath"]
if g.grantee_type == enums.GRANTEE_DEPT else None
),
"access": g.access,
}
for g in rows
],
}
@router.post("/kb/{kb_id}/grant")
async def grant_kb(
kb_id: str,
request: Request,
granteeIds: list[str] = Body(..., embed=True),
access: str = Body(default=enums.KB_ACCESS_READER, embed=True),
me: WikiOaUser = Depends(require_perm("kb:grant")),
):
"""把某库以 editor/reader 级别授予一批组织节点(部门/中心)。授任一节点=授其整棵子树,可一次多 id。
editor=可读写(上传/摄入/摄出/删除,按角色)、reader=只读(查看/预览/查询/下载)。
Owner(部门库归属)由 wiki_kb_info.dept_id 承载,不经此接口授予。
"""
ids = [i for i in {i.strip() for i in (granteeIds or [])} if i]
if not ids:
raise HTTPException(status_code=400, detail="请至少选择一个部门/中心")
if access not in enums.KB_ACCESS_LEVELS:
raise HTTPException(status_code=400, detail="授权级别非法")
granted: list[str] = []
async with AsyncSessionLocal() as session:
kb = await session.get(WikiKbInfo, kb_id)
if kb is None or kb.del_flag != enums.DEL_NORMAL:
raise HTTPException(status_code=404, detail="知识库不存在")
# Owner 部门恒有读写(最高权限),不允许再对它授 Editor/Reader
ids = [i for i in ids if i != kb.dept_id]
if not ids:
raise HTTPException(status_code=400, detail="绑定部门(Owner)已有读写权限,无需再授权")
for gid_target in ids:
dept = await session.get(WikiOaDept, gid_target)
if dept is None or dept.del_flag != enums.DEL_NORMAL:
continue # 忽略非法节点,不整批失败
existing = (
await session.execute(
select(WikiKbGrant).where(
WikiKbGrant.kb_id == kb_id,
WikiKbGrant.grantee_type == enums.GRANTEE_DEPT,
WikiKbGrant.grantee_id == gid_target,
WikiKbGrant.access == access,
)
)
).scalars().first()
if existing is not None:
existing.status = enums.GRANT_ACTIVE
existing.del_flag = enums.DEL_NORMAL
existing.granted_by = me.id
else:
session.add(WikiKbGrant(
kb_id=kb_id, grantee_type=enums.GRANTEE_DEPT, grantee_id=gid_target,
access=access, granted_by=me.id, status=enums.GRANT_ACTIVE,
))
granted.append(gid_target)
await session.commit()
await log_oper(
operator=me, request=request, module="kb", action="grant",
target_type="kb", target_id=kb_id, detail={"granteeIds": granted, "access": access},
)
return {"success": True, "granted": granted}
@router.delete("/kb/{kb_id}/grant/{grant_id}")
async def revoke_kb(
kb_id: str, grant_id: str, request: Request,
me: WikiOaUser = Depends(require_perm("kb:revoke")),
):
"""撤销某条授权。"""
async with AsyncSessionLocal() as session:
g = await session.get(WikiKbGrant, grant_id)
if g is None or g.kb_id != kb_id:
raise HTTPException(status_code=404, detail="授权不存在")
g.status = enums.GRANT_REVOKED
g.del_flag = enums.DEL_DELETED
await session.commit()
await log_oper(
operator=me, request=request, module="kb", action="revoke",
target_type="kb", target_id=kb_id, detail={"grantId": grant_id},
)
return {"success": True}