Spaces:
Running

File size: 14,461 Bytes
d3c6de4
c56f47b
f9d6bc4
d3c6de4
 
c56f47b
 
 
d3c6de4
c56f47b
 
 
 
 
 
 
 
 
229300b
 
 
 
 
 
 
a043a19
 
c13b20f
a043a19
 
 
 
 
 
 
 
 
 
 
 
d3c6de4
 
a043a19
d3c6de4
a043a19
d3c6de4
 
c13b20f
d3c6de4
 
c13b20f
d3c6de4
 
229300b
c56f47b
229300b
 
c56f47b
 
229300b
c56f47b
 
 
 
 
 
 
 
229300b
c56f47b
bc65edb
 
229300b
bc65edb
 
 
229300b
bc65edb
9fb267a
229300b
 
bc65edb
 
 
c56f47b
bc65edb
229300b
bc65edb
229300b
 
bc65edb
 
 
9fb267a
bc65edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c56f47b
229300b
f81e845
229300b
 
f81e845
 
229300b
 
 
 
f81e845
229300b
 
 
 
 
 
 
 
 
 
 
 
 
 
f81e845
229300b
f81e845
ace167a
 
229300b
ace167a
d3c6de4
 
 
ace167a
d3c6de4
 
 
ace167a
 
d3c6de4
ace167a
 
f81e845
229300b
 
f81e845
229300b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ace167a
229300b
ace167a
f81e845
d3c6de4
 
9b16b22
 
d3c6de4
 
9b16b22
 
d3c6de4
 
9b16b22
d3c6de4
 
 
9b16b22
 
d3c6de4
9b16b22
d3c6de4
 
 
 
 
 
 
 
 
9b16b22
d3c6de4
 
 
 
 
 
 
 
 
 
9b16b22
d3c6de4
9b16b22
d3c6de4
f9d6bc4
 
229300b
f9d6bc4
 
 
 
 
 
 
229300b
 
f9d6bc4
 
229300b
 
 
f9d6bc4
229300b
 
 
 
 
 
 
 
 
 
f9d6bc4
229300b
895402e
229300b
 
895402e
 
229300b
 
895402e
229300b
 
 
 
 
 
 
 
 
895402e
c56f47b
 
6d9f4f9
455a5d9
 
6d9f4f9
 
455a5d9
 
6d9f4f9
c56f47b
 
 
 
 
 
 
 
455a5d9
c56f47b
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
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()