admin.py 10 KB
"""管理员路由:用户管理、密码重置、岗位模板维护。

全部接口要求 role=admin。
"""
import logging
from datetime import datetime

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

from config import DEFAULT_USER_PASSWORD
from src.database.models import WikiPosition, WikiUser, WikiUserProfile
from src.database.session import AsyncSessionLocal
from src.services.identity.local import build_password_fields
from src.services.identity.tokens import require_admin

logger = logging.getLogger(__name__)

router = APIRouter()


def _position_payload(position: WikiPosition) -> dict:
    return {
        "id": position.id,
        "name": position.name,
        "deptL1": position.dept_l1,
        "deptL2": position.dept_l2,
        "dutyTemplate": position.duty_template,
        "commonOpsTemplate": position.common_ops_template,
        "templateMissing": bool(position.template_missing),
    }


# ==================================== 用户管理 ====================================


@router.get("/admin/users")
async def list_users(
    keyword: str = Query(default="", description="按姓名/账号/手机号模糊搜索"),
    limit: int = Query(default=50, ge=1, le=200),
    offset: int = Query(default=0, ge=0),
    _: WikiUser = Depends(require_admin),
):
    """用户列表,支持关键字搜索与分页。"""
    async with AsyncSessionLocal() as session:
        stmt = select(WikiUser)
        count_stmt = select(func.count()).select_from(WikiUser)

        keyword = (keyword or "").strip()
        if keyword:
            pattern = f"%{keyword}%"
            condition = or_(
                WikiUser.display_name.like(pattern),
                WikiUser.username.like(pattern),
                WikiUser.phone.like(pattern),
            )
            stmt = stmt.where(condition)
            count_stmt = count_stmt.where(condition)

        total = (await session.execute(count_stmt)).scalar() or 0
        stmt = stmt.order_by(WikiUser.created_at.desc()).limit(limit).offset(offset)
        users = (await session.execute(stmt)).scalars().all()

        # 一次性把岗位名查出来,避免逐行查询
        position_ids = {u.position_id for u in users if u.position_id}
        positions: dict[str, str] = {}
        if position_ids:
            rows = await session.execute(
                select(WikiPosition.id, WikiPosition.name).where(WikiPosition.id.in_(position_ids))
            )
            positions = {pid: name for pid, name in rows}

        items = [
            {
                "id": u.id,
                "username": u.username,
                "displayName": u.display_name,
                "phone": u.phone,
                "email": u.email,
                "role": u.role,
                "status": u.status,
                "storeName": u.store_name,
                "positionId": u.position_id,
                "positionName": positions.get(u.position_id),
                "lastLoginAt": u.last_login_at.isoformat() if u.last_login_at else None,
            }
            for u in users
        ]

    return {"success": True, "total": total, "items": items}


@router.post("/admin/users")
async def create_user(
    data: dict = Body(...),
    _: WikiUser = Depends(require_admin),
):
    """新建用户。账号统一使用手机号,初始密码取 DEFAULT_USER_PASSWORD。"""
    phone = (data.get("phone") or "").strip()
    display_name = (data.get("displayName") or "").strip()
    position_id = (data.get("positionId") or "").strip() or None
    store_name = (data.get("storeName") or "").strip() or None
    role = (data.get("role") or "user").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="姓名不能为空")
    if role not in ("user", "admin"):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="角色只能是 user 或 admin")

    async with AsyncSessionLocal() as session:
        exists = await session.execute(
            select(WikiUser).where(or_(WikiUser.username == phone, WikiUser.phone == phone))
        )
        if exists.scalars().first() is not None:
            raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="该手机号已存在")

        if position_id is not None:
            if await session.get(WikiPosition, position_id) is None:
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="岗位不存在")

        password_hash, password_salt = build_password_fields(DEFAULT_USER_PASSWORD)
        user = WikiUser(
            username=phone,
            phone=phone,
            display_name=display_name,
            email=(data.get("email") or "").strip() or None,
            password_hash=password_hash,
            password_salt=password_salt,
            position_id=position_id,
            store_name=store_name,
            role=role,
            status="active",
            created_at=datetime.now(),
        )
        session.add(user)
        await session.flush()
        session.add(WikiUserProfile(user_id=user.id, profile_generated=False))
        await session.commit()
        user_id = user.id

    logger.info("[Admin] 新建用户: %s(%s)", display_name, phone)
    return {"success": True, "id": user_id, "initialPassword": DEFAULT_USER_PASSWORD}


