kb.py 33.8 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 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
"""知识库管理路由(前缀 /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_TYPES:
        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_DEPT:
        owner_dept = None  # 基础库/项目库不绑定部门
    # 项目库以创建者为 owner(部门/基础库无个人 owner)
    owner_user = me.id if kbType == enums.KB_PROJECT else 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,
            owner_user_id=owner_user,
            root_dir=kb_root_rel(new_id, kbType),  # 按类型落 ware/kb/base|dept|project/<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.post("/kb/provision-dept")
async def provision_dept_kbs(
    request: Request,
    me: WikiOaUser = Depends(require_perm("kb:create")),
):
    """一键为所有「叶子部门」批量新建部门库(已绑定库的部门自动跳过)。

    - 目标 = 无下属部门的叶子节点(中心/架构是纯分组、不作 Owner,与单建的 _assert_valid_owner_dept
      叶子约束一致)。
    - 幂等:已被有效部门库绑定(1:1)的部门跳过。
    - 每库:uuid 主键 + root_dir=ware/kb/dept/<id> + 建 raw/wiki 目录 + 重建 index.md。
    - 权限:部门库 Owner 由 dept_id 绑定隐式获得(resolve_kb_access 处理),无需额外写 grant。
    返回 {created:[{deptId,deptName,kbId}], skipped:[{deptId,deptName,reason}]}。
    """
    await ensure_base_kb()
    created: list[dict] = []
    skipped: list[dict] = []
    async with AsyncSessionLocal() as session:
        depts = (
            await session.execute(
                select(WikiOaDept).where(WikiOaDept.del_flag == enums.DEL_NORMAL)
            )
        ).scalars().all()
        # 有子部门的节点 = 分组中心/架构;其余为叶子
        parent_ids = {d.parent_id for d in depts if d.parent_id}
        leaves = [d for d in depts if d.id not in parent_ids]
        # 已被有效部门库绑定的部门(1:1)
        bound = set(
            (
                await session.execute(
                    select(WikiKbInfo.dept_id).where(
                        WikiKbInfo.kb_type == enums.KB_DEPT,
                        WikiKbInfo.del_flag == enums.DEL_NORMAL,
                        WikiKbInfo.dept_id.isnot(None),
                    )
                )
            ).scalars().all()
        )
        # 现有库名集合,用于同名规避(kb_name 无唯一约束,但配置页按名识别,避免撞名)
        existing_names = set(
            (
                await session.execute(
                    select(WikiKbInfo.kb_name).where(WikiKbInfo.del_flag == enums.DEL_NORMAL)
                )
            ).scalars().all()
        )

        for d in leaves:
            if d.id in bound:
                skipped.append({"deptId": d.id, "deptName": d.dept_name, "reason": "已有部门库"})
                continue
            name = d.dept_name
            if name in existing_names:  # 同名部门:附库 id 短前缀区分
                name = f"{d.dept_name}-{uuid_str()[:8]}"
            new_id = uuid_str()
            kb = WikiKbInfo(
                id=new_id,
                kb_type=enums.KB_DEPT,
                kb_name=name,
                dept_id=d.id,
                root_dir=kb_root_rel(new_id, enums.KB_DEPT),
                status=enums.STATUS_ACTIVE,
            )
            session.add(kb)
            existing_names.add(name)
            # 建目录 + 重建索引在 commit 前做(属性仍新鲜,避免读过期对象);fs 失败不阻断
            try:
                ensure_kb_dirs(kb)
                rebuild_index(kb_wiki_dir(kb))
            except Exception:
                pass
            created.append({"deptId": d.id, "deptName": d.dept_name, "kbId": new_id})
        if created:
            await session.commit()

    await log_oper(
        operator=me, request=request, module="kb", action="provisionDept",
        target_type="kb", target_id="",
        target_name=f"一键建部门库:新建 {len(created)},跳过 {len(skipped)}",
    )
    return {"success": True, "created": created, "skipped": skipped}


# ==================== 项目库(project):用户自建 + 按人协作 ====================


async def _get_owned_project(session, kb_id: str, me: WikiOaUser) -> WikiKbInfo:
    """取项目库并校验当前用户是其 owner(或超管),否则抛错。"""
    kb = await session.get(WikiKbInfo, kb_id)
    if kb is None or kb.del_flag != enums.DEL_NORMAL or kb.kb_type != enums.KB_PROJECT:
        raise HTTPException(status_code=404, detail="项目库不存在")
    if not me.is_superadmin and kb.owner_user_id != me.id:
        raise HTTPException(status_code=403, detail="仅项目库创建者可管理")
    return kb


@router.post("/kb/project")
async def create_project_kb(
    request: Request,
    kbName: str = Body(..., embed=True),
    me: WikiOaUser = Depends(require_perm("kb:project:manage")),
):
    """新建**项目库**:任意具 kb:project:manage 的用户可建自己的项目库(类 git 仓库)。

    owner=创建者(隐式读写 + 管协作者 + 删库);协作者经 /kb/{id}/collaborator 按人授 editor/reader。
    物理落 ware/kb/project/<uuid>,与部门/基础库隔离。
    """
    name = (kbName or "").strip()
    if not name:
        raise HTTPException(status_code=400, detail="项目库名称不能为空")
    async with AsyncSessionLocal() as session:
        new_id = uuid_str()
        kb = WikiKbInfo(
            id=new_id,
            kb_type=enums.KB_PROJECT,
            kb_name=name,
            owner_user_id=me.id,
            dept_id=None,
            root_dir=kb_root_rel(new_id, enums.KB_PROJECT),
            status=enums.STATUS_ACTIVE,
        )
        session.add(kb)
        try:
            ensure_kb_dirs(kb)
            rebuild_index(kb_wiki_dir(kb))
        except Exception:
            pass
        await session.commit()
    await log_oper(
        operator=me, request=request, module="kb", action="createProject",
        target_type="kb", target_id=new_id, target_name=name,
    )
    return {"success": True, "id": new_id}


@router.get("/kb/project/user-search")
async def project_user_search(
    q: str = Query(default=""),
    me: WikiOaUser = Depends(require_perm("kb:project:manage")),
):
    """按姓名/账号搜索用户,供项目库 owner 添加协作者(仅返回 id+姓名,供选人用)。

    独立于 oa:user:list(管理员权限):项目协作是普通用户能力,只暴露最小选人字段。
    """
    kw = (q or "").strip()
    async with AsyncSessionLocal() as session:
        stmt = select(WikiOaUser).where(
            WikiOaUser.del_flag == enums.DEL_NORMAL,
            WikiOaUser.status == enums.STATUS_ACTIVE,
        )
        if kw:
            stmt = stmt.where(
                WikiOaUser.display_name.like(f"%{kw}%") | WikiOaUser.username.like(f"%{kw}%")
            )
        rows = (await session.execute(stmt.limit(20))).scalars().all()
    return {
        "success": True,
        "items": [{"id": u.id, "name": u.display_name, "username": u.username} for u in rows if u.id != me.id],
    }


@router.get("/kb/project/mine")
async def my_project_kbs(me: WikiOaUser = Depends(require_perm("kb:project:manage"))):
    """当前用户能访问的项目库(自建 owner + 被授协作),带级别与是否本人 owner。"""
    pairs = await resolve_readable_kbs_with_access(me)
    items = [
        {
            "id": kb.id,
            "kbName": kb.kb_name,
            "access": acc,
            "isOwner": kb.owner_user_id == me.id,
        }
        for kb, acc in pairs
        if kb.kb_type == enums.KB_PROJECT
    ]
    items.sort(key=lambda it: (0 if it["isOwner"] else 1, it["kbName"]))
    return {"success": True, "items": items}


@router.get("/kb/{kb_id}/collaborators")
async def list_project_collaborators(kb_id: str, me: WikiOaUser = Depends(require_perm("kb:project:manage"))):
    """列出项目库的协作者(grantee_type=user 的 editor/reader),带用户姓名。"""
    async with AsyncSessionLocal() as session:
        await _get_owned_project(session, kb_id, me)
        grants = (
            await session.execute(
                select(WikiKbGrant).where(
                    WikiKbGrant.kb_id == kb_id,
                    WikiKbGrant.grantee_type == enums.GRANTEE_USER,
                    WikiKbGrant.del_flag == enums.DEL_NORMAL,
                    WikiKbGrant.status == enums.GRANT_ACTIVE,
                )
            )
        ).scalars().all()
        uids = [g.grantee_id for g in grants]
        umap: dict[str, str] = {}
        if uids:
            users = (
                await session.execute(select(WikiOaUser).where(WikiOaUser.id.in_(uids)))
            ).scalars().all()
            umap = {u.id: u.display_name for u in users}
    return {
        "success": True,
        "items": [
            {"grantId": g.id, "userId": g.grantee_id, "userName": umap.get(g.grantee_id, "用户"), "access": g.access}
            for g in grants
        ],
    }


@router.post("/kb/{kb_id}/collaborator")
async def add_project_collaborator(
    kb_id: str,
    request: Request,
    userId: str = Body(..., embed=True),
    access: str = Body(default=enums.KB_ACCESS_EDITOR, embed=True),
    me: WikiOaUser = Depends(require_perm("kb:project:manage")),
):
    """项目库 owner 按人添加/更新协作者(editor=读写 / reader=只读)。"""
    if access not in enums.KB_ACCESS_LEVELS:
        raise HTTPException(status_code=400, detail="协作级别非法(仅 editor/reader)")
    target = (userId or "").strip()
    if not target:
        raise HTTPException(status_code=400, detail="请指定协作者用户")
    async with AsyncSessionLocal() as session:
        kb = await _get_owned_project(session, kb_id, me)
        if target == kb.owner_user_id:
            raise HTTPException(status_code=400, detail="创建者已是 owner,无需再授协作")
        user = await session.get(WikiOaUser, target)
        if user is None or user.del_flag != enums.DEL_NORMAL:
            raise HTTPException(status_code=404, detail="协作者用户不存在")
        # 同一用户在本库唯一:已存在任意级别则改级别复用,避免重复行
        existing = (
            await session.execute(
                select(WikiKbGrant).where(
                    WikiKbGrant.kb_id == kb_id,
                    WikiKbGrant.grantee_type == enums.GRANTEE_USER,
                    WikiKbGrant.grantee_id == target,
                    WikiKbGrant.del_flag == enums.DEL_NORMAL,
                )
            )
        ).scalars().first()
        if existing is not None:
            existing.access = access
            existing.status = enums.GRANT_ACTIVE
            existing.granted_by = me.id
        else:
            session.add(WikiKbGrant(
                kb_id=kb_id, grantee_type=enums.GRANTEE_USER, grantee_id=target,
                access=access, granted_by=me.id, status=enums.GRANT_ACTIVE,
            ))
        await session.commit()
    await log_oper(
        operator=me, request=request, module="kb", action="addCollaborator",
        target_type="kb", target_id=kb_id, detail={"userId": target, "access": access},
    )
    return {"success": True}


@router.delete("/kb/{kb_id}/collaborator/{user_id}")
async def remove_project_collaborator(
    kb_id: str, user_id: str, request: Request,
    me: WikiOaUser = Depends(require_perm("kb:project:manage")),
):
    """项目库 owner 移除某协作者。"""
    async with AsyncSessionLocal() as session:
        await _get_owned_project(session, kb_id, me)
        rows = (
            await session.execute(
                select(WikiKbGrant).where(
                    WikiKbGrant.kb_id == kb_id,
                    WikiKbGrant.grantee_type == enums.GRANTEE_USER,
                    WikiKbGrant.grantee_id == user_id,
                    WikiKbGrant.del_flag == enums.DEL_NORMAL,
                )
            )
        ).scalars().all()
        for g in rows:
            g.del_flag = enums.DEL_DELETED
            g.status = enums.GRANT_REVOKED
        await session.commit()
    await log_oper(
        operator=me, request=request, module="kb", action="removeCollaborator",
        target_type="kb", target_id=kb_id, detail={"userId": user_id},
    )
    return {"success": True}


@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}