skills.py 17.9 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
"""技能管理路由(/skills):上传/列表/预览/下载/启停/删除。

上传/删除仅管理员(oa:skill:upload / oa:skill:remove);启用后的上传技能会被问答 Agent
按需自动加载(被动,模型据 description 命中)。内置技能只读,不可删除/停用。
"""
from __future__ import annotations

import io
import logging
import os
import zipfile

from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, Request, UploadFile
from fastapi.responses import PlainTextResponse, StreamingResponse
from sqlalchemy import func, or_, select

from config import BASE_DIR
from src.database.models import WikiSkill, WikiSkillDeptGrant, WikiOaDept, WikiOaUser
from src.database.session import AsyncSessionLocal
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.perms import dept_ancestor_ids
from src.services.skills.registry import (
    SkillError,
    delete_uploaded_skill,
    save_uploaded_skill,
)

logger = logging.getLogger(__name__)

router = APIRouter(tags=["skills"])

_SORTABLE_COL = {
    "name": WikiSkill.name,
    "enabled": WikiSkill.enabled,
    "createdAt": WikiSkill.created_at,
}


def _dept_path(dept_id: str | None, idx: dict[str, WikiOaDept]) -> str | None:
    """据 ancestors 拼部门完整路径(根在前,含自身),如「广联总部 / 平台产品中心 / 产品部」。"""
    d = idx.get(dept_id) if dept_id else None
    if d is None:
        return None
    parts = [p for p in (d.ancestors or "").split(",") if p]
    chain = [idx[p] for p in parts if p in idx] + [d]
    return " / ".join(x.dept_name for x in chain)


def _serialize(s: WikiSkill, granted: dict[str, list[str]] | None = None) -> dict:
    return {
        "id": s.id,
        "name": s.name,
        "displayName": s.display_name,
        "description": s.description,
        "sourceType": s.source_type,
        "enabled": bool(s.enabled),
        "isBuiltin": bool(s.is_builtin),
        "scope": s.scope,
        "fileSize": s.file_size,
        "uploadedBy": s.uploaded_by,
        "createdAt": s.created_at.isoformat() if s.created_at else None,
        # 已授权部门完整路径列表(供列表「已授权部门」列展示)
        "grantedLabels": (granted or {}).get(s.id, []),
    }


