Рефакторинга чуть чуть вроде
This commit is contained in:
@@ -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