Рефакторинга чуть чуть вроде
This commit is contained in:
@@ -38,17 +38,21 @@ async def buy_subscription(
|
||||
result = await database_manager.buy_sub(request_data.telegram_id, request_data.plan_id)
|
||||
|
||||
if result == "ERROR":
|
||||
raise HTTPException(status_code=500, detail="Failed to buy subscription")
|
||||
raise HTTPException(status_code=500, detail="ERROR")
|
||||
elif result == "INSUFFICIENT_FUNDS":
|
||||
raise HTTPException(status_code=400, detail="Insufficient funds")
|
||||
raise HTTPException(status_code=400, detail="INSUFFICIENT_FUNDS")
|
||||
elif result == "TARIFF_NOT_FOUND":
|
||||
raise HTTPException(status_code=400, detail="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"}
|
||||
raise HTTPException(status_code=400, detail="ACTIVE_SUBSCRIPTION_EXISTS")
|
||||
result = await database_manager.generate_uri(request_data.telegram_id)
|
||||
return {"message": result}
|
||||
except HTTPException as http_exc:
|
||||
# Пропускаем HTTPException, чтобы FastAPI обработал его корректно
|
||||
raise http_exc
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
# Обрабатываем остальные исключения
|
||||
raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")
|
||||
|
||||
|
||||
# Эндпоинт для получения последней подписки
|
||||
@@ -59,11 +63,12 @@ async def last_subscription(user_id: UUID, database_manager: DatabaseManager = D
|
||||
"""
|
||||
logger.info(f"Получение последней подписки для пользователя: {user_id}")
|
||||
try:
|
||||
subscriptions = await database_manager.last_subscriptions(user_id=str(user_id), limit=1)
|
||||
subscriptions = await database_manager.get_last_subscriptions(user_id=user_id, limit=1)
|
||||
|
||||
if not subscriptions:
|
||||
logger.warning(f"Подписки для пользователя {user_id} не найдены")
|
||||
raise HTTPException(status_code=404, detail="No subscriptions found")
|
||||
|
||||
sub = subscriptions[0]
|
||||
|
||||
return {
|
||||
@@ -77,9 +82,12 @@ async def last_subscription(user_id: UUID, database_manager: DatabaseManager = D
|
||||
except SQLAlchemyError as e:
|
||||
logger.error(f"Ошибка базы данных при получении подписки для пользователя {user_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Database error")
|
||||
except HTTPException as e:
|
||||
# Пропускаем HTTPException, чтобы FastAPI обработал её автоматически
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"Неожиданная ошибка: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
raise HTTPException(status_code=500, detail="Internal Server Error")
|
||||
|
||||
@router.get("/subscriptions/{user_id}", response_model=List[SubscriptionResponse])
|
||||
async def get_subscriptions(user_id: UUID, database_manager: DatabaseManager = Depends(get_database_manager)):
|
||||
@@ -114,3 +122,25 @@ async def get_subscriptions(user_id: UUID, database_manager: DatabaseManager = D
|
||||
logger.error(f"Неожиданная ошибка: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@router.get("/uri", response_model=dict)
|
||||
async def get_uri(telegram_id: int, database_manager: DatabaseManager = Depends(get_database_manager)):
|
||||
"""
|
||||
Возвращает список подписок пользователя.
|
||||
"""
|
||||
logger.info(f"Получение подписок для пользователя: {telegram_id}")
|
||||
try:
|
||||
# Получаем подписки без ограничений или с указанным лимитом
|
||||
uri = await database_manager.generate_uri(telegram_id)
|
||||
if uri == "SUB_ERROR":
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
if not uri:
|
||||
logger.warning(f"Не удалось сгенерировать URI для пользователя с telegram_id {telegram_id}")
|
||||
raise HTTPException(status_code=404, detail="URI not found")
|
||||
|
||||
return {"detail": uri }
|
||||
except SQLAlchemyError as e:
|
||||
logger.error(f"Ошибка базы данных при получении подписок для пользователя {telegram_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))
|
||||
@@ -43,8 +43,6 @@ def handle_exception(e: Exception, message: str):
|
||||
logger.error(f"{message}: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"{message}: {str(e)}")
|
||||
|
||||
|
||||
|
||||
@router.post("/support/tickets/{ticket_id}/messages", response_model=TicketMessageResponse, summary="Добавить сообщение")
|
||||
async def add_message(
|
||||
ticket_id: int,
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.exceptions import HTTPException
|
||||
from app.services.db_manager import DatabaseManager
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from instance.configdb import get_database_manager
|
||||
from pydantic import BaseModel
|
||||
from uuid import UUID
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -11,7 +17,7 @@ class CreateUserRequest(BaseModel):
|
||||
telegram_id: int
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: str
|
||||
id: UUID
|
||||
telegram_id: int
|
||||
username: str
|
||||
balance: float
|
||||
@@ -44,6 +50,7 @@ async def create_user(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
|
||||
@router.get("/user/{telegram_id}", response_model=UserResponse, summary="Получить информацию о пользователе")
|
||||
async def get_user(
|
||||
telegram_id: int,
|
||||
@@ -53,11 +60,15 @@ async def get_user(
|
||||
Получение информации о пользователе.
|
||||
"""
|
||||
try:
|
||||
logger.info(f"Получение пользователя с telegram_id: {telegram_id}")
|
||||
user = await db_manager.get_user_by_telegram_id(telegram_id)
|
||||
if not user:
|
||||
logger.warning(f"Пользователь с telegram_id {telegram_id} не найден.")
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
return UserResponse(
|
||||
logger.info(f"Пользователь найден: ID={user.id}, Username={user.username}")
|
||||
|
||||
user_response = UserResponse(
|
||||
id=user.id,
|
||||
telegram_id=user.telegram_id,
|
||||
username=user.username,
|
||||
@@ -65,9 +76,23 @@ async def get_user(
|
||||
created_at=user.created_at.isoformat(),
|
||||
updated_at=user.updated_at.isoformat()
|
||||
)
|
||||
logger.debug(f"Формирование ответа для пользователя: {user_response}")
|
||||
|
||||
return user_response
|
||||
|
||||
except HTTPException as http_ex: # Позволяет обработать HTTPException отдельно
|
||||
raise http_ex
|
||||
|
||||
except SQLAlchemyError as e:
|
||||
logger.error(f"Ошибка базы данных при получении пользователя с telegram_id {telegram_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Database error")
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Неожиданная ошибка при получении пользователя с telegram_id {telegram_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
|
||||
@router.post("/user/{telegram_id}/balance/{amount}", summary="Обновить баланс")
|
||||
async def update_balance(
|
||||
telegram_id: int,
|
||||
@@ -77,14 +102,26 @@ async def update_balance(
|
||||
"""
|
||||
Обновляет баланс пользователя.
|
||||
"""
|
||||
logger.info(f"Получен запрос на обновление баланса: telegram_id={telegram_id}, amount={amount}")
|
||||
try:
|
||||
result = await db_manager.update_balance(telegram_id, amount)
|
||||
if result == "ERROR":
|
||||
logger.error(f"Ошибка обновления баланса для пользователя {telegram_id}")
|
||||
raise HTTPException(status_code=500, detail="Failed to update balance")
|
||||
|
||||
logger.info(f"Баланс пользователя {telegram_id} успешно обновлен на {amount}")
|
||||
return {"message": "Balance updated successfully"}
|
||||
except HTTPException as http_ex:
|
||||
logger.warning(f"HTTP ошибка: {http_ex.detail}")
|
||||
raise http_ex
|
||||
except SQLAlchemyError as db_ex:
|
||||
logger.error(f"Ошибка базы данных при обновлении баланса пользователя {telegram_id}: {db_ex}")
|
||||
raise HTTPException(status_code=500, detail="Database error")
|
||||
except Exception as e:
|
||||
logger.exception(f"Неожиданная ошибка при обновлении баланса пользователя {telegram_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/user/{user_id}/transactions", summary="Последние транзакции пользователя")
|
||||
async def last_transactions(
|
||||
user_id: UUID,
|
||||
@@ -93,11 +130,17 @@ async def last_transactions(
|
||||
"""
|
||||
Возвращает список последних транзакций пользователя.
|
||||
"""
|
||||
logger.info(f"Получен запрос на транзакции для пользователя: {user_id}")
|
||||
try:
|
||||
transactions = await db_manager.last_transaction(user_id)
|
||||
logger.debug(f"Вызов метода get_transaction с user_id={user_id}")
|
||||
transactions = await db_manager.get_transaction(user_id)
|
||||
|
||||
if transactions == "ERROR":
|
||||
logger.error(f"Ошибка при получении транзакций для пользователя: {user_id}")
|
||||
raise HTTPException(status_code=500, detail="Failed to fetch transactions")
|
||||
return [
|
||||
|
||||
logger.debug(f"Транзакции для {user_id}: {transactions}")
|
||||
response = [
|
||||
{
|
||||
"id": tx.id,
|
||||
"amount": tx.amount,
|
||||
@@ -105,5 +148,17 @@ async def last_transactions(
|
||||
"transaction_type": tx.transaction_type,
|
||||
} for tx in transactions
|
||||
]
|
||||
logger.info(f"Формирование ответа для пользователя {user_id}: {response}")
|
||||
return response
|
||||
|
||||
except HTTPException as http_ex:
|
||||
logger.warning(f"HTTP ошибка для {user_id}: {http_ex.detail}")
|
||||
raise http_ex
|
||||
|
||||
except SQLAlchemyError as db_ex:
|
||||
logger.error(f"Ошибка базы данных для {user_id}: {db_ex}")
|
||||
raise HTTPException(status_code=500, detail="Database error")
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Неожиданная ошибка для {user_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
Reference in New Issue
Block a user