From 574d2094e539e1303a15bfadd00d1ac49d16a04c Mon Sep 17 00:00:00 2001 From: Vladimir Date: Fri, 5 Dec 2025 15:47:17 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9D=D0=B5=D0=BA=D0=BE=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D1=8B=D0=B5=20=D0=BF=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= =?UTF-8?q?=20=D1=87=D1=82=D0=BE=20=D0=B1=D1=8B=20=D0=B2=D1=81=D1=91=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=D0=BB=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/routes/subscription_routes.py | 45 ++++++++++++++++++++----------- app/routes/user_routes.py | 35 +++++++++++++++++------- app/services/postgres_rep.py | 1 + 3 files changed, 55 insertions(+), 26 deletions(-) diff --git a/app/routes/subscription_routes.py b/app/routes/subscription_routes.py index 6147201..2104c0a 100644 --- a/app/routes/subscription_routes.py +++ b/app/routes/subscription_routes.py @@ -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") diff --git a/app/routes/user_routes.py b/app/routes/user_routes.py index 67ad455..f5c6656 100644 --- a/app/routes/user_routes.py +++ b/app/routes/user_routes.py @@ -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, diff --git a/app/services/postgres_rep.py b/app/services/postgres_rep.py index d5431a4..3c165bb 100644 --- a/app/services/postgres_rep.py +++ b/app/services/postgres_rep.py @@ -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()