users.py 20.4 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
"""用户管理路由(含数据范围过滤、中心/部门解析、岗位与角色维护、操作审计)。"""
from datetime import datetime

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

from config import DEFAULT_USER_PASSWORD
from src.database.models import (
    WikiOaDept,
    WikiOaPost,
    WikiOaRole,
    WikiOaUser,
    WikiOaUserPost,
    WikiOaUserRole,
    WikiUserProfile,
)
from src.database.session import AsyncSessionLocal
from src.services.identity.local import build_password_fields
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_subtree_ids, resolve_data_scope

router = APIRouter()

# 标量排序列
_SORTABLE_COL = {
    "displayName": WikiOaUser.display_name,
    "username": WikiOaUser.username,
    "status": WikiOaUser.status,
    "createdAt": WikiOaUser.created_at,
    "lastLoginAt": WikiOaUser.last_login_at,
}


def _dept_index(depts: list[WikiOaDept]) -> dict[str, WikiOaDept]:
    return {d.id: d for d in depts}


def _resolve_center(
    dept_id: str | None, idx: dict[str, WikiOaDept]
) -> tuple[str | None, str | None, str | None, str | None]:
    """返回 (archName, centerId, centerName, deptName)。层级:架构(根) → 中心 → 部门。

    ancestors 是层级的唯一真相源,架构=parts[0]、中心=parts[1]。用户可能挂在任一层:

    | 所挂部门   | ancestors      | 架构     | 中心 | 部门 |
    |-----------|----------------|---------|------|------|
    | 三级部门   | [架构, 中心]    | parts[0] | parts[1] | 自身 |
    | 二级中心   | [架构]          | parts[0] | 自身 | 空   |
    | 一级架构   | []             | 自身     | 空   | 空   |
    """
    if not dept_id or dept_id not in idx:
        return None, None, None, None
    d = idx[dept_id]
    parts = [p for p in (d.ancestors or "").split(",") if p]
    arch = idx.get(parts[0]) if parts else None
    arch_name = arch.dept_name if arch else (None if parts else d.dept_name)

    if len(parts) >= 2:
        center = idx.get(parts[1])
        return arch_name, parts[1], (center.dept_name if center else None), d.dept_name
    if len(parts) == 1:
        # 直挂中心:自身即中心,无三级部门
        return arch_name, d.id, d.dept_name, None
    # 直挂架构:无中心概念
    return arch_name, None, None, None


