org.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 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
"""部门与岗位管理路由(无审批,纯 CRUD + 操作审计)。"""
from datetime import datetime

from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request, status
from sqlalchemy import func, select

from src.database.models import (
    WikiOaDept,
    WikiOaPost,
    WikiOaPostRole,
    WikiOaRole,
    WikiOaUser,
    WikiOaUserPost,
)
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

router = APIRouter()


def _center_of(dept_id: str | None, idx: dict[str, WikiOaDept]) -> tuple[str | None, str | None]:
    """由部门解析所属中心。层级 架构(根)→中心→部门;中心=根的直接子级(ancestors[1])。"""
    if not dept_id or dept_id not in idx:
        return None, None
    d = idx[dept_id]
    parts = [p for p in (d.ancestors or "").split(",") if p]
    if len(parts) >= 2:
        c = idx.get(parts[1])
        return (c.id if c else None), (c.dept_name if c else None)
    return d.id, d.dept_name


# ==================================== 部门 ====================================

def _dept_payload(d: WikiOaDept) -> dict:
    return {
        "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,
    }


async def _compute_ancestors(session, parent_id: str | None) -> str:
    """父的 ancestors + 父 id(逗号 id 路径,不含自身)。顶级为空串。"""
    if not parent_id:
        return ""
    parent = await session.get(WikiOaDept, parent_id)
    if parent is None or parent.del_flag:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="上级部门不存在")
    prefix = (parent.ancestors or "").strip(",")
    return ",".join(filter(None, [prefix, parent.id]))


@router.get("/oa/depts", dependencies=[Depends(require_perm("oa:dept:list"))])
async def list_depts():
    """返回部门树。"""
    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: {**_dept_payload(d), "children": []} for d in rows}
    roots = []
    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("/oa/depts")
async def create_dept(
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:dept:add")),
):
    name = (data.get("deptName") or "").strip()
    if not name:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="部门名称不能为空")
    parent_id = (data.get("parentId") or "").strip() or None
    category = (data.get("deptCategory") or enums.DEPT_HQ).strip()
    if category not in enums.DEPT_CATEGORIES:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="部门类别非法")
    async with AsyncSessionLocal() as session:
        ancestors = await _compute_ancestors(session, parent_id)
        dept = WikiOaDept(
            parent_id=parent_id, ancestors=ancestors, dept_name=name,
            dept_category=category, duty=(data.get("duty") or None),
            order_num=int(data.get("orderNum") or 0),
            status=enums.STATUS_ACTIVE, del_flag=enums.DEL_NORMAL,
        )
        session.add(dept)
        await session.commit()
        did = dept.id
    await log_oper(operator=me, request=request, module="dept", action="create",
                   target_type="dept", target_id=did, target_name=name,
                   detail={"parentId": parent_id, "category": category})
    return {"success": True, "id": did}


@router.patch("/oa/depts/{dept_id}")
async def update_dept(
    dept_id: str,
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:dept:edit")),
):
    async with AsyncSessionLocal() as session:
        dept = await session.get(WikiOaDept, dept_id)
        if dept is None or dept.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="部门不存在")
        if "deptName" in data:
            dept.dept_name = (data.get("deptName") or "").strip() or dept.dept_name
        if "deptCategory" in data and data["deptCategory"] in enums.DEPT_CATEGORIES:
            dept.dept_category = data["deptCategory"]
        if "duty" in data:
            dept.duty = data.get("duty") or None
        if "orderNum" in data:
            dept.order_num = int(data.get("orderNum") or 0)
        if "status" in data and data["status"] in enums.STATUSES:
            dept.status = data["status"]
        dept.updated_at = datetime.now()
        name = dept.dept_name
        await session.commit()
    await log_oper(operator=me, request=request, module="dept", action="update",
                   target_type="dept", target_id=dept_id, target_name=name, detail=data)
    return {"success": True}


async def _dept_block_reason(session, dept_id: str) -> str | None:
    """返回该部门不可删除的原因(存在下属部门 / 部门下有成员);可删除返回 None。"""
    child = (
        await session.execute(
            select(WikiOaDept.id).where(
                WikiOaDept.parent_id == dept_id, WikiOaDept.del_flag == enums.DEL_NORMAL
            )
        )
    ).scalars().first()
    if child:
        return "存在下属部门"
    user_count = (
        await session.execute(
            select(func.count()).select_from(WikiOaUser).where(
                WikiOaUser.dept_id == dept_id, WikiOaUser.del_flag == enums.DEL_NORMAL
            )
        )
    ).scalar() or 0
    if user_count:
        return f"部门下有 {user_count} 名成员"
    return None


