Spaces:
Running

microfunnel-api / backend /app /services /notification.py
axeronis
fix: chat_id fallback to include admins and frontend settings sync
a043a19
Raw History Blame Contribute Delete
14.5 kB
import logging
from typing import Optional, Dict, Any
from datetime import datetime
from sqlmodel import select
from app.models.tenant import Tenant
from app.models.order import Order
from app.models.booking import Appointment
from app.models.user import User, UserRole
logger = logging.getLogger(__name__)
class NotificationService:
"""
Handles internal notifications (ALERTS) for the Tenant/Admin.
Triggers when important events occur (Order, Booking).
"""
async def _get_settings(self, session: Any, tenant_id: Any):
"""Fetch settings from the dedicated table."""
from app.models.notification import NotificationSettings
stmt = select(NotificationSettings).where(NotificationSettings.tenant_id == tenant_id)
result = await session.execute(stmt)
return result.scalar_one_or_none()
# Fallback: Find Owner or Admin
logger.info(f"🔍 [GET_CHAT_ID] Trying fallback to Owner/Admin's chat_id...")
# Check for OWNER or admin (case insensitive just in case)
# Note: In SQLModel/SQLAlchemy we can use IN operator
from sqlalchemy import or_
stmt = select(User).where(
User.tenant_id == tenant_id,
or_(
User.role == UserRole.OWNER,
User.role == "admin",
User.role == "ADMIN"
)
)
result = await session.execute(stmt)
owner_users = result.scalars().all()
logger.info(f"🔍 [GET_CHAT_ID] Found {len(owner_users)} potential owner/admin(s)")
# Return first user with chat_id configured
for user in owner_users:
if user.telegram_chat_id:
logger.info(f"🔍 [GET_CHAT_ID] Using Owner {user.email}'s chat_id: {user.telegram_chat_id}")
return user.telegram_chat_id
logger.warning(f"🔍 [GET_CHAT_ID] No chat_id found anywhere!")
return None
async def notify_new_order(self, session: Any, tenant: Tenant, order: Order, items_text: str):
"""Send alert about a new order."""
settings = await self._get_settings(session, tenant.id)
if not settings or not settings.telegram_enabled or not settings.telegram_chat_id:
return
if settings.notify_orders:
message = (
f"🚨 **НОВЫЙ ЗАКАЗ** 🚨\n\n"
f"🆔 ID: {str(order.id)[:8]}\n"
f"👤 Клиент: {order.lead.name or 'Неизвестно'} (ID: {order.lead_id})\n"
f"📦 Товары:\n{items_text}\n"
f"💰 Сумма: {order.total_amount:.2f}\n"
f"📅 Дата: {order.created_at.strftime('%Y-%m-%d %H:%M')}"
)
await self._send_telegram(tenant.telegram_bot_token, settings.telegram_chat_id, message)
async def notify_new_appointment(
self,
session: Any,
tenant: Tenant,
appointment: Appointment,
ai_summary: dict = None,
resource_telegram_id: str = None
):
"""Send alert about a new booking with smart context from AI."""
settings = await self._get_settings(session, tenant.id)
# Determine notification target: resource owner first, then tenant settings
tg_chat_id = resource_telegram_id
notify_enabled = True
if not tg_chat_id:
if not settings or not settings.telegram_enabled or not settings.telegram_chat_id:
return
tg_chat_id = settings.telegram_chat_id
notify_enabled = settings.notify_bookings
if not tg_chat_id or not notify_enabled:
return
# Format time
start = appointment.start_time.strftime('%d.%m %H:%M')
# Extract smart context from AI summary
lead_name = appointment.lead.name if appointment.lead else 'Неизвестно'
intent = ai_summary.get("intent", "Не определено") if ai_summary else "—"
pain_points = ai_summary.get("pain_points", []) if ai_summary else []
pain_text = ', '.join(pain_points[:2]) if pain_points else '—'
heat_score = ai_summary.get("heat_score", 0) if ai_summary else 0
# Heat indicator emoji
heat_emoji = "🔥" if heat_score >= 70 else "🟡" if heat_score >= 50 else "❄️"
# Add resource info if booking to specific resource
resource_info = ""
if hasattr(appointment, 'resource') and appointment.resource:
resource_info = f"📌 Ресурс: {appointment.resource.name}\n"
message = (
f"📅 **НОВАЯ ЗАПИСЬ** 📅\n\n"
f"👤 Клиент: {lead_name}\n"
f"{heat_emoji} Теплота: {heat_score}%\n"
f"🎯 Интерес: {intent}\n"
f"💡 Боли: {pain_text}\n"
f"───────────────\n"
f"🕒 Время: {start}\n"
f"{resource_info}"
f"📝 Услуга: {appointment.service.name if appointment.service else 'Общая'}\n"
f"💬 Заметка: {appointment.notes}"
)
await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
async def notify_escalation(self, session: Any, tenant: Tenant, lead, reason: str = None, last_message: str = None):
"""Send alert when client requests human manager (escalation)."""
settings = await self._get_settings(session, tenant.id)
if not settings or not settings.telegram_enabled or not settings.telegram_chat_id or not settings.notify_escalations:
return
tg_chat_id = settings.telegram_chat_id
lead_name = lead.name if lead else 'Неизвестно'
heat_score = getattr(lead, 'heat_score', 0) or 0
heat_emoji = "🔥" if heat_score >= 70 else "🟡" if heat_score >= 50 else "❄️"
# Get intent from AI summary
ai_summary = getattr(lead, 'ai_summary_json', {}) or {}
intent = ai_summary.get("intent", "—")
message = (
f"🚨 **ЭСКАЛАЦИЯ** 🚨\n\n"
f"👤 Клиент: {lead_name}\n"
f"{heat_emoji} Теплота: {heat_score}%\n"
f"🎯 Интерес: {intent}\n"
f"───────────────\n"
f"📝 Причина: {reason or 'Клиент запросил менеджера'}\n"
f"💬 Последнее сообщение: {last_message[:100] if last_message else '—'}..."
)
await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
async def notify_hot_lead(self, session: Any, tenant: Tenant, lead, trigger_reason: str = None):
"""Send alert when lead becomes HOT (heat >= 70)."""
logger.info(f"🔥 [HOT_LEAD] notify_hot_lead called for lead={lead.id}, tenant={tenant.id}")
settings = await self._get_settings(session, tenant.id)
logger.info(f"🔥 [HOT_LEAD] Settings: {settings}, telegram_enabled={getattr(settings, 'telegram_enabled', None) if settings else None}")
# Check explicit disabled flag ONLY if settings exist
if settings and settings.telegram_enabled is False:
logger.info(f"🔥 [HOT_LEAD] Telegram disabled in settings, skipping")
return
tg_chat_id = await self._get_target_chat_id(session, tenant.id, settings)
logger.info(f"🔥 [HOT_LEAD] Target chat_id: {tg_chat_id}")
if not tg_chat_id:
logger.warning(f"🔥 [HOT_LEAD] No chat_id found - notification NOT sent!")
return
lead_name = lead.name if lead else 'Неизвестно'
heat_score = getattr(lead, 'heat_score', 0) or 0
# Get context from AI summary
ai_summary = getattr(lead, 'ai_summary_json', {}) or {}
intent = ai_summary.get("intent", "—")
pain_points = ai_summary.get("pain_points", [])
pain_text = ', '.join(pain_points[:2]) if pain_points else '—'
message = (
f"🔥 **ГОРЯЧИЙ ЛИД** 🔥\n\n"
f"👤 Клиент: {lead_name}\n"
f"📊 Теплота: {heat_score}%\n"
f"🎯 Интерес: {intent}\n"
f"💡 Боли: {pain_text}\n"
f"───────────────\n"
f"⚡ Причина: {trigger_reason or 'Набрал высокий скор'}"
)
logger.info(f"🔥 [HOT_LEAD] Sending notification to {tg_chat_id}...")
await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
logger.info(f"🔥 [HOT_LEAD] Notification sent successfully!")
async def notify_qualification_complete(self, session: Any, lead, tenant: Tenant, qualification_data: Dict = None):
"""Send alert when lead is qualified."""
logger.info(f"📋 [QUALIFICATION] notify_qualification_complete called for lead={lead.id}, tenant={tenant.id}")
if not qualification_data:
qualification_data = lead.qualification_data or {}
logger.info(f"📋 [QUALIFICATION] qualification_data: {qualification_data}")
settings = await self._get_settings(session, tenant.id)
logger.info(f"📋 [QUALIFICATION] Settings: {settings}, notify_qualification_complete={getattr(settings, 'notify_qualification_complete', None) if settings else None}")
# Fail-safe check
tg_chat_id = await self._get_target_chat_id(session, tenant.id, settings)
logger.info(f"📋 [QUALIFICATION] Target chat_id: {tg_chat_id}")
if not tg_chat_id:
logger.warning(f"📋 [QUALIFICATION] No chat_id found - notification NOT sent!")
return
# Format fields
fields_text = ""
for k, v in qualification_data.items():
if v and str(v).lower() not in ['не выявлено', 'unknown', 'none']:
fields_text += f"✅ {k}: {v}\n"
if not fields_text:
logger.info(f"📋 [QUALIFICATION] No fields to report - skipping notification")
return # Don't send empty alerts
lead_name = lead.name or "Неизвестно"
message = (
f"📋 **ЛИД КВАЛИФИЦИРОВАН**\n"
f"👤 {lead_name}\n\n"
f"{fields_text}\n"
f"👉 <a href='https://app.microfunnel.online/leads/{lead.id}'>Открыть карточку</a>"
)
logger.info(f"📋 [QUALIFICATION] Sending notification to {tg_chat_id}...")
await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
logger.info(f"📋 [QUALIFICATION] Notification sent successfully!")
async def notify_reschedule(
self,
session: Any,
tenant: Tenant,
old_appointment,
old_time: datetime,
new_time: datetime,
lead_name: str
):
"""Send alert when appointment is rescheduled."""
settings = await self._get_settings(session, tenant.id)
if not settings or not settings.telegram_enabled or not settings.telegram_chat_id or not settings.notify_bookings:
return
tg_chat_id = settings.telegram_chat_id
old_time_str = old_time.strftime('%d.%m в %H:%M')
new_time_str = new_time.strftime('%d.%m в %H:%M')
message = (
f"🔄 **ПЕРЕНОС ЗАПИСИ** 🔄\n\n"
f"👤 Клиент: {lead_name}\n"
f"───────────────\n"
f"❌ Было: {old_time_str}\n"
f"✅ Стало: {new_time_str}\n"
f"───────────────\n"
f"📝 Заметка: {old_appointment.notes or '—'}"
)
await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
async def notify_kill_switch(self, session: Any, tenant: Tenant, lead, msg_count: int):
"""Send alert when Kill Switch is activated due to abnormal activity."""
settings = await self._get_settings(session, tenant.id)
if not settings or not settings.telegram_enabled or not settings.telegram_chat_id:
return
tg_chat_id = settings.telegram_chat_id
lead_name = lead.name if lead else 'Неизвестно'
message = (
f"🚨 **АНТИ-СПАМ: ИИ ОТКЛЮЧЕН** 🚨\n\n"
f"👤 Клиент: {lead_name} (ID: {lead.id})\n"
f"⚠️ Активность: {msg_count} сообщ./час\n"
f"───────────────\n"
f"🛑 Действие: ИИ автоматически переведен в режим 'Human Takeover'.\n"
f"💡 Требуется проверка менеджера."
)
await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
async def _send_telegram(self, bot_token: str, chat_id: str, text: str):
"""Helper to send TG message."""
# ALWAYS use Platform Notification Bot - NOT tenant's automation bot
from app.core.config import settings as global_settings
# Platform token only - notifications come from central bot
token_to_use = global_settings.TELEGRAM_NOTIFICATION_TOKEN
if not token_to_use or not chat_id:
logger.warning("⚠️ Cannot send notification: Missing TELEGRAM_NOTIFICATION_TOKEN env var or chat_id")
return
try:
# We can reuse the existing utility from webhook or define strict request here
# Ideally verify if 'app.utils.telegram' exists or similar.
# Using the one imported from deps/webhook context usually
from app.api.webhook import send_telegram_message as send_tg
await send_tg(token_to_use, chat_id, text)
logger.info(f"📧 Notification sent to Admin {chat_id}")
except Exception as e:
logger.error(f"❌ Failed to send admin notification: {e}")
# Singleton
notification_service = NotificationService()