@router.get("/oa/users")
async def list_users(
    keyword: str = Query(default=""),
    deptId: str = Query(default=""),
    roleId: str = Query(default=""),
    postName: str = Query(default=""),
    status_: str = Query(default="", alias="status"),
    sortBy: str = Query(default="createdAt"),
    sortOrder: str = Query(default="desc"),
    limit: int = Query(default=20, ge=1, le=500),
    offset: int = Query(default=0, ge=0),
    me: WikiOaUser = Depends(require_perm("oa:user:list")),
):
    """用户列表:关键字/部门(含中心子树)/角色/岗位/状态筛选 + 服务端排序 + 分页,按数据范围收窄。"""
    scope = await resolve_data_scope(me)
    async with AsyncSessionLocal() as session:
        all_depts = (
            await session.execute(
                select(WikiOaDept).where(WikiOaDept.del_flag == enums.DEL_NORMAL)
            )
        ).scalars().all()
        idx = _dept_index(all_depts)

        stmt = select(WikiOaUser).where(WikiOaUser.del_flag == enums.DEL_NORMAL)
        count_stmt = select(func.count(func.distinct(WikiOaUser.id))).select_from(
            WikiOaUser
        ).where(WikiOaUser.del_flag == enums.DEL_NORMAL)

        # 数据范围
        if not scope.is_all:
            if scope.dept_ids:
                cond = WikiOaUser.dept_id.in_(scope.dept_ids)
            else:
                cond = WikiOaUser.id == me.id
            stmt = stmt.where(cond)
            count_stmt = count_stmt.where(cond)

        kw = keyword.strip()
        if kw:
            pattern = f"%{kw}%"
            cond = or_(
                WikiOaUser.display_name.like(pattern),
                WikiOaUser.username.like(pattern),
                WikiOaUser.phone.like(pattern),
                WikiOaUser.store_name.like(pattern),
            )
            stmt = stmt.where(cond)
            count_stmt = count_stmt.where(cond)

        # 部门/中心筛选:选中的若是中心,则展开为其下所有部门(本部门及以下)
        if deptId.strip():
            sub_ids = await dept_subtree_ids(session, deptId.strip())
            stmt = stmt.where(WikiOaUser.dept_id.in_(sub_ids))
            count_stmt = count_stmt.where(WikiOaUser.dept_id.in_(sub_ids))

        if status_.strip() in enums.STATUSES:
            stmt = stmt.where(WikiOaUser.status == status_.strip())
            count_stmt = count_stmt.where(WikiOaUser.status == status_.strip())

        if roleId.strip():
            sub = select(WikiOaUserRole.user_id).where(WikiOaUserRole.role_id == roleId.strip())
            stmt = stmt.where(WikiOaUser.id.in_(sub))
            count_stmt = count_stmt.where(WikiOaUser.id.in_(sub))

        # 岗位按“名称”筛选:同名岗位可能分散在多条记录(不同部门),按名匹配所有持有者
        if postName.strip():
            sub = (
                select(WikiOaUserPost.user_id)
                .join(WikiOaPost, WikiOaPost.id == WikiOaUserPost.post_id)
                .where(WikiOaPost.post_name == postName.strip(), WikiOaPost.del_flag == enums.DEL_NORMAL)
            )
            stmt = stmt.where(WikiOaUser.id.in_(sub))
            count_stmt = count_stmt.where(WikiOaUser.id.in_(sub))

        total = (await session.execute(count_stmt)).scalar() or 0

        # 排序:超管置顶 + 选定列/子查询
        if sortBy in _SORTABLE_COL:
            order_col = _SORTABLE_COL[sortBy]
        elif sortBy == "deptName":
            order_col = (
                select(WikiOaDept.dept_name)
                .where(WikiOaDept.id == WikiOaUser.dept_id)
                .correlate(WikiOaUser)
                .scalar_subquery()
            )
        elif sortBy == "postName":
            order_col = (
                select(func.min(WikiOaPost.post_name))
                .select_from(WikiOaUserPost)
                .join(WikiOaPost, WikiOaPost.id == WikiOaUserPost.post_id)
                .where(WikiOaUserPost.user_id == WikiOaUser.id)
                .correlate(WikiOaUser)
                .scalar_subquery()
            )
        elif sortBy == "roleName":
            order_col = (
                select(func.min(WikiOaRole.role_name))
                .select_from(WikiOaUserRole)
                .join(WikiOaRole, WikiOaRole.id == WikiOaUserRole.role_id)
                .where(WikiOaUserRole.user_id == WikiOaUser.id)
                .correlate(WikiOaUser)
                .scalar_subquery()
            )
        else:
            order_col = WikiOaUser.created_at
        ordered = order_col.asc() if sortOrder == "asc" else order_col.desc()
        stmt = stmt.order_by(WikiOaUser.is_superadmin.desc(), ordered, WikiOaUser.id)
        users = (await session.execute(stmt.limit(limit).offset(offset))).scalars().all()

        user_ids = [u.id for u in users]
        role_map: dict[str, list[dict]] = {}
        post_map: dict[str, list[dict]] = {}
        if user_ids:
            rows = await session.execute(
                select(WikiOaUserRole.user_id, WikiOaRole.id, WikiOaRole.role_name)
                .join(WikiOaRole, WikiOaRole.id == WikiOaUserRole.role_id)
                .where(WikiOaUserRole.user_id.in_(user_ids), WikiOaRole.del_flag == enums.DEL_NORMAL)
            )
            for uid, rid, rname in rows:
                role_map.setdefault(uid, []).append({"id": rid, "name": rname})
            rows = await session.execute(
                select(WikiOaUserPost.user_id, WikiOaPost.id, WikiOaPost.post_name)
                .join(WikiOaPost, WikiOaPost.id == WikiOaUserPost.post_id)
                .where(WikiOaUserPost.user_id.in_(user_ids), WikiOaPost.del_flag == enums.DEL_NORMAL)
            )
            for uid, pid, pname in rows:
                post_map.setdefault(uid, []).append({"id": pid, "name": pname})

        items = []
        for u in users:
            arch_name, center_id, center_name, dept_name = _resolve_center(u.dept_id, idx)
            posts = post_map.get(u.id, [])
            roles = role_map.get(u.id, [])
            items.append(
                {
                    "id": u.id,
                    "username": u.username,
                    "displayName": u.display_name,
                    "phone": u.phone,
                    "email": u.email,
                    "deptId": u.dept_id,
                    "deptName": dept_name,
                    "archName": arch_name,
                    "centerId": center_id,
                    "centerName": center_name,
                    "storeName": u.store_name,
                    "isSuperadmin": bool(u.is_superadmin),
                    "status": u.status,
                    "roles": [r["name"] for r in roles],
                    "roleIds": [r["id"] for r in roles],
                    "posts": [p["name"] for p in posts],
                    "postIds": [p["id"] for p in posts],
                    "lastLoginAt": u.last_login_at.isoformat() if u.last_login_at else None,
                }
            )
    return {"success": True, "total": total, "items": items}


