Некоторые поправки что бы всё работало
This commit is contained in:
@@ -129,26 +129,39 @@ async def get_subscriptions(telegram_id: int, database_manager: DatabaseManager
|
||||
logger.info(f"Получение подписок для пользователя: {telegram_id}")
|
||||
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} не найдены")
|
||||
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 [
|
||||
{
|
||||
"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
|
||||
]
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
# 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 subscription
|
||||
# ]
|
||||
return [{
|
||||
"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:
|
||||
logger.error(f"Ошибка базы данных при получении подписок для пользователя {telegram_id}: {e}")
|
||||
raise HTTPException(status_code=500, detail="Database error")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from datetime import datetime
|
||||
import sys
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.exceptions import HTTPException
|
||||
@@ -108,7 +109,7 @@ async def last_transactions(
|
||||
"""
|
||||
logger.info(f"Получен запрос на транзакции для пользователя: {telegram_id}")
|
||||
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)
|
||||
|
||||
if transactions == "ERROR":
|
||||
@@ -118,15 +119,30 @@ async def last_transactions(
|
||||
response = []
|
||||
logger.info(f"Формирование ответа для пользователя {telegram_id}: {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,
|
||||
"amount": tx.amount,
|
||||
"created_at": tx.created_at.isoformat(),
|
||||
"type": tx.type,
|
||||
} for tx in transactions
|
||||
]
|
||||
"amount": float(tx.amount) if tx.amount else 0.0,
|
||||
"created_at": created_at_str,
|
||||
"type": tx.type.value if hasattr(tx.type, 'value') else str(tx.type),
|
||||
})
|
||||
|
||||
logger.info(f"Формирование ответа для пользователя {telegram_id}: {response}")
|
||||
return response
|
||||
|
||||
@@ -143,7 +159,6 @@ async def last_transactions(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
|
||||
@router.post("/user/{referrer_id}/add_referral", summary="Обновить баланс")
|
||||
async def add_referal(
|
||||
referrer_id: int,
|
||||
|
||||
@@ -123,6 +123,7 @@ class PostgresRepository:
|
||||
select(Subscription)
|
||||
.where(Subscription.user_id == user_telegram_id)
|
||||
.order_by(desc(Subscription.created_at))
|
||||
.options(joinedload(Subscription.plan))
|
||||
.limit(1)
|
||||
)
|
||||
subscription = result.scalars().first()
|
||||
|
||||
Reference in New Issue
Block a user