Сделаны подписки и переделаны роуты
This commit is contained in:
@@ -1,15 +1,17 @@
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from pydantic import BaseModel
|
||||
from app.services.db_manager import DatabaseManager
|
||||
from instance.configdb import get_database_manager
|
||||
from uuid import UUID
|
||||
import logging
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# DatabaseManager должен передаваться через Depends
|
||||
def get_database_manager():
|
||||
# Здесь должна быть логика инициализации DatabaseManager
|
||||
return DatabaseManager()
|
||||
|
||||
# Схемы запросов и ответов
|
||||
class BuySubscriptionRequest(BaseModel):
|
||||
telegram_id: int
|
||||
plan_id: str
|
||||
@@ -38,6 +40,10 @@ async def buy_subscription(
|
||||
raise HTTPException(status_code=500, detail="Failed to buy subscription")
|
||||
elif result == "INSUFFICIENT_FUNDS":
|
||||
raise HTTPException(status_code=400, detail="Insufficient funds")
|
||||
elif result == "TARIFF_NOT_FOUND":
|
||||
raise HTTPException(status_code=400, detail="Tariff not found")
|
||||
elif result == "ACTIVE_SUBSCRIPTION_EXISTS":
|
||||
raise HTTPException(status_code=400, detail="User already had subscription",)
|
||||
|
||||
return {"message": "Subscription purchased successfully"}
|
||||
except Exception as e:
|
||||
@@ -45,28 +51,27 @@ async def buy_subscription(
|
||||
|
||||
|
||||
# Эндпоинт для получения последней подписки
|
||||
@router.get("/subscription/{user_id}/last", response_model=list[SubscriptionResponse])
|
||||
async def last_subscription(
|
||||
user_id: int,
|
||||
database_manager: DatabaseManager = Depends(get_database_manager)
|
||||
):
|
||||
"""
|
||||
Получение последней подписки пользователя.
|
||||
"""
|
||||
@router.get("/subscription/{user_id}/last", response_model=SubscriptionResponse)
|
||||
async def last_subscription(user_id: UUID, database_manager: DatabaseManager = Depends(get_database_manager)):
|
||||
logger.info(f"Получение последней подписки для пользователя: {user_id}")
|
||||
try:
|
||||
subscriptions = await database_manager.last_subscription(user_id)
|
||||
if subscriptions == "ERROR":
|
||||
raise HTTPException(status_code=500, detail="Failed to fetch subscriptions")
|
||||
|
||||
return [
|
||||
{
|
||||
"id": sub.id,
|
||||
"plan": sub.plan,
|
||||
"vpn_server_id": sub.vpn_server_id,
|
||||
"expiry_date": sub.expiry_date.isoformat(),
|
||||
"created_at": sub.created_at.isoformat(),
|
||||
"updated_at": sub.updated_at.isoformat(),
|
||||
} for sub in subscriptions
|
||||
]
|
||||
sub = await database_manager.last_subscription(user_id)
|
||||
if sub is None:
|
||||
logger.warning(f"Подписки для пользователя {user_id} не найдены")
|
||||
raise HTTPException(status_code=404, detail="No subscriptions found")
|
||||
return {
|
||||
"id": sub.id,
|
||||
"plan": sub.plan,
|
||||
"vpn_server_id": sub.vpn_server_id,
|
||||
"expiry_date": sub.expiry_date.isoformat(),
|
||||
"created_at": sub.created_at.isoformat(),
|
||||
"updated_at": sub.updated_at.isoformat(),
|
||||
}
|
||||
except SQLAlchemyError as e:
|
||||
logger.error(f"Ошибка базы данных при получении подписки для пользователя {user_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Database error")
|
||||
except Exception as e:
|
||||
logger.error(f"Неожиданная ошибка: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user