Некоторые поправки что бы всё работало

This commit is contained in:
2025-12-05 15:47:17 +03:00
parent f16cb3bc2e
commit 574d2094e5
3 changed files with 55 additions and 26 deletions

View File

@@ -129,26 +129,39 @@ async def get_subscriptions(telegram_id: int, database_manager: DatabaseManager
logger.info(f"Получение подписок для пользователя: {telegram_id}") logger.info(f"Получение подписок для пользователя: {telegram_id}")
try: try:
# Получаем подписки без ограничений или с указанным лимитом # Получаем подписки без ограничений или с указанным лимитом
subscriptions = await database_manager.get_last_subscriptions(telegram_id=telegram_id) subscription = await database_manager.get_last_subscriptions(telegram_id=telegram_id)
if not subscriptions: if not subscription:
logger.warning(f"Подписки для пользователя {telegram_id} не найдены") logger.warning(f"Подписки для пользователя {telegram_id} не найдены")
raise HTTPException(status_code=404, detail="No subscriptions found") raise HTTPException(status_code=404, detail="No subscriptions found")
plan = await database_manager.get_plan_by_id(subscription.plan_id)
if not plan:
logger.warning(f"Тариф для подписки {subscription.id} не найден")
plan_name = "Unknown"
else:
plan_name = plan.name
# Формируем список подписок для ответа # Формируем список подписок для ответа
return [ # return [
{ # {
"id": sub.id, # "id": sub.id,
"plan": sub.plan, # "plan": sub.plan,
"vpn_server_id": sub.vpn_server_id, # "vpn_server_id": sub.vpn_server_id,
"expiry_date": sub.expiry_date.isoformat(), # "expiry_date": sub.expiry_date.isoformat(),
"created_at": sub.created_at.isoformat(), # "created_at": sub.created_at.isoformat(),
"updated_at": sub.updated_at.isoformat(), # "updated_at": sub.updated_at.isoformat(),
} # }
for sub in subscriptions # for sub in subscription
] # ]
except HTTPException as e: return [{
raise e "id": str(subscription.id), # Конвертируем UUID в строку
"user_id": subscription.user_id,
"plan_name": plan_name,
"vpn_server_id": subscription.vpn_server_id,
"end_date": subscription.end_date.isoformat(),
"status": subscription.status.value, # Извлекаем значение enum
"start_date": subscription.start_date.isoformat(),
"created_at": subscription.created_at.isoformat()
}]
except SQLAlchemyError as e: except SQLAlchemyError as e:
logger.error(f"Ошибка базы данных при получении подписок для пользователя {telegram_id}: {e}") logger.error(f"Ошибка базы данных при получении подписок для пользователя {telegram_id}: {e}")
raise HTTPException(status_code=500, detail="Database error") raise HTTPException(status_code=500, detail="Database error")

View File

@@ -1,3 +1,4 @@
from datetime import datetime
import sys import sys
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from fastapi.exceptions import HTTPException from fastapi.exceptions import HTTPException
@@ -108,7 +109,7 @@ async def last_transactions(
""" """
logger.info(f"Получен запрос на транзакции для пользователя: {telegram_id}") logger.info(f"Получен запрос на транзакции для пользователя: {telegram_id}")
try: try:
logger.info(f"Вызов метода get_transaction с user_id={telegram_id}") logger.debug(f"Вызов метода get_transaction с user_id={telegram_id}")
transactions = await db_manager.get_transaction(telegram_id) transactions = await db_manager.get_transaction(telegram_id)
if transactions == "ERROR": if transactions == "ERROR":
@@ -118,15 +119,30 @@ async def last_transactions(
response = [] response = []
logger.info(f"Формирование ответа для пользователя {telegram_id}: {response}") logger.info(f"Формирование ответа для пользователя {telegram_id}: {response}")
return response return response
logger.info(f"Транзакции для {telegram_id}: {transactions}")
response = [ logger.debug(f"Транзакции для {telegram_id}: {transactions}")
{ response = []
for tx in transactions:
# Проверяем, что транзакция существует и имеет created_at
if tx is None:
continue
if tx.status.value == "pending":
continue
# Обрабатываем created_at (может быть None)
created_at_str = None
if tx.created_at:
created_at_str = tx.created_at.isoformat()
else:
created_at_str = datetime.utcnow().isoformat() # или любое значение по умолчанию
response.append({
"id": tx.id, "id": tx.id,
"amount": tx.amount, "amount": float(tx.amount) if tx.amount else 0.0,
"created_at": tx.created_at.isoformat(), "created_at": created_at_str,
"type": tx.type, "type": tx.type.value if hasattr(tx.type, 'value') else str(tx.type),
} for tx in transactions })
]
logger.info(f"Формирование ответа для пользователя {telegram_id}: {response}") logger.info(f"Формирование ответа для пользователя {telegram_id}: {response}")
return response return response
@@ -143,7 +159,6 @@ async def last_transactions(
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
@router.post("/user/{referrer_id}/add_referral", summary="Обновить баланс") @router.post("/user/{referrer_id}/add_referral", summary="Обновить баланс")
async def add_referal( async def add_referal(
referrer_id: int, referrer_id: int,

View File

@@ -123,6 +123,7 @@ class PostgresRepository:
select(Subscription) select(Subscription)
.where(Subscription.user_id == user_telegram_id) .where(Subscription.user_id == user_telegram_id)
.order_by(desc(Subscription.created_at)) .order_by(desc(Subscription.created_at))
.options(joinedload(Subscription.plan))
.limit(1) .limit(1)
) )
subscription = result.scalars().first() subscription = result.scalars().first()