@router.post("/admin/users/{user_id}/reset-password")
async def reset_password(
    user_id: str,
    _: WikiUser = Depends(require_admin),
):
    """把指定用户的密码重置为初始密码。"""
    password_hash, password_salt = build_password_fields(DEFAULT_USER_PASSWORD)

    async with AsyncSessionLocal() as session:
        user = await session.get(WikiUser, user_id)
        if user is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
        user.password_hash = password_hash
        user.password_salt = password_salt
        await session.commit()
        username = user.username

    logger.info("[Admin] 重置用户密码: %s", username)
    return {"success": True, "initialPassword": DEFAULT_USER_PASSWORD}


@router.patch("/admin/users/{user_id}")
async def update_user(
    user_id: str,
    data: dict = Body(...),
    _: WikiUser = Depends(require_admin),
):
    """更新用户的岗位、门店、角色或启用状态。"""
    async with AsyncSessionLocal() as session:
        user = await session.get(WikiUser, user_id)
        if user is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

        if "positionId" in data:
            position_id = (data.get("positionId") or "").strip() or None
            if position_id is not None and await session.get(WikiPosition, position_id) is None:
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="岗位不存在")
            # 岗位变更后画像需要重新生成
            if position_id != user.position_id:
                profile = (
                    await session.execute(
                        select(WikiUserProfile).where(WikiUserProfile.user_id == user_id)
                    )
                ).scalars().first()
                if profile is not None:
                    profile.profile_generated = False
            user.position_id = position_id

        if "storeName" in data:
            user.store_name = (data.get("storeName") or "").strip() or None
        if "displayName" in data:
            new_name = (data.get("displayName") or "").strip()
            if new_name:
                user.display_name = new_name
        if "role" in data:
            role = (data.get("role") or "").strip()
            if role not in ("user", "admin"):
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="角色只能是 user 或 admin")
            user.role = role
        if "status" in data:
            new_status = (data.get("status") or "").strip()
            if new_status not in ("active", "disabled"):
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="状态只能是 active 或 disabled")
            user.status = new_status

        await session.commit()

    return {"success": True}


# ==================================== 岗位模板 ====================================


@router.get("/admin/positions")
async def list_positions(
    only_missing: bool = Query(default=False, description="只看缺职责模板的岗位"),
    _: WikiUser = Depends(require_admin),
):
    """岗位列表。`only_missing=true` 用于筛出需要人工补模板的岗位。"""
    async with AsyncSessionLocal() as session:
        stmt = select(WikiPosition)
        if only_missing:
            stmt = stmt.where(WikiPosition.template_missing.is_(True))
        stmt = stmt.order_by(WikiPosition.dept_l1, WikiPosition.dept_l2, WikiPosition.name)
        positions = (await session.execute(stmt)).scalars().all()
        items = [_position_payload(p) for p in positions]

    return {"success": True, "total": len(items), "items": items}


@router.patch("/admin/positions/{position_id}")
async def update_position(
    position_id: str,
    data: dict = Body(...),
    _: WikiUser = Depends(require_admin),
):
    """维护岗位的职责与常用操作模板。"""
    async with AsyncSessionLocal() as session:
        position = await session.get(WikiPosition, position_id)
        if position is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="岗位不存在")

        if "dutyTemplate" in data:
            position.duty_template = data.get("dutyTemplate") or None
        if "commonOpsTemplate" in data:
            position.common_ops_template = data.get("commonOpsTemplate") or None

        # 职责模板补齐后自动摘掉「待补充」标记
        position.template_missing = not bool((position.duty_template or "").strip())
        await session.commit()
        payload = _position_payload(position)

    return {"success": True, "position": payload}