async def _apply_roles(session, user_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(WikiOaUserRole).where(WikiOaUserRole.user_id == user_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(WikiOaUserRole(user_id=user_id, role_id=rid))


async def _apply_posts(session, user_id: str, post_ids: list[str]) -> None:
    valid = set(
        (
            await session.execute(
                select(WikiOaPost.id).where(
                    WikiOaPost.id.in_(post_ids), WikiOaPost.del_flag == enums.DEL_NORMAL
                )
            )
        ).scalars().all()
    )
    existing = (
        await session.execute(select(WikiOaUserPost).where(WikiOaUserPost.user_id == user_id))
    ).scalars().all()
    existing_ids = {p.post_id for p in existing}
    for p in existing:
        if p.post_id not in valid:
            await session.delete(p)
    for pid in valid - existing_ids:
        session.add(WikiOaUserPost(user_id=user_id, post_id=pid))


@router.post("/oa/users")
async def create_user(
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:user:add")),
):
    phone = (data.get("phone") or "").strip()
    display_name = (data.get("displayName") or "").strip()
    if not phone:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="手机号不能为空")
    if not display_name:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="姓名不能为空")
    async with AsyncSessionLocal() as session:
        exists = (
            await session.execute(
                select(WikiOaUser).where(
                    or_(WikiOaUser.username == phone, WikiOaUser.phone == phone),
                    WikiOaUser.del_flag == enums.DEL_NORMAL,
                )
            )
        ).scalars().first()
        if exists is not None:
            raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="该手机号已存在")
        password_hash, password_salt = build_password_fields(DEFAULT_USER_PASSWORD)
        user = WikiOaUser(
            username=phone, phone=phone, display_name=display_name,
            email=(data.get("email") or "").strip() or None,
            password_hash=password_hash, password_salt=password_salt,
            dept_id=(data.get("deptId") or None),
            store_name=(data.get("storeName") or "").strip() or None,
            is_superadmin=1 if data.get("isSuperadmin") else 0,
            must_change_pwd=1, status=enums.STATUS_ACTIVE, del_flag=enums.DEL_NORMAL,
        )
        session.add(user)
        await session.flush()
        session.add(WikiUserProfile(user_id=user.id, profile_generated=False))
        await _apply_posts(session, user.id, data.get("postIds") or [])
        await _apply_roles(session, user.id, data.get("roleIds") or [])
        await session.commit()
        uid = user.id
    await log_oper(operator=me, request=request, module="user", action="create",
                   target_type="user", target_id=uid, target_name=display_name,
                   detail={"phone": phone, "deptId": data.get("deptId")})
    return {"success": True, "id": uid, "initialPassword": DEFAULT_USER_PASSWORD}


@router.patch("/oa/users/{user_id}")
async def update_user(
    user_id: str,
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:user:edit")),
):
    async with AsyncSessionLocal() as session:
        user = await session.get(WikiOaUser, user_id)
        if user is None or user.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
        if "displayName" in data:
            new_name = (data.get("displayName") or "").strip()
            if new_name:
                user.display_name = new_name
        if "phone" in data:
            new_phone = (data.get("phone") or "").strip()
            if new_phone and new_phone != user.phone:
                dup = (
                    await session.execute(
                        select(WikiOaUser).where(
                            or_(WikiOaUser.username == new_phone, WikiOaUser.phone == new_phone),
                            WikiOaUser.id != user_id,
                            WikiOaUser.del_flag == enums.DEL_NORMAL,
                        )
                    )
                ).scalars().first()
                if dup is not None:
                    raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="该手机号已被占用")
                user.phone = new_phone
                user.username = new_phone
        if "deptId" in data:
            user.dept_id = data.get("deptId") or None
        if "storeName" in data:
            user.store_name = (data.get("storeName") or "").strip() or None
        if "email" in data:
            user.email = (data.get("email") or "").strip() or None
        if "isSuperadmin" in data:
            user.is_superadmin = 1 if data.get("isSuperadmin") else 0
        if "status" in data and data["status"] in enums.STATUSES:
            user.status = data["status"]
        if "roleIds" in data and isinstance(data["roleIds"], list):
            await _apply_roles(session, user_id, data["roleIds"])
        if "postIds" in data and isinstance(data["postIds"], list):
            await _apply_posts(session, user_id, data["postIds"])
        user.updated_at = datetime.now()
        name = user.display_name
        await session.commit()
    await log_oper(operator=me, request=request, module="user", action="update",
                   target_type="user", target_id=user_id, target_name=name,
                   detail={k: data[k] for k in data if k != "password"})
    return {"success": True}


