kb.py
18.5 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
"""知识库管理路由(前缀 /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
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) -> 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, []),
}
@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]
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:
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 ∪ 部门库(继承+管辖) ∪ 被授权库)。供前端库下拉/Copilot。"""
kbs = await resolve_readable_kbs(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) for k in kbs]
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),
me: WikiOaUser = Depends(require_perm("kb:create")),
):
"""新建知识库:库名 + 类型,不绑定部门。访问权限由管理员通过「授权」显式分配给部门。
dept(部门库)/ base(公共库)两种类型都可建,且都各自独立命名空间——类型只决定权限语义
(公共库仅超管可写,部门库本部门可写),不影响物理存储,故建库后仍可自由改类型。
"""
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="知识库名称不能为空")
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="同名知识库已存在")
new_id = uuid_str()
kb = WikiKbInfo(
id=new_id,
kb_type=kbType,
kb_name=name,
dept_id=None,
root_dir=kb_root_rel(new_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),
status_: str = Body(default=None, embed=True, alias="status"),
me: WikiOaUser = Depends(require_perm("kb:create")),
):
"""改名 / 改类型 / 启停知识库。
类型可自由切换:物理路径只由 root_dir 决定(见 kb_paths.py),改类型不动任何文件,
仅改变权限语义(公共库仅超管可写、部门库本部门可写)。唯独内置公共库是系统兜底库,
类型/停用/删除一律锁死。
"""
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:
if kbType not in (enums.KB_DEPT, enums.KB_BASE):
raise HTTPException(status_code=400, detail="知识库类型不合法")
if builtin:
raise HTTPException(status_code=400, detail="内置公共库类型不可修改")
kb.kb_type = kbType
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"))):
"""列出某库的授权记录(供授权管理弹窗展示,带组织节点完整路径)。"""
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
),
"perm": g.perm,
}
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),
perm: str = Body(default=enums.KB_PERM_QUERY, embed=True),
me: WikiOaUser = Depends(require_perm("kb:grant")),
):
"""把某库读权限授予一批组织节点(部门/中心)。授任一节点=授其整棵子树,可一次多 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 perm not in enums.KB_GRANT_PERMS:
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="知识库不存在")
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.perm == perm,
)
)
).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,
perm=perm, 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, "perm": perm},
)
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}