@router.delete("/oa/depts/{dept_id}")
async def delete_dept(
    dept_id: str,
    request: Request,
    me: WikiOaUser = Depends(require_perm("oa:dept:remove")),
):
    async with AsyncSessionLocal() as session:
        dept = await session.get(WikiOaDept, dept_id)
        if dept is None or dept.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="部门不存在")
        name = dept.dept_name
        reason = await _dept_block_reason(session, dept_id)
        if reason:
            await log_oper(operator=me, request=request, module="dept", action="delete",
                           target_type="dept", target_id=dept_id, target_name=name,
                           detail={"reason": reason}, result="failed")
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail=f"无法删除「{name}」:{reason},请先处理后再删除",
            )
        dept.del_flag = enums.DEL_DELETED
        dept.updated_at = datetime.now()
        await session.commit()
    await log_oper(operator=me, request=request, module="dept", action="delete",
                   target_type="dept", target_id=dept_id, target_name=name)
    return {"success": True}


# ==================================== 岗位 ====================================

def _post_payload(
    p: WikiOaPost, role_ids: list[str] | None = None,
    center_id: str | None = None, center_name: str | None = None, dept_name: str | None = None,
) -> dict:
    return {
        "id": p.id,
        "deptId": p.dept_id,
        "deptName": dept_name,
        "centerId": center_id,
        "centerName": center_name,
        "postName": p.post_name,
        "duty": p.duty,
        "orderNum": p.order_num,
        "status": p.status,
        "defaultRoleIds": role_ids or [],
    }


@router.get("/oa/posts", dependencies=[Depends(require_perm("oa:post:list"))])
async def list_posts(
    deptId: str = Query(default=""),
    keyword: str = Query(default=""),
):
    async with AsyncSessionLocal() as session:
        all_depts = (
            await session.execute(select(WikiOaDept).where(WikiOaDept.del_flag == enums.DEL_NORMAL))
        ).scalars().all()
        idx = {d.id: d for d in all_depts}

        stmt = select(WikiOaPost).where(WikiOaPost.del_flag == enums.DEL_NORMAL)
        if deptId.strip():
            stmt = stmt.where(WikiOaPost.dept_id == deptId.strip())
        if keyword.strip():
            stmt = stmt.where(WikiOaPost.post_name.like(f"%{keyword.strip()}%"))
        posts = (await session.execute(stmt.order_by(WikiOaPost.post_name))).scalars().all()
        # 默认角色映射
        post_ids = [p.id for p in posts]
        role_map: dict[str, list[str]] = {}
        if post_ids:
            rows = (
                await session.execute(
                    select(WikiOaPostRole.post_id, WikiOaPostRole.role_id).where(
                        WikiOaPostRole.post_id.in_(post_ids)
                    )
                )
            ).all()
            for pid, rid in rows:
                role_map.setdefault(pid, []).append(rid)
        items = []
        for p in posts:
            cid, cname = _center_of(p.dept_id, idx)
            dname = idx[p.dept_id].dept_name if p.dept_id in idx else None
            # 若部门本身即中心(根),则部门名与中心名相同,部门列留空更清晰
            if dname == cname:
                dname = None
            items.append(_post_payload(p, role_map.get(p.id), cid, cname, dname))
    return {"success": True, "total": len(items), "items": items}


@router.post("/oa/posts")
async def create_post(
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:post:add")),
):
    name = (data.get("postName") or "").strip()
    if not name:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="岗位名称不能为空")
    role_ids = data.get("defaultRoleIds") or []
    dept_id = data.get("deptId") or None
    async with AsyncSessionLocal() as session:
        post = WikiOaPost(
            dept_id=dept_id,
            post_name=name,
            duty=(data.get("duty") or None),
            order_num=int(data.get("orderNum") or 0),
            status=enums.STATUS_ACTIVE, del_flag=enums.DEL_NORMAL,
        )
        session.add(post)
        await session.flush()
        if isinstance(role_ids, list):
            await _apply_post_roles(session, post.id, role_ids)
        await session.commit()
        pid = post.id
    await log_oper(operator=me, request=request, module="post", action="create",
                   target_type="post", target_id=pid, target_name=name, detail={"deptId": data.get("deptId")})
    return {"success": True, "id": pid}


@router.patch("/oa/posts/{post_id}")
async def update_post(
    post_id: str,
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:post:edit")),
):
    async with AsyncSessionLocal() as session:
        post = await session.get(WikiOaPost, post_id)
        if post is None or post.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="岗位不存在")
        if "postName" in data:
            post.post_name = (data.get("postName") or "").strip() or post.post_name
        if "deptId" in data:
            post.dept_id = data.get("deptId") or None
        if "duty" in data:
            post.duty = data.get("duty") or None
        if "orderNum" in data:
            post.order_num = int(data.get("orderNum") or 0)
        if "status" in data and data["status"] in enums.STATUSES:
            post.status = data["status"]
        if "defaultRoleIds" in data and isinstance(data["defaultRoleIds"], list):
            await _apply_post_roles(session, post_id, data["defaultRoleIds"])
        post.updated_at = datetime.now()
        name = post.post_name
        await session.commit()
    await log_oper(operator=me, request=request, module="post", action="update",
                   target_type="post", target_id=post_id, target_name=name, detail=data)
    return {"success": True}


