Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
711b9a2487 | ||
|
|
6e7eb6acfd | ||
|
|
b42fae8772 | ||
|
|
f707662125 | ||
|
|
60c6e0e961 | ||
|
|
b23b75b72e | ||
|
|
c69f02f7c0 | ||
|
|
f22e359684 | ||
|
|
d2402fea77 | ||
|
|
9b8ddb39da | ||
|
|
459b655ae3 | ||
|
|
d81ab4137d | ||
|
|
cb6ae1e052 | ||
|
|
f4e2ae5fbd | ||
|
|
157c3a7c61 | ||
|
|
ef9ebc1918 | ||
|
|
87664a7735 | ||
|
|
3d58f60a4d | ||
|
|
a75a1f483c | ||
|
|
70d472e71c | ||
|
|
13a9e58e27 | ||
|
|
7219a6ac30 |
@@ -76,6 +76,8 @@ SUBSCRIPTION_NOTIFY_ON_EXPIRE=True
|
||||
SUBSCRIPTION_NOTIFY_AFTER_EXPIRE=True
|
||||
SUBSCRIPTION_NOTIFY_DAYS_BEFORE=3
|
||||
|
||||
|
||||
REFERRAL_ONE_BONUS_PER_REFEREE=False
|
||||
# Referral Bonus Days
|
||||
REFERRAL_BONUS_DAYS_1_MONTH=3
|
||||
REFERRAL_BONUS_DAYS_3_MONTHS=7
|
||||
|
||||
@@ -28,7 +28,6 @@
|
||||
- **aiohttp:** Для запуска веб-сервера (вебхуки).
|
||||
- **SQLAlchemy 2.x & asyncpg:** Асинхронная работа с базой данных PostgreSQL.
|
||||
- **YooKassa, aiocryptopay:** SDK для интеграции с платежными системами.
|
||||
- **APScheduler:** Для выполнения отложенных задач (например, уведомления об окончании подписки).
|
||||
- **Pydantic:** Для управления настройками из `.env` файла.
|
||||
- **Docker & Docker Compose:** Для контейнеризации и развертывания.
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import logging
|
||||
from typing import Dict
|
||||
|
||||
from aiogram import Bot, Dispatcher
|
||||
from aiogram.enums import ParseMode
|
||||
from aiogram.client.default import DefaultBotProperties
|
||||
from aiogram.fsm.storage.memory import MemoryStorage
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from config.settings import Settings
|
||||
from bot.middlewares.db_session import DBSessionMiddleware
|
||||
from bot.middlewares.i18n import I18nMiddleware, get_i18n_instance, JsonI18n
|
||||
from bot.middlewares.ban_check_middleware import BanCheckMiddleware
|
||||
from bot.middlewares.action_logger_middleware import ActionLoggerMiddleware
|
||||
from bot.middlewares.profile_sync import ProfileSyncMiddleware
|
||||
|
||||
|
||||
def build_dispatcher(settings: Settings, async_session_factory: sessionmaker) -> tuple[Dispatcher, Bot, Dict]:
|
||||
storage = MemoryStorage()
|
||||
default_props = DefaultBotProperties(parse_mode=ParseMode.HTML)
|
||||
bot = Bot(token=settings.BOT_TOKEN, default=default_props)
|
||||
|
||||
dp = Dispatcher(storage=storage, settings=settings, bot_instance=bot)
|
||||
|
||||
i18n_instance = get_i18n_instance(path="locales", default=settings.DEFAULT_LANGUAGE)
|
||||
|
||||
dp["i18n_instance"] = i18n_instance
|
||||
dp["async_session_factory"] = async_session_factory
|
||||
|
||||
dp.update.outer_middleware(DBSessionMiddleware(async_session_factory))
|
||||
dp.update.outer_middleware(I18nMiddleware(i18n=i18n_instance, settings=settings))
|
||||
dp.update.outer_middleware(ProfileSyncMiddleware())
|
||||
dp.update.outer_middleware(BanCheckMiddleware(settings=settings, i18n_instance=i18n_instance))
|
||||
dp.update.outer_middleware(ActionLoggerMiddleware(settings=settings))
|
||||
|
||||
return dp, bot, {"i18n_instance": i18n_instance}
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
from aiogram import Bot
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from config.settings import Settings
|
||||
from bot.middlewares.i18n import JsonI18n
|
||||
from bot.services.yookassa_service import YooKassaService
|
||||
from bot.services.panel_api_service import PanelApiService
|
||||
from bot.services.subscription_service import SubscriptionService
|
||||
from bot.services.referral_service import ReferralService
|
||||
from bot.services.promo_code_service import PromoCodeService
|
||||
from bot.services.stars_service import StarsService
|
||||
from bot.services.tribute_service import TributeService
|
||||
from bot.services.crypto_pay_service import CryptoPayService
|
||||
from bot.services.panel_webhook_service import PanelWebhookService
|
||||
|
||||
|
||||
def build_core_services(
|
||||
settings: Settings,
|
||||
bot: Bot,
|
||||
async_session_factory: sessionmaker,
|
||||
i18n: JsonI18n,
|
||||
bot_username_for_default_return: str,
|
||||
):
|
||||
panel_service = PanelApiService(settings)
|
||||
subscription_service = SubscriptionService(settings, panel_service, bot, i18n)
|
||||
referral_service = ReferralService(settings, subscription_service, bot, i18n)
|
||||
promo_code_service = PromoCodeService(settings, subscription_service, bot, i18n)
|
||||
stars_service = StarsService(bot, settings, i18n, subscription_service, referral_service)
|
||||
cryptopay_service = CryptoPayService(
|
||||
settings.CRYPTOPAY_TOKEN,
|
||||
settings.CRYPTOPAY_NETWORK,
|
||||
bot,
|
||||
settings,
|
||||
i18n,
|
||||
async_session_factory,
|
||||
subscription_service,
|
||||
referral_service,
|
||||
)
|
||||
tribute_service = TributeService(
|
||||
bot,
|
||||
settings,
|
||||
i18n,
|
||||
async_session_factory,
|
||||
panel_service,
|
||||
subscription_service,
|
||||
referral_service,
|
||||
)
|
||||
panel_webhook_service = PanelWebhookService(bot, settings, i18n, async_session_factory)
|
||||
yookassa_service = YooKassaService(
|
||||
shop_id=settings.YOOKASSA_SHOP_ID,
|
||||
secret_key=settings.YOOKASSA_SECRET_KEY,
|
||||
configured_return_url=settings.YOOKASSA_RETURN_URL,
|
||||
bot_username_for_default_return=bot_username_for_default_return,
|
||||
settings_obj=settings,
|
||||
)
|
||||
|
||||
return {
|
||||
"panel_service": panel_service,
|
||||
"subscription_service": subscription_service,
|
||||
"referral_service": referral_service,
|
||||
"promo_code_service": promo_code_service,
|
||||
"stars_service": stars_service,
|
||||
"cryptopay_service": cryptopay_service,
|
||||
"tribute_service": tribute_service,
|
||||
"panel_webhook_service": panel_webhook_service,
|
||||
"yookassa_service": yookassa_service,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from aiohttp import web
|
||||
from aiogram import Bot, Dispatcher
|
||||
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from config.settings import Settings
|
||||
|
||||
|
||||
async def build_and_start_web_app(
|
||||
dp: Dispatcher,
|
||||
bot: Bot,
|
||||
settings: Settings,
|
||||
async_session_factory: sessionmaker,
|
||||
):
|
||||
app = web.Application()
|
||||
app["bot"] = bot
|
||||
app["dp"] = dp
|
||||
app["settings"] = settings
|
||||
app["async_session_factory"] = async_session_factory
|
||||
# Inject shared instances used by webhook handlers
|
||||
app["i18n"] = dp.get("i18n_instance")
|
||||
for key in (
|
||||
"yookassa_service",
|
||||
"subscription_service",
|
||||
"referral_service",
|
||||
"panel_service",
|
||||
"stars_service",
|
||||
"cryptopay_service",
|
||||
"tribute_service",
|
||||
"panel_webhook_service",
|
||||
):
|
||||
# Access dispatcher workflow_data directly to avoid sequence protocol issues
|
||||
if hasattr(dp, "workflow_data") and key in dp.workflow_data: # type: ignore
|
||||
app[key] = dp.workflow_data[key] # type: ignore
|
||||
|
||||
setup_application(app, dp, bot=bot)
|
||||
|
||||
telegram_uses_webhook_mode = bool(settings.WEBHOOK_BASE_URL)
|
||||
|
||||
if telegram_uses_webhook_mode:
|
||||
telegram_webhook_path = f"/{settings.BOT_TOKEN}"
|
||||
app.router.add_post(telegram_webhook_path, SimpleRequestHandler(dispatcher=dp, bot=bot))
|
||||
logging.info(
|
||||
f"Telegram webhook route configured at: [POST] {telegram_webhook_path} (relative to base URL)"
|
||||
)
|
||||
|
||||
from bot.handlers.user.payment import yookassa_webhook_route
|
||||
from bot.services.tribute_service import tribute_webhook_route
|
||||
from bot.services.crypto_pay_service import cryptopay_webhook_route
|
||||
from bot.services.panel_webhook_service import panel_webhook_route
|
||||
|
||||
tribute_path = settings.tribute_webhook_path
|
||||
if tribute_path.startswith("/"):
|
||||
app.router.add_post(tribute_path, tribute_webhook_route)
|
||||
logging.info(f"Tribute webhook route configured at: [POST] {tribute_path}")
|
||||
|
||||
cp_path = settings.cryptopay_webhook_path
|
||||
if cp_path.startswith("/"):
|
||||
app.router.add_post(cp_path, cryptopay_webhook_route)
|
||||
logging.info(f"CryptoPay webhook route configured at: [POST] {cp_path}")
|
||||
|
||||
# YooKassa webhook (register only when base URL present and path configured)
|
||||
yk_path = settings.yookassa_webhook_path
|
||||
if settings.WEBHOOK_BASE_URL and yk_path and yk_path.startswith("/"):
|
||||
app.router.add_post(yk_path, yookassa_webhook_route)
|
||||
logging.info(f"YooKassa webhook route configured at: [POST] {yk_path}")
|
||||
|
||||
panel_path = settings.panel_webhook_path
|
||||
if panel_path.startswith("/"):
|
||||
app.router.add_post(panel_path, panel_webhook_route)
|
||||
logging.info(f"Panel webhook route configured at: [POST] {panel_path}")
|
||||
|
||||
web_app_runner = web.AppRunner(app)
|
||||
await web_app_runner.setup()
|
||||
site = web.TCPSite(
|
||||
web_app_runner,
|
||||
host=settings.WEB_SERVER_HOST,
|
||||
port=settings.WEB_SERVER_PORT,
|
||||
)
|
||||
|
||||
await site.start()
|
||||
logging.info(
|
||||
f"AIOHTTP server started on http://{settings.WEB_SERVER_HOST}:{settings.WEB_SERVER_PORT}"
|
||||
)
|
||||
|
||||
# Run until cancelled
|
||||
await asyncio.Event().wait()
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ from bot.keyboards.inline.admin_keyboards import (
|
||||
)
|
||||
from bot.middlewares.i18n import JsonI18n
|
||||
from bot.utils.message_queue import get_queue_manager
|
||||
from bot.utils import get_message_content, send_message_by_type, send_message_via_queue, MessageContent
|
||||
|
||||
router = Router(name="admin_broadcast_router")
|
||||
|
||||
@@ -76,30 +77,34 @@ async def process_broadcast_message_handler(
|
||||
|
||||
_ = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs)
|
||||
|
||||
# Сохраняем в state исходный текст и entities
|
||||
text = (message.text or message.caption or "").strip()
|
||||
# Определяем тип содержимого и сохраняем данные в state
|
||||
entities = message.entities or message.caption_entities or []
|
||||
content = get_message_content(message)
|
||||
|
||||
# Если текст пустой (например, прислали стикер/фото без подписи) — просим ввести текст
|
||||
if not text:
|
||||
# Если нет ни текста, ни медиа — ошибка
|
||||
if not content.text and not content.file_id:
|
||||
await message.answer(_("admin_broadcast_error_no_message"))
|
||||
return
|
||||
|
||||
# Предварительная проверка HTML: попробуем отправить и сразу удалить
|
||||
# Если HTML некорректный, Telegram вернёт ошибку парсинга
|
||||
# Сохраняем данные для рассылки
|
||||
await state.update_data(
|
||||
broadcast_text=content.text,
|
||||
broadcast_entities=entities,
|
||||
broadcast_content_type=content.content_type,
|
||||
broadcast_file_id=content.file_id,
|
||||
broadcast_target="all",
|
||||
)
|
||||
|
||||
# Отправляем превью-копию того, что будет разослано
|
||||
try:
|
||||
test_msg = await bot.send_message(
|
||||
chat_id=message.chat.id,
|
||||
text=text,
|
||||
await send_message_by_type(
|
||||
bot,
|
||||
chat_id=message.chat.id,
|
||||
content=content,
|
||||
parse_mode="HTML",
|
||||
disable_web_page_preview=True,
|
||||
disable_notification=True,
|
||||
)
|
||||
# Удалим тестовое сообщение
|
||||
try:
|
||||
await bot.delete_message(chat_id=message.chat.id, message_id=test_msg.message_id)
|
||||
except Exception:
|
||||
pass
|
||||
except TelegramBadRequest as e:
|
||||
await message.answer(
|
||||
_(
|
||||
@@ -110,20 +115,55 @@ async def process_broadcast_message_handler(
|
||||
)
|
||||
return
|
||||
|
||||
await state.update_data(
|
||||
broadcast_text=text,
|
||||
broadcast_entities=entities,
|
||||
)
|
||||
|
||||
confirmation_prompt = _("admin_broadcast_confirm_prompt", message_preview=text)
|
||||
# Показываем короткое подтверждение без дублирования текста — сообщение выше служит превью
|
||||
confirmation_prompt = _("admin_broadcast_confirm_prompt_short")
|
||||
|
||||
await message.answer(
|
||||
confirmation_prompt,
|
||||
reply_markup=get_broadcast_confirmation_keyboard(current_lang, i18n),
|
||||
reply_markup=get_broadcast_confirmation_keyboard(current_lang, i18n, target="all"),
|
||||
)
|
||||
await state.set_state(AdminStates.confirming_broadcast)
|
||||
|
||||
|
||||
@router.callback_query(
|
||||
F.data.startswith("broadcast_target:"),
|
||||
AdminStates.confirming_broadcast,
|
||||
)
|
||||
async def change_broadcast_target_handler(
|
||||
callback: types.CallbackQuery,
|
||||
state: FSMContext,
|
||||
i18n_data: dict,
|
||||
settings: Settings,
|
||||
):
|
||||
current_lang = i18n_data.get("current_language", settings.DEFAULT_LANGUAGE)
|
||||
i18n: Optional[JsonI18n] = i18n_data.get("i18n_instance")
|
||||
if not i18n or not callback.message:
|
||||
await callback.answer("Error updating selection.", show_alert=True)
|
||||
return
|
||||
|
||||
new_target = callback.data.split(":")[1]
|
||||
if new_target not in {"all", "active", "inactive"}:
|
||||
await callback.answer("Unknown target.", show_alert=True)
|
||||
return
|
||||
|
||||
await state.update_data(broadcast_target=new_target)
|
||||
user_fsm_data = await state.get_data()
|
||||
_ = lambda key, **kwargs: i18n.gettext(current_lang, key, **kwargs)
|
||||
confirmation_prompt = _(
|
||||
"admin_broadcast_confirm_prompt_short"
|
||||
)
|
||||
try:
|
||||
await callback.message.edit_text(
|
||||
confirmation_prompt,
|
||||
reply_markup=get_broadcast_confirmation_keyboard(
|
||||
current_lang, i18n, target=new_target
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
await callback.answer()
|
||||
|
||||
|
||||
@router.callback_query(
|
||||
F.data == "admin_action:main", AdminStates.waiting_for_broadcast_message
|
||||
)
|
||||
@@ -180,10 +220,15 @@ async def confirm_broadcast_callback_handler(
|
||||
user_fsm_data = await state.get_data()
|
||||
|
||||
if action == "send":
|
||||
text = user_fsm_data.get("broadcast_text")
|
||||
# Создаем объект контента из сохраненных данных
|
||||
content = MessageContent(
|
||||
content_type=user_fsm_data.get("broadcast_content_type", "text"),
|
||||
file_id=user_fsm_data.get("broadcast_file_id"),
|
||||
text=user_fsm_data.get("broadcast_text")
|
||||
)
|
||||
entities = user_fsm_data.get("broadcast_entities", [])
|
||||
|
||||
if not text:
|
||||
|
||||
if not content.text and content.content_type == "text":
|
||||
await callback.message.edit_text(_("admin_broadcast_error_no_message"))
|
||||
await state.clear()
|
||||
await callback.answer(
|
||||
@@ -194,13 +239,19 @@ async def confirm_broadcast_callback_handler(
|
||||
await callback.message.edit_text(_("admin_broadcast_sending_started"), reply_markup=None)
|
||||
await callback.answer()
|
||||
|
||||
user_ids = await user_dal.get_all_active_user_ids_for_broadcast(session)
|
||||
target = user_fsm_data.get("broadcast_target", "all")
|
||||
if target == "active":
|
||||
user_ids = await user_dal.get_user_ids_with_active_subscription(session)
|
||||
elif target == "inactive":
|
||||
user_ids = await user_dal.get_user_ids_without_active_subscription(session)
|
||||
else:
|
||||
user_ids = await user_dal.get_all_active_user_ids_for_broadcast(session)
|
||||
|
||||
sent_count = 0
|
||||
failed_count = 0
|
||||
admin_user = callback.from_user
|
||||
logging.info(
|
||||
f"Admin {admin_user.id} broadcasting '{text[:50]}...' to {len(user_ids)} users."
|
||||
f"Admin {admin_user.id} broadcasting '{(content.text or '')[:50]}...' to {len(user_ids)} users."
|
||||
)
|
||||
|
||||
# Get message queue manager
|
||||
@@ -212,9 +263,10 @@ async def confirm_broadcast_callback_handler(
|
||||
# Queue all messages for sending
|
||||
for uid in user_ids:
|
||||
try:
|
||||
await queue_manager.send_message(
|
||||
chat_id=uid,
|
||||
text=text,
|
||||
await send_message_via_queue(
|
||||
queue_manager,
|
||||
uid,
|
||||
content,
|
||||
parse_mode="HTML",
|
||||
disable_web_page_preview=True,
|
||||
)
|
||||
@@ -228,7 +280,7 @@ async def confirm_broadcast_callback_handler(
|
||||
"telegram_username": admin_user.username,
|
||||
"telegram_first_name": admin_user.first_name,
|
||||
"event_type": "admin_broadcast_queued",
|
||||
"content": f"To user {uid}: {text[:70]}...",
|
||||
"content": f"To user {uid}: [{content.content_type}] {(content.text or '')[:70]}...",
|
||||
"is_admin_event": True,
|
||||
"target_user_id": uid,
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import logging
|
||||
import re
|
||||
from aiogram import Router, F, types, Bot
|
||||
from aiogram.exceptions import TelegramBadRequest
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.utils.markdown import hcode, hbold
|
||||
from typing import Optional, Dict, Any
|
||||
@@ -15,6 +16,7 @@ from bot.keyboards.inline.admin_keyboards import get_back_to_admin_panel_keyboar
|
||||
from bot.services.subscription_service import SubscriptionService
|
||||
from bot.services.panel_api_service import PanelApiService
|
||||
from bot.middlewares.i18n import JsonI18n
|
||||
from bot.utils import get_message_content, send_direct_message
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder, InlineKeyboardButton
|
||||
|
||||
router = Router(name="admin_user_management_router")
|
||||
@@ -578,7 +580,7 @@ async def process_subscription_days_handler(message: types.Message, state: FSMCo
|
||||
await state.clear()
|
||||
|
||||
|
||||
@router.message(AdminStates.waiting_for_direct_message_to_user, F.text)
|
||||
@router.message(AdminStates.waiting_for_direct_message_to_user)
|
||||
async def process_direct_message_handler(message: types.Message, state: FSMContext,
|
||||
settings: Settings, i18n_data: dict,
|
||||
bot: Bot, session: AsyncSession):
|
||||
@@ -597,8 +599,9 @@ async def process_direct_message_handler(message: types.Message, state: FSMConte
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
message_text = message.text.strip()
|
||||
if len(message_text) > 4000:
|
||||
# Determine content similar to broadcast
|
||||
text = (message.text or message.caption or "").strip()
|
||||
if len(text) > 4000:
|
||||
await message.answer(_(
|
||||
"admin_user_message_too_long",
|
||||
default="❌ Сообщение слишком длинное (максимум 4000 символов)"
|
||||
@@ -613,15 +616,40 @@ async def process_direct_message_handler(message: types.Message, state: FSMConte
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
# Prepare message with admin signature
|
||||
# Prepare admin signature and get content
|
||||
admin_signature = _(
|
||||
"admin_direct_message_signature",
|
||||
default="\n\n---\n💬 Сообщение от администратора"
|
||||
)
|
||||
full_message = message_text + admin_signature
|
||||
|
||||
content = get_message_content(message)
|
||||
|
||||
# Send message to user
|
||||
await bot.send_message(target_user_id, full_message)
|
||||
if not content.text and not content.file_id:
|
||||
await message.answer(_(
|
||||
"admin_direct_empty_message",
|
||||
default="❌ Пустое сообщение. Отправьте текст или медиа."
|
||||
))
|
||||
return
|
||||
|
||||
caption_with_signature = (content.text + admin_signature) if content.text else None
|
||||
|
||||
# Send to target user using our fancy match/case function
|
||||
try:
|
||||
await send_direct_message(
|
||||
bot,
|
||||
target_user_id,
|
||||
content,
|
||||
extra_text=admin_signature,
|
||||
parse_mode="HTML",
|
||||
disable_web_page_preview=True,
|
||||
)
|
||||
except TelegramBadRequest as e:
|
||||
await message.answer(_(
|
||||
"admin_broadcast_invalid_html",
|
||||
default="❌ Некорректный HTML в сообщении. Пожалуйста, отправьте корректный HTML (поддерживаются теги Telegram) или уберите теги.\nОшибка: {error}",
|
||||
error=str(e),
|
||||
))
|
||||
return
|
||||
|
||||
# Confirm to admin
|
||||
await message.answer(_(
|
||||
|
||||
@@ -123,7 +123,12 @@ async def process_successful_payment(session: AsyncSession, bot: Bot,
|
||||
"applied_promo_bonus_days", 0)
|
||||
|
||||
referral_bonus_info = await referral_service.apply_referral_bonuses_for_payment(
|
||||
session, user_id, subscription_months)
|
||||
session,
|
||||
user_id,
|
||||
subscription_months,
|
||||
current_payment_db_id=payment_db_id,
|
||||
skip_if_active_before_payment=False,
|
||||
)
|
||||
applied_referee_bonus_days_from_referral: Optional[int] = None
|
||||
if referral_bonus_info and referral_bonus_info.get(
|
||||
"referee_new_end_date"):
|
||||
|
||||
+25
-17
@@ -165,24 +165,25 @@ async def start_command_handler(message: types.Message,
|
||||
"registration_date": datetime.now(timezone.utc)
|
||||
}
|
||||
try:
|
||||
db_user = await user_dal.create_user(session, user_data_to_create)
|
||||
db_user, created = await user_dal.create_user(session, user_data_to_create)
|
||||
|
||||
logging.info(
|
||||
f"New user {user_id} added to session. Referred by: {referred_by_user_id or 'N/A'}."
|
||||
)
|
||||
|
||||
# Send notification about new user registration
|
||||
try:
|
||||
from bot.services.notification_service import NotificationService
|
||||
notification_service = NotificationService(message.bot, settings, i18n)
|
||||
await notification_service.notify_new_user_registration(
|
||||
user_id=user_id,
|
||||
username=user.username,
|
||||
first_name=user.first_name,
|
||||
referred_by_id=referred_by_user_id
|
||||
if created:
|
||||
logging.info(
|
||||
f"New user {user_id} added to session. Referred by: {referred_by_user_id or 'N/A'}."
|
||||
)
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to send new user notification: {e}")
|
||||
|
||||
# Send notification about new user registration
|
||||
try:
|
||||
from bot.services.notification_service import NotificationService
|
||||
notification_service = NotificationService(message.bot, settings, i18n)
|
||||
await notification_service.notify_new_user_registration(
|
||||
user_id=user_id,
|
||||
username=user.username,
|
||||
first_name=user.first_name,
|
||||
referred_by_id=referred_by_user_id
|
||||
)
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to send new user notification: {e}")
|
||||
except Exception as e_create:
|
||||
|
||||
logging.error(
|
||||
@@ -194,8 +195,15 @@ async def start_command_handler(message: types.Message,
|
||||
update_payload = {}
|
||||
if db_user.language_code != current_lang:
|
||||
update_payload["language_code"] = current_lang
|
||||
# Set referral only if not already set AND user is not currently active.
|
||||
# This allows previously subscribed but currently inactive users to be attributed.
|
||||
if referred_by_user_id and db_user.referred_by_id is None:
|
||||
update_payload["referred_by_id"] = referred_by_user_id
|
||||
try:
|
||||
is_active_now = await subscription_service.has_active_subscription(session, user_id)
|
||||
except Exception:
|
||||
is_active_now = False
|
||||
if not is_active_now:
|
||||
update_payload["referred_by_id"] = referred_by_user_id
|
||||
if user.username != db_user.username:
|
||||
update_payload["username"] = user.username
|
||||
if user.first_name != db_user.first_name:
|
||||
|
||||
@@ -260,12 +260,47 @@ def get_confirmation_keyboard(yes_callback_data: str, no_callback_data: str,
|
||||
|
||||
|
||||
def get_broadcast_confirmation_keyboard(lang: str,
|
||||
i18n_instance) -> InlineKeyboardMarkup:
|
||||
i18n_instance,
|
||||
target: str = "all") -> InlineKeyboardMarkup:
|
||||
_ = lambda key, **kwargs: i18n_instance.gettext(lang, key, **kwargs)
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.button(text=_(key="confirm_broadcast_send_button"),
|
||||
|
||||
# Row: target selection (all / active / inactive)
|
||||
target_all_label = _(
|
||||
key="broadcast_target_all_button",
|
||||
default="👥 Все"
|
||||
)
|
||||
target_active_label = _(
|
||||
key="broadcast_target_active_button",
|
||||
default="✅ Активные"
|
||||
)
|
||||
target_inactive_label = _(
|
||||
key="broadcast_target_inactive_button",
|
||||
default="⌛ Неактивные"
|
||||
)
|
||||
|
||||
# Highlight current selection with a prefix
|
||||
def mark_selected(label: str, is_selected: bool) -> str:
|
||||
return ("• " + label) if is_selected else label
|
||||
|
||||
builder.button(
|
||||
text=mark_selected(target_all_label, target == "all"),
|
||||
callback_data="broadcast_target:all",
|
||||
)
|
||||
builder.button(
|
||||
text=mark_selected(target_active_label, target == "active"),
|
||||
callback_data="broadcast_target:active",
|
||||
)
|
||||
builder.button(
|
||||
text=mark_selected(target_inactive_label, target == "inactive"),
|
||||
callback_data="broadcast_target:inactive",
|
||||
)
|
||||
builder.adjust(3)
|
||||
|
||||
# Row: confirmation
|
||||
builder.button(text=_(key="confirm_broadcast_send_button", default="🚀 Отправить"),
|
||||
callback_data="broadcast_final_action:send")
|
||||
builder.button(text=_(key="cancel_broadcast_button"),
|
||||
builder.button(text=_(key="cancel_broadcast_button", default="❌ Отмена"),
|
||||
callback_data="broadcast_final_action:cancel")
|
||||
builder.adjust(2)
|
||||
return builder.as_markup()
|
||||
|
||||
+36
-193
@@ -20,6 +20,10 @@ from bot.middlewares.i18n import I18nMiddleware, get_i18n_instance, JsonI18n
|
||||
from bot.middlewares.db_session import DBSessionMiddleware
|
||||
from bot.middlewares.ban_check_middleware import BanCheckMiddleware
|
||||
from bot.middlewares.action_logger_middleware import ActionLoggerMiddleware
|
||||
from bot.middlewares.profile_sync import ProfileSyncMiddleware
|
||||
from bot.app.controllers.dispatcher_controller import build_dispatcher
|
||||
from bot.app.factories.build_services import build_core_services
|
||||
from bot.app.web.web_server import build_and_start_web_app
|
||||
|
||||
from bot.routers import build_root_router
|
||||
|
||||
@@ -103,10 +107,10 @@ async def on_startup_configured(dispatcher: Dispatcher):
|
||||
"STARTUP: Skipped setting Telegram webhook due to security or configuration error."
|
||||
)
|
||||
else:
|
||||
logging.info(
|
||||
"STARTUP: WEBHOOK_BASE_URL not set in environment. Running in polling mode and clearing any existing webhook."
|
||||
logging.error(
|
||||
"STARTUP: WEBHOOK_BASE_URL not set in environment. Webhook mode is required. Exiting."
|
||||
)
|
||||
await bot.delete_webhook(drop_pending_updates=True)
|
||||
raise SystemExit("WEBHOOK_BASE_URL is required. Polling mode is disabled.")
|
||||
|
||||
if settings.SUBSCRIPTION_MINI_APP_URL:
|
||||
try:
|
||||
@@ -224,19 +228,16 @@ async def on_shutdown_configured(dispatcher: Dispatcher):
|
||||
|
||||
|
||||
async def run_bot(settings_param: Settings):
|
||||
storage = MemoryStorage()
|
||||
default_props = DefaultBotProperties(parse_mode=ParseMode.HTML)
|
||||
bot = Bot(token=settings_param.BOT_TOKEN, default=default_props)
|
||||
|
||||
local_async_session_factory = init_db_connection(settings_param)
|
||||
if local_async_session_factory is None:
|
||||
logging.critical(
|
||||
"Failed to initialize database connection and session factory. Exiting."
|
||||
)
|
||||
return
|
||||
dp, bot, extra = build_dispatcher(settings_param, local_async_session_factory)
|
||||
i18n_instance = extra["i18n_instance"]
|
||||
|
||||
dp = Dispatcher(storage=storage, settings=settings_param, bot_instance=bot)
|
||||
|
||||
# Get bot username for YooKassa default return URL if needed
|
||||
actual_bot_username = "your_bot_username"
|
||||
try:
|
||||
bot_info = await bot.get_me()
|
||||
@@ -247,211 +248,53 @@ async def run_bot(settings_param: Settings):
|
||||
f"Failed to get bot info (e.g., for YooKassa default URL): {e}. Using fallback: {actual_bot_username}"
|
||||
)
|
||||
|
||||
i18n_instance = get_i18n_instance(
|
||||
path="locales", default=settings_param.DEFAULT_LANGUAGE
|
||||
)
|
||||
|
||||
yookassa_service = YooKassaService(
|
||||
shop_id=settings_param.YOOKASSA_SHOP_ID,
|
||||
secret_key=settings_param.YOOKASSA_SECRET_KEY,
|
||||
configured_return_url=settings_param.YOOKASSA_RETURN_URL,
|
||||
bot_username_for_default_return=actual_bot_username,
|
||||
settings_obj=settings_param,
|
||||
)
|
||||
panel_service = PanelApiService(settings_param)
|
||||
|
||||
subscription_service = SubscriptionService(
|
||||
settings_param, panel_service, bot, i18n_instance
|
||||
)
|
||||
referral_service = ReferralService(
|
||||
settings_param, subscription_service, bot, i18n_instance
|
||||
)
|
||||
promo_code_service = PromoCodeService(
|
||||
settings_param, subscription_service, bot, i18n_instance
|
||||
)
|
||||
stars_service = StarsService(
|
||||
bot, settings_param, i18n_instance, subscription_service, referral_service
|
||||
)
|
||||
cryptopay_service = CryptoPayService(
|
||||
settings_param.CRYPTOPAY_TOKEN,
|
||||
settings_param.CRYPTOPAY_NETWORK,
|
||||
bot,
|
||||
services = build_core_services(
|
||||
settings_param,
|
||||
i18n_instance,
|
||||
local_async_session_factory,
|
||||
subscription_service,
|
||||
referral_service,
|
||||
)
|
||||
tribute_service = TributeService(
|
||||
bot,
|
||||
settings_param,
|
||||
i18n_instance,
|
||||
local_async_session_factory,
|
||||
panel_service,
|
||||
subscription_service,
|
||||
referral_service,
|
||||
)
|
||||
panel_webhook_service = PanelWebhookService(
|
||||
bot,
|
||||
settings_param,
|
||||
i18n_instance,
|
||||
local_async_session_factory,
|
||||
actual_bot_username,
|
||||
)
|
||||
|
||||
dp["i18n_instance"] = i18n_instance
|
||||
dp["yookassa_service"] = yookassa_service
|
||||
dp["panel_service"] = panel_service
|
||||
dp["subscription_service"] = subscription_service
|
||||
dp["referral_service"] = referral_service
|
||||
dp["promo_code_service"] = promo_code_service
|
||||
dp["stars_service"] = stars_service
|
||||
dp["cryptopay_service"] = cryptopay_service
|
||||
dp["tribute_service"] = tribute_service
|
||||
dp["panel_webhook_service"] = panel_webhook_service
|
||||
for key, service in services.items():
|
||||
dp[key] = service
|
||||
dp["panel_service"] = services["panel_service"]
|
||||
dp["async_session_factory"] = local_async_session_factory
|
||||
|
||||
dp.update.outer_middleware(DBSessionMiddleware(local_async_session_factory))
|
||||
dp.update.outer_middleware(
|
||||
I18nMiddleware(i18n=i18n_instance, settings=settings_param)
|
||||
)
|
||||
dp.update.outer_middleware(
|
||||
BanCheckMiddleware(settings=settings_param, i18n_instance=i18n_instance)
|
||||
)
|
||||
dp.update.outer_middleware(ActionLoggerMiddleware(settings=settings_param))
|
||||
|
||||
dp.startup.register(on_startup_configured)
|
||||
# Register shutdown callback directly so Dispatcher instance is provided
|
||||
dp.shutdown.register(on_shutdown_configured)
|
||||
# Wrap startup/shutdown handlers to satisfy aiogram event signature (no args passed)
|
||||
async def _on_startup_wrapper():
|
||||
await on_startup_configured(dp)
|
||||
async def _on_shutdown_wrapper():
|
||||
await on_shutdown_configured(dp)
|
||||
dp.startup.register(_on_startup_wrapper)
|
||||
dp.shutdown.register(_on_shutdown_wrapper)
|
||||
|
||||
await register_all_routers(dp, settings_param)
|
||||
|
||||
tg_webhook_base = settings_param.WEBHOOK_BASE_URL
|
||||
yk_webhook_base = settings_param.WEBHOOK_BASE_URL
|
||||
|
||||
should_run_aiohttp_server = bool(tg_webhook_base) or (
|
||||
bool(yk_webhook_base) and bool(settings_param.yookassa_webhook_path)
|
||||
)
|
||||
|
||||
telegram_uses_webhook_mode = bool(tg_webhook_base)
|
||||
run_telegram_polling = not telegram_uses_webhook_mode
|
||||
# Webhook mode is now required - exit if not configured
|
||||
if not tg_webhook_base:
|
||||
logging.error("WEBHOOK_BASE_URL is required. Polling mode is disabled. Exiting.")
|
||||
await dp.emit_shutdown()
|
||||
raise SystemExit("WEBHOOK_BASE_URL is required. Polling mode is disabled.")
|
||||
|
||||
logging.info(f"--- Bot Run Mode Decision ---")
|
||||
logging.info(
|
||||
f"Configured WEBHOOK_BASE_URL: '{tg_webhook_base}' -> Telegram Webhook Mode: {telegram_uses_webhook_mode}"
|
||||
)
|
||||
logging.info(
|
||||
f"YooKassa webhook path: '{settings_param.yookassa_webhook_path}'"
|
||||
)
|
||||
logging.info(f"Decision: Run AIOHTTP server: {should_run_aiohttp_server}")
|
||||
logging.info(f"Decision: Run Telegram Polling: {run_telegram_polling}")
|
||||
logging.info(f"Configured WEBHOOK_BASE_URL: '{tg_webhook_base}' -> Webhook Mode: ENABLED")
|
||||
logging.info(f"YooKassa webhook path: '{settings_param.yookassa_webhook_path}'")
|
||||
logging.info(f"Decision: Run AIOHTTP server: ENABLED (required for webhooks)")
|
||||
logging.info(f"--- End Bot Run Mode Decision ---")
|
||||
|
||||
web_app_runner = None
|
||||
main_tasks = []
|
||||
|
||||
if should_run_aiohttp_server:
|
||||
app = web.Application()
|
||||
app["bot"] = bot
|
||||
app["dp"] = dp
|
||||
app["settings"] = settings_param
|
||||
app["i18n"] = i18n_instance
|
||||
app["async_session_factory"] = local_async_session_factory
|
||||
# Only run AIOHTTP server for webhook mode
|
||||
async def web_server_task():
|
||||
await build_and_start_web_app(dp, bot, settings_param, local_async_session_factory)
|
||||
|
||||
app["yookassa_service"] = yookassa_service
|
||||
app["subscription_service"] = subscription_service
|
||||
app["referral_service"] = referral_service
|
||||
app["panel_service"] = panel_service
|
||||
app["stars_service"] = stars_service
|
||||
app["cryptopay_service"] = cryptopay_service
|
||||
app["tribute_service"] = tribute_service
|
||||
app["panel_webhook_service"] = panel_webhook_service
|
||||
main_tasks.append(asyncio.create_task(web_server_task(), name="AIOHTTPServerTask"))
|
||||
|
||||
setup_application(app, dp, bot=bot)
|
||||
|
||||
if telegram_uses_webhook_mode:
|
||||
telegram_webhook_path = f"/{settings_param.BOT_TOKEN}"
|
||||
if not telegram_webhook_path.startswith("/"):
|
||||
telegram_webhook_path = "/" + telegram_webhook_path
|
||||
app.router.add_post(
|
||||
telegram_webhook_path, SimpleRequestHandler(dispatcher=dp, bot=bot)
|
||||
)
|
||||
logging.info(
|
||||
f"Telegram webhook route configured at: [POST] {telegram_webhook_path} (relative to base URL)"
|
||||
)
|
||||
|
||||
if yk_webhook_base and settings_param.yookassa_webhook_path:
|
||||
yk_path = settings_param.yookassa_webhook_path
|
||||
if not yk_path or not isinstance(yk_path, str):
|
||||
logging.error(
|
||||
f"YooKassa webhook path is invalid or not configured in settings: {yk_path}. Skipping YooKassa webhook setup."
|
||||
)
|
||||
elif not yk_path.startswith("/"):
|
||||
logging.error(
|
||||
f"CRITICAL: YooKassa webhook path '{yk_path}' from settings does not start with '/'. Correct settings.py or .env. Skipping YooKassa webhook."
|
||||
)
|
||||
else:
|
||||
app.router.add_post(
|
||||
yk_path, user_payment_webhook_module.yookassa_webhook_route
|
||||
)
|
||||
logging.info(f"YooKassa webhook route configured at: [POST] {yk_path}")
|
||||
|
||||
tribute_path = settings_param.tribute_webhook_path
|
||||
if tribute_path.startswith("/"):
|
||||
app.router.add_post(tribute_path, tribute_webhook_route)
|
||||
logging.info(f"Tribute webhook route configured at: [POST] {tribute_path}")
|
||||
|
||||
cp_path = settings_param.cryptopay_webhook_path
|
||||
if cp_path.startswith("/"):
|
||||
app.router.add_post(cp_path, cryptopay_webhook_route)
|
||||
logging.info(f"CryptoPay webhook route configured at: [POST] {cp_path}")
|
||||
|
||||
panel_path = settings_param.panel_webhook_path
|
||||
if panel_path.startswith("/"):
|
||||
app.router.add_post(panel_path, panel_webhook_route)
|
||||
logging.info(f"Panel webhook route configured at: [POST] {panel_path}")
|
||||
|
||||
web_app_runner = web.AppRunner(app)
|
||||
await web_app_runner.setup()
|
||||
site = web.TCPSite(
|
||||
web_app_runner,
|
||||
host=settings_param.WEB_SERVER_HOST,
|
||||
port=settings_param.WEB_SERVER_PORT,
|
||||
)
|
||||
|
||||
async def web_server_task():
|
||||
await site.start()
|
||||
logging.info(
|
||||
f"AIOHTTP server started on http://{settings_param.WEB_SERVER_HOST}:{settings_param.WEB_SERVER_PORT}"
|
||||
)
|
||||
(
|
||||
await asyncio.Event().wait()
|
||||
if not run_telegram_polling
|
||||
else await asyncio.sleep(31536000)
|
||||
)
|
||||
|
||||
main_tasks.append(
|
||||
asyncio.create_task(web_server_task(), name="AIOHTTPServerTask")
|
||||
)
|
||||
|
||||
if run_telegram_polling:
|
||||
logging.info("Starting bot in Telegram Polling mode...")
|
||||
main_tasks.append(
|
||||
asyncio.create_task(
|
||||
dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types()),
|
||||
name="TelegramPollingTask",
|
||||
)
|
||||
)
|
||||
|
||||
if not main_tasks:
|
||||
logging.error(
|
||||
"Bot is not configured for any run mode (neither Webhook nor Polling). Exiting."
|
||||
)
|
||||
await dp.emit_shutdown()
|
||||
return
|
||||
|
||||
logging.info(
|
||||
f"Starting bot with main tasks: {[task.get_name() for task in main_tasks]}"
|
||||
)
|
||||
logging.info("Starting bot in Webhook mode with AIOHTTP server...")
|
||||
logging.info(f"Starting bot with main tasks: {[task.get_name() for task in main_tasks]}")
|
||||
|
||||
try:
|
||||
await asyncio.gather(*main_tasks)
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import logging
|
||||
from typing import Callable, Dict, Any, Awaitable, Optional
|
||||
|
||||
from aiogram import BaseMiddleware
|
||||
from aiogram.types import Update, User as TgUser
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from db.dal import user_dal
|
||||
|
||||
|
||||
class ProfileSyncMiddleware(BaseMiddleware):
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
handler: Callable[[Update, Dict[str, Any]], Awaitable[Any]],
|
||||
event: Update,
|
||||
data: Dict[str, Any],
|
||||
) -> Any:
|
||||
session: AsyncSession = data.get("session")
|
||||
tg_user: Optional[TgUser] = data.get("event_from_user")
|
||||
|
||||
if session and tg_user:
|
||||
try:
|
||||
db_user = await user_dal.get_user_by_id(session, tg_user.id)
|
||||
if db_user:
|
||||
update_payload: Dict[str, Any] = {}
|
||||
if db_user.username != tg_user.username:
|
||||
update_payload["username"] = tg_user.username
|
||||
if db_user.first_name != tg_user.first_name:
|
||||
update_payload["first_name"] = tg_user.first_name
|
||||
if db_user.last_name != tg_user.last_name:
|
||||
update_payload["last_name"] = tg_user.last_name
|
||||
|
||||
if update_payload:
|
||||
await user_dal.update_user(session, tg_user.id, update_payload)
|
||||
logging.info(
|
||||
f"ProfileSyncMiddleware: Updated user {tg_user.id} profile fields: {list(update_payload.keys())}"
|
||||
)
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
f"ProfileSyncMiddleware: Failed to sync profile for user {getattr(tg_user, 'id', 'N/A')}: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
return await handler(event, data)
|
||||
|
||||
|
||||
+5
-1
@@ -1,4 +1,4 @@
|
||||
from aiogram import Router
|
||||
from aiogram import Router, F
|
||||
|
||||
from bot.handlers.user import user_router_aggregate
|
||||
from bot.handlers import inline_mode
|
||||
@@ -10,6 +10,10 @@ from config.settings import Settings
|
||||
def build_root_router(settings: Settings) -> Router:
|
||||
root = Router(name="root")
|
||||
|
||||
# Allow all updates only in private chats (messages, callback queries, etc.)
|
||||
root.message.filter(F.chat.type == "private")
|
||||
root.callback_query.filter(F.message.chat.type == "private")
|
||||
|
||||
# Public routers
|
||||
root.include_router(user_router_aggregate)
|
||||
root.include_router(inline_mode.router)
|
||||
|
||||
@@ -142,7 +142,11 @@ class CryptoPayService:
|
||||
provider="cryptopay",
|
||||
)
|
||||
referral_bonus = await referral_service.apply_referral_bonuses_for_payment(
|
||||
session, user_id, months
|
||||
session,
|
||||
user_id,
|
||||
months,
|
||||
current_payment_db_id=payment_db_id,
|
||||
skip_if_active_before_payment=False,
|
||||
)
|
||||
await session.commit()
|
||||
except Exception as e:
|
||||
|
||||
@@ -11,6 +11,7 @@ from config.settings import Settings
|
||||
from bot.middlewares.i18n import JsonI18n
|
||||
from bot.keyboards.inline.user_keyboards import get_subscribe_only_markup
|
||||
from db.dal import user_dal
|
||||
from bot.utils.date_utils import add_months
|
||||
|
||||
EVENT_MAP = {
|
||||
"user.expires_in_72_hours": (3, "subscription_72h_notification"),
|
||||
@@ -42,12 +43,16 @@ class PanelWebhookService:
|
||||
logging.error(f"Failed to send notification to {user_id}: {e}")
|
||||
|
||||
async def _handle_expired_subscription(self, session, user_id: int, user_payload: dict,
|
||||
lang: str, markup, first_name: str):
|
||||
"""Handle expired subscription - auto-renew tribute users if no cancellation was received"""
|
||||
lang: str, markup, first_name: str) -> bool:
|
||||
"""Handle expired subscription - auto-renew tribute users if no cancellation was received.
|
||||
|
||||
Returns True if an auto-renewal was performed (and renewal message sent), False otherwise.
|
||||
"""
|
||||
from db.dal import subscription_dal, payment_dal
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from datetime import datetime, timezone
|
||||
|
||||
try:
|
||||
auto_renewed = False
|
||||
# Check if user has tribute subscriptions that weren't cancelled
|
||||
user_subs = await subscription_dal.get_active_subscriptions_for_user(session, user_id)
|
||||
|
||||
@@ -64,8 +69,8 @@ class PanelWebhookService:
|
||||
# This user has tribute payments, auto-renew for the same duration
|
||||
logging.info(f"Auto-renewing tribute subscription for user {user_id} for {last_tribute_duration} months")
|
||||
|
||||
# Extend subscription by the last payment duration
|
||||
new_end_date = datetime.now(timezone.utc) + timedelta(days=last_tribute_duration * 30)
|
||||
# Extend subscription by the last payment duration (calendar months)
|
||||
new_end_date = add_months(datetime.now(timezone.utc), last_tribute_duration)
|
||||
|
||||
await subscription_dal.update_subscription(
|
||||
session,
|
||||
@@ -96,14 +101,17 @@ class PanelWebhookService:
|
||||
reply_markup=markup,
|
||||
parse_mode="HTML"
|
||||
)
|
||||
auto_renewed = True
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to send auto-renewal notification to user {user_id}: {e}")
|
||||
|
||||
await session.commit()
|
||||
return auto_renewed
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Error handling expired subscription for user {user_id}: {e}")
|
||||
await session.rollback()
|
||||
return False
|
||||
|
||||
async def handle_event(self, event_name: str, user_payload: dict):
|
||||
telegram_id = user_payload.get("telegramId")
|
||||
@@ -135,10 +143,10 @@ class PanelWebhookService:
|
||||
)
|
||||
elif event_name == "user.expired":
|
||||
# Check if this is a tribute user that should be auto-renewed (regardless of notification settings)
|
||||
await self._handle_expired_subscription(session, user_id, user_payload, lang, markup, first_name)
|
||||
auto_renewed = await self._handle_expired_subscription(session, user_id, user_payload, lang, markup, first_name)
|
||||
|
||||
# Send notification only if enabled
|
||||
if self.settings.SUBSCRIPTION_NOTIFY_ON_EXPIRE:
|
||||
# If auto-renewed via Tribute, suppress expiration notification. Otherwise, send it if enabled.
|
||||
if not auto_renewed and self.settings.SUBSCRIPTION_NOTIFY_ON_EXPIRE:
|
||||
await self._send_message(
|
||||
user_id,
|
||||
lang,
|
||||
|
||||
@@ -7,6 +7,7 @@ from datetime import datetime, timezone, timedelta
|
||||
|
||||
from config.settings import Settings
|
||||
from db.dal import user_dal
|
||||
from db.dal import payment_dal
|
||||
from db.models import User
|
||||
from db.dal import subscription_dal
|
||||
from bot.middlewares.i18n import JsonI18n
|
||||
@@ -24,8 +25,12 @@ class ReferralService:
|
||||
self.i18n = i18n
|
||||
|
||||
async def apply_referral_bonuses_for_payment(
|
||||
self, session: AsyncSession, referee_user_id: int,
|
||||
purchased_subscription_months: int) -> Dict[str, Any]:
|
||||
self,
|
||||
session: AsyncSession,
|
||||
referee_user_id: int,
|
||||
purchased_subscription_months: int,
|
||||
current_payment_db_id: Optional[int] = None,
|
||||
skip_if_active_before_payment: bool = True) -> Dict[str, Any]:
|
||||
|
||||
referee_final_end_date: Optional[datetime] = None
|
||||
referee_bonus_applied_days: Optional[int] = None
|
||||
@@ -43,6 +48,39 @@ class ReferralService:
|
||||
"referee_new_end_date": None
|
||||
}
|
||||
|
||||
# If configured to apply referral bonuses only once per invited user,
|
||||
# check if the referee already has succeeded payments.
|
||||
# Use getattr with a safe default (True) to avoid AttributeError if
|
||||
# running with an older settings schema.
|
||||
if getattr(self.settings, "REFERRAL_ONE_BONUS_PER_REFEREE", True):
|
||||
try:
|
||||
succeeded_count = await payment_dal.count_user_succeeded_payments(
|
||||
session, referee_user_id, exclude_payment_id=current_payment_db_id
|
||||
)
|
||||
if succeeded_count and succeeded_count > 0:
|
||||
logging.info(
|
||||
f"Referral bonuses skipped for user {referee_user_id}: already has {succeeded_count} succeeded payments.")
|
||||
return {
|
||||
"referee_bonus_applied_days": None,
|
||||
"referee_new_end_date": None
|
||||
}
|
||||
except Exception as e_cnt:
|
||||
logging.error(f"Failed counting succeeded payments for user {referee_user_id}: {e_cnt}")
|
||||
|
||||
# Additionally, do not award referral bonuses if the user was active at payment time
|
||||
# (has an active subscription now). This avoids giving bonuses to already active users.
|
||||
if skip_if_active_before_payment:
|
||||
try:
|
||||
if await self.subscription_service.has_active_subscription(session, referee_user_id):
|
||||
logging.info(
|
||||
f"Referral bonuses skipped for user {referee_user_id}: user currently has an active subscription.")
|
||||
return {
|
||||
"referee_bonus_applied_days": None,
|
||||
"referee_new_end_date": None
|
||||
}
|
||||
except Exception as e_sub:
|
||||
logging.error(f"Failed to check active subscription for {referee_user_id}: {e_sub}")
|
||||
|
||||
inviter_user_id = referee_user_model.referred_by_id
|
||||
inviter_user_model = await user_dal.get_user_by_id(
|
||||
session, inviter_user_id)
|
||||
|
||||
@@ -96,7 +96,12 @@ class StarsService:
|
||||
return
|
||||
|
||||
referral_bonus = await self.referral_service.apply_referral_bonuses_for_payment(
|
||||
session, message.from_user.id, months)
|
||||
session,
|
||||
message.from_user.id,
|
||||
months,
|
||||
current_payment_db_id=payment_db_id,
|
||||
skip_if_active_before_payment=False,
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
applied_days = referral_bonus.get("referee_bonus_applied_days") if referral_bonus else None
|
||||
|
||||
@@ -6,6 +6,7 @@ from aiogram import Bot
|
||||
from bot.middlewares.i18n import JsonI18n
|
||||
|
||||
from db.dal import user_dal, subscription_dal, promo_code_dal, payment_dal
|
||||
from bot.utils.date_utils import add_months
|
||||
from db.models import User, Subscription
|
||||
|
||||
from config.settings import Settings
|
||||
@@ -37,6 +38,22 @@ class SubscriptionService:
|
||||
async def has_had_any_subscription(self, session: AsyncSession, user_id: int) -> bool:
|
||||
return await subscription_dal.has_any_subscription_for_user(session, user_id)
|
||||
|
||||
async def has_active_subscription(self, session: AsyncSession, user_id: int) -> bool:
|
||||
"""Return True if user currently has an active subscription (end_date in future)."""
|
||||
try:
|
||||
user_record = await user_dal.get_user_by_id(session, user_id)
|
||||
if not user_record or not user_record.panel_user_uuid:
|
||||
return False
|
||||
active_sub = await subscription_dal.get_active_subscription_by_user_id(
|
||||
session, user_id, user_record.panel_user_uuid
|
||||
)
|
||||
if not active_sub or not active_sub.end_date:
|
||||
return False
|
||||
from datetime import datetime, timezone
|
||||
return active_sub.is_active and active_sub.end_date > datetime.now(timezone.utc)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
async def _notify_admin_panel_user_creation_failed(self, user_id: int):
|
||||
if not self.bot or not self.i18n or not self.settings.ADMIN_IDS:
|
||||
return
|
||||
@@ -216,23 +233,10 @@ class SubscriptionService:
|
||||
"panel_user_uuid": actual_panel_uuid_from_api
|
||||
}
|
||||
|
||||
if (
|
||||
actual_panel_username_from_api
|
||||
and actual_panel_username_from_api
|
||||
!= panel_username_on_panel_standard
|
||||
and (
|
||||
db_user.username is None
|
||||
or db_user.username != actual_panel_username_from_api
|
||||
)
|
||||
):
|
||||
update_data_for_local_user["username"] = (
|
||||
actual_panel_username_from_api
|
||||
)
|
||||
|
||||
# Do not overwrite Telegram username with panel username.
|
||||
# Only update the local linkage to panel UUID here.
|
||||
await user_dal.update_user(session, user_id, update_data_for_local_user)
|
||||
db_user.panel_user_uuid = actual_panel_uuid_from_api
|
||||
if "username" in update_data_for_local_user:
|
||||
db_user.username = update_data_for_local_user["username"]
|
||||
panel_user_created_or_linked_now = True
|
||||
current_local_panel_uuid = actual_panel_uuid_from_api
|
||||
else:
|
||||
@@ -421,7 +425,9 @@ class SubscriptionService:
|
||||
):
|
||||
start_date = current_active_sub.end_date
|
||||
|
||||
duration_days_total = months * 30
|
||||
# base duration by months
|
||||
end_after_months = add_months(start_date, months)
|
||||
duration_days_total = (end_after_months - start_date).days
|
||||
applied_promo_bonus_days = 0
|
||||
|
||||
if promo_code_id_from_payment:
|
||||
|
||||
@@ -65,18 +65,30 @@ class TributeService:
|
||||
subscription_service = self.subscription_service
|
||||
referral_service = self.referral_service
|
||||
|
||||
def ok(data: Optional[dict] = None) -> web.Response:
|
||||
payload = {"status": "ok"}
|
||||
if data:
|
||||
payload.update(data)
|
||||
return web.json_response(payload, status=200)
|
||||
|
||||
def ignored(reason: str) -> web.Response:
|
||||
return web.json_response({"status": "ignored", "reason": reason}, status=200)
|
||||
|
||||
def bad_request(reason: str) -> web.Response:
|
||||
return web.json_response({"status": "error", "reason": reason}, status=400)
|
||||
|
||||
if settings.TRIBUTE_API_KEY:
|
||||
if not signature_header:
|
||||
return web.Response(status=403, text="no_signature")
|
||||
return web.json_response({"status": "error", "reason": "no_signature"}, status=403)
|
||||
expected_sig = hmac.new(settings.TRIBUTE_API_KEY.encode(), raw_body,
|
||||
hashlib.sha256).hexdigest()
|
||||
if not hmac.compare_digest(expected_sig, signature_header):
|
||||
return web.Response(status=403, text="invalid_signature")
|
||||
return web.json_response({"status": "error", "reason": "invalid_signature"}, status=403)
|
||||
|
||||
try:
|
||||
payload = json.loads(raw_body.decode())
|
||||
except Exception:
|
||||
return web.Response(status=400, text="bad_request")
|
||||
return bad_request("invalid_json")
|
||||
|
||||
logging.info(
|
||||
"Tribute webhook data: %s",
|
||||
@@ -91,7 +103,8 @@ class TributeService:
|
||||
# Mandatory routing fields
|
||||
user_id = data.get("telegram_user_id")
|
||||
if not user_id:
|
||||
return web.Response(status=400, text="missing_telegram_user_id")
|
||||
# Permanent format issue — acknowledge to avoid retries
|
||||
return ignored("missing_telegram_user_id")
|
||||
|
||||
period_val = data.get("period")
|
||||
months = convert_period_to_months(period_val)
|
||||
@@ -110,8 +123,19 @@ class TributeService:
|
||||
|
||||
async with async_session_factory() as session:
|
||||
if event_name == "new_subscription":
|
||||
# Build a stable provider payment id from subscription and timestamps
|
||||
provider_payment_id = str(data.get("subscription_id"))
|
||||
# Use a unique, idempotent provider payment id per webhook event
|
||||
# Prefer explicit event/payment identifiers if present; otherwise fall back to payload hash suffix
|
||||
candidate_event_id = (
|
||||
str(data.get("event_id") or data.get("payment_id") or data.get("purchase_id") or data.get("invoice_id") or "")
|
||||
)
|
||||
if candidate_event_id:
|
||||
provider_payment_id = candidate_event_id
|
||||
else:
|
||||
# Combine subscription_id (if any) with a stable hash of the raw payload to ensure uniqueness per event
|
||||
sub_id_part = str(data.get("subscription_id") or "sub")
|
||||
payload_hash = hashlib.sha256(raw_body).hexdigest()[:16]
|
||||
provider_payment_id = f"{sub_id_part}:{payload_hash}"
|
||||
|
||||
# Idempotent ensure payment
|
||||
payment_record = await payment_dal.ensure_payment_with_provider_id(
|
||||
session,
|
||||
@@ -133,7 +157,12 @@ class TributeService:
|
||||
provider="tribute",
|
||||
)
|
||||
referral_bonus = await referral_service.apply_referral_bonuses_for_payment(
|
||||
session, int(user_id), months)
|
||||
session,
|
||||
int(user_id),
|
||||
months,
|
||||
current_payment_db_id=payment_record.payment_id,
|
||||
skip_if_active_before_payment=False,
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
db_user = await user_dal.get_user_by_id(session, int(user_id))
|
||||
@@ -210,7 +239,8 @@ class TributeService:
|
||||
|
||||
else:
|
||||
await session.commit()
|
||||
return web.Response(status=200, text="ok")
|
||||
# Acknowledge to Tribute that webhook was received and processed/accepted
|
||||
return ok({"event": event_name or "unknown"})
|
||||
|
||||
async def _handle_tribute_cancellation(self, session, user_id: int, bot: Bot, i18n: JsonI18n):
|
||||
"""Handle tribute subscription cancellation - set subscription to 1 day grace period"""
|
||||
|
||||
+263
-1
@@ -1 +1,263 @@
|
||||
# Bot utilities package
|
||||
# Bot utilities package
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional, Dict, Any
|
||||
from aiogram import types
|
||||
|
||||
|
||||
@dataclass
|
||||
class MessageContent:
|
||||
"""Класс для хранения информации о контенте сообщения"""
|
||||
content_type: str
|
||||
file_id: Optional[str] = None
|
||||
text: Optional[str] = None
|
||||
|
||||
|
||||
# Словари поддерживаемых параметров для каждого типа сообщения
|
||||
SUPPORTED_PARAMS = {
|
||||
"text": {"parse_mode", "entities", "disable_web_page_preview", "disable_notification", "protect_content", "reply_markup", "reply_to_message_id", "allow_sending_without_reply", "message_thread_id"},
|
||||
"photo": {"caption", "parse_mode", "caption_entities", "disable_notification", "protect_content", "reply_markup", "reply_to_message_id", "allow_sending_without_reply", "message_thread_id", "has_spoiler"},
|
||||
"video": {"duration", "width", "height", "thumbnail", "caption", "parse_mode", "caption_entities", "supports_streaming", "disable_notification", "protect_content", "reply_markup", "reply_to_message_id", "allow_sending_without_reply", "message_thread_id", "has_spoiler"},
|
||||
"animation": {"duration", "width", "height", "thumbnail", "caption", "parse_mode", "caption_entities", "disable_notification", "protect_content", "reply_markup", "reply_to_message_id", "allow_sending_without_reply", "message_thread_id", "has_spoiler"},
|
||||
"document": {"thumbnail", "caption", "parse_mode", "caption_entities", "disable_content_type_detection", "disable_notification", "protect_content", "reply_markup", "reply_to_message_id", "allow_sending_without_reply", "message_thread_id"},
|
||||
"audio": {"caption", "parse_mode", "caption_entities", "duration", "performer", "title", "thumbnail", "disable_notification", "protect_content", "reply_markup", "reply_to_message_id", "allow_sending_without_reply", "message_thread_id"},
|
||||
"voice": {"caption", "parse_mode", "caption_entities", "duration", "disable_notification", "protect_content", "reply_markup", "reply_to_message_id", "allow_sending_without_reply", "message_thread_id"},
|
||||
"sticker": {"disable_notification", "protect_content", "reply_markup", "reply_to_message_id", "allow_sending_without_reply", "message_thread_id"},
|
||||
"video_note": {"duration", "length", "thumbnail", "disable_notification", "protect_content", "reply_markup", "reply_to_message_id", "allow_sending_without_reply", "message_thread_id"},
|
||||
}
|
||||
|
||||
|
||||
def filter_kwargs(content_type: str, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Фильтрует kwargs, оставляя только поддерживаемые параметры для данного типа сообщения"""
|
||||
supported = SUPPORTED_PARAMS.get(content_type, set())
|
||||
return {k: v for k, v in kwargs.items() if k in supported}
|
||||
|
||||
|
||||
def get_message_content(message: types.Message) -> MessageContent:
|
||||
"""
|
||||
Определяет тип контента сообщения и возвращает его данные.
|
||||
Использует match/case вместо длинных if-elif цепочек.
|
||||
"""
|
||||
text = (message.text or message.caption or "").strip()
|
||||
|
||||
# Проверяем наличие медиа-контента
|
||||
media_content = None
|
||||
if message.photo:
|
||||
media_content = ("photo", message.photo[-1].file_id)
|
||||
elif message.video:
|
||||
media_content = ("video", message.video.file_id)
|
||||
elif message.animation:
|
||||
media_content = ("animation", message.animation.file_id)
|
||||
elif message.document:
|
||||
media_content = ("document", message.document.file_id)
|
||||
elif message.audio:
|
||||
media_content = ("audio", message.audio.file_id)
|
||||
elif message.voice:
|
||||
media_content = ("voice", message.voice.file_id)
|
||||
elif message.sticker:
|
||||
media_content = ("sticker", message.sticker.file_id)
|
||||
elif message.video_note:
|
||||
media_content = ("video_note", message.video_note.file_id)
|
||||
|
||||
# Используем match/case для определения типа контента
|
||||
match media_content:
|
||||
case (content_type, file_id):
|
||||
return MessageContent(content_type=content_type, file_id=file_id, text=text)
|
||||
case None:
|
||||
return MessageContent(content_type="text", text=text)
|
||||
case _:
|
||||
return MessageContent(content_type="text", text=text)
|
||||
|
||||
|
||||
async def send_message_by_type(bot, chat_id: int, content: MessageContent, **kwargs) -> None:
|
||||
"""
|
||||
Отправляет сообщение указанного типа.
|
||||
Использует match/case вместо длинных if-elif цепочек.
|
||||
Автоматически фильтрует неподдерживаемые параметры.
|
||||
"""
|
||||
# Фильтруем kwargs для данного типа сообщения
|
||||
filtered_kwargs = filter_kwargs(content.content_type, kwargs)
|
||||
|
||||
match content.content_type:
|
||||
case "text":
|
||||
await bot.send_message(
|
||||
chat_id=chat_id,
|
||||
text=content.text,
|
||||
**filtered_kwargs
|
||||
)
|
||||
case "photo":
|
||||
await bot.send_photo(
|
||||
chat_id=chat_id,
|
||||
photo=content.file_id,
|
||||
caption=content.text or None,
|
||||
**filtered_kwargs
|
||||
)
|
||||
case "video":
|
||||
await bot.send_video(
|
||||
chat_id=chat_id,
|
||||
video=content.file_id,
|
||||
caption=content.text or None,
|
||||
**filtered_kwargs
|
||||
)
|
||||
case "animation":
|
||||
await bot.send_animation(
|
||||
chat_id=chat_id,
|
||||
animation=content.file_id,
|
||||
caption=content.text or None,
|
||||
**filtered_kwargs
|
||||
)
|
||||
case "document":
|
||||
await bot.send_document(
|
||||
chat_id=chat_id,
|
||||
document=content.file_id,
|
||||
caption=content.text or None,
|
||||
**filtered_kwargs
|
||||
)
|
||||
case "audio":
|
||||
await bot.send_audio(
|
||||
chat_id=chat_id,
|
||||
audio=content.file_id,
|
||||
caption=content.text or None,
|
||||
**filtered_kwargs
|
||||
)
|
||||
case "voice":
|
||||
await bot.send_voice(
|
||||
chat_id=chat_id,
|
||||
voice=content.file_id,
|
||||
caption=content.text or None,
|
||||
**filtered_kwargs
|
||||
)
|
||||
case "sticker":
|
||||
await bot.send_sticker(
|
||||
chat_id=chat_id,
|
||||
sticker=content.file_id,
|
||||
**filtered_kwargs
|
||||
)
|
||||
case "video_note":
|
||||
await bot.send_video_note(
|
||||
chat_id=chat_id,
|
||||
video_note=content.file_id,
|
||||
**filtered_kwargs
|
||||
)
|
||||
case _:
|
||||
# Fallback для неизвестных типов - отправляем как текст
|
||||
text_kwargs = filter_kwargs("text", kwargs)
|
||||
await bot.send_message(
|
||||
chat_id=chat_id,
|
||||
text=content.text or "Unknown content type",
|
||||
**text_kwargs
|
||||
)
|
||||
|
||||
|
||||
async def send_message_via_queue(queue_manager, uid: int, content: MessageContent, **kwargs) -> None:
|
||||
"""
|
||||
Отправляет сообщение через очередь в зависимости от типа контента.
|
||||
Использует match/case вместо длинных if-elif цепочек.
|
||||
Автоматически фильтрует неподдерживаемые параметры.
|
||||
"""
|
||||
# Фильтруем kwargs для данного типа сообщения
|
||||
filtered_kwargs = filter_kwargs(content.content_type, kwargs)
|
||||
|
||||
match content.content_type:
|
||||
case "text":
|
||||
await queue_manager.send_message(
|
||||
chat_id=uid, text=content.text, **filtered_kwargs
|
||||
)
|
||||
case "photo":
|
||||
await queue_manager.send_photo(
|
||||
chat_id=uid, photo=content.file_id, caption=content.text or None, **filtered_kwargs
|
||||
)
|
||||
case "video":
|
||||
await queue_manager.send_video(
|
||||
chat_id=uid, video=content.file_id, caption=content.text or None, **filtered_kwargs
|
||||
)
|
||||
case "animation":
|
||||
await queue_manager.send_animation(
|
||||
chat_id=uid, animation=content.file_id, caption=content.text or None, **filtered_kwargs
|
||||
)
|
||||
case "document":
|
||||
await queue_manager.send_document(
|
||||
chat_id=uid, document=content.file_id, caption=content.text or None, **filtered_kwargs
|
||||
)
|
||||
case "audio":
|
||||
await queue_manager.send_audio(
|
||||
chat_id=uid, audio=content.file_id, caption=content.text or None, **filtered_kwargs
|
||||
)
|
||||
case "voice":
|
||||
await queue_manager.send_voice(
|
||||
chat_id=uid, voice=content.file_id, caption=content.text or None, **filtered_kwargs
|
||||
)
|
||||
case "sticker":
|
||||
await queue_manager.send_sticker(
|
||||
chat_id=uid, sticker=content.file_id, **filtered_kwargs
|
||||
)
|
||||
case "video_note":
|
||||
await queue_manager.send_video_note(
|
||||
chat_id=uid, video_note=content.file_id, **filtered_kwargs
|
||||
)
|
||||
case _:
|
||||
# Fallback для неизвестных типов - отправляем как текст
|
||||
text_kwargs = filter_kwargs("text", kwargs)
|
||||
await queue_manager.send_message(
|
||||
chat_id=uid, text=content.text or "Unknown content type", **text_kwargs
|
||||
)
|
||||
|
||||
|
||||
async def send_direct_message(bot, chat_id: int, content: MessageContent, extra_text: str = "", **kwargs) -> None:
|
||||
"""
|
||||
Отправляет прямое сообщение с дополнительной обработкой для sticker и video_note.
|
||||
Для этих типов медиа отправляется отдельное текстовое сообщение, т.к. они не поддерживают caption.
|
||||
Автоматически фильтрует неподдерживаемые параметры.
|
||||
"""
|
||||
match content.content_type:
|
||||
case "sticker":
|
||||
# Отправляем стикер с отфильтрованными параметрами
|
||||
sticker_kwargs = filter_kwargs("sticker", kwargs)
|
||||
await bot.send_sticker(
|
||||
chat_id=chat_id,
|
||||
sticker=content.file_id,
|
||||
**sticker_kwargs
|
||||
)
|
||||
# Если есть текст с подписью, отправляем отдельно
|
||||
if content.text or extra_text:
|
||||
text_to_send = (content.text + extra_text) if content.text else extra_text
|
||||
text_kwargs = filter_kwargs("text", kwargs)
|
||||
await bot.send_message(
|
||||
chat_id,
|
||||
text_to_send,
|
||||
**text_kwargs
|
||||
)
|
||||
case "video_note":
|
||||
# Отправляем видео-заметку с отфильтрованными параметрами
|
||||
video_note_kwargs = filter_kwargs("video_note", kwargs)
|
||||
await bot.send_video_note(
|
||||
chat_id=chat_id,
|
||||
video_note=content.file_id,
|
||||
**video_note_kwargs
|
||||
)
|
||||
# Если есть текст с подписью, отправляем отдельно
|
||||
if content.text or extra_text:
|
||||
text_to_send = (content.text + extra_text) if content.text else extra_text
|
||||
text_kwargs = filter_kwargs("text", kwargs)
|
||||
await bot.send_message(
|
||||
chat_id,
|
||||
text_to_send,
|
||||
**text_kwargs
|
||||
)
|
||||
case "text":
|
||||
# Для текста объединяем с extra_text
|
||||
final_text = (content.text + extra_text) if content.text else extra_text
|
||||
text_kwargs = filter_kwargs("text", kwargs)
|
||||
await bot.send_message(
|
||||
chat_id=chat_id,
|
||||
text=final_text,
|
||||
**text_kwargs
|
||||
)
|
||||
case _:
|
||||
# Для остальных типов медиа используем caption
|
||||
final_caption = (content.text + extra_text) if content.text else None
|
||||
await send_message_by_type(
|
||||
bot, chat_id,
|
||||
MessageContent(content.content_type, content.file_id, final_caption),
|
||||
**kwargs
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
def add_months(base_dt: datetime, months_to_add: int) -> datetime:
|
||||
"""Add calendar months to a datetime, clamping the day to the month's length.
|
||||
|
||||
Preserves tzinfo from base_dt.
|
||||
"""
|
||||
year = base_dt.year
|
||||
month = base_dt.month + months_to_add
|
||||
day = base_dt.day
|
||||
|
||||
# Normalize year and month
|
||||
year += (month - 1) // 12
|
||||
month = ((month - 1) % 12) + 1
|
||||
|
||||
# Determine last day of target month by rolling to next month's first day and subtracting 1 day
|
||||
if month == 12:
|
||||
next_month_first = datetime(year + 1, 1, 1, tzinfo=base_dt.tzinfo)
|
||||
else:
|
||||
next_month_first = datetime(year, month + 1, 1, tzinfo=base_dt.tzinfo)
|
||||
last_day = (next_month_first - timedelta(days=1)).day
|
||||
|
||||
clamped_day = min(day, last_day)
|
||||
return base_dt.replace(year=year, month=month, day=clamped_day)
|
||||
|
||||
|
||||
@@ -151,6 +151,76 @@ class MessageQueueManager:
|
||||
)
|
||||
await queue.add_message(message)
|
||||
|
||||
async def send_photo(self, chat_id: int, **kwargs) -> None:
|
||||
"""Queue a send_photo call"""
|
||||
queue = self.group_queue if self._is_group_chat(chat_id) else self.user_queue
|
||||
message = QueuedMessage(
|
||||
chat_id=chat_id,
|
||||
method_name='send_photo',
|
||||
kwargs=kwargs
|
||||
)
|
||||
await queue.add_message(message)
|
||||
|
||||
async def send_video(self, chat_id: int, **kwargs) -> None:
|
||||
"""Queue a send_video call"""
|
||||
queue = self.group_queue if self._is_group_chat(chat_id) else self.user_queue
|
||||
message = QueuedMessage(
|
||||
chat_id=chat_id,
|
||||
method_name='send_video',
|
||||
kwargs=kwargs
|
||||
)
|
||||
await queue.add_message(message)
|
||||
|
||||
async def send_animation(self, chat_id: int, **kwargs) -> None:
|
||||
"""Queue a send_animation (GIF) call"""
|
||||
queue = self.group_queue if self._is_group_chat(chat_id) else self.user_queue
|
||||
message = QueuedMessage(
|
||||
chat_id=chat_id,
|
||||
method_name='send_animation',
|
||||
kwargs=kwargs
|
||||
)
|
||||
await queue.add_message(message)
|
||||
|
||||
async def send_audio(self, chat_id: int, **kwargs) -> None:
|
||||
"""Queue a send_audio call"""
|
||||
queue = self.group_queue if self._is_group_chat(chat_id) else self.user_queue
|
||||
message = QueuedMessage(
|
||||
chat_id=chat_id,
|
||||
method_name='send_audio',
|
||||
kwargs=kwargs
|
||||
)
|
||||
await queue.add_message(message)
|
||||
|
||||
async def send_voice(self, chat_id: int, **kwargs) -> None:
|
||||
"""Queue a send_voice call"""
|
||||
queue = self.group_queue if self._is_group_chat(chat_id) else self.user_queue
|
||||
message = QueuedMessage(
|
||||
chat_id=chat_id,
|
||||
method_name='send_voice',
|
||||
kwargs=kwargs
|
||||
)
|
||||
await queue.add_message(message)
|
||||
|
||||
async def send_sticker(self, chat_id: int, **kwargs) -> None:
|
||||
"""Queue a send_sticker call"""
|
||||
queue = self.group_queue if self._is_group_chat(chat_id) else self.user_queue
|
||||
message = QueuedMessage(
|
||||
chat_id=chat_id,
|
||||
method_name='send_sticker',
|
||||
kwargs=kwargs
|
||||
)
|
||||
await queue.add_message(message)
|
||||
|
||||
async def send_video_note(self, chat_id: int, **kwargs) -> None:
|
||||
"""Queue a send_video_note call"""
|
||||
queue = self.group_queue if self._is_group_chat(chat_id) else self.user_queue
|
||||
message = QueuedMessage(
|
||||
chat_id=chat_id,
|
||||
method_name='send_video_note',
|
||||
kwargs=kwargs
|
||||
)
|
||||
await queue.add_message(message)
|
||||
|
||||
async def answer_callback_query(self, callback_query_id: str, **kwargs) -> None:
|
||||
"""Send callback query answer immediately (not rate limited)"""
|
||||
await self.bot.answer_callback_query(callback_query_id, **kwargs)
|
||||
|
||||
@@ -93,6 +93,12 @@ class Settings(BaseSettings):
|
||||
REFERRAL_BONUS_DAYS_REFEREE_12_MONTHS: Optional[int] = Field(
|
||||
default=15, alias="REFEREE_BONUS_DAYS_12_MONTHS")
|
||||
|
||||
# Referral program configuration
|
||||
REFERRAL_ONE_BONUS_PER_REFEREE: bool = Field(
|
||||
default=True,
|
||||
description="When true, referral bonuses (for inviter and referee) are applied only once per invited user – on their first successful payment."
|
||||
)
|
||||
|
||||
PANEL_API_URL: Optional[str] = None
|
||||
PANEL_API_KEY: Optional[str] = None
|
||||
USER_TRAFFIC_LIMIT_GB: Optional[float] = Field(default=0.0)
|
||||
|
||||
@@ -138,6 +138,23 @@ async def get_all_succeeded_payments_with_user(session: AsyncSession) -> List[Pa
|
||||
return result.scalars().all()
|
||||
|
||||
|
||||
async def count_user_succeeded_payments(
|
||||
session: AsyncSession, user_id: int, exclude_payment_id: Optional[int] = None
|
||||
) -> int:
|
||||
"""Count succeeded payments for a specific user.
|
||||
|
||||
If exclude_payment_id is provided, that specific payment will be excluded
|
||||
from the count. Useful to check "prior" payments while processing the
|
||||
current payment in the same transaction.
|
||||
"""
|
||||
conditions = [Payment.user_id == user_id, Payment.status == 'succeeded']
|
||||
if exclude_payment_id is not None:
|
||||
conditions.append(Payment.payment_id != exclude_payment_id)
|
||||
stmt = select(func.count(Payment.payment_id)).where(and_(*conditions))
|
||||
result = await session.execute(stmt)
|
||||
return result.scalar() or 0
|
||||
|
||||
|
||||
async def update_provider_payment_and_status(
|
||||
session: AsyncSession, payment_db_id: int,
|
||||
provider_payment_id: str, new_status: str) -> Optional[Payment]:
|
||||
|
||||
+88
-17
@@ -4,7 +4,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from sqlalchemy.orm import selectinload
|
||||
from sqlalchemy import update, delete, func, and_
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from ..models import User, Subscription
|
||||
|
||||
@@ -33,19 +34,41 @@ async def get_user_by_panel_uuid(
|
||||
## Removed unused generic get_user helper to keep DAL explicit and simple
|
||||
|
||||
|
||||
async def create_user(session: AsyncSession, user_data: Dict[str, Any]) -> User:
|
||||
async def create_user(session: AsyncSession, user_data: Dict[str, Any]) -> Tuple[User, bool]:
|
||||
"""Create a user if not exists in a race-safe way.
|
||||
|
||||
Returns a tuple of (user, created_flag).
|
||||
"""
|
||||
|
||||
if "registration_date" not in user_data:
|
||||
user_data["registration_date"] = datetime.now()
|
||||
user_data["registration_date"] = datetime.now(timezone.utc)
|
||||
|
||||
new_user = User(**user_data)
|
||||
session.add(new_user)
|
||||
await session.flush()
|
||||
await session.refresh(new_user)
|
||||
logging.info(
|
||||
f"New user {new_user.user_id} created in DAL. Referred by: {new_user.referred_by_id or 'N/A'}."
|
||||
# Use PostgreSQL upsert to avoid IntegrityError on concurrent inserts
|
||||
stmt = (
|
||||
pg_insert(User)
|
||||
.values(**user_data)
|
||||
.on_conflict_do_nothing(index_elements=[User.user_id])
|
||||
.returning(User.user_id)
|
||||
)
|
||||
return new_user
|
||||
|
||||
result = await session.execute(stmt)
|
||||
inserted_row = result.first()
|
||||
created = inserted_row is not None
|
||||
|
||||
# Fetch the user (inserted just now or pre-existing)
|
||||
user_id: int = user_data["user_id"]
|
||||
user = await get_user_by_id(session, user_id)
|
||||
|
||||
if created and user is not None:
|
||||
logging.info(
|
||||
f"New user {user.user_id} created in DAL. Referred by: {user.referred_by_id or 'N/A'}."
|
||||
)
|
||||
elif user is not None:
|
||||
logging.info(
|
||||
f"User {user.user_id} already exists in DAL. Proceeding without creation."
|
||||
)
|
||||
|
||||
return user, created
|
||||
|
||||
|
||||
async def update_user(
|
||||
@@ -93,9 +116,10 @@ async def get_all_users_with_panel_uuid(session: AsyncSession) -> List[User]:
|
||||
|
||||
async def get_enhanced_user_statistics(session: AsyncSession) -> Dict[str, Any]:
|
||||
"""Get comprehensive user statistics including active users, trial users, etc."""
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timezone
|
||||
|
||||
now = datetime.utcnow()
|
||||
# Use timezone-aware UTC to avoid naive/aware comparison issues in SQL queries
|
||||
now = datetime.now(timezone.utc)
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
# Total users
|
||||
@@ -106,13 +130,11 @@ async def get_enhanced_user_statistics(session: AsyncSession) -> Dict[str, Any]:
|
||||
banned_users_stmt = select(func.count(User.user_id)).where(User.is_banned == True)
|
||||
banned_users = (await session.execute(banned_users_stmt)).scalar() or 0
|
||||
|
||||
# Active users today (users with login activity - for now using registration as proxy)
|
||||
active_today_stmt = select(func.count(User.user_id)).where(
|
||||
User.registration_date >= today_start
|
||||
)
|
||||
# Active users today (proxy: registered today)
|
||||
active_today_stmt = select(func.count(User.user_id)).where(User.registration_date >= today_start)
|
||||
active_today = (await session.execute(active_today_stmt)).scalar() or 0
|
||||
|
||||
# Users with active paid subscriptions
|
||||
# Users with active paid subscriptions (non-trial providers only)
|
||||
paid_subs_stmt = (
|
||||
select(func.count(func.distinct(Subscription.user_id)))
|
||||
.join(User, Subscription.user_id == User.user_id)
|
||||
@@ -156,3 +178,52 @@ async def get_enhanced_user_statistics(session: AsyncSession) -> Dict[str, Any]:
|
||||
"inactive_users": max(0, inactive_users),
|
||||
"referral_users": referral_users
|
||||
}
|
||||
|
||||
|
||||
async def get_user_ids_with_active_subscription(session: AsyncSession) -> List[int]:
|
||||
"""Return non-banned user IDs who have an active subscription (paid or trial)."""
|
||||
from datetime import datetime, timezone
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
stmt = (
|
||||
select(func.distinct(Subscription.user_id))
|
||||
.join(User, Subscription.user_id == User.user_id)
|
||||
.where(
|
||||
and_(
|
||||
User.is_banned == False,
|
||||
Subscription.is_active == True,
|
||||
Subscription.end_date > now,
|
||||
)
|
||||
)
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
|
||||
async def get_user_ids_without_active_subscription(session: AsyncSession) -> List[int]:
|
||||
"""Return non-banned user IDs who do NOT have any active subscription."""
|
||||
from datetime import datetime, timezone
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Subquery for users with active subscription
|
||||
active_subs_subq = (
|
||||
select(Subscription.user_id)
|
||||
.where(
|
||||
and_(
|
||||
Subscription.is_active == True,
|
||||
Subscription.end_date > now,
|
||||
)
|
||||
)
|
||||
).scalar_subquery()
|
||||
|
||||
stmt = (
|
||||
select(User.user_id)
|
||||
.where(
|
||||
and_(
|
||||
User.is_banned == False,
|
||||
~User.user_id.in_(active_subs_subq),
|
||||
)
|
||||
)
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
@@ -155,6 +155,10 @@
|
||||
|
||||
"admin_broadcast_enter_message": "Enter the broadcast message (HTML supported):",
|
||||
"admin_broadcast_confirm_prompt": "You are about to send the following message:\n\n{message_preview}\n\nConfirm sending?",
|
||||
"admin_broadcast_confirm_prompt_short": "The message above will be sent. Confirm?",
|
||||
"broadcast_target_all_button": "👥 All",
|
||||
"broadcast_target_active_button": "✅ Active",
|
||||
"broadcast_target_inactive_button": "⌛ Inactive",
|
||||
"confirm_broadcast_send_button": "✅ Send",
|
||||
"cancel_broadcast_button": "❌ Cancel",
|
||||
"admin_broadcast_sending_started": "Starting broadcast...",
|
||||
|
||||
@@ -155,6 +155,10 @@
|
||||
|
||||
"admin_broadcast_enter_message": "Введите сообщение для рассылки (HTML поддерживается):",
|
||||
"admin_broadcast_confirm_prompt": "Вы собираетесь отправить следующее сообщение:\n\n{message_preview}\n\nПодтверждаете отправку?",
|
||||
"admin_broadcast_confirm_prompt_short": "Сообщение выше будет отправлено. Подтвердить отправку?",
|
||||
"broadcast_target_all_button": "👥 Все",
|
||||
"broadcast_target_active_button": "✅ Активные",
|
||||
"broadcast_target_inactive_button": "⌛ Неактивные",
|
||||
"confirm_broadcast_send_button": "✅ Отправить",
|
||||
"cancel_broadcast_button": "❌ Отмена",
|
||||
"admin_broadcast_sending_started": "Начинаю рассылку...",
|
||||
|
||||
Reference in New Issue
Block a user