@router.get("/skills")
async def list_skills(
    keyword: str = Query(default=""),
    enabled: str = Query(default=""),
    granteeDeptId: str = Query(default=""),
    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("oa:skill:list")),
):
    """技能列表:关键字(名称/描述)/启停/已授权部门筛选 + 排序 + 分页。"""
    async with AsyncSessionLocal() as session:
        stmt = select(WikiSkill).where(WikiSkill.del_flag == enums.DEL_NORMAL)
        count_stmt = select(func.count(WikiSkill.id)).where(
            WikiSkill.del_flag == enums.DEL_NORMAL
        )
        kw = keyword.strip()
        if kw:
            # 名称 + 描述 模糊搜索
            cond = or_(WikiSkill.name.like(f"%{kw}%"), WikiSkill.description.like(f"%{kw}%"))
            stmt = stmt.where(cond)
            count_stmt = count_stmt.where(cond)
        if enabled in ("0", "1"):
            stmt = stmt.where(WikiSkill.enabled == int(enabled))
            count_stmt = count_stmt.where(WikiSkill.enabled == int(enabled))
        # 已授权部门过滤:展示「该部门(含其祖先节点授权)可用」的技能
        if granteeDeptId.strip():
            my_depts = await dept_ancestor_ids(session, granteeDeptId.strip())
            sub = select(WikiSkillDeptGrant.skill_id).where(
                WikiSkillDeptGrant.grantee_type == enums.GRANTEE_DEPT,
                WikiSkillDeptGrant.grantee_id.in_(my_depts or {granteeDeptId.strip()}),
                WikiSkillDeptGrant.status == enums.GRANT_ACTIVE,
                WikiSkillDeptGrant.del_flag == enums.DEL_NORMAL,
            )
            stmt = stmt.where(WikiSkill.id.in_(sub))
            count_stmt = count_stmt.where(WikiSkill.id.in_(sub))

        total = (await session.execute(count_stmt)).scalar() or 0
        col = _SORTABLE_COL.get(sortBy, WikiSkill.created_at)
        col = col.desc() if sortOrder.lower() == "desc" else col.asc()
        # 内置技能置顶,便于识别
        rows = (
            await session.execute(
                stmt.order_by(WikiSkill.is_builtin.desc(), col).limit(limit).offset(offset)
            )
        ).scalars().all()

        # 汇总本页技能的「已授权部门」标签
        granted: dict[str, list[str]] = {}
        skill_ids = [r.id for r in rows]
        if skill_ids:
            depts = (
                await session.execute(
                    select(WikiOaDept).where(WikiOaDept.del_flag == enums.DEL_NORMAL)
                )
            ).scalars().all()
            idx = {d.id: d for d in depts}
            grows = (
                await session.execute(
                    select(WikiSkillDeptGrant).where(
                        WikiSkillDeptGrant.skill_id.in_(skill_ids),
                        WikiSkillDeptGrant.grantee_type == enums.GRANTEE_DEPT,
                        WikiSkillDeptGrant.status == enums.GRANT_ACTIVE,
                        WikiSkillDeptGrant.del_flag == enums.DEL_NORMAL,
                    )
                )
            ).scalars().all()
            for g in grows:
                dept = idx.get(g.grantee_id)
                label = dept.dept_name if dept else g.grantee_id
                granted.setdefault(g.skill_id, []).append(label)
    return {"success": True, "total": total, "items": [_serialize(r, granted) for r in rows]}


@router.post("/skills/upload")
async def upload_skill(
    request: Request,
    file: UploadFile = File(...),
    me: WikiOaUser = Depends(require_perm("oa:skill:upload")),
):
    """上传技能(.md 或 .zip),解析校验后落盘并登记(默认停用)。"""
    raw = await file.read()
    try:
        skill = await save_uploaded_skill(raw, file.filename or "skill.md", me.id)
    except SkillError as exc:
        raise HTTPException(status_code=400, detail=str(exc))
    await log_oper(
        operator=me, request=request, module="skill", action="upload",
        target_type="skill", target_id=skill.id, target_name=skill.name,
        detail={"sourceType": skill.source_type, "size": skill.file_size},
    )
    return {"success": True, "id": skill.id, "name": skill.name}


@router.post("/skills/{skill_id}/toggle")
async def toggle_skill(
    skill_id: str, request: Request,
    me: WikiOaUser = Depends(require_perm("oa:skill:toggle")),
):
    """启用/停用一个上传技能(内置不可切换)。"""
    async with AsyncSessionLocal() as session:
        s = await session.get(WikiSkill, skill_id)
        if s is None or s.del_flag != enums.DEL_NORMAL:
            raise HTTPException(status_code=404, detail="技能不存在")
        if s.is_builtin:
            raise HTTPException(status_code=400, detail="内置技能不可停用")
        s.enabled = 0 if s.enabled else 1
        new_state = s.enabled
        name = s.name
        await session.commit()
    await log_oper(
        operator=me, request=request, module="skill", action="toggle",
        target_type="skill", target_id=skill_id, target_name=name,
        detail={"enabled": new_state},
    )
    return {"success": True, "enabled": bool(new_state)}


@router.get("/skills/{skill_id}/preview", response_class=PlainTextResponse)
async def preview_skill(skill_id: str, me: WikiOaUser = Depends(require_perm("oa:skill:list"))):
    """预览技能 SKILL.md 全文。"""
    async with AsyncSessionLocal() as session:
        s = await session.get(WikiSkill, skill_id)
        if s is None or s.del_flag != enums.DEL_NORMAL:
            raise HTTPException(status_code=404, detail="技能不存在")
        dir_path = s.dir_path
    skill_md = os.path.join(BASE_DIR, dir_path, "SKILL.md")
    if not os.path.exists(skill_md):
        raise HTTPException(status_code=404, detail="SKILL.md 不存在")
    with open(skill_md, "r", encoding="utf-8", errors="replace") as f:
        return f.read()


