Spaces:
Running

axeronis commited on
Commit
466bb5f
·
1 Parent(s): 4b19259

feat(ai): smart AI-powered payment/order detection with context analysis

Browse files
backend/app/services/ai_core/lead_analyzer.py CHANGED
@@ -282,6 +282,161 @@ async def check_and_notify_qualification_complete(
282
  logger.error(f"Failed to send qualification notification: {e}")
283
 
284
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  # ============================================================================
286
  # BANT Extraction
287
  # ============================================================================
@@ -559,6 +714,16 @@ async def analyze_lead_impl(
559
 
560
  # Trigger CRM auto-sync
561
  await trigger_crm_auto_sync(session, lead)
 
 
 
 
 
 
 
 
 
 
562
 
563
 
564
  # PLAYBOOK: Evaluate Stage Transition
 
282
  logger.error(f"Failed to send qualification notification: {e}")
283
 
284
 
285
+ async def detect_payment_or_order(
286
+ ai_core: "AICore",
287
+ session: AsyncSession,
288
+ lead: Lead,
289
+ conversation_history: List[Message],
290
+ tenant
291
+ ) -> bool:
292
+ """
293
+ AI-powered smart payment/order detection.
294
+
295
+ Instead of simple keyword matching, uses LLM to understand context:
296
+ - "Я оплатил" → payment
297
+ - "Скинь реквизиты, сейчас переведу" → intent to pay
298
+ - "Готово, чек отправил" → payment confirmation
299
+ - Client sends screenshot of payment → payment
300
+ - "Заказал через сайт" → order placed
301
+
302
+ Returns True if payment/order detected.
303
+ """
304
+ # Skip if already notified about this payment
305
+ if getattr(lead, 'payment_notified', False):
306
+ return False
307
+
308
+ # Get last 10 messages for context
309
+ recent_messages = conversation_history[-10:]
310
+ conversation_text = "\n".join([
311
+ f"{'КЛИЕНТ' if msg.sender_type == 'user' else 'БОТ'}: {msg.content[:200]}"
312
+ for msg in recent_messages
313
+ ])
314
+
315
+ # Check if any message has media (could be payment screenshot)
316
+ has_media = any(
317
+ msg.media_type and 'image' in (msg.media_type or '').lower()
318
+ for msg in recent_messages[-3:] # Only last 3 messages
319
+ )
320
+
321
+ prompt = f"""Проанализируй диалог и определи: ОПЛАТИЛ ли клиент или СДЕЛАЛ ЗАКАЗ?
322
+
323
+ ДИАЛОГ:
324
+ {conversation_text}
325
+
326
+ {'⚠️ КЛИЕНТ ОТПРАВИЛ ИЗОБРАЖЕНИЕ (возможно скриншот оплаты)' if has_media else ''}
327
+
328
+ ПРИЗНАКИ ОПЛАТЫ/ЗАКАЗА:
329
+ - Клиент говорит "оплатил", "перевёл", "отправил деньги", "заплатил"
330
+ - Клиент говорит "готово", "сделано" после обсуждения оплаты
331
+ - Клиент говорит "заказал", "оформил заказ", "купил"
332
+ - Клиент отправляет чек/скриншот оплаты
333
+ - Клиент подтверждает покупку
334
+
335
+ НЕ СЧИТАТЬ ОПЛАТОЙ:
336
+ - Клиент только СПРАШИВАЕТ как оплатить
337
+ - Клиент говорит "оплачу позже/завтра"
338
+ - Клиент обсуждает цену
339
+ - Нет явного подтверждения оплаты
340
+
341
+ Ответь в JSON формате (только JSON):
342
+ {{"payment_detected": true/false, "type": "payment/order/none", "confidence": "high/medium/low", "evidence": "краткое объяснение"}}"""
343
+
344
+ try:
345
+ response = await ai_core.llm.generate_response(
346
+ prompt=prompt,
347
+ system_instruction="Ты аналитик. Отвечай ТОЛЬКО валидным JSON. Будь точным - лучше пропустить чем ошибиться.",
348
+ temperature=0.1
349
+ )
350
+
351
+ import json
352
+ import re
353
+
354
+ text = response["text"].strip()
355
+ json_match = re.search(r'\{[^{}]+\}', text, re.DOTALL)
356
+
357
+ if json_match:
358
+ data = json.loads(json_match.group())
359
+ payment_detected = data.get("payment_detected", False)
360
+ payment_type = data.get("type", "none")
361
+ confidence = data.get("confidence", "low")
362
+ evidence = data.get("evidence", "")
363
+
364
+ # Only consider high/medium confidence detections
365
+ if payment_detected and confidence in ["high", "medium"]:
366
+ logger.info(f"💰 Payment/order detected for lead {lead.id}: {payment_type} ({confidence})")
367
+
368
+ # Send notification
369
+ await _notify_payment_or_order(
370
+ session, lead, tenant, payment_type, evidence
371
+ )
372
+ return True
373
+
374
+ return False
375
+
376
+ except Exception as e:
377
+ logger.error(f"Payment detection failed: {e}")
378
+ return False
379
+
380
+
381
+ async def _notify_payment_or_order(
382
+ session: AsyncSession,
383
+ lead: Lead,
384
+ tenant,
385
+ payment_type: str,
386
+ evidence: str
387
+ ):
388
+ """Send Telegram notification about payment/order."""
389
+ try:
390
+ settings = tenant.notification_settings or {}
391
+
392
+ # Check if order notifications are enabled
393
+ if not settings.get("notify_on_order", True):
394
+ return
395
+
396
+ tg_chat_id = settings.get("telegram_chat_id")
397
+ if not tg_chat_id:
398
+ return
399
+
400
+ # Build message
401
+ emoji = "💰" if payment_type == "payment" else "🛒"
402
+ title = "ОПЛАТА ПОЛУЧЕНА!" if payment_type == "payment" else "НОВЫЙ ЗАКАЗ!"
403
+
404
+ message = (
405
+ f"{emoji} <b>{title}</b>\n\n"
406
+ f"👤 Клиент: {lead.name or 'Неизвестно'}\n"
407
+ f"📊 Теплота: {lead.heat_score or 0}%\n"
408
+ f"───────────────\n"
409
+ f"💬 Что случилось:\n{evidence}\n"
410
+ f"───────────────\n"
411
+ f"➡️ <a href=\"https://app.microfunnel.io/chats?lead={lead.id}\">Открыть чат</a>"
412
+ )
413
+
414
+ from app.services.notification_service import get_notification_service
415
+ notification_service = get_notification_service()
416
+
417
+ await notification_service._send_telegram_notification(
418
+ chat_id=tg_chat_id,
419
+ lead=lead,
420
+ tenant=tenant
421
+ )
422
+
423
+ # Alternative: direct send
424
+ from app.core.config import settings as app_settings
425
+ from app.services.telegram_service import telegram_service
426
+
427
+ token = app_settings.TELEGRAM_NOTIFICATION_TOKEN
428
+ if token:
429
+ await telegram_service.send_message(
430
+ token=token,
431
+ chat_id=tg_chat_id,
432
+ text=message
433
+ )
434
+ logger.info(f"✅ Payment notification sent for lead {lead.id}")
435
+
436
+ except Exception as e:
437
+ logger.error(f"Failed to send payment notification: {e}")
438
+
439
+
440
  # ============================================================================
441
  # BANT Extraction
442
  # ============================================================================
 
714
 
715
  # Trigger CRM auto-sync
716
  await trigger_crm_auto_sync(session, lead)
717
+
718
+ # AI-POWERED PAYMENT/ORDER DETECTION
719
+ try:
720
+ payment_detected = await detect_payment_or_order(
721
+ ai_core, session, lead, conversation_history, tenant
722
+ )
723
+ if payment_detected:
724
+ print(f"💰 Payment/order detected and notification sent for {lead.id}")
725
+ except Exception as pe:
726
+ print(f"⚠️ Payment detection failed (non-critical): {pe}")
727
 
728
 
729
  # PLAYBOOK: Evaluate Stage Transition