From afb4f162d07dfd8f699e2beede61448700770a21 Mon Sep 17 00:00:00 2001 From: Egor Date: Wed, 4 Feb 2026 03:55:59 +0300 Subject: [PATCH] Update admin_notification_service.py --- app/services/admin_notification_service.py | 171 +++++++++++++++------ 1 file changed, 126 insertions(+), 45 deletions(-) diff --git a/app/services/admin_notification_service.py b/app/services/admin_notification_service.py index 08907a07..c4db50cf 100644 --- a/app/services/admin_notification_service.py +++ b/app/services/admin_notification_service.py @@ -288,9 +288,7 @@ class AdminNotificationService: return False user_status = '🆕 Новый' if not user.has_had_paid_subscription else '🔄 Существующий' - referrer_info = await self._get_referrer_info(db, user.referred_by_id) promo_group = await self._get_user_promo_group(db, user) - promo_block = self._format_promo_group_block(promo_group) user_display = self._get_user_display(user) trial_device_limit = subscription.device_limit @@ -308,28 +306,59 @@ class AdminNotificationService: user_id_label = self._get_user_identifier_label(user) user_id_display = self._get_user_identifier_display(user) - message = f"""🎯 АКТИВАЦИЯ ТРИАЛА + # Получаем название тарифа (если режим тарифов) + tariff_name = await self._get_tariff_name(db, subscription) -👤 Пользователь: {user_display} -🆔 {user_id_label}: {user_id_display} -📱 Username: @{getattr(user, 'username', None) or 'отсутствует'} -👥 Статус: {user_status} + message_lines = [ + '🎯 АКТИВАЦИЯ ТРИАЛА', + '', + f'👤 Пользователь: {user_display}', + f'🆔 {user_id_label}: {user_id_display}', + f'📱 Username: @{getattr(user, "username", None) or "отсутствует"}', + f'👥 Статус: {user_status}', + '', + ] -{promo_block} + # Промогруппа — только название, без скидок + if promo_group: + message_lines.append(f'🏷️ Промогруппа: {promo_group.name}') + else: + message_lines.append('🏷️ Промогруппа: —') -⏰ Параметры триала: -📅 Период: {settings.TRIAL_DURATION_DAYS} дней -📊 Трафик: {self._format_traffic(settings.TRIAL_TRAFFIC_LIMIT_GB)} -📱 Устройства: {trial_device_limit} -🌐 Сервер: {subscription.connected_squads[0] if subscription.connected_squads else 'По умолчанию'} -{payment_block} + # Тариф триала (если есть) + if tariff_name: + message_lines.append(f'📦 Тариф: {tariff_name}') -📆 Действует до: {format_local_datetime(subscription.end_date, '%d.%m.%Y %H:%M')} -🔗 Реферер: {referrer_info} + message_lines.append('') -⏰ {format_local_datetime(datetime.utcnow(), '%d.%m.%Y %H:%M:%S')}""" + message_lines.extend( + [ + '⏰ Параметры триала:', + f'📅 Период: {settings.TRIAL_DURATION_DAYS} дней', + f'📊 Трафик: {self._format_traffic(settings.TRIAL_TRAFFIC_LIMIT_GB)}', + f'📱 Устройства: {trial_device_limit}', + f'🌐 Сервер: {subscription.connected_squads[0] if subscription.connected_squads else "По умолчанию"}', + ] + ) - return await self._send_message(message) + if payment_block: + message_lines.append(payment_block) + + message_lines.append('') + message_lines.append( + f'📆 Действует до: {format_local_datetime(subscription.end_date, "%d.%m.%Y %H:%M")}' + ) + + # Реферер — только если есть + if user.referred_by_id: + referrer_info = await self._get_referrer_info(db, user.referred_by_id) + if referrer_info != 'Нет': + message_lines.append(f'🔗 Реферер: {referrer_info}') + + message_lines.append('') + message_lines.append(f'⏰ {format_local_datetime(datetime.utcnow(), "%d.%m.%Y %H:%M:%S")}') + + return await self._send_message('\n'.join(message_lines)) except Exception as e: logger.error(f'Ошибка отправки уведомления о триале: {e}') @@ -540,35 +569,81 @@ class AdminNotificationService: payment_method = self._get_payment_method_display(transaction.payment_method) balance_change = user.balance_kopeks - old_balance subscription_status = self._get_subscription_status(subscription) - promo_block = self._format_promo_group_block(promo_group) timestamp = format_local_datetime(datetime.utcnow(), '%d.%m.%Y %H:%M:%S') user_display = self._get_user_display(user) - user_id_label = self._get_user_identifier_label(user) user_id_display = self._get_user_identifier_display(user) - return f"""💰 ПОПОЛНЕНИЕ БАЛАНСА + # --- Основной блок --- + message_lines: list[str] = [ + '💰 ПОПОЛНЕНИЕ БАЛАНСА', + '', + f'👤 {user_display} ({user_id_display})', + ] -👤 Пользователь: {user_display} -🆔 {user_id_label}: {user_id_display} -📱 Username: @{getattr(user, 'username', None) or 'отсутствует'} -💳 Статус: {topup_status} + username = getattr(user, 'username', None) + if username: + message_lines.append(f'📱 @{username}') -{promo_block} + message_lines.append(f'💳 {topup_status}') -💰 Детали пополнения: -💵 Сумма: {settings.format_price(transaction.amount_kopeks)} -💳 Способ: {payment_method} -🆔 ID транзакции: {transaction.id} + # Промогруппа -- только название + if promo_group: + message_lines.append(f'🏷️ Промогруппа: {promo_group.name}') -💰 Баланс: -📉 Было: {settings.format_price(old_balance)} -📈 Стало: {settings.format_price(user.balance_kopeks)} -➕ Изменение: +{settings.format_price(balance_change)} + message_lines.append('') -🔗 Реферер: {referrer_info} -📱 Подписка: {subscription_status} + # --- Детали пополнения --- + message_lines.extend( + [ + f'💵 {settings.format_price(transaction.amount_kopeks)} | {payment_method}', + '', + f'📉 {settings.format_price(old_balance)} → 📈 {settings.format_price(user.balance_kopeks)}' + f' (+{settings.format_price(balance_change)})', + ] + ) -⏰ {timestamp}""" + # --- Подписка --- + message_lines.append(f'📱 Подписка: {subscription_status}') + + # --- Реферер (только если есть) --- + if referrer_info and referrer_info != 'Нет': + message_lines.append(f'🔗 Реферер: {referrer_info}') + + # --- Expandable blockquote с техническими деталями --- + detail_lines: list[str] = [ + f'ID транзакции: {transaction.id}', + f'Способ оплаты: {transaction.payment_method or "balance"}', + ] + + if transaction.external_id: + detail_lines.append(f'Внешний ID: {transaction.external_id}') + + if transaction.description: + desc = transaction.description + if len(desc) > 120: + desc = desc[:117] + '...' + detail_lines.append(f'Описание: {desc}') + + if transaction.created_at: + detail_lines.append(f'Создана: {format_local_datetime(transaction.created_at, "%d.%m.%Y %H:%M:%S")}') + + if transaction.completed_at: + detail_lines.append(f'Завершена: {format_local_datetime(transaction.completed_at, "%d.%m.%Y %H:%M:%S")}') + + if transaction.receipt_uuid: + detail_lines.append(f'Чек UUID: {transaction.receipt_uuid}') + + blockquote_body = '\n'.join(detail_lines) + message_lines.extend( + [ + '', + f'
{blockquote_body}
', + ] + ) + + message_lines.append(f'{timestamp}') + + return '\n'.join(message_lines) async def _reload_topup_notification_entities( self, @@ -1121,21 +1196,27 @@ class AdminNotificationService: return self.enabled and bool(self.chat_id) def _get_payment_method_display(self, payment_method: str | None) -> str: - mulenpay_name = settings.get_mulenpay_display_name() - method_names = { + if not payment_method: + return '💰 С баланса' + + method_names: dict[str, str] = { 'telegram_stars': '⭐ Telegram Stars', 'yookassa': '💳 YooKassa (карта)', 'tribute': '💎 Tribute (карта)', - 'mulenpay': f'💳 {mulenpay_name} (карта)', - 'pal24': '🏦 PayPalych (СБП)', + 'mulenpay': f'💳 {settings.get_mulenpay_display_name()} (карта)', + 'pal24': f'🏦 {settings.get_pal24_display_name()} (СБП)', + 'cryptobot': f'🪙 {settings.get_cryptobot_display_name()} (крипто)', + 'heleket': f'🪙 {settings.get_heleket_display_name()} (крипто)', + 'wata': f'💳 {settings.get_wata_display_name()}', + 'platega': f'💳 {settings.get_platega_display_name()}', + 'cloudpayments': f'💳 {settings.get_cloudpayments_display_name()}', + 'freekassa': f'💳 {settings.get_freekassa_display_name()}', + 'kassa_ai': f'💳 {settings.get_kassa_ai_display_name()}', 'manual': '🛠️ Вручную (админ)', 'balance': '💰 С баланса', } - if not payment_method: - return '💰 С баланса' - - return method_names.get(payment_method, '💰 С баланса') + return method_names.get(payment_method, f'💳 {payment_method}') def _format_traffic(self, traffic_gb: int) -> str: if traffic_gb == 0: