81 lines
3.0 KiB
Python
81 lines
3.0 KiB
Python
from __future__ import annotations
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Path
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.dependencies import get_admin_user, get_db
|
|
from app.models.user import User
|
|
from app.models.virtual_portrait_v3.api_key_quota import VpV3ApiKeyQuota
|
|
from app.schemas.admin_api.vp_v3_quota import (
|
|
VpV3QuotaConfigData,
|
|
VpV3QuotaConfigResponse,
|
|
)
|
|
from app.services.api_v3 import key_service
|
|
from app.services.virtual_portrait_v3.quota_service import get_quota
|
|
|
|
router = APIRouter(prefix="/admin/api-keys", tags=["admin-vp-v3-quota"])
|
|
|
|
|
|
def _to_response(quota: VpV3ApiKeyQuota) -> VpV3QuotaConfigResponse:
|
|
enabled = any([
|
|
(quota.project_limit or 0) > 0,
|
|
(quota.asset_limit or 0) > 0,
|
|
(quota.storage_mb_limit or 0) > 0,
|
|
])
|
|
return VpV3QuotaConfigResponse(
|
|
api_key_id=quota.api_key_id,
|
|
project_limit=int(quota.project_limit or 0),
|
|
asset_limit=int(quota.asset_limit or 0),
|
|
storage_mb_limit=int(quota.storage_mb_limit or 0),
|
|
remark=quota.remark,
|
|
project_used=int(quota.project_used or 0),
|
|
asset_used=int(quota.asset_used or 0),
|
|
storage_mb_used=float(quota.storage_mb_used or 0),
|
|
enabled=enabled,
|
|
)
|
|
|
|
|
|
@router.get(
|
|
"/{key_id}/vp-v3-quota",
|
|
response_model=VpV3QuotaConfigResponse,
|
|
summary="获取 API Key 的虚拟素材库配额配置",
|
|
description="返回指定 API Key 的虚拟素材库配额上限及当前使用量。不存在配额记录时自动创建默认 0 值。",
|
|
)
|
|
async def get_vp_v3_quota(
|
|
key_id: str = Path(..., description="API Key ID"),
|
|
admin: User = Depends(get_admin_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> VpV3QuotaConfigResponse:
|
|
key = await key_service.get_api_key(db, key_id)
|
|
if not key:
|
|
raise HTTPException(status_code=404, detail="API Key 不存在")
|
|
quota = await get_quota(db, api_key_id=key_id, refresh=True)
|
|
await db.commit()
|
|
return _to_response(quota)
|
|
|
|
|
|
@router.post(
|
|
"/{key_id}/vp-v3-quota",
|
|
response_model=VpV3QuotaConfigResponse,
|
|
summary="保存 API Key 的虚拟素材库配额配置",
|
|
description="保存虚拟素材库配额(项目数/素材数/存储 MB),默认 0=不可使用该功能。保存后自动刷新已使用量。",
|
|
)
|
|
async def save_vp_v3_quota(
|
|
payload: VpV3QuotaConfigData,
|
|
key_id: str = Path(..., description="API Key ID"),
|
|
admin: User = Depends(get_admin_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> VpV3QuotaConfigResponse:
|
|
key = await key_service.get_api_key(db, key_id)
|
|
if not key:
|
|
raise HTTPException(status_code=404, detail="API Key 不存在")
|
|
quota = await get_quota(db, api_key_id=key_id, refresh=True)
|
|
quota.project_limit = int(payload.project_limit or 0)
|
|
quota.asset_limit = int(payload.asset_limit or 0)
|
|
quota.storage_mb_limit = int(payload.storage_mb_limit or 0)
|
|
quota.remark = payload.remark if payload.remark is not None else quota.remark
|
|
await db.flush()
|
|
await db.refresh(quota)
|
|
await db.commit()
|
|
return _to_response(quota)
|