Сделаны подписки и переделаны роуты
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
from .payment_routes import router as payment_router
|
||||
#from .payment_routes import router as payment_router
|
||||
from .user_routes import router as user_router
|
||||
from .subscription_routes import router as subscription_router
|
||||
|
||||
# Экспорт всех маршрутов
|
||||
__all__ = ["payment_router", "user_router", "subscription_router"]
|
||||
__all__ = [ "user_router", "subscription_router"]
|
||||
|
||||
0
app/routes/payment_routes.py
Normal file
0
app/routes/payment_routes.py
Normal file
@@ -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))
|
||||
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from app.services.db_manager import DatabaseManager
|
||||
from instance.configdb import get_database_manager
|
||||
from pydantic import BaseModel
|
||||
from uuid import UUID
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -66,3 +67,43 @@ async def get_user(
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.post("/user/{telegram_id}/balance/{amount}", summary="Обновить баланс")
|
||||
async def update_balance(
|
||||
telegram_id: int,
|
||||
amount: float,
|
||||
db_manager: DatabaseManager = Depends(get_database_manager)
|
||||
):
|
||||
"""
|
||||
Обновляет баланс пользователя.
|
||||
"""
|
||||
try:
|
||||
result = await db_manager.update_balance(telegram_id, amount)
|
||||
if result == "ERROR":
|
||||
raise HTTPException(status_code=500, detail="Failed to update balance")
|
||||
return {"message": "Balance updated successfully"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/user/{user_id}/transactions", summary="Последние транзакции пользователя")
|
||||
async def last_transactions(
|
||||
user_id: UUID,
|
||||
db_manager: DatabaseManager = Depends(get_database_manager)
|
||||
):
|
||||
"""
|
||||
Возвращает список последних транзакций пользователя.
|
||||
"""
|
||||
try:
|
||||
transactions = await db_manager.last_transaction(user_id)
|
||||
if transactions == "ERROR":
|
||||
raise HTTPException(status_code=500, detail="Failed to fetch transactions")
|
||||
return [
|
||||
{
|
||||
"id": tx.id,
|
||||
"amount": tx.amount,
|
||||
"created_at": tx.created_at.isoformat(),
|
||||
"transaction_type": tx.transaction_type,
|
||||
} for tx in transactions
|
||||
]
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
Reference in New Issue
Block a user