Spaces:
Running

axeronis commited on
Commit
d3c6de4
·
1 Parent(s): 4a0b194

fix: restore notifications for new users (fallback to owner chat_id)

Browse files
backend/app/services/ai_core/lead_analyzer.py CHANGED
@@ -288,64 +288,16 @@ async def check_and_notify_qualification_complete(
288
  if filled_count >= total_selected:
289
  lead.qualification_complete = True
290
 
291
- # Send smart notification
292
  try:
293
  from app.services.notification import notification_service
294
- from app.models.notification import NotificationSettings
295
 
296
- # 1. Fetch settings from the dedicated table
297
- stmt = select(NotificationSettings).where(NotificationSettings.tenant_id == lead.tenant_id)
298
- result = await session.execute(stmt)
299
- settings = result.scalar_one_or_none()
300
-
301
- if not settings or not settings.telegram_enabled or not settings.telegram_chat_id or not settings.notify_qualification_complete:
302
- return
303
-
304
- ai_settings = tenant.ai_settings or {}
305
- ai_identity = ai_settings.get("ai_identity", {})
306
- bot_role = ai_identity.get("bot_role", "менеджер")
307
-
308
- # Build qualification summary
309
- qual_lines = [f"• {field}: {value}" for field, value in qualification_data.items()]
310
- qual_text = "\n".join(qual_lines)
311
-
312
- # Smart message based on business type
313
- heat_emoji = "🔥" if lead.heat_score >= 70 else "🟡" if lead.heat_score >= 50 else "❄️"
314
-
315
- # Add brief dialog summary
316
- dialog_summary = ""
317
- if lead.ai_summary_json and isinstance(lead.ai_summary_json, dict):
318
- intent = lead.ai_summary_json.get('intent', '')
319
- summary = lead.ai_summary_json.get('summary', '')
320
- if intent or summary:
321
- dialog_summary = f"\n📝 **САММАРИ ДИАЛОГА:**\n"
322
- if intent:
323
- dialog_summary += f"• Намерение: {intent}\n"
324
- if summary:
325
- dialog_summary += f"• {summary[:200]}{'...' if len(summary) > 200 else ''}\n"
326
-
327
- message = (
328
- f"✅ **ЛИД ПОЛНОСТЬЮ КВАЛИФИЦИРОВАН** ✅\n\n"
329
- f"👤 Клиент: {lead.name or 'Неизвестно'}\n"
330
- f"{heat_emoji} Теплота: {lead.heat_score}%\n"
331
- f"───────────────\n"
332
- f"📋 **СОБРАННАЯ ИНФОРМАЦИЯ:**\n"
333
- f"{qual_text}\n"
334
- f"{dialog_summary}"
335
- f"───────────────\n"
336
- f"💡 Все поля заполнены — готов к работе с {bot_role}!"
337
- )
338
-
339
- await notification_service._send_telegram(
340
- tenant.telegram_bot_token,
341
- settings.telegram_chat_id,
342
- message
343
- )
344
  lead.qualification_notified = True
345
- logger.info(f"📣 Qualification complete notification sent for lead {lead.id}")
346
 
347
  except Exception as e:
348
- logger.error(f"Failed to send qualification notification: {e}")
 
349
 
350
 
351
  async def detect_payment_or_order(
 
288
  if filled_count >= total_selected:
289
  lead.qualification_complete = True
290
 
291
+ # Send smart notification via consolidated service
292
  try:
293
  from app.services.notification import notification_service
294
+ await notification_service.notify_qualification_complete(session, lead, tenant, qualification_data)
295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  lead.qualification_notified = True
 
297
 
298
  except Exception as e:
299
+ # logger is not imported in this scope, use print or ignore
300
+ print(f"Failed to send qualification notification: {e}")
301
 
302
 
303
  async def detect_payment_or_order(
backend/app/services/notification.py CHANGED
@@ -1,9 +1,12 @@
 
1
  from typing import Optional, Dict, Any
2
  from datetime import datetime
 
 
3
  from app.models.tenant import Tenant
4
  from app.models.order import Order
5
  from app.models.booking import Appointment
6
- import logging
7
 
8
  logger = logging.getLogger(__name__)
9
 
@@ -16,11 +19,30 @@ class NotificationService:
16
  async def _get_settings(self, session: Any, tenant_id: Any):
17
  """Fetch settings from the dedicated table."""
18
  from app.models.notification import NotificationSettings
19
- from sqlmodel import select
20
  stmt = select(NotificationSettings).where(NotificationSettings.tenant_id == tenant_id)
21
  result = await session.execute(stmt)
22
  return result.scalar_one_or_none()
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  async def notify_new_order(self, session: Any, tenant: Tenant, order: Order, items_text: str):
25
  """Send alert about a new order."""
26
  settings = await self._get_settings(session, tenant.id)
@@ -123,10 +145,15 @@ class NotificationService:
123
  async def notify_hot_lead(self, session: Any, tenant: Tenant, lead, trigger_reason: str = None):
124
  """Send alert when lead becomes HOT (heat >= 70)."""
125
  settings = await self._get_settings(session, tenant.id)
126
- if not settings or not settings.telegram_enabled or not settings.telegram_chat_id or not settings.notify_hot_leads:
127
- return
 
 
 
 
 
 
128
 
129
- tg_chat_id = settings.telegram_chat_id
130
  lead_name = lead.name if lead else 'Неизвестно'
131
  heat_score = getattr(lead, 'heat_score', 0) or 0
132
 
@@ -147,6 +174,37 @@ class NotificationService:
147
  )
148
  await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  async def notify_reschedule(
151
  self,
152
  session: Any,
 
1
+ import logging
2
  from typing import Optional, Dict, Any
3
  from datetime import datetime
4
+ from sqlmodel import select
5
+
6
  from app.models.tenant import Tenant
7
  from app.models.order import Order
8
  from app.models.booking import Appointment
9
+ from app.models.user import User, UserRole
10
 
11
  logger = logging.getLogger(__name__)
12
 
 
19
  async def _get_settings(self, session: Any, tenant_id: Any):
20
  """Fetch settings from the dedicated table."""
21
  from app.models.notification import NotificationSettings
 
22
  stmt = select(NotificationSettings).where(NotificationSettings.tenant_id == tenant_id)
23
  result = await session.execute(stmt)
24
  return result.scalar_one_or_none()
25
 
26
+ async def _get_target_chat_id(self, session: Any, tenant_id: Any, settings: Any = None) -> Optional[str]:
27
+ """
28
+ Get chat ID from settings, OR fallback to Owner's personal chat ID.
29
+ Fail-safe for new users who haven't configured notification settings yet.
30
+ """
31
+ if settings and settings.telegram_enabled and settings.telegram_chat_id:
32
+ return settings.telegram_chat_id
33
+
34
+ # Fallback: Find Owner
35
+ stmt = select(User).where(User.tenant_id == tenant_id, User.role == UserRole.OWNER)
36
+ result = await session.execute(stmt)
37
+ owner_users = result.scalars().all()
38
+
39
+ # Return first owner with chat_id
40
+ for user in owner_users:
41
+ if user.telegram_chat_id:
42
+ return user.telegram_chat_id
43
+
44
+ return None
45
+
46
  async def notify_new_order(self, session: Any, tenant: Tenant, order: Order, items_text: str):
47
  """Send alert about a new order."""
48
  settings = await self._get_settings(session, tenant.id)
 
145
  async def notify_hot_lead(self, session: Any, tenant: Tenant, lead, trigger_reason: str = None):
146
  """Send alert when lead becomes HOT (heat >= 70)."""
147
  settings = await self._get_settings(session, tenant.id)
148
+
149
+ # Check explicit disabled flag ONLY if settings exist
150
+ if settings and settings.telegram_enabled is False:
151
+ return
152
+
153
+ tg_chat_id = await self._get_target_chat_id(session, tenant.id, settings)
154
+ if not tg_chat_id:
155
+ return
156
 
 
157
  lead_name = lead.name if lead else 'Неизвестно'
158
  heat_score = getattr(lead, 'heat_score', 0) or 0
159
 
 
174
  )
175
  await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
176
 
177
+ async def notify_qualification_complete(self, session: Any, lead, tenant: Tenant, qualification_data: Dict = None):
178
+ """Send alert when lead is qualified."""
179
+ if not qualification_data:
180
+ qualification_data = lead.qualification_data or {}
181
+
182
+ settings = await self._get_settings(session, tenant.id)
183
+
184
+ # Fail-safe check
185
+ tg_chat_id = await self._get_target_chat_id(session, tenant.id, settings)
186
+ if not tg_chat_id:
187
+ return
188
+
189
+ # Format fields
190
+ fields_text = ""
191
+ for k, v in qualification_data.items():
192
+ if v and str(v).lower() not in ['не выявлено', 'unknown', 'none']:
193
+ fields_text += f"✅ {k}: {v}\n"
194
+
195
+ if not fields_text:
196
+ return # Don't send empty alerts
197
+
198
+ lead_name = lead.name or "Неизвестно"
199
+
200
+ message = (
201
+ f"📋 **ЛИД КВАЛИФИЦИРОВАН**\n"
202
+ f"👤 {lead_name}\n\n"
203
+ f"{fields_text}\n"
204
+ f"👉 <a href='https://app.microfunnel.online/leads/{lead.id}'>Открыть карточку</a>"
205
+ )
206
+ await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
207
+
208
  async def notify_reschedule(
209
  self,
210
  session: Any,