Spaces:
Running

axeronis commited on
Commit
3e22cd3
·
1 Parent(s): b5833df

fix: consolidate notifications and enable fail-safe defaults

Browse files
backend/app/services/ai_core/lead_analyzer.py CHANGED
@@ -696,8 +696,9 @@ async def analyze_lead_impl(
696
  if previous_heat_level != LeadHeat.HOT and lead.heat_level == LeadHeat.HOT:
697
  print(f"🔥 Lead {lead.id} became HOT! Sending notification...")
698
  try:
699
- from app.services.notification import notification_service
700
- await notification_service.notify_hot_lead(session=session, lead=lead, tenant=tenant)
 
701
  except Exception as e:
702
  print(f"⚠️ HOT lead notification failed: {e}")
703
 
@@ -775,7 +776,8 @@ async def analyze_lead_impl(
775
  await session.refresh(lead)
776
 
777
  # Check qualification complete notification
778
- await check_and_notify_qualification_complete(session, lead, tenant)
 
779
  except Exception as qe:
780
  print(f"⚠️ Qualification extraction failed: {qe}")
781
 
 
696
  if previous_heat_level != LeadHeat.HOT and lead.heat_level == LeadHeat.HOT:
697
  print(f"🔥 Lead {lead.id} became HOT! Sending notification...")
698
  try:
699
+ from app.services.notification_service import get_notification_service
700
+ notif_service = get_notification_service()
701
+ await notif_service.notify_hot_lead(session=session, lead=lead, tenant=tenant)
702
  except Exception as e:
703
  print(f"⚠️ HOT lead notification failed: {e}")
704
 
 
776
  await session.refresh(lead)
777
 
778
  # Check qualification complete notification
779
+ from app.services.notification_service import get_notification_service
780
+ await get_notification_service().notify_qualification_complete(session, lead, tenant)
781
  except Exception as qe:
782
  print(f"⚠️ Qualification extraction failed: {qe}")
783
 
backend/app/services/notification_service.py CHANGED
@@ -29,22 +29,13 @@ class NotificationService:
29
  lead: Lead,
30
  tenant: Tenant
31
  ):
32
- """
33
- Send notification when lead becomes HOT.
34
-
35
- Channels:
36
- 1. Telegram (if configured)
37
- 2. Dashboard (always)
38
- """
39
- logger.info(f"Sending HOT lead notification for lead {lead.id}")
40
 
41
- # 1. Check settings
42
  settings = await self._get_notification_settings(session, tenant.id)
43
  if not settings or not settings.notify_hot_leads:
44
- logger.info("Hot lead notifications disabled, skipping")
45
  return
46
 
47
- # 2. Create notification in DB (for Dashboard)
48
  notification = await self._create_notification(
49
  session=session,
50
  tenant_id=tenant.id,
@@ -54,54 +45,119 @@ class NotificationService:
54
  message=self._format_hot_lead_message(lead)
55
  )
56
 
57
- # 3. Send to Telegram (if configured)
58
- # 3. Send to Telegram (Tenant Level)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  sent_to_ids = []
 
 
60
  if settings.telegram_enabled and settings.telegram_chat_id:
61
  try:
62
- await self._send_telegram_notification(
63
- chat_id=settings.telegram_chat_id,
64
- lead=lead,
65
- tenant=tenant
66
- )
67
  sent_to_ids.append(settings.telegram_chat_id)
68
- logger.info(f"Telegram notification sent to Tenant channel {settings.telegram_chat_id}")
69
  except Exception as e:
70
- logger.error(f"Failed to send Telegram notification to Tenant: {e}")
71
 
72
- # 4. Send to Assigned Manager (Personal Level)
73
  if lead.assigned_to_manager_id:
74
  try:
75
  from app.models.user import User
76
  manager = await session.get(User, lead.assigned_to_manager_id)
77
  if manager and manager.telegram_chat_id and manager.telegram_chat_id not in sent_to_ids:
78
- await self._send_telegram_notification(
79
- chat_id=manager.telegram_chat_id,
80
- lead=lead,
81
- tenant=tenant
82
- )
83
  sent_to_ids.append(manager.telegram_chat_id)
84
- logger.info(f"Telegram notification sent to Manager {manager.email}")
85
  except Exception as e:
86
- logger.error(f"Failed to send Telegram notification to Manager: {e}")
87
-
88
- if sent_to_ids:
89
- notification.sent_telegram = True
90
- await session.commit()
91
 
92
- logger.info(f"HOT lead notification sent successfully")
93
-
94
  async def _get_notification_settings(
95
  self,
96
  session: AsyncSession,
97
  tenant_id: UUID
98
- ) -> Optional[NotificationSettings]:
99
- """Get notification settings for tenant."""
100
  stmt = select(NotificationSettings).where(
101
  NotificationSettings.tenant_id == tenant_id
102
  )
103
  result = await session.execute(stmt)
104
- return result.scalar_one_or_none()
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  async def _create_notification(
107
  self,
@@ -129,32 +185,17 @@ class NotificationService:
129
  def _format_hot_lead_message(self, lead: Lead) -> str:
130
  """Format HOT lead message with dialog summary."""
131
  parts = []
 
 
 
132
 
133
- if lead.name:
134
- parts.append(f"👤 {lead.name}")
135
-
136
- if lead.budget:
137
- parts.append(f"💰 Бюджет: {lead.budget}")
138
-
139
- if lead.heat_score:
140
- parts.append(f"📊 Heat Score: {lead.heat_score}/100")
141
-
142
- # Add dialog summary from AI summary
143
  if lead.ai_summary_json and isinstance(lead.ai_summary_json, dict):
144
  intent = lead.ai_summary_json.get('intent', '')
145
  summary = lead.ai_summary_json.get('summary', '')
146
- recommendation = lead.ai_summary_json.get('recommendation', '')
147
-
148
  if intent or summary:
149
  parts.append("\n📝 Краткое саммари:")
150
- if intent:
151
- parts.append(f"• Намерение: {intent}")
152
- if summary:
153
- # Truncate long summaries
154
- summary_text = summary[:300] + ('...' if len(summary) > 300 else '')
155
- parts.append(f"• {summary_text}")
156
- if recommendation:
157
- parts.append(f"💡 {recommendation[:150]}")
158
 
159
  return "\n".join(parts) if parts else "Новый горячий лид!"
160
 
@@ -162,46 +203,45 @@ class NotificationService:
162
  self,
163
  chat_id: str,
164
  lead: Lead,
165
- tenant: Tenant
 
166
  ):
167
- """Send notification to Telegram."""
168
- # Import here to avoid circular dependency
169
- from app.services.telegram_service import telegram_service
170
  from app.core.config import settings
171
 
172
- # ALWAYS use platform notification bot - NOT tenant's automation bot
173
- token = settings.TELEGRAM_NOTIFICATION_TOKEN
174
-
175
- if not token:
176
- logger.error(f"❌ TELEGRAM_NOTIFICATION_TOKEN not configured in environment")
177
- logger.error("⚠️ Set TELEGRAM_NOTIFICATION_TOKEN env var to enable notifications")
178
- return
179
-
180
- # Build notification URL from settings
181
  base_url = settings.FRONTEND_URL or "https://app.microfunnel.io"
182
  notification_url = f"{base_url}/chats?lead={lead.id}"
183
 
 
 
184
  message = f"""
185
- 🔥 <b>ГОРЯЧИЙ ЛИД!</b>
186
 
187
  {self._format_hot_lead_message(lead)}
188
 
189
  ➡️ <a href="{notification_url}">Открыть чат</a>
190
- """
 
 
 
 
 
 
 
191
 
 
 
 
 
 
 
 
192
  try:
193
- result = await telegram_service.send_message(
194
- token=token,
195
- chat_id=chat_id,
196
- text=message.strip()
197
- )
198
-
199
- success = result.get("success", False) if isinstance(result, dict) else result
200
- if not success:
201
- logger.error(f"❌ Telegram API returned failure for chat {chat_id}")
202
  except Exception as e:
203
- logger.error(f"❌ Exception sending Telegram notification: {e}", exc_info=True)
204
- raise
205
 
206
  async def notify_resource_booking(
207
  self,
 
29
  lead: Lead,
30
  tenant: Tenant
31
  ):
32
+ """Send notification when lead becomes HOT (heat >= 70)."""
33
+ logger.info(f"🚀 Sending HOT lead notification for lead {lead.id}")
 
 
 
 
 
 
34
 
 
35
  settings = await self._get_notification_settings(session, tenant.id)
36
  if not settings or not settings.notify_hot_leads:
 
37
  return
38
 
 
39
  notification = await self._create_notification(
40
  session=session,
41
  tenant_id=tenant.id,
 
45
  message=self._format_hot_lead_message(lead)
46
  )
47
 
48
+ sent_to_ids = await self._broadcast_telegram(session, tenant, lead, settings, "hot_lead")
49
+ if sent_to_ids:
50
+ notification.sent_telegram = True
51
+ await session.commit()
52
+
53
+ async def notify_new_order(self, session: AsyncSession, tenant: Tenant, order: "Order", items_text: str):
54
+ """Send alert about a new order."""
55
+ settings = await self._get_notification_settings(session, tenant.id)
56
+ if not settings or not settings.notify_orders:
57
+ return
58
+
59
+ message = (
60
+ f"💰 <b>НОВЫЙ ЗАКАЗ</b> 💰\n\n"
61
+ f"👤 Клиент: {order.lead.name or 'Неизвестно'}\n"
62
+ f"📦 Товары:\n{items_text}\n"
63
+ f"💵 Сумма: {order.total_amount:.2f}\n"
64
+ f"📅 Дата: {order.created_at.strftime('%d.%m %H:%M')}"
65
+ )
66
+ await self._send_telegram_raw(settings.telegram_chat_id, message)
67
+
68
+ async def notify_new_appointment(self, session: AsyncSession, tenant: Tenant, appointment: "Appointment", ai_summary: dict = None, resource_telegram_id: str = None):
69
+ """Send alert about a new booking."""
70
+ settings = await self._get_notification_settings(session, tenant.id)
71
+
72
+ chat_id = resource_telegram_id or (settings.telegram_chat_id if settings else None)
73
+ enabled = settings.notify_bookings if settings else True
74
+
75
+ if not chat_id or not enabled:
76
+ return
77
+
78
+ lead_name = appointment.lead.name if appointment.lead else 'Неизвестно'
79
+ heat_score = ai_summary.get("heat_score", 0) if ai_summary else 0
80
+ heat_emoji = "🔥" if heat_score >= 70 else "🟡" if heat_score >= 50 else "❄️"
81
+
82
+ message = (
83
+ f"📅 <b>НОВАЯ ЗАПИСЬ</b> 📅\n\n"
84
+ f"👤 Клиент: {lead_name}\n"
85
+ f"{heat_emoji} Теплота: {heat_score}%\n"
86
+ f"🎯 Интерес: {ai_summary.get('intent', '—') if ai_summary else '—'}\n"
87
+ f"───────────────\n"
88
+ f"🕒 Время: {appointment.start_time.strftime('%d.%m %H:%M')}\n"
89
+ f"📝 Услуга: {appointment.service.name if appointment.service else 'Общая'}\n"
90
+ )
91
+ await self._send_telegram_raw(chat_id, message)
92
+
93
+ async def notify_qualification_complete(self, session: AsyncSession, lead: Lead, tenant: Tenant):
94
+ """Send alert when all required qualification fields are filled."""
95
+ settings = await self._get_notification_settings(session, tenant.id)
96
+ if not settings or not settings.notify_qualification_complete:
97
+ return
98
+
99
+ qual_data = lead.qualification_data or {}
100
+ qual_text = "\n".join([f"• {k}: {v}" for k, v in qual_data.items() if v and str(v).lower() not in ["не выявлено", "unknown"]])
101
+
102
+ message = (
103
+ f"✅ <b>ЛИД КВАЛИФИЦИРОВАН</b> ✅\n\n"
104
+ f"👤 Клиент: {lead.name or 'Неизвестно'}\n"
105
+ f"📊 Теплота: {lead.heat_score}%\n"
106
+ f"───────────────\n"
107
+ f"📋 <b>ИНФОРМАЦИЯ:</b>\n"
108
+ f"{qual_text}\n"
109
+ )
110
+ await self._broadcast_telegram(session, tenant, lead, settings, "qualification")
111
+
112
+ async def _broadcast_telegram(self, session: AsyncSession, tenant: Tenant, lead: Lead, settings: NotificationSettings, type: str) -> list:
113
+ """Broadcast notification to both tenant channel and assigned manager."""
114
  sent_to_ids = []
115
+
116
+ # 1. Tenant Level
117
  if settings.telegram_enabled and settings.telegram_chat_id:
118
  try:
119
+ await self._send_telegram_notification(settings.telegram_chat_id, lead, tenant, type)
 
 
 
 
120
  sent_to_ids.append(settings.telegram_chat_id)
 
121
  except Exception as e:
122
+ logger.error(f"Failed to notify tenant channel: {e}")
123
 
124
+ # 2. Manager Level (assigned manager)
125
  if lead.assigned_to_manager_id:
126
  try:
127
  from app.models.user import User
128
  manager = await session.get(User, lead.assigned_to_manager_id)
129
  if manager and manager.telegram_chat_id and manager.telegram_chat_id not in sent_to_ids:
130
+ await self._send_telegram_notification(manager.telegram_chat_id, lead, tenant, type)
 
 
 
 
131
  sent_to_ids.append(manager.telegram_chat_id)
 
132
  except Exception as e:
133
+ logger.error(f"Failed to notify manager: {e}")
 
 
 
 
134
 
135
+ return sent_to_ids
136
+
137
  async def _get_notification_settings(
138
  self,
139
  session: AsyncSession,
140
  tenant_id: UUID
141
+ ) -> NotificationSettings:
142
+ """Get notification settings for tenant. Returns defaults if not found."""
143
  stmt = select(NotificationSettings).where(
144
  NotificationSettings.tenant_id == tenant_id
145
  )
146
  result = await session.execute(stmt)
147
+ settings = result.scalar_one_or_none()
148
+
149
+ if not settings:
150
+ # RETURN DEFAULT SETTINGS if not in DB - This fixes the "no notifications" bug for new tenants
151
+ logger.info(f"No notification settings found for tenant {tenant_id}, using defaults")
152
+ return NotificationSettings(
153
+ tenant_id=tenant_id,
154
+ telegram_enabled=True,
155
+ notify_hot_leads=True,
156
+ notify_qualification_complete=True,
157
+ notify_orders=True,
158
+ notify_bookings=True
159
+ )
160
+ return settings
161
 
162
  async def _create_notification(
163
  self,
 
185
  def _format_hot_lead_message(self, lead: Lead) -> str:
186
  """Format HOT lead message with dialog summary."""
187
  parts = []
188
+ if lead.name: parts.append(f"👤 {lead.name}")
189
+ if lead.budget: parts.append(f"💰 Бюджет: {lead.budget}")
190
+ if lead.heat_score: parts.append(f"📊 Heat Score: {lead.heat_score}/100")
191
 
 
 
 
 
 
 
 
 
 
 
192
  if lead.ai_summary_json and isinstance(lead.ai_summary_json, dict):
193
  intent = lead.ai_summary_json.get('intent', '')
194
  summary = lead.ai_summary_json.get('summary', '')
 
 
195
  if intent or summary:
196
  parts.append("\n📝 Краткое саммари:")
197
+ if intent: parts.append(f"• Намерение: {intent}")
198
+ if summary: parts.append(f"• {summary[:300]}...")
 
 
 
 
 
 
199
 
200
  return "\n".join(parts) if parts else "Новый горячий лид!"
201
 
 
203
  self,
204
  chat_id: str,
205
  lead: Lead,
206
+ tenant: Tenant,
207
+ notif_type: str = "hot_lead"
208
  ):
209
+ """Format and send a structured lead notification."""
 
 
210
  from app.core.config import settings
211
 
 
 
 
 
 
 
 
 
 
212
  base_url = settings.FRONTEND_URL or "https://app.microfunnel.io"
213
  notification_url = f"{base_url}/chats?lead={lead.id}"
214
 
215
+ title = "🔥 <b>ГОРЯЧИЙ ЛИД!</b>" if notif_type == "hot_lead" else "✅ <b>ЛИД КВАЛИФИЦИРОВАН!</b>"
216
+
217
  message = f"""
218
+ {title}
219
 
220
  {self._format_hot_lead_message(lead)}
221
 
222
  ➡️ <a href="{notification_url}">Открыть чат</a>
223
+ """.strip()
224
+
225
+ await self._send_telegram_raw(chat_id, message)
226
+
227
+ async def _send_telegram_raw(self, chat_id: str, text: str):
228
+ """Low-level Telegram sender using platform bot token."""
229
+ from app.services.telegram_service import telegram_service
230
+ from app.core.config import settings
231
 
232
+ token = settings.TELEGRAM_NOTIFICATION_TOKEN
233
+ if not token:
234
+ logger.error("❌ TELEGRAM_NOTIFICATION_TOKEN not set")
235
+ return
236
+ if not chat_id:
237
+ return
238
+
239
  try:
240
+ await telegram_service.send_message(token=token, chat_id=chat_id, text=text)
241
+ logger.info(f"📧 Notification sent to {chat_id}")
 
 
 
 
 
 
 
242
  except Exception as e:
243
+ logger.error(f"❌ Telegram error: {e}")
244
+
245
 
246
  async def notify_resource_booking(
247
  self,