async def _skill_dir(skill_id: str) -> str:
    async with AsyncSessionLocal() as session:
        s = await session.get(WikiSkill, skill_id)
        if s is None or s.del_flag != enums.DEL_NORMAL:
            raise HTTPException(status_code=404, detail="技能不存在")
        return os.path.abspath(os.path.join(BASE_DIR, s.dir_path))


@router.get("/skills/{skill_id}/tree")
async def skill_tree(skill_id: str, me: WikiOaUser = Depends(require_perm("oa:skill:list"))):
    """返回技能目录下的文件树(相对技能根,供预览左侧目录)。"""
    root = await _skill_dir(skill_id)

    # 忽略噪声:避免 __pycache__/.pyc 等污染视觉
    _IGNORE_DIRS = {"__pycache__", ".git", ".idea", ".vscode", "node_modules", ".DS_Store"}
    _IGNORE_EXTS = {".pyc", ".pyo"}

    def build(dir_path: str, rel: str = ""):
        out = []
        try:
            items = sorted(os.listdir(dir_path))
        except Exception:
            return out
        items = [
            n for n in items
            if n not in _IGNORE_DIRS and os.path.splitext(n)[1].lower() not in _IGNORE_EXTS
        ]
        # 目录在前、文件在后;各自按名不区分大小写自然排序。
        # 下划线(_,0x5F)排在字母前,故 __init__.py 自然落到文件区最上面(右侧默认仍打开 SKILL.md)。
        items.sort(key=lambda n: (os.path.isfile(os.path.join(dir_path, n)), n.lower()))
        for it in items:
            full = os.path.join(dir_path, it)
            item_rel = f"{rel}/{it}" if rel else it
            if os.path.isdir(full):
                out.append({"name": it, "type": "dir", "path": item_rel, "children": build(full, item_rel)})
            else:
                out.append({"name": it, "type": "file", "path": item_rel})
        return out

    return {"tree": build(root)}


@router.get("/skills/{skill_id}/file", response_class=PlainTextResponse)
async def skill_file(skill_id: str, path: str, me: WikiOaUser = Depends(require_perm("oa:skill:list"))):
    """读取技能目录内某个文件的文本内容(路径校验,防越界)。"""
    root = await _skill_dir(skill_id)
    target = os.path.abspath(os.path.join(root, path))
    if target != root and not target.startswith(root + os.sep):
        raise HTTPException(status_code=403, detail="路径越界")
    if not os.path.isfile(target):
        raise HTTPException(status_code=404, detail="文件不存在")
    with open(target, "r", encoding="utf-8", errors="replace") as f:
        return f.read()


@router.get("/skills/{skill_id}/download")
async def download_skill(skill_id: str, me: WikiOaUser = Depends(require_perm("oa:skill:download"))):
    """下载技能:打包整个技能目录为 zip。"""
    async with AsyncSessionLocal() as session:
        s = await session.get(WikiSkill, skill_id)
        if s is None or s.del_flag != enums.DEL_NORMAL:
            raise HTTPException(status_code=404, detail="技能不存在")
        name, dir_path = s.name, s.dir_path
    skill_dir = os.path.join(BASE_DIR, dir_path)
    if not os.path.isdir(skill_dir):
        raise HTTPException(status_code=404, detail="技能目录不存在")
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
        for root, _, files in os.walk(skill_dir):
            for fn in files:
                fpath = os.path.join(root, fn)
                arc = os.path.join(name, os.path.relpath(fpath, skill_dir))
                zf.write(fpath, arc)
    buf.seek(0)
    return StreamingResponse(
        buf, media_type="application/zip",
        headers={"Content-Disposition": f'attachment; filename="{name}.zip"'},
    )


