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

全部接口要求 role=admin。
"""
import asyncio
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
from src.services.memory.profile_gen import generate_profile
from src.services.memory.store import get_memory_store

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),
):
    """更新用户的岗位、门店、角色或启用状态。"""
    position_changed = False
    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:
                position_changed = True
                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()

    # 岗位变更:立即异步重生成用户画像,无需等用户下次登录
    if position_changed:
        asyncio.create_task(_regenerate_quietly(user_id))

    return {"success": True}


async def _regenerate_quietly(user_id: str) -> None:
    """后台重生成画像,任何异常都不影响主请求。"""
    try:
        await generate_profile(user_id, force=True)
    except Exception as exc:
        logger.warning("[Admin] 改岗后重生成画像失败(不影响): user_id=%s err=%s", user_id, exc)


# ==================================== 用户画像(管理员可编辑) ====================================


@router.get("/admin/users/{user_id}/profile")
async def get_user_profile(
    user_id: str,
    _: WikiUser = Depends(require_admin),
):
    """读取指定用户的岗位画像与长期记忆,供管理员查看/编辑。

    与用户自查的 `/profile` 不同:这里的 `agentMd` 返回**未剥离元信息**的原文
    (含 `<!-- hits:N last:... -->`),因为管理员是直接编辑档案本身。
    """
    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="用户不存在")

        record = (
            await session.execute(
                select(WikiUserProfile).where(WikiUserProfile.user_id == user_id)
            )
        ).scalars().first()

        profile_md = (record.profile_md if record else "") or ""
        agent_md = (record.agent_md if record else "") or ""
        generated = bool(record.profile_generated) if record else False
        version = (record.profile_version if record else 1) or 1
        display_name = user.display_name

    stats = await get_memory_store().stats(user_id)

    return {
        "success": True,
        "userId": user_id,
        "displayName": display_name,
        "profileMd": profile_md,
        "agentMd": agent_md,
        "profileGenerated": generated,
        "profileVersion": version,
        "memoryStats": stats,
    }


@router.patch("/admin/users/{user_id}/profile")
async def update_user_profile(
    user_id: str,
    data: dict = Body(...),
    _: WikiUser = Depends(require_admin),
):
    """管理员编辑指定用户的岗位画像与/或长期记忆。

    - 写 `profileMd` 时置 `profile_generated=True`,避免该用户下次登录时被首登画像覆盖。
    - 写 `agentMd` 直接落 `agent_md` 字段,**不动** `reflected_upto_at` 沉淀游标
      (管理员手改不代表沉淀进度变化)。
    """
    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="用户不存在")

        record = (
            await session.execute(
                select(WikiUserProfile).where(WikiUserProfile.user_id == user_id)
            )
        ).scalars().first()
        if record is None:
            record = WikiUserProfile(user_id=user_id, profile_generated=False)
            session.add(record)

        if "profileMd" in data:
            record.profile_md = (data.get("profileMd") or "").strip() or None
            record.profile_generated = True
        if "agentMd" in data:
            record.agent_md = (data.get("agentMd") or "").strip() or None

        record.updated_at = datetime.now()
        await session.commit()

    logger.info("[Admin] 编辑用户画像: user_id=%s", user_id)
    return {"success": True}


@router.post("/admin/users/{user_id}/profile/regenerate")
async def regenerate_user_profile(
    user_id: str,
    _: WikiUser = Depends(require_admin),
):
    """管理员为指定用户重新生成岗位画像(例如改岗后)。"""
    result = await generate_profile(user_id, force=True)
    logger.info("[Admin] 重新生成用户画像: user_id=%s -> %s", user_id, result.get("action"))
    return {"success": result.get("action") == "generated", "detail": result}


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


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