accounts.py 3.58 KB
"""账号 API 路由"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.schemas.account import (
    AccountCreate, AccountUpdate, AccountResponse, AccountListResponse, AccountStatusUpdate, DecryptedKeyResponse
)
from app.services import account_service

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/accounts", tags=["模型账号配置"])


@router.post("", status_code=201)
async def create_account(data: AccountCreate, db: AsyncSession = Depends(get_db)):
    """新增模型账号(API Key 加密存储)"""
    try:
        return await account_service.create_account(db, data)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.put("/{account_id}")
async def update_account(account_id: str, data: AccountUpdate, db: AsyncSession = Depends(get_db)):
    """编辑模型账号信息"""
    result = await account_service.update_account(db, account_id, data)
    if not result:
        raise HTTPException(status_code=404, detail="账号不存在")
    return result


@router.get("")
async def list_accounts(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页条数"),
    provider_id: Optional[str] = Query(None, description="按供应商筛选"),
    model_name: Optional[str] = Query(None, description="按模型名称筛选"),
    status: Optional[str] = Query(None, description="按状态筛选:active/disabled"),
    keyword: Optional[str] = Query(None, description="关键词搜索"),
    db: AsyncSession = Depends(get_db),
):
    """分页查询模型账号列表(API Key 脱敏返回)"""
    return await account_service.list_accounts(
        db=db, page=page, page_size=page_size,
        provider_id=provider_id, model_name=model_name,
        status=status, keyword=keyword,
    )


@router.get("/decrypt-key/{account_id}", response_model=DecryptedKeyResponse)
async def get_decrypted_key(account_id: str, db: AsyncSession = Depends(get_db)):
    """获取解密后的 API Key(用于编辑时明文查看,需认证)"""
    result = await account_service.get_decrypted_api_key(db, account_id)
    if not result:
        raise HTTPException(status_code=404, detail="账号不存在")
    return {"api_key": result}


@router.get("/{account_id}")
async def get_account(account_id: str, db: AsyncSession = Depends(get_db)):
    """查询账号详情(API Key 脱敏返回)"""
    result = await account_service.get_account(db, account_id)
    if not result:
        raise HTTPException(status_code=404, detail="账号不存在")
    return result


@router.patch("/{account_id}/status")
async def update_account_status(account_id: str, data: AccountStatusUpdate, db: AsyncSession = Depends(get_db)):
    """启用/停用账号"""
    if data.status not in ("active", "disabled"):
        raise HTTPException(status_code=400, detail="状态值无效,仅支持 active/disabled")
    result = await account_service.update_account_status(db, account_id, data)
    if not result:
        raise HTTPException(status_code=404, detail="账号不存在")
    return result


@router.delete("/{account_id}")
async def delete_account(account_id: str, db: AsyncSession = Depends(get_db)):
    """删除账号,同时级联删除关联的调用策略"""
    result = await account_service.delete_account(db, account_id)
    if not result:
        raise HTTPException(status_code=404, detail="账号不存在")
    return {"message": "删除成功"}