@router.delete("/oa/users/{user_id}")
async def delete_user(
    user_id: str,
    request: Request,
    me: WikiOaUser = Depends(require_perm("oa:user:remove")),
):
    async with AsyncSessionLocal() as session:
        user = await session.get(WikiOaUser, user_id)
        if user is None or user.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
        if user.is_superadmin:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="超级管理员不可删除")
        user.del_flag = enums.DEL_DELETED
        user.status = enums.STATUS_DISABLED
        user.updated_at = datetime.now()
        name = user.display_name
        await session.commit()
    await log_oper(operator=me, request=request, module="user", action="delete",
                   target_type="user", target_id=user_id, target_name=name)
    return {"success": True}


@router.post("/oa/users/batch-delete")
async def batch_delete_users(
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:user: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, skipped = 0, 0
    async with AsyncSessionLocal() as session:
        rows = (
            await session.execute(
                select(WikiOaUser).where(
                    WikiOaUser.id.in_(ids), WikiOaUser.del_flag == enums.DEL_NORMAL
                )
            )
        ).scalars().all()
        for user in rows:
            if user.is_superadmin:
                skipped += 1
                continue
            user.del_flag = enums.DEL_DELETED
            user.status = enums.STATUS_DISABLED
            user.updated_at = datetime.now()
            deleted += 1
        await session.commit()
    await log_oper(operator=me, request=request, module="user", action="batchDelete",
                   detail={"ids": ids, "deleted": deleted, "skipped": skipped})
    return {"success": True, "deleted": deleted, "skipped": skipped}


@router.post("/oa/users/{user_id}/reset-password")
async def reset_password(
    user_id: str,
    request: Request,
    me: WikiOaUser = Depends(require_perm("oa:user:resetPwd")),
):
    password_hash, password_salt = build_password_fields(DEFAULT_USER_PASSWORD)
    async with AsyncSessionLocal() as session:
        user = await session.get(WikiOaUser, user_id)
        if user is None or user.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
        user.password_hash = password_hash
        user.password_salt = password_salt
        user.must_change_pwd = 1
        name = user.display_name
        await session.commit()
    await log_oper(operator=me, request=request, module="user", action="resetPwd",
                   target_type="user", target_id=user_id, target_name=name)
    return {"success": True, "initialPassword": DEFAULT_USER_PASSWORD}


@router.put("/oa/users/{user_id}/roles")
async def set_user_roles(
    user_id: str,
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:user:assignRole")),
):
    """全量覆盖用户角色。"""
    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:
        user = await session.get(WikiOaUser, user_id)
        if user is None or user.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
        await _apply_roles(session, user_id, role_ids)
        name = user.display_name
        await session.commit()
    await log_oper(operator=me, request=request, module="user", action="assignRole",
                   target_type="user", target_id=user_id, target_name=name, detail={"roleIds": role_ids})
    return {"success": True}


@router.put("/oa/users/{user_id}/posts")
async def set_user_posts(
    user_id: str,
    request: Request,
    data: dict = Body(...),
    me: WikiOaUser = Depends(require_perm("oa:user:edit")),
):
    """全量覆盖用户岗位(多岗位)。"""
    post_ids = data.get("postIds") or []
    if not isinstance(post_ids, list):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="postIds 必须是数组")
    async with AsyncSessionLocal() as session:
        user = await session.get(WikiOaUser, user_id)
        if user is None or user.del_flag:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
        await _apply_posts(session, user_id, post_ids)
        name = user.display_name
        await session.commit()
    await log_oper(operator=me, request=request, module="user", action="assignPost",
                   target_type="user", target_id=user_id, target_name=name, detail={"postIds": post_ids})
    return {"success": True}