@router.delete("/skills/{skill_id}")
async def remove_skill(
    skill_id: str, request: Request,
    me: WikiOaUser = Depends(require_perm("oa:skill:remove")),
):
    """删除上传技能(逻辑删除 + 物理清目录;内置不可删)。"""
    async with AsyncSessionLocal() as session:
        s = await session.get(WikiSkill, skill_id)
        if s is None or s.del_flag != enums.DEL_NORMAL:
            raise HTTPException(status_code=404, detail="技能不存在")
        if s.is_builtin:
            raise HTTPException(status_code=400, detail="内置技能不可删除")
        s.del_flag = enums.DEL_DELETED
        s.enabled = 0
        name = s.name
        skill_copy = s
        await session.commit()
        await delete_uploaded_skill(skill_copy)
    await log_oper(
        operator=me, request=request, module="skill", action="remove",
        target_type="skill", target_id=skill_id, target_name=name,
    )
    return {"success": True}


# ============================ 技能部门授权 ============================

@router.get("/skills/org-tree")
async def skill_org_tree(me: WikiOaUser = Depends(require_perm("oa:skill:grant"))):
    """完整部门组织树(供技能授权弹窗的组织树多选)。按 oa:skill:grant 授权。"""
    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.get("/skills/{skill_id}/grants")
async def list_skill_grants(skill_id: str, me: WikiOaUser = Depends(require_perm("oa:skill: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(WikiSkillDeptGrant).where(
                    WikiSkillDeptGrant.skill_id == skill_id,
                    WikiSkillDeptGrant.del_flag == enums.DEL_NORMAL,
                    WikiSkillDeptGrant.status == enums.GRANT_ACTIVE,
                )
            )
        ).scalars().all()
    return {
        "success": True,
        "items": [
            {
                "id": g.id,
                "granteeType": g.grantee_type,
                "granteeId": g.grantee_id,
                "granteeLabel": (
                    _dept_path(g.grantee_id, idx) if g.grantee_type == enums.GRANTEE_DEPT else None
                ),
            }
            for g in rows
        ],
    }


@router.post("/skills/{skill_id}/grant")
async def grant_skill(
    skill_id: str,
    request: Request,
    granteeIds: list[str] = Body(..., embed=True),
    me: WikiOaUser = Depends(require_perm("oa:skill: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="请至少选择一个部门/中心")
    granted: list[str] = []
    async with AsyncSessionLocal() as session:
        skill = await session.get(WikiSkill, skill_id)
        if skill is None or skill.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(WikiSkillDeptGrant).where(
                        WikiSkillDeptGrant.skill_id == skill_id,
                        WikiSkillDeptGrant.grantee_type == enums.GRANTEE_DEPT,
                        WikiSkillDeptGrant.grantee_id == gid_target,
                    )
                )
            ).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(WikiSkillDeptGrant(
                    skill_id=skill_id, grantee_type=enums.GRANTEE_DEPT, grantee_id=gid_target,
                    granted_by=me.id, status=enums.GRANT_ACTIVE,
                ))
            granted.append(gid_target)
        await session.commit()
    await log_oper(
        operator=me, request=request, module="skill", action="grant",
        target_type="skill", target_id=skill_id, detail={"granteeIds": granted},
    )
    return {"success": True, "granted": granted}


@router.delete("/skills/{skill_id}/grant/{grant_id}")
async def revoke_skill(
    skill_id: str, grant_id: str, request: Request,
    me: WikiOaUser = Depends(require_perm("oa:skill:grant")),
):
    """撤销某条技能部门授权。"""
    async with AsyncSessionLocal() as session:
        g = await session.get(WikiSkillDeptGrant, grant_id)
        if g is None or g.skill_id != skill_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="skill", action="revoke",
        target_type="skill", target_id=skill_id, detail={"grantId": grant_id},
    )
    return {"success": True}