async def _post_block_reason(session, post_id: str) -> str | None:
    """返回该岗位不可删除的原因(仍有在职人员);可删除返回 None。"""
    user_count = (
        await session.execute(
            select(func.count()).select_from(WikiOaUserPost)
            .join(WikiOaUser, WikiOaUser.id == WikiOaUserPost.user_id)
            .where(WikiOaUserPost.post_id == post_id, WikiOaUser.del_flag == enums.DEL_NORMAL)
        )
    ).scalar() or 0
    if user_count:
        return f"仍有 {user_count} 名成员任职该岗位"
    return None


@router.delete("/oa/posts/{post_id}")
async def delete_post(
    post_id: str,
    request: Request,
    me: WikiOaUser = Depends(require_perm("oa:post:remove")),
):
    async with AsyncSessionLocal() as session:
        post = await session.get(WikiOaPost, post_id)
        if post is None or post.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="岗位不存在")
        name = post.post_name
        reason = await _post_block_reason(session, post_id)
        if reason:
            await log_oper(operator=me, request=request, module="post", action="delete",
                           target_type="post", target_id=post_id, target_name=name,
                           detail={"reason": reason}, result="failed")
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail=f"无法删除「{name}」:{reason},请先调整人员岗位后再删除",
            )
        post.del_flag = enums.DEL_DELETED
        post.updated_at = datetime.now()
        await session.commit()
    await log_oper(operator=me, request=request, module="post", action="delete",
                   target_type="post", target_id=post_id, target_name=name)
    return {"success": True}


@router.post("/oa/posts/batch-delete")
async def batch_delete_posts(
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:post:remove")),
):
    """批量删除岗位(逻辑删除);仍有人员任职的自动跳过并回报原因。"""
    ids = data.get("ids") or []
    if not isinstance(ids, list) or not ids:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="ids 不能为空")
    deleted = 0
    skipped_items: list[dict] = []
    async with AsyncSessionLocal() as session:
        rows = (
            await session.execute(
                select(WikiOaPost).where(
                    WikiOaPost.id.in_(ids), WikiOaPost.del_flag == enums.DEL_NORMAL
                )
            )
        ).scalars().all()
        found_ids = {p.id for p in rows}
        for missing_id in [i for i in ids if i not in found_ids]:
            skipped_items.append({"id": missing_id, "name": None, "reason": "岗位不存在或已删除"})
        for post in rows:
            reason = await _post_block_reason(session, post.id)
            if reason:
                skipped_items.append({"id": post.id, "name": post.post_name, "reason": reason})
                continue
            post.del_flag = enums.DEL_DELETED
            post.updated_at = datetime.now()
            deleted += 1
        await session.commit()
    await log_oper(operator=me, request=request, module="post", action="batchDelete",
                   detail={"ids": ids, "deleted": deleted, "skipped": skipped_items},
                   result="success" if deleted else "failed")
    return {"success": True, "deleted": deleted, "skipped": len(skipped_items), "skippedItems": skipped_items}


async def _apply_post_roles(session, post_id: str, role_ids: list[str]) -> None:
    valid = set(
        (
            await session.execute(
                select(WikiOaRole.id).where(
                    WikiOaRole.id.in_(role_ids), WikiOaRole.del_flag == enums.DEL_NORMAL
                )
            )
        ).scalars().all()
    )
    existing = (
        await session.execute(select(WikiOaPostRole).where(WikiOaPostRole.post_id == post_id))
    ).scalars().all()
    existing_ids = {r.role_id for r in existing}
    for r in existing:
        if r.role_id not in valid:
            await session.delete(r)
    for rid in valid - existing_ids:
        session.add(WikiOaPostRole(post_id=post_id, role_id=rid))


@router.put("/oa/posts/{post_id}/roles")
async def set_post_roles(
    post_id: str,
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:post:setRole")),
):
    """设置岗位默认角色(全量覆盖)。"""
    role_ids = data.get("roleIds") or []
    if not isinstance(role_ids, list):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="roleIds 必须是数组")
    async with AsyncSessionLocal() as session:
        post = await session.get(WikiOaPost, post_id)
        if post is None or post.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="岗位不存在")
        name = post.post_name
        # 校验角色存在
        valid = set(
            (
                await session.execute(
                    select(WikiOaRole.id).where(
                        WikiOaRole.id.in_(role_ids), WikiOaRole.del_flag == enums.DEL_NORMAL
                    )
                )
            ).scalars().all()
        )
        existing = (
            await session.execute(
                select(WikiOaPostRole).where(WikiOaPostRole.post_id == post_id)
            )
        ).scalars().all()
        existing_ids = {r.role_id for r in existing}
        # 删除多余
        for r in existing:
            if r.role_id not in valid:
                await session.delete(r)
        # 新增缺失
        for rid in valid - existing_ids:
            session.add(WikiOaPostRole(post_id=post_id, role_id=rid))
        await session.commit()
    await log_oper(operator=me, request=request, module="post", action="setRole",
                   target_type="post", target_id=post_id, target_name=name,
                   detail={"roleIds": list(valid)})
    return {"success": True}