platform_stats_router.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. 平台统计和日志路由
  3. 提供调用统计和费用明细的API端点
  4. 需求: 11.1, 12.1
  5. """
  6. from datetime import date
  7. from typing import Optional
  8. from fastapi import APIRouter, Depends, Query
  9. from sqlalchemy.orm import Session
  10. from app.database import get_db
  11. from app.dependencies.auth import get_current_user
  12. from app.models.user import User
  13. from app.services.api_call_log_service import ApiCallLogService
  14. from app.schemas.platform_stats import StatsResponse, CallLogResponse
  15. from app.schemas.model_schema import ApiResponse, PaginatedResponse
  16. router = APIRouter(prefix="/api/platform", tags=["平台统计"])
  17. @router.get("/stats", response_model=ApiResponse[StatsResponse])
  18. def get_stats(
  19. trend_days: int = Query(default=7, ge=1, le=30, description="趋势数据天数"),
  20. key_type: Optional[str] = Query(None, description="密钥类型: public 或 local"),
  21. current_user: User = Depends(get_current_user),
  22. db: Session = Depends(get_db)
  23. ):
  24. """
  25. 获取调用统计
  26. 需求 11.1: 显示今日调用次数、本月调用次数、总调用次数
  27. 需求 11.2: 显示今日消费金额、本月消费金额
  28. 需求 11.3: 显示调用趋势图
  29. 需求 11.4: 显示各模型调用占比饼图
  30. """
  31. service = ApiCallLogService(db)
  32. stats = service.get_user_stats(current_user.id, trend_days, key_type)
  33. return ApiResponse(code=200, message="success", data=stats)
  34. @router.get("/call-logs", response_model=ApiResponse[PaginatedResponse[CallLogResponse]])
  35. def get_call_logs(
  36. start_date: Optional[date] = Query(None, description="开始日期"),
  37. end_date: Optional[date] = Query(None, description="结束日期"),
  38. model_id: Optional[int] = Query(None, description="模型ID"),
  39. api_key_id: Optional[int] = Query(None, description="API Key ID"),
  40. key_type: Optional[str] = Query(None, description="密钥类型: public 或 local"),
  41. page: int = Query(default=1, ge=1, description="页码"),
  42. page_size: int = Query(default=20, ge=1, le=100, description="每页数量"),
  43. current_user: User = Depends(get_current_user),
  44. db: Session = Depends(get_db)
  45. ):
  46. """
  47. 获取调用日志
  48. 需求 12.1: 支持按时间范围、模型、API Key进行筛选
  49. 需求 12.2: 显示调用时间、模型名称、Token用量、费用金额、使用的API Key
  50. 需求 12.4: 支持分页查询
  51. """
  52. service = ApiCallLogService(db)
  53. logs, total = service.get_call_logs(
  54. user_id=current_user.id,
  55. start_date=start_date,
  56. end_date=end_date,
  57. model_id=model_id,
  58. api_key_id=api_key_id,
  59. key_type=key_type,
  60. page=page,
  61. page_size=page_size
  62. )
  63. return ApiResponse(
  64. code=200,
  65. message="success",
  66. data=PaginatedResponse(
  67. items=logs,
  68. total=total,
  69. page=page,
  70. page_size=page_size,
  71. total_pages=(total + page_size - 1) // page_size
  72. )
  73. )