Spaces:
Running

microfunnel-api / backend /app /api /webhook.py
axeronis's picture
Fix: [SEND_VOICE] tag leak when voice disabled + Update notification bot token
79c4ca3
Raw History Blame Contribute Delete
114 kB
from fastapi import APIRouter, Request, HTTPException, Depends, BackgroundTasks, Header from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import func from sqlmodel import select from typing import Dict, Any, Optional from datetime import datetime from uuid import UUID import httpx import hmac import hashlib import asyncio from app.core.database import get_session from app.models.tenant import Tenant from app.models.lead import Lead, Conversation, Message, LeadStatus, Psychotype, MessageStatus from app.services.ai_core import get_ai_core from app.services.email import get_email_service from app.services.subscription_manager import SubscriptionManager from app.core.config import settings from app.core.logging import get_logger from app.api.telegram_webhook import transcribe_telegram_voice, analyze_telegram_image, analyze_telegram_document logger = get_logger(__name__) def _extract_topic_from_conversation(conversation_history, user_message: str) -> str: """ Extract topic from conversation for booking notes. Returns topic string like "автоматизация, продажи" """ topic_keywords = [] keywords_to_find = [ "автоматизация", "продажи", "консультация", "внедрение", "аудит", "ai", "бот", "crm", "интеграция", "помощь", "партнер", "цена", "стоимость", "демо", "обучение", "вопрос", "услуга", "тариф", "подписка" ] # Check last 10 user messages for keywords user_messages = [msg.content.lower() for msg in conversation_history[-10:] if msg.sender_type == "user"] user_messages.append(user_message.lower()) for msg in user_messages: for keyword in keywords_to_find: if keyword in msg and keyword not in topic_keywords: topic_keywords.append(keyword) if len(topic_keywords) >= 3: break return ", ".join(topic_keywords) if topic_keywords else "Консультация" def _extract_booking_info_from_conversation(conversation_history, lead, user_text: str) -> dict: """ Extract booking info from conversation history. Returns dict with: name, phone, topic for comprehensive notes. Universal for any business type. """ import re # Get best available name: AI-extracted > lead.name > "Клиент" best_name = "Клиент" # 1. Try AI-extracted name from summary (most reliable) if lead and lead.ai_summary_json: ai_name = lead.ai_summary_json.get('client_name') if ai_name and isinstance(ai_name, str) and len(ai_name) >= 2: best_name = ai_name # 2. Fallback to lead.name if no AI name if best_name == "Клиент" and lead and lead.name: best_name = lead.name info = { "name": best_name, "phone": lead.phone if lead and lead.phone else None, "topic": None } # Get user messages user_messages = [msg.content for msg in conversation_history if msg.sender_type == "user"] # Patterns for phone extraction phone_patterns = [ r'[\+]?[0-9]{10,15}', # International format r'[\+]?996\s*\d{9}', # Kyrgyzstan r'[\+]?7\s*\d{10}', # Russia r'\d{3}[\s\-]?\d{3}[\s\-]?\d{4}', # 999-123-4567 ] # Extract phone if not already have if not info["phone"]: for msg in reversed(user_messages[-15:]): for pattern in phone_patterns: match = re.search(pattern, msg) if match: info["phone"] = match.group(0).strip() break if info["phone"]: break # Extract topic from AI summary (niche or intent) - UNIVERSAL for any business topic_parts = [] if lead and lead.ai_summary_json: # Try niche first (client's business area) niche = lead.ai_summary_json.get('niche') if niche and isinstance(niche, str) and len(niche) > 2: topic_parts.append(niche) # Then intent intent = lead.ai_summary_json.get('intent', '') if intent and len(intent) > 3 and len(intent) < 50: # Clean up generic phrases intent_clean = intent.replace('Не выявлен', '').replace('Анализ в процессе', '').strip() if intent_clean and intent_clean not in topic_parts: topic_parts.append(intent_clean[:40]) # Limit length info["topic"] = " | ".join(topic_parts) if topic_parts else "Консультация" return info async def _find_available_slots( session, tenant_id: UUID, requested_time: datetime, count: int = 3, duration_minutes: int = 30 ) -> list: """ Find next N available time slots after requested_time. Returns list of datetime objects for available slots. """ from app.models.booking import Appointment, AppointmentStatus from app.models.tenant import Tenant from datetime import timedelta available_slots = [] # Get tenant booking settings for working hours tenant = await session.get(Tenant, tenant_id) booking_settings = tenant.booking_settings or {} if tenant else {} working_hours = booking_settings.get('working_hours', {}) working_days = booking_settings.get('working_days', ['mon', 'tue', 'wed', 'thu', 'fri']) start_hour = int(working_hours.get('start', '09:00').split(':')[0]) end_hour = int(working_hours.get('end', '18:00').split(':')[0]) # Day mapping day_map = {'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5, 'sun': 6} working_day_nums = [day_map.get(d, 0) for d in working_days] # Get all booked slots for the next 7 days end_search = requested_time + timedelta(days=7) stmt = select(Appointment).where( Appointment.tenant_id == tenant_id, Appointment.status == AppointmentStatus.SCHEDULED, Appointment.start_time >= requested_time, Appointment.start_time <= end_search ) result = await session.execute(stmt) booked_appointments = result.scalars().all() booked_times = {appt.start_time for appt in booked_appointments} # Start searching from requested time, move forward in 30-min increments current = requested_time + timedelta(minutes=duration_minutes) while len(available_slots) < count and current < end_search: # Check if within working hours is_working_day = current.weekday() in working_day_nums is_working_hour = start_hour <= current.hour < end_hour if is_working_day and is_working_hour: # Check if not booked if current not in booked_times: available_slots.append(current) # Move to next slot current += timedelta(minutes=duration_minutes) # If we've moved past end of day, jump to next day start if current.hour >= end_hour: next_day = current.date() + timedelta(days=1) current = datetime.combine(next_day, datetime.min.time().replace(hour=start_hour)) return available_slots async def send_product_images_if_mentioned( session, tenant_id: UUID, bot_token: str, chat_id: str, ai_text: str, lead_id: UUID, # NEW: for media tracking conversation_id: UUID = None ) -> Optional[int]: """ Detect product names mentioned in AI response and send ALL their images. Also saves image messages to database so they appear in chat UI. """ from app.models.product import Product from app.services.telegram_service import telegram_service from app.services.ai_core.media_tracker import media_tracker # Import tracker # Get all products with images for this tenant stmt = select(Product).where( Product.tenant_id == tenant_id, Product.is_active == True ) result = await session.execute(stmt) products = result.scalars().all() if not products: return None import re # Fetch lead to access/update DB persistence from app.models.lead import Lead lead = await session.get(Lead, lead_id) if not lead: return None ai_text_lower = ai_text.lower() last_message_id = None # Load persistent sent products: { "product_id": "message_id" } summary = lead.ai_summary_json or {} sent_products_db = summary.get("sent_products", {}) # Ensure it's a dict (migration from older list format if any) if isinstance(sent_products_db, list): sent_products_db = {pid: None for pid in sent_products_db} for product in products: # Strict Regex Match (Word Boundary) to avoid "Start" matching "Start your day" # Escape special chars in product name pattern = r'(?<!\w)' + re.escape(product.name.lower()) + r'(?!\w)' if re.search(pattern, ai_text_lower): product_id_str = str(product.id) lead_id_str = str(lead_id) # 1. Check DB Persistence (Primary) cached_msg_id_db = sent_products_db.get(product_id_str) # 2. Check RAM Persistence (Secondary/Fallback) cached_msg_id_ram = media_tracker.get_message_id_for_product(lead_id_str, product_id_str) cached_msg_id = cached_msg_id_db or cached_msg_id_ram if cached_msg_id: logger.info(f"♻️ Product {product.name} already sent (DB/RAM cache). Using msg_id {cached_msg_id} for reply.") try: last_message_id = int(cached_msg_id) return last_message_id except: pass continue # Collect all image URLs all_image_urls = [] # Add all images from image_urls array if product.image_urls and len(product.image_urls) > 0: all_image_urls.extend(product.image_urls) # Fallback: add single image_url if present and not already in list elif product.image_url and product.image_url not in all_image_urls: all_image_urls.append(product.image_url) if not all_image_urls: continue # Caption without box emoji caption = product.name try: # Send all photos as a media group (album) result = await telegram_service.send_media_group( token=bot_token, chat_id=chat_id, photo_urls=all_image_urls, caption=caption ) if result["success"]: last_message_id = result["message_id"] logger.info(f"📷 Auto-sent {len(all_image_urls)} images as album for product: {product.name} (msg_id: {last_message_id})") # TRACK SENT STATUS (RAM) media_tracker.mark_product_sent( lead_id_str, product_id_str, message_id=str(last_message_id) ) # TRACK SENT STATUS (DB) sent_products_db[product_id_str] = str(last_message_id) summary["sent_products"] = sent_products_db lead.ai_summary_json = summary session.add(lead) await session.commit() # Save one message for the album in database if conversation_id and result["success"]: image_message = Message( conversation_id=conversation_id, tenant_id=tenant_id, sender_type="ai", content=f"{product.name} ({len(all_image_urls)} фото)", media_url=all_image_urls[0], # First image as preview media_type="image", media_name=f"{product.name}.jpg" ) session.add(image_message) except Exception as e: logger.error(f"❌ Failed to send album for {product.name}: {e}") # Commit all image messages if any were added if conversation_id: await session.commit() return last_message_id async def send_payment_qr_codes( session, tenant_id: UUID, bot_token: str, chat_id: str, payment_qr_ids: list, conversation_id: UUID = None ) -> Optional[int]: """ Send payment QR codes from PaymentMethod when AI uses [SEND_PAYMENT_QR:ID] tag. """ from app.models.knowledge import PaymentMethod from app.services.telegram_service import telegram_service last_sent_message_id = None for qr_id_short in payment_qr_ids: try: # Find payment method by ID prefix (first 8 chars) stmt = select(PaymentMethod).where( PaymentMethod.tenant_id == tenant_id, PaymentMethod.is_active == True ) result = await session.execute(stmt) all_payments = result.scalars().all() # Find matching payment by ID prefix payment = None for pm in all_payments: if str(pm.id).startswith(qr_id_short): payment = pm break if not payment: logger.warning(f"⚠️ Payment method not found: {qr_id_short}") continue if not payment.image_url: logger.warning(f"⚠️ Payment method {payment.name} has no QR image") continue # Send QR code image try: result = await telegram_service.send_photo( token=bot_token, chat_id=chat_id, photo_url=payment.image_url, caption=f"💳 {payment.name}" ) if result and result.get("message_id"): last_sent_message_id = result["message_id"] logger.info(f"📱 Payment QR sent: {payment.name}, message_id: {last_sent_message_id}") except Exception as e: logger.error(f"❌ Failed to send payment QR {payment.name}: {e}") except Exception as e: logger.error(f"❌ Failed to process payment QR {qr_id_short}: {e}") return last_sent_message_id async def send_media_files( session, tenant_id: UUID, lead_id: UUID, bot_token: str, chat_id: str, media_ids: list, conversation_id: UUID = None, user_message: str = "" # For context in Reply ) -> Optional[int]: """ Send media files from MediaLibrary when AI uses [SEND_MEDIA:ID] tag. Records progress to prevent duplicate sends. NEW: If media was already sent, uses Reply feature to reference it. """ from app.models.knowledge import KnowledgeFile, LeadContentProgress from app.models.lead import Message from app.services.telegram_service import telegram_service from app.services.ai_core.media_tracker import media_tracker from app.services.llm_client import get_llm_client from datetime import datetime last_sent_message_id = None for media_id_short in media_ids: try: # Find media file by ID prefix (we use first 8 chars in prompt) stmt = select(KnowledgeFile).where( KnowledgeFile.tenant_id == tenant_id, KnowledgeFile.is_active == True ) result = await session.execute(stmt) all_files = result.scalars().all() # Find matching file by ID prefix media_file = None for f in all_files: if str(f.id).startswith(media_id_short): media_file = f break if not media_file: logger.warning(f"⚠️ Media file not found: {media_id_short}") continue # Check if already sent to this lead progress_stmt = select(LeadContentProgress).where( LeadContentProgress.lead_id == lead_id, LeadContentProgress.knowledge_file_id == media_file.id ) progress_result = await session.execute(progress_stmt) existing_progress = progress_result.scalar_one_or_none() media_id_str = str(media_file.id) lead_id_str = str(lead_id) # Check if already sent - use Reply feature instead of skipping if existing_progress and existing_progress.sent_at: # Get cached message_id for Reply cached_message_id = media_tracker.get_message_id_for_media(lead_id_str, media_id_str) if cached_message_id: # Generate contextual reference to the media try: llm = get_llm_client() reference_text = await llm.generate_media_reference_text( media_type=media_file.file_type or "image", product_name=media_file.name, user_question=user_message ) except Exception: reference_text = f"Обратите внимание на {media_file.name} выше:" # Send Reply to the original media message await telegram_service.send_message( token=bot_token, chat_id=chat_id, text=reference_text, reply_to_message_id=int(cached_message_id) ) logger.info(f"📎 Sent Reply reference to already-sent media: {media_file.name}") else: logger.info(f"📁 Media already sent but no message_id cached: {media_file.name}") continue # Determine what to send file_url = media_file.file_url or media_file.external_link if not file_url: logger.warning(f"⚠️ Media file has no URL: {media_file.name}") continue # Send based on file type caption = media_file.name if media_file.description: caption += f"\n{media_file.description}" send_result = {"success": False, "message_id": None} if media_file.file_type in ['image', 'qr']: send_result = await telegram_service.send_photo( token=bot_token, chat_id=chat_id, photo_url=file_url, caption=caption ) elif media_file.file_type == 'video': send_result = await telegram_service.send_video( token=bot_token, chat_id=chat_id, video_url=file_url, caption=caption ) elif media_file.file_type == 'document': send_result = await telegram_service.send_document( token=bot_token, chat_id=chat_id, document_url=file_url, caption=caption ) elif media_file.file_type in ['link']: # Send as text message with link # send_message returns dict with message_id in recent update (not yet, send_message returns dict? No, check telegram_service) # Ah, send_message in telegram_service returns dict! send_result = await telegram_service.send_message( token=bot_token, chat_id=chat_id, text=f"🔗 {media_file.name}\n{file_url}" ) else: # Default: send as document send_result = await telegram_service.send_document( token=bot_token, chat_id=chat_id, document_url=file_url, caption=caption ) if send_result.get("success"): last_sent_message_id = send_result.get("message_id") # Store message_id in MediaTracker for Reply feature if send_result.get("message_id"): media_tracker.mark_sent(lead_id_str, media_id_str, str(send_result["message_id"])) logger.info(f"📁 Sent media file: {media_file.name} ({media_file.file_type})") # Record progress if existing_progress: existing_progress.sent_at = datetime.utcnow() session.add(existing_progress) else: progress = LeadContentProgress( lead_id=lead_id, knowledge_file_id=media_file.id, sent_at=datetime.utcnow() ) session.add(progress) # Save message to chat history if conversation_id: file_message = Message( conversation_id=conversation_id, tenant_id=tenant_id, sender_type="ai", content=f"📁 {media_file.name}", media_url=file_url, media_type=media_file.file_type, media_name=media_file.name ) session.add(file_message) except Exception as e: logger.error(f"❌ Failed to send media {media_id_short}: {e}") await session.commit() async def download_telegram_file(bot_token: str, file_id: str) -> tuple[bytes, str]: """ Download file from Telegram Bot API. Returns (file_bytes, file_extension) """ async with httpx.AsyncClient() as client: # 1. Get file path file_info_url = f"https://api.telegram.org/bot{bot_token}/getFile" file_response = await client.post(file_info_url, json={"file_id": file_id}, timeout=10.0) file_response.raise_for_status() file_data = file_response.json() if not file_data.get("ok"): raise Exception(f"Telegram getFile failed: {file_data}") file_path = file_data["result"]["file_path"] # 2. Download file download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}" download_response = await client.get(download_url, timeout=30.0) download_response.raise_for_status() # 3. Extract extension file_ext = file_path.split(".")[-1] if "." in file_path else "bin" return download_response.content, file_ext def get_mime_type(extension: str) -> str: """Map file extension to MIME type.""" mime_map = { "jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp", "gif": "image/gif", "ogg": "audio/ogg", "oga": "audio/ogg", "mp3": "audio/mpeg", "m4a": "audio/mp4", "pdf": "application/pdf", "doc": "application/msword", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "txt": "text/plain", } return mime_map.get(extension.lower(), "application/octet-stream") router = APIRouter(prefix="/webhook", tags=["Webhooks"]) @router.post("/telegram/{tenant_id}") async def telegram_webhook( tenant_id: UUID, request: Request, background_tasks: BackgroundTasks, session = Depends(get_session), x_telegram_bot_api_secret_token: Optional[str] = Header(None) ): """ Telegram webhook endpoint for receiving messages. Each tenant has unique webhook URL: /webhook/telegram/{tenant_id} Security: Validates X-Telegram-Bot-Api-Secret-Token header """ try: # Get tenant first to validate webhook secret tenant = await session.get(Tenant, tenant_id) if not tenant or not tenant.is_active: raise HTTPException(status_code=404, detail="Tenant not found or inactive") # Validate webhook secret token (if configured) # Note: Telegram sends this header if you set secret_token in setWebhook # TODO: Uncomment when telegram_webhook_secret column is added to DB # webhook_secret = getattr(tenant, 'telegram_webhook_secret', None) # if webhook_secret and x_telegram_bot_api_secret_token != webhook_secret: # logger.warning( # "Invalid Telegram webhook secret", # tenant_id=str(tenant_id) # ) # raise HTTPException(status_code=403, detail="Invalid webhook secret") # Parse Telegram update update = await request.json() # Extract message data if "message" not in update: return {"ok": True} # Ignore non-message updates message = update["message"] # Check for voice/audio/photo/document (multimodal content) voice = message.get("voice") or message.get("audio") photo_list = message.get("photo", []) document = message.get("document") has_text = "text" in message has_voice = voice is not None has_photo = len(photo_list) > 0 has_document = document is not None has_media = has_voice or has_photo or has_document # Log what we received logger.info(f"📩 Telegram message: text={has_text}, voice={has_voice}, photo={has_photo}, doc={has_document}") # Validate required fields if "from" not in message: return {"ok": True} # Ignore messages without sender # Must have either text or media if not has_text and not has_media: logger.info("⏭️ Ignoring message without text or media") return {"ok": True} # Check if message is from a real user (not bot) telegram_user = message["from"] if telegram_user.get("is_bot", False): return {"ok": True} # Ignore bot messages telegram_id = str(telegram_user["id"]) chat_id = str(message["chat"]["id"]) # Extract text (or caption from media) or transcribe voice user_text = message.get("text") or message.get("caption") or "" # 👋 HANDLE /start COMMAND - Send welcome message instantly AND save to history if user_text.strip().lower() == '/start': from app.services.telegram_service import telegram_service # Get custom welcome message or build template welcome_message = getattr(tenant, 'telegram_welcome_message', None) if not welcome_message: # Build template: "Здравствуйте! Я [AI_NAME], чем могу помочь?" # FIXED: ai_identity is stored INSIDE ai_settings, not as direct tenant field ai_settings = tenant.ai_settings or {} ai_identity = ai_settings.get('ai_identity', {}) ai_name = ai_identity.get('name', '').strip() # 'name' is the bot name field if ai_name: welcome_message = f"Здравствуйте! Я {ai_name}, чем могу помочь?" else: welcome_message = "Здравствуйте! Чем могу помочь?" # Create or get lead and conversation BEFORE sending (so we can save to history) lead = await get_or_create_lead( session=session, tenant_id=tenant_id, telegram_id=telegram_id, telegram_user=telegram_user ) conversation = await get_or_create_conversation( session=session, tenant_id=tenant_id, lead_id=lead.id, channel="telegram" ) # Send welcome message try: await telegram_service.send_message( token=tenant.telegram_bot_token, chat_id=chat_id, text=welcome_message ) logger.info( "👋 Welcome message sent", chat_id=chat_id, tenant_id=str(tenant_id) ) # SAVE to conversation history so AI knows what was said # Note: Message is already imported at top of file welcome_msg = Message( tenant_id=tenant_id, # Required field! conversation_id=conversation.id, sender_type="ai", content=welcome_message, status=MessageStatus.SENT ) session.add(welcome_msg) await session.commit() logger.info("📝 Welcome message saved to conversation history") except Exception as e: logger.error(f"❌ Failed to send welcome message: {e}") return {"ok": True, "status": "welcome_sent"} # Handle reply_to_message - include context of quoted message reply_to = message.get("reply_to_message") reply_context = "" if reply_to: # Extract quoted message content quoted_text = reply_to.get("text") or reply_to.get("caption") or "" quoted_from = reply_to.get("from", {}) is_from_bot = quoted_from.get("is_bot", False) if quoted_text: quoted_source = "бот" if is_from_bot else "клиент" reply_context = f"[В ответ на сообщение {quoted_source}: \"{quoted_text[:200]}{'...' if len(quoted_text) > 200 else ''}\"] " logger.info(f"↩️ Reply detected: quoting {quoted_source} message") elif reply_to.get("photo"): reply_context = "[В ответ на фото] " logger.info("↩️ Reply to photo detected") elif reply_to.get("voice") or reply_to.get("audio"): reply_context = "[В ответ на голосовое сообщение] " logger.info("↩️ Reply to voice detected") voice_file_id = voice.get("file_id") if voice else None photo_file_id = photo_list[-1]["file_id"] if photo_list else None doc_file_id = document.get("file_id") if document else None doc_mime_type = document.get("mime_type") if document else None doc_file_name = document.get("file_name", "document") if document else None # Process voice message (transcribe to text) if voice_file_id and tenant.telegram_bot_token: try: user_text = await transcribe_telegram_voice(tenant.telegram_bot_token, voice_file_id) logger.info(f"🎤 Voice transcribed: {user_text[:50]}...") except Exception as e: logger.error(f"❌ Voice transcription failed: {e}") user_text = "[Голосовое сообщение - не удалось распознать]" # Process photo (analyze with Vision) elif photo_file_id and tenant.telegram_bot_token and not user_text: try: user_text = await analyze_telegram_image(tenant.telegram_bot_token, photo_file_id) logger.info(f"📷 Image analyzed: {user_text[:50]}...") except Exception as e: logger.error(f"❌ Image analysis failed: {e}") user_text = "[Фото - не удалось проанализировать]" # Process document (analyze based on type) elif doc_file_id and tenant.telegram_bot_token and not user_text: try: user_text = await analyze_telegram_document( tenant.telegram_bot_token, doc_file_id, doc_mime_type, doc_file_name ) logger.info(f"📄 Document analyzed: {user_text[:50]}...") except Exception as e: logger.error(f"❌ Document analysis failed: {e}") user_text = f"[Документ: {doc_file_name}] (Ошибка анализа)" # If still no text after all processing, use placeholder if not user_text: user_text = "[Медиа-сообщение без содержимого]" # Prepend reply context so AI knows what message user is replying to if reply_context: user_text = reply_context + user_text # Tenant already fetched and validated above # Find or create lead lead = await get_or_create_lead( session=session, tenant_id=tenant_id, telegram_id=telegram_id, telegram_user=telegram_user ) # Find or create conversation conversation = await get_or_create_conversation( session=session, tenant_id=tenant_id, lead_id=lead.id, channel="telegram" ) # Download and upload media if present media_url = None media_type = None media_name = None if (voice_file_id or photo_file_id or doc_file_id) and tenant.telegram_bot_token: try: file_id = voice_file_id or photo_file_id or doc_file_id # 1. Download from Telegram logger.info(f"⬇️ Downloading file {file_id[:8]}... from Telegram") file_bytes, file_ext = await download_telegram_file( tenant.telegram_bot_token, file_id ) logger.info(f"✅ Downloaded {len(file_bytes)} bytes, ext: {file_ext}") # 2. Upload to Supabase from app.core.supabase import supabase_client import time import re if supabase_client: bucket = "chat-attachments" ts = int(time.time()) safe_name = f"{ts}_{file_id[:12]}.{file_ext}" path = f"{tenant_id}/{conversation.id}/{safe_name}" mime_type = get_mime_type(file_ext) try: logger.info(f"⬆️ Uploading to Supabase: {path} ({mime_type})") upload_result = supabase_client.storage.from_(bucket).upload( path=path, file=file_bytes, file_options={"content-type": mime_type} ) media_url = supabase_client.storage.from_(bucket).get_public_url(path) logger.info(f"✅ Uploaded to Supabase: {media_url[:80]}...") # 3. Set media metadata media_type = mime_type if voice_file_id: media_name = "voice.ogg" elif photo_file_id: media_name = f"photo.{file_ext}" elif doc_file_id: media_name = doc_file_name or f"document.{file_ext}" except Exception as upload_err: import traceback logger.error(f"❌ Supabase upload failed: {upload_err}") logger.error(f"📋 Traceback: {traceback.format_exc()}") # Check if bucket exists issue if "not found" in str(upload_err).lower() or "bucket" in str(upload_err).lower(): logger.error(f"💡 Hint: Check if bucket '{bucket}' exists in Supabase Storage") else: logger.warning("⚠️ Supabase client not available, media will not be uploaded") except Exception as e: import traceback logger.error(f"❌ Failed to download/upload media: {e}") logger.error(f"📋 Full traceback: {traceback.format_exc()}") # Continue without media - at least save the transcribed text # Save user message WITH media fields user_message = Message( tenant_id=tenant_id, conversation_id=conversation.id, sender_type="user", content=user_text, media_url=media_url, media_type=media_type, media_name=media_name ) session.add(user_message) await session.commit() await session.refresh(user_message) # Notify WebSocket clients about new message (real-time updates) try: from app.api.websocket_chat import notify_new_message await notify_new_message(str(lead.id), { "id": str(user_message.id), "content": user_message.content, "sender_type": "user", "created_at": user_message.created_at.isoformat() if user_message.created_at else None, "media_url": user_message.media_url, "media_type": user_message.media_type }) logger.debug(f"📡 WebSocket notified: user message {user_message.id}") except Exception as e: logger.warning(f"⚠️ WebSocket notify failed (non-critical): {e}") # NOTE: Automatic name extraction removed # Lead name = Telegram display name by default # Users can configure AI to ask for name in settings if needed # Update lead activity lead.last_message_at = datetime.utcnow() lead.last_activity_at = datetime.utcnow() session.add(lead) await session.commit() # Check if human took over if conversation.human_takeover: # Don't respond with AI, human is handling logger.info( "👤 Human takeover active, skipping AI response", conversation_id=str(conversation.id) ) return {"ok": True, "status": "human_handling"} # Process AI response in background to respond quickly to Telegram logger.info( "🎯 Adding background task for AI response", user_message_id=str(user_message.id), conversation_id=str(conversation.id), chat_id=chat_id ) # Determine if we should respond with voice (voice-to-voice mode) respond_with_voice = voice_file_id is not None background_tasks.add_task( process_ai_response_background, tenant.id, lead.id, conversation.id, user_message.id, # Pass message ID for debouncing user_text, chat_id, respond_with_voice # New parameter: respond with voice if user sent voice ) # Return immediately to Telegram (prevents retry) return {"ok": True, "status": "processing"} except Exception as e: logger.error( "Webhook error", tenant_id=str(tenant_id), error=str(e), exc_info=True ) raise async def get_or_create_lead( session: AsyncSession, tenant_id: UUID, telegram_id: str, telegram_user: Dict[str, Any] ) -> Lead: """Find existing lead or create new one.""" # Try to find existing lead stmt = select(Lead).where( Lead.tenant_id == tenant_id, Lead.telegram_id == telegram_id ) result = await session.execute(stmt) lead = result.scalar_one_or_none() if lead: return lead # Create new lead name = telegram_user.get("first_name", "") if telegram_user.get("last_name"): name += f" {telegram_user['last_name']}" lead = Lead( tenant_id=tenant_id, telegram_id=telegram_id, name=name or None, status=LeadStatus.NEW, psychotype=Psychotype.UNKNOWN, heat_score=0 ) session.add(lead) await session.commit() await session.refresh(lead) return lead async def get_or_create_conversation( session: AsyncSession, tenant_id: UUID, lead_id: UUID, channel: str ) -> Conversation: """Find active conversation or create new one.""" # Try to find active conversation stmt = select(Conversation).where( Conversation.tenant_id == tenant_id, Conversation.lead_id == lead_id, Conversation.channel == channel, Conversation.is_active == True ) result = await session.execute(stmt) conversation = result.scalar_one_or_none() if conversation: return conversation # ✅ ПРОВЕРКА ЛИМИТОВ ПЕРЕД СОЗДАНИЕМ НОВОГО ДИАЛОГА tenant = await session.get(Tenant, tenant_id) if not tenant: raise HTTPException(status_code=404, detail="Tenant not found") can_create, reason = await SubscriptionManager.check_can_create_conversation( tenant=tenant, session=session ) if not can_create: logger.warning( "❌ Conversation blocked by subscription limit", tenant_id=str(tenant_id), reason=reason, plan=tenant.subscription_plan, leads_count=tenant.leads_this_month ) raise HTTPException( status_code=403, detail=reason or "Достигнут лимит подписки" ) # Create new conversation conversation = Conversation( tenant_id=tenant_id, lead_id=lead_id, channel=channel, is_active=True ) session.add(conversation) # ✅ УВЕЛИЧИВАЕМ СЧЁТЧИК ДИАЛОГОВ await SubscriptionManager.increment_conversation_count( tenant=tenant, session=session ) await session.commit() await session.refresh(conversation) logger.info( "✅ New conversation created", conversation_id=str(conversation.id), tenant_plan=tenant.subscription_plan, leads_count=tenant.leads_this_month ) return conversation async def send_telegram_message( bot_token: str, chat_id: str, text: str, reply_to_message_id: int = None ) -> bool: """Send message via Telegram Bot API (Text or Photo).""" import re if not bot_token or not bot_token.strip(): logger.warning( "⚠️ No valid bot token configured for tenant", chat_id=chat_id ) return False # 1. Extract Image URLs (Supabase or standard extensions) # Matches: https://...supabase... or ending in .jpg/png/webp img_pattern = r"(https?://[^\s\)]+(?:supabase\.co|products)[^\s\)]+)|(https?://[^\s\)]+\.(?:jpg|jpeg|png|webp))" matches = re.findall(img_pattern, text, re.IGNORECASE) # Flatten matches and filter empty images = [m[0] or m[1] for m in matches if m[0] or m[1]] # 2. Clean Text (Remove links to images to avoid duplicates) clean_text = text for img in images: # Remove Markdown links: [text](url) clean_text = re.sub(r"\[.*?\]\(" + re.escape(img) + r"\)", "", clean_text) # Remove plain URLs in parens: (url) clean_text = clean_text.replace(f"({img})", "") # Remove plain URLs clean_text = clean_text.replace(img, "") clean_text = clean_text.strip() async with httpx.AsyncClient() as client: success = True # 3. Send Text (if any remains) if clean_text: text_url = f"https://api.telegram.org/bot{bot_token}/sendMessage" payload = { "chat_id": chat_id, "text": clean_text, "parse_mode": "Markdown" } if reply_to_message_id: payload["reply_to_message_id"] = reply_to_message_id try: # Attempt 1: Markdown response = await client.post(text_url, json=payload, timeout=10.0) # Retry Plain Text if Markdown fails (ANY 400 error) if response.status_code == 400: logger.warning( "⚠️ Markdown failed, retrying with plain text", error=response.text[:200], chat_id=chat_id ) del payload["parse_mode"] # Remove parse_mode entirely response = await client.post(text_url, json=payload, timeout=10.0) response.raise_for_status() except Exception as e: logger.error("❌ Failed to send text", error=str(e)) success = False # 4. Send Images (as Photos) photo_url = f"https://api.telegram.org/bot{bot_token}/sendPhoto" for img in images: try: # Check extension, if it's .jfif or unknown, Telegram might reject as photo. # But Supabase usually serves content-type correctly. # If Telegram rejects generic URL, we might need download/re-upload, # but usually passing URL works fine. payload = { "chat_id": chat_id, "photo": img, "caption": "" # Optional: add caption? } logger.info("📸 Sending photo", url=img) resp = await client.post(photo_url, json=payload, timeout=20.0) resp.raise_for_status() except Exception as e: logger.error("❌ Failed to send photo", url=img, error=str(e)) # Don't fail the whole task if one image fails, but log it. # If we rely on image for context, this might be bad. pass return success async def process_ai_response_background( tenant_id: UUID, lead_id: UUID, conversation_id: UUID, user_message_id: UUID, # Message ID for debouncing check user_text: str, chat_id: str, respond_with_voice: bool = False # New: respond with voice message if True ): """ Background task: Generate AI response and send to Telegram. Creates its own database session to avoid session lifecycle issues. **ANTI-SPAM DEBOUNCING:** - Waits 4 seconds before processing - Checks if user sent newer messages during wait - Only processes if this is still the latest message (prevents spam) **VOICE-TO-VOICE MODE:** - If respond_with_voice=True, AI will send voice message instead of text """ from app.core.database import async_session_maker from app.services.voice_service import voice_service from app.services.telegram_service import telegram_service import asyncio logger.info( "🚀 Starting debounced AI response task", user_message_id=str(user_message_id), conversation_id=str(conversation_id), lead_id=str(lead_id) ) # TASK 2: Set status during processing (NO "waiting" - not allowed by DB constraint) try: async with async_session_maker() as session: lead = await session.get(Lead, lead_id) if lead: # NOTE: "waiting" is NOT in DB constraint, using "idle" instead # Allowed values: idle, generating, analyzing, error lead.processing_status = "idle" # Keep as idle until we start generating session.add(lead) await session.commit() logger.info( "✅ Lead status confirmed as idle", lead_id=str(lead_id) ) else: logger.error( "❌ Lead not found for debouncing", lead_id=str(lead_id) ) return except Exception as e: logger.error( "❌ Failed to set processing status", lead_id=str(lead_id), error=str(e), exc_info=True ) return # NOTE: Debounce removed for faster AI response # Message batching still works via the check on lines 1176-1202 # which collects all user messages since last AI response async with async_session_maker() as session: try: # TASK 2: Check for Newer Messages (The Filter) # If user sent more messages during the sleep, abort this task stmt = select(Message).where( Message.conversation_id == conversation_id, Message.sender_type == "user" ).order_by(Message.created_at.desc()).limit(1) result = await session.execute(stmt) latest_user_message = result.scalar_one_or_none() if latest_user_message and latest_user_message.id != user_message_id: # User sent a newer message during the debounce period logger.info( "⏭️ Debouncing: Skipping old message", current_msg_id=str(user_message_id), latest_msg_id=str(latest_user_message.id), conversation_id=str(conversation_id) ) # Reset status to idle since we're not processing lead = await session.get(Lead, lead_id) if lead: lead.processing_status = "idle" session.add(lead) await session.commit() return # Abort - let the newer message's task handle the reply logger.info( "✅ This is the latest message, proceeding with AI generation", user_message_id=str(user_message_id), conversation_id=str(conversation_id) ) # Fetch fresh objects from database tenant = await session.get(Tenant, tenant_id) lead = await session.get(Lead, lead_id) conversation = await session.get(Conversation, conversation_id) if not tenant or not lead or not conversation: logger.error( "Background task: objects not found", tenant_id=str(tenant_id), lead_id=str(lead_id) ) return # 🔴 CHECK AI MASTER TOGGLE - Skip if disabled if not getattr(tenant, 'ai_enabled', True): logger.info( "🔇 AI is DISABLED for this tenant - skipping response", tenant_id=str(tenant_id) ) return # 🔒 CHECK SUBSCRIPTION PLAN - AI only works for paid plans (start, growth, enterprise) # Trial accounts can save settings but AI doesn't respond subscription_plan = (tenant.subscription_plan or "trial").lower() if subscription_plan == "trial": logger.info( "🔒 AI disabled for trial accounts - upgrade to Start/Growth/Enterprise", tenant_id=str(tenant_id), plan=subscription_plan ) return # Set processing status to GENERATING lead.processing_status = "generating" session.add(lead) await session.commit() ai_core = get_ai_core() # Get conversation history history_stmt = select(Message).where( Message.conversation_id == conversation.id ).order_by(Message.created_at.desc()).limit(settings.MAX_CONTEXT_MESSAGES) history_result = await session.execute(history_stmt) conversation_history = list(reversed(history_result.scalars().all())) # BATCH MESSAGES: Collect all user messages since last AI response # This ensures AI responds to ALL messages sent during debounce period batched_user_text = user_text if conversation_history: # Find the last AI message index last_ai_index = -1 for i in range(len(conversation_history) - 1, -1, -1): if conversation_history[i].sender_type == "ai": last_ai_index = i break # Collect all user messages after last AI message user_messages_since_ai = [] for msg in conversation_history[last_ai_index + 1:]: if msg.sender_type == "user" and msg.content: user_messages_since_ai.append(msg.content) if len(user_messages_since_ai) > 1: # Multiple messages - combine them batched_user_text = "\n".join(user_messages_since_ai) logger.info( f"📦 Batching {len(user_messages_since_ai)} user messages for single AI response", conversation_id=str(conversation_id) ) elif len(user_messages_since_ai) == 1: batched_user_text = user_messages_since_ai[0] # Generate response to ALL batched messages # Send "typing" indicator so user sees bot is working await telegram_service.send_chat_action( token=tenant.telegram_bot_token, chat_id=chat_id, action="typing" ) ai_response = await ai_core.generate_sales_response( session=session, tenant=tenant, lead=lead, user_message=batched_user_text, conversation_history=conversation_history ) # POST-GENERATION CHECK: Did new messages arrive during AI generation? # If yes, abort sending - the newer message's task will handle response post_gen_stmt = select(Message).where( Message.conversation_id == conversation_id, Message.sender_type == "user" ).order_by(Message.created_at.desc()).limit(1) post_gen_result = await session.execute(post_gen_stmt) post_gen_latest = post_gen_result.scalar_one_or_none() if post_gen_latest and post_gen_latest.id != user_message_id: # New message arrived DURING generation - abort! logger.info( "⏭️ Post-generation abort: New message arrived during AI generation", original_msg_id=str(user_message_id), new_msg_id=str(post_gen_latest.id), conversation_id=str(conversation_id) ) # Reset lead status lead.processing_status = "idle" session.add(lead) await session.commit() return # Exit - let the newer message's background task respond # --- BOOKING INTERCEPTION START --- import re from datetime import datetime from app.models.booking import Appointment, AppointmentStatus, Service, Resource # Added Resource ai_text = ai_response["text"] # Updated regex to capture optional resource: [BOOK_CONFIRMED: YYYY-MM-DD HH:MM] or [BOOK_CONFIRMED: YYYY-MM-DD HH:MM | Resource Name] booking_match = re.search(r'\[BOOK_CONFIRMED:\s*([\d\-]+\s[\d:]+)(?:\s*\|\s*(.+?))?\]', ai_text) if booking_match: try: date_str = booking_match.group(1) # Expected format: YYYY-MM-DD HH:MM start_time = datetime.strptime(date_str, "%Y-%m-%d %H:%M") end_time = start_time.replace(minute=start_time.minute + 30) # Default 30 min # Find default service srv_stmt = select(Service).where(Service.tenant_id == tenant_id).limit(1) srv_result = await session.execute(srv_stmt) default_srv = srv_result.scalar_one_or_none() if not default_srv: # Auto-create default service if missing default_srv = Service( tenant_id=tenant_id, name="General Consultation", duration_minutes=30, price=0.0, is_active=True ) session.add(default_srv) await session.commit() await session.refresh(default_srv) logger.info(f"🆕 Auto-created default service for tenant {tenant_id}") # CHECK FOR DUPLICATE: Same lead + same time = already booked # Use minute-level comparison to avoid seconds/milliseconds mismatches duplicate_stmt = select(Appointment).where( Appointment.lead_id == lead_id, Appointment.status == AppointmentStatus.SCHEDULED, func.date_trunc('minute', Appointment.start_time) == start_time ) duplicate_result = await session.execute(duplicate_stmt) existing_matching = duplicate_result.scalar_one_or_none() if existing_matching: # Already booked for this lead at this time - just confirm, don't create duplicate or notify reschedule logger.info(f"📅 Booking already exists for lead {lead_id} at {start_time}, skipping duplicate logic") # Remove the tag and add confirmation (so user knows it's active) ai_text = ai_text.replace(booking_match.group(0), "").strip() if "(Система: Запись уже подтверждена!)" not in ai_text: ai_text += "\n\n✅ (Система: Запись уже подтверждена!)" ai_response["text"] = ai_text else: # NEW OR CHANGED TIME - Proceed with auto-cancel and new booking # AUTO-CANCEL OLD BOOKINGS for this lead (other than the same time which we checked above) old_appts_stmt = select(Appointment).where( Appointment.lead_id == lead_id, Appointment.status == AppointmentStatus.SCHEDULED, func.date_trunc('minute', Appointment.start_time) != start_time # Explicitly different time ) old_appts_result = await session.execute(old_appts_stmt) old_appointments = old_appts_result.scalars().all() is_rescheduled = len(old_appointments) > 0 # Track if this is a reschedule for old_appt in old_appointments: old_time = old_appt.start_time old_appt.status = AppointmentStatus.CANCELLED old_appt.notes = f"[Перенесено на {start_time.strftime('%d.%m в %H:%M')}] {old_appt.notes or ''}" session.add(old_appt) logger.info(f"🔄 Auto-cancelled old appointment {old_appt.id} for lead {lead_id}") # 🔔 NOTIFY ADMIN about reschedule try: from app.services.notification import notification_service old_appt.lead = lead await notification_service.notify_reschedule( tenant=tenant, old_appointment=old_appt, old_time=old_time, new_time=start_time, lead_name=lead.name or "Клиент" ) except Exception as ns_err: logger.error(f"⚠️ Reschedule notification failed: {ns_err}") if old_appointments: await session.commit() # CHECK FOR TIME SLOT CONFLICT (with OTHER leads) conflict_stmt = select(Appointment).where( Appointment.tenant_id == tenant_id, Appointment.status == AppointmentStatus.SCHEDULED, func.date_trunc('minute', Appointment.start_time) == start_time, Appointment.lead_id != lead_id # Not us ) conflict_result = await session.execute(conflict_stmt) existing_booking = conflict_result.scalar_one_or_none() if existing_booking: # Slot is taken - find alternatives and suggest them logger.warning(f"⚠️ Time slot {start_time} taken by another client, searching alternatives") # Find next 3 available slots available_slots = await _find_available_slots( session=session, tenant_id=tenant_id, requested_time=start_time, count=3 ) ai_text = ai_text.replace(booking_match.group(0), "").strip() if available_slots: # Format slots nicely slots_formatted = [] for slot in available_slots: slots_formatted.append(slot.strftime("%d.%m в %H:%M")) ai_text += f"\n\n⚠️ К сожалению, это время уже занято.\n\n📅 Ближайшие свободные слоты:\n• " + "\n• ".join(slots_formatted) + "\n\nКакое время вам подходит?" else: ai_text += "\n\n⚠️ К сожалению, это время уже занято. Пожалуйста, предложите другое время." ai_response["text"] = ai_text else: # ALL CLEAR - CREATE NEW APPOINTMENT # Create new appointment with comprehensive notes booking_info = _extract_booking_info_from_conversation(conversation_history, lead, user_text) # Build informative notes notes_parts = [booking_info["name"]] if booking_info["phone"]: notes_parts.append(f"📞 {booking_info['phone']}") notes_parts.append(f"Тема: {booking_info['topic']}") notes = " | ".join(notes_parts) # RESOURCE LOOKUP: Find resource by name if specified in tag resource_name = booking_match.group(2) if booking_match.lastindex >= 2 else None resource_id = None selected_resource = None if resource_name: resource_name = resource_name.strip() # Search for resource by name (case-insensitive partial match) resource_stmt = select(Resource).where( Resource.tenant_id == tenant_id, Resource.is_active == True, Resource.name.ilike(f"%{resource_name}%") ) resource_result = await session.execute(resource_stmt) selected_resource = resource_result.scalar_one_or_none() if selected_resource: resource_id = selected_resource.id logger.info(f"📌 Booking to resource: {selected_resource.name} (ID: {resource_id})") else: logger.warning(f"⚠️ Resource '{resource_name}' not found, booking without resource") new_appt = Appointment( tenant_id=tenant_id, lead_id=lead_id, service_id=default_srv.id, resource_id=resource_id, # Now saves resource! start_time=start_time, end_time=end_time, status=AppointmentStatus.SCHEDULED, notes=notes ) session.add(new_appt) await session.commit() logger.info(f"📅 AI Booked Appointment: {date_str} for Lead {lead_id}" + (f" with Resource {resource_name}" if resource_name else "")) # 🔔 NOTIFY: Send to resource owner if telegram_chat_id set, else to tenant if not is_rescheduled: try: from app.services.notification import notification_service new_appt.lead = lead new_appt.service = default_srv # Determine notification target resource_telegram_id = None if selected_resource and selected_resource.telegram_chat_id: resource_telegram_id = selected_resource.telegram_chat_id logger.info(f"📱 Sending notification to resource: {selected_resource.name} ({resource_telegram_id})") # Pass AI summary and resource notification target await notification_service.notify_new_appointment( tenant, new_appt, ai_summary=lead.ai_summary_json, resource_telegram_id=resource_telegram_id # New: notify resource directly ) except Exception as ns_err: logger.error(f"⚠️ Notification failed: {ns_err}") else: logger.info(f"📅 Skipping notification for rescheduled appointment {new_appt.id}") # Remove tag from text ai_text = ai_text.replace(booking_match.group(0), "").strip() ai_text += "\n\n✅ (Система: Запись создана успешно!)" # Update response text in object ai_response["text"] = ai_text except Exception as e: logger.error(f"❌ Failed to process AI booking tag: {e}") ai_response["text"] += "\n\n⚠️ (Система: Ошибка при сохранении записи. Менеджер свяжется с вами.)" # --- BOOKING INTERCEPTION END --- # --- ORDER INTERCEPTION START --- import json from app.models.order import Order, OrderItem, OrderStatus from app.models.product import Product order_match = re.search(r'\[CREATE_ORDER:\s*({.*?})\]', ai_text, re.DOTALL) if order_match: try: json_str = order_match.group(1) # Sanitize JSON if needed (AI might leave trailing commas) # For now assume valid JSON from Gemini 1.5 order_data = json.loads(json_str) logger.info(f"🛒 Processing Order Request: {json_str}") # 1. Create Order Shell new_order = Order( tenant_id=tenant_id, lead_id=lead_id, status=OrderStatus.NEW, total_amount=0.0 ) session.add(new_order) await session.flush() # Get ID total_sum = 0.0 items_info_text = [] currency = "USD" # 2. Process Items for item in order_data.get("items", []): p_name = item.get("product_name") qty = int(item.get("quantity", 1)) # Find product (Best Effort Fuzzy Match) # We use ILIKE for case-insensitive partial match p_stmt = select(Product).where( Product.tenant_id == tenant_id, Product.name.ilike(f"%{p_name}%") ).limit(1) p_res = await session.execute(p_stmt) product = p_res.scalar_one_or_none() price = 0.0 p_id = None if product: price = product.price p_id = product.id currency = product.currency # Use last product's currency else: # Fallback if product not found by name logger.warning(f"⚠️ Product '{p_name}' not found in DB") line_total = price * qty total_sum += line_total order_item = OrderItem( order_id=new_order.id, product_id=p_id, product_name=p_name, quantity=qty, unit_price=price, total_price=line_total ) session.add(order_item) items_info_text.append(f"{p_name} x{qty}") # 3. Update Order Total and Customer details if provided new_order.total_amount = total_sum customer_info = order_data.get("customer", {}) notes = order_data.get("notes", "") # Update Lead info if missing using gathered data if customer_info.get("name") and not lead.name: lead.name = customer_info.get("name") session.add(lead) # Save order notes if notes: # You might want a 'notes' field in Order model, currently absent? # I defined Order model earlier. Did I add notes? # Let's check model definition. Assuming NO for now, log it. logger.info(f"📝 Order Notes: {notes}") session.add(new_order) await session.commit() logger.info(f"✅ AI Created Order {new_order.id} for Lead {lead_id}") # 4. Clean up response & Add Confirmation ai_text = ai_text.replace(order_match.group(0), "").strip() confirmation_msg = f"\n\n✅ Заказ №{str(new_order.id)[:8]} оформлен!\n📦 Товары: {', '.join(items_info_text)}\n💰 Итого: {total_sum:.2f} {currency}" ai_text += confirmation_msg # Update response text object ai_response["text"] = ai_text # 🔔 NOTIFY ADMIN try: from app.services.notification import notification_service await notification_service.notify_new_order(tenant, new_order, '\n'.join(items_info_text)) except Exception as ns_err: logger.error(f"⚠️ Notification failed: {ns_err}") except Exception as e: logger.error(f"❌ Failed to process AI Order tag: {e}") import traceback traceback.print_exc() # Fallback message # Don't fail the chat, just append error note ai_text = ai_text.replace(order_match.group(0), "").strip() ai_text += "\n\n⚠️ (Система: Заявка принята, но произошла ошибка автоматической регистрации. Менеджер проверит вручную.)" ai_response["text"] = ai_text # --- ORDER INTERCEPTION END --- # --- BANNED WORDS POST-CHECK --- # Extra safety: replace banned words even if AI ignores the prompt rule if tenant.banned_words: ai_text = ai_response["text"] for word in tenant.banned_words: if word and word.lower() in ai_text.lower(): # Case-insensitive replacement import re pattern = re.compile(re.escape(word), re.IGNORECASE) ai_text = pattern.sub("***", ai_text) logger.warning(f"🚫 Replaced banned word: {word}") ai_response["text"] = ai_text # --- BANNED WORDS POST-CHECK END --- # --- MARKDOWN STRIPPING (STRICT PLAIN TEXT) --- # Remove **bold**, __bold__, ## Headers to ensure plain text if ai_response.get("text"): txt = ai_response["text"] import re # 1. Remove Headers (## Title) txt = re.sub(r'^#+\s+', '', txt, flags=re.MULTILINE) # 2. Remove **Bold** / __Bold__ # Note: We replace **text** with text. txt = re.sub(r'\*\*(.*?)\*\*', r'\1', txt) txt = re.sub(r'__(.*?)__', r'\1', txt) # 3. Remove "Photo 1:" style hallucinations if standard pattern # (Optional, but user complained about it) txt = re.sub(r'\*?\*?Фото \d+:.*?\*?\*?', '', txt, flags=re.IGNORECASE) ai_response["text"] = txt.strip() # --- MARKDOWN STRIPPING END --- # --- REMOVE INTERNAL AI STAGES (Chain of Thought leak protection) --- # If AI accidentally outputs its internal analysis, strip it # IMPORTANT: Only remove if it looks like actual internal analysis (has specific markers) # Delete [NEED_HUMAN] and common internal markers txt = re.sub(r'\[NEED_HUMAN\]', '', txt, flags=re.IGNORECASE) txt = re.sub(r'\[НУЖЕН_ЧЕЛОВЕК\]', '', txt, flags=re.IGNORECASE) txt = re.sub(r'\[WILL_NOTIFY\]', '', txt, flags=re.IGNORECASE) txt = re.sub(r'\[УВЕДОМЛЮ\]', '', txt, flags=re.IGNORECASE) ai_response["text"] = txt.strip() # --- INTERNAL STAGES REMOVAL END --- # --- CLEAN UP INTERNAL TAGS BEFORE SAVE --- # Remove [SEND_VOICE] tag so it doesn't appear in UI if "[SEND_VOICE]" in ai_response["text"]: ai_response["text"] = ai_response["text"].replace("[SEND_VOICE]", "").strip() # Process [SEND_MEDIA:ID] tags - extract media IDs to send media_ids_to_send = [] # Flexible pattern: handles [SEND_MEDIA:ID], SEND_MEDIA:ID, SEND_MEDIA: ID (with space) media_pattern = r'\[?SEND_MEDIA:\s*([a-f0-9-]+)\]?' media_matches = re.findall(media_pattern, ai_response["text"], re.IGNORECASE) if media_matches: media_ids_to_send = list(set(media_matches)) # Unique IDs logger.info(f"📁 AI wants to send {len(media_ids_to_send)} media files: {media_ids_to_send}") # Clean tags from response (both formats) ai_response["text"] = re.sub(r'\[?SEND_MEDIA:\s*[a-f0-9-]+\]?', '', ai_response["text"]).strip() # Process [SEND_PAYMENT_QR:ID] tags - extract payment QR IDs to send payment_qr_ids_to_send = [] payment_qr_pattern = r'\[SEND_PAYMENT_QR:([a-f0-9-]+)\]' payment_qr_matches = re.findall(payment_qr_pattern, ai_response["text"], re.IGNORECASE) if payment_qr_matches: payment_qr_ids_to_send = list(set(payment_qr_matches)) # Unique IDs logger.info(f"📱 AI wants to send {len(payment_qr_ids_to_send)} payment QR codes: {payment_qr_ids_to_send}") # Clean tags from response ai_response["text"] = re.sub(payment_qr_pattern, '', ai_response["text"]).strip() # Process [REPLY_TO_MEDIA:ID] tags reply_to_media_id = None reply_pattern = r'\[REPLY_TO_MEDIA:([a-f0-9-]+)\]' reply_match = re.search(reply_pattern, ai_response["text"], re.IGNORECASE) if reply_match: reply_to_media_id = reply_match.group(1) logger.info(f"↩️ AI wants to reply to media {reply_to_media_id}") ai_response["text"] = re.sub(reply_pattern, '', ai_response["text"]).strip() # Process [BOOK_SLOT: YYYY-MM-DD HH:MM] tags - auto-create appointment book_slot_pattern = r'\[BOOK_SLOT:\s*(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})(?:\s+(.+?))?\s*\]' book_slot_match = re.search(book_slot_pattern, ai_response["text"], re.IGNORECASE) if book_slot_match: try: from datetime import datetime, timedelta from app.models.booking import Appointment, Resource slot_date = book_slot_match.group(1) # 2024-12-09 slot_time = book_slot_match.group(2) # 10:00 resource_hint = book_slot_match.group(3) # Optional: resource name # Parse datetime start_dt = datetime.fromisoformat(f"{slot_date}T{slot_time}:00") end_dt = start_dt + timedelta(minutes=tenant.booking_settings.get("slot_duration", 30) if tenant.booking_settings else 30) # Find resource if mentioned resource_id = None if resource_hint: resource_stmt = select(Resource).where( Resource.tenant_id == tenant.id, Resource.is_active == True, Resource.name.ilike(f"%{resource_hint.strip()}%") ) resource_result = await session.execute(resource_stmt) resource = resource_result.scalars().first() if resource: resource_id = resource.id logger.info(f"📅 Found resource '{resource.name}' for booking") # Create appointment new_appointment = Appointment( tenant_id=tenant.id, lead_id=lead_id, start_time=start_dt, end_time=end_dt, resource_id=resource_id, status="pending", notes=f"Автоматическая запись через AI (диалог #{conversation.id})" ) session.add(new_appointment) await session.flush() logger.info(f"📅 Created appointment: {slot_date} {slot_time} for lead {lead_id}, resource={resource_id}") except Exception as e: logger.error(f"❌ Failed to create booking slot: {e}") # Clean tag from response ai_response["text"] = re.sub(book_slot_pattern, '', ai_response["text"]).strip() ai_message = Message( tenant_id=tenant.id, conversation_id=conversation.id, sender_type="ai", content=ai_response["text"], status=MessageStatus.PENDING, # Initialize as PENDING prompt_tokens=ai_response["prompt_tokens"], completion_tokens=ai_response["completion_tokens"], model_used=settings.GEMINI_MODEL ) session.add(ai_message) await session.commit() await session.refresh(ai_message) # Notify WebSocket clients about AI response (real-time updates) try: from app.api.websocket_chat import notify_new_message await notify_new_message(str(lead_id), { "id": str(ai_message.id), "content": ai_message.content, "sender_type": "ai", "created_at": ai_message.created_at.isoformat() if ai_message.created_at else None, "media_url": None, "media_type": None }) logger.debug(f"📡 WebSocket notified: AI message {ai_message.id}") except Exception as e: logger.warning(f"⚠️ WebSocket notify failed (non-critical): {e}") # Send response to Telegram logger.info( "📤 Sending AI response to Telegram", chat_id=chat_id, response_length=len(ai_response["text"]) ) # Determine Channel channel = conversation.channel if conversation.channel else 'telegram' send_success = False try: if channel == 'telegram': # Pre-send Media (Images / Files) so we can reply to them media_reply_id = None # 1. Product Images prod_msg_id = await send_product_images_if_mentioned( session=session, tenant_id=tenant.id, bot_token=tenant.telegram_bot_token, chat_id=chat_id, ai_text=ai_response["text"], lead_id=lead.id, # Pass Lead ID conversation_id=conversation.id ) if prod_msg_id: media_reply_id = prod_msg_id # 2. Media Files ([SEND_MEDIA:ID]) if media_ids_to_send: media_msg_id = await send_media_files( session=session, tenant_id=tenant.id, lead_id=lead_id, bot_token=tenant.telegram_bot_token, chat_id=chat_id, media_ids=media_ids_to_send, conversation_id=conversation.id ) if media_msg_id: media_reply_id = media_msg_id # Prioritize explicit media for reply # 3. Payment QR Codes ([SEND_PAYMENT_QR:ID]) if payment_qr_ids_to_send: qr_msg_id = await send_payment_qr_codes( session=session, tenant_id=tenant.id, bot_token=tenant.telegram_bot_token, chat_id=chat_id, payment_qr_ids=payment_qr_ids_to_send, conversation_id=conversation.id ) if qr_msg_id: media_reply_id = qr_msg_id # 4. OVERRIDE: If AI wants to reply to a specific PREVIOUS media ID if reply_to_media_id: from app.services.ai_core.media_tracker import media_tracker prev_msg_id = media_tracker.get_message_id_for_media(str(lead_id), reply_to_media_id) if not prev_msg_id: prev_msg_id = media_tracker.get_message_id_for_product(str(lead_id), reply_to_media_id) if prev_msg_id: logger.info(f"↩️ Found Telegram message ID for reference: {prev_msg_id}") media_reply_id = int(prev_msg_id) # Count AI messages to detect first message ai_msg_count = len([m for m in conversation_history if getattr(m, 'sender_type', None) == 'ai']) is_first_message = ai_msg_count == 0 # Check if AI wants to send voice (proactive) or user sent voice (reactive) # AI can add [SEND_VOICE] tag when it detects persuasion/trust moment ai_wants_voice = "[SEND_VOICE]" in ai_response["text"] # === CHECK USER'S LATEST VOICE PREFERENCE === # Use smart detection from response_generator which tracks LATEST preference # (handles both "no voice" and "yes voice" requests, using the most recent one) user_requested_no_voice = ai_response.get("user_requested_no_voice", False) if user_requested_no_voice: logger.info("🔇 USER REQUESTED NO VOICE (latest preference from response_generator)") # If user requested no voice, disable all voice triggers if user_requested_no_voice: ai_wants_voice = False respond_with_voice = False logger.info("🔇 Voice DISABLED because user requested no voice messages") # === SMART VOICE DETECTION (LLM-based semantic analysis) === voice_trigger_reason = None user_text_lower = user_text.lower() if user_text else "" ai_text_lower = ai_response["text"].lower() # Count recent voice messages to limit frequency recent_ai_voice_count = 0 for msg in conversation_history[-10:]: # Last 10 messages if getattr(msg, 'sender_type', None) == 'ai': if getattr(msg, 'media_type', None) == 'voice' or getattr(msg, 'media_url', None): recent_ai_voice_count += 1 # FREQUENCY LIMIT: Only 1 voice per 5+ messages voice_allowed_by_frequency = recent_ai_voice_count < 1 or ai_msg_count % 5 == 0 # 0. USER EXPLICITLY REQUESTED VOICE - highest priority, bypasses frequency limit user_requested_voice = ai_response.get("user_requested_voice", False) if not ai_wants_voice and tenant.voice_enabled and not user_requested_no_voice and user_requested_voice: voice_trigger_reason = "USER_REQUESTED" ai_wants_voice = True logger.info("🎙️ Voice triggered: USER explicitly requested voice (bypasses frequency limit)") # Smart triggers (subject to frequency limit) elif not ai_wants_voice and tenant.voice_enabled and not user_requested_no_voice and voice_allowed_by_frequency: # 1. FIRST MESSAGE - greeting (only if enabled in settings) if is_first_message and getattr(tenant, 'voice_first_required', False): voice_trigger_reason = "FIRST_MESSAGE" ai_wants_voice = True # 2. SMART LLM ANALYSIS for critical moments else: try: voice_ai_core = get_ai_core() voice_analysis = await voice_ai_core.llm.generate_response( prompt=f"""Is this a CRITICAL MOMENT that requires a personal voice message to build trust? User's message: "{user_text}" AI's response: "{ai_response['text'][:200]}..." Critical moments are ONLY: - OBJECTION: Client has serious doubts, concerns about price/quality, hesitation (not just questions) - UPSET: Client is frustrated, angry, disappointed, complaining - DEAL_CLOSING: Client explicitly agrees to buy, pay, book, sign up Answer with ONE word: - OBJECTION - if client has serious doubts/objections - UPSET - if client is frustrated/angry - DEAL_CLOSING - if client agrees to purchase/book - NONE - if this is just a normal conversation (most messages)""", system_instruction="Output only: OBJECTION, UPSET, DEAL_CLOSING, or NONE. Most messages should be NONE.", context=None, chat_history=[] ) llm_result = voice_analysis["text"].strip().upper() if "OBJECTION" in llm_result: voice_trigger_reason = "CLIENT_OBJECTION" ai_wants_voice = True elif "UPSET" in llm_result: voice_trigger_reason = "CLIENT_UPSET" ai_wants_voice = True elif "DEAL_CLOSING" in llm_result: voice_trigger_reason = "DEAL_CLOSING" ai_wants_voice = True else: logger.info(f"🧠 LLM: No critical moment detected (NONE)") except Exception as e: logger.warning(f"Voice LLM analysis failed: {e}") # Log if voice was blocked by frequency if not voice_allowed_by_frequency and not user_requested_no_voice: logger.info(f"🔇 Voice blocked by frequency limit (recent voice count: {recent_ai_voice_count})") if voice_trigger_reason: logger.info(f"🎙️ Smart voice trigger: {voice_trigger_reason}") should_send_voice = ( tenant.voice_enabled and (respond_with_voice or ai_wants_voice) ) logger.info(f"🔊 Voice decision: enabled={tenant.voice_enabled}, trigger={voice_trigger_reason}, ai_wants={ai_wants_voice}, RESULT={should_send_voice}") # ALWAYS clean up voice tag from response text (even if voice is disabled) if "[SEND_VOICE]" in ai_response["text"]: ai_response["text"] = ai_response["text"].replace("[SEND_VOICE]", "").strip() if should_send_voice: try: # Generate speech using tenant's selected voice voice_id = getattr(tenant, 'voice_id', 'professional_male') custom_voice_url = getattr(tenant, 'voice_reference_url', None) logger.info(f"🎙️ Generating voice response (voice={voice_id})...") audio_bytes, extracted_items = await voice_service.generate_audio( text=ai_response["text"], voice=voice_id, custom_voice_url=custom_voice_url ) # Upload audio to Supabase for platform playback try: from app.core.supabase import supabase_client import time if supabase_client and audio_bytes: bucket = "chat-attachments" ts = int(time.time()) path = f"{tenant_id}/{conversation_id}/{ts}_ai_voice.mp3" supabase_client.storage.from_(bucket).upload( path=path, file=audio_bytes, file_options={"content-type": "audio/mpeg"} ) voice_media_url = supabase_client.storage.from_(bucket).get_public_url(path) # Update AI message with media_url ai_message.media_url = voice_media_url ai_message.media_type = "audio/mpeg" ai_message.media_name = "ai_voice.mp3" session.add(ai_message) await session.commit() logger.info(f"✅ AI voice uploaded to Supabase: {voice_media_url[:60]}...") # Notify WebSocket again with updated media_url try: await notify_new_message(str(lead_id), { "id": str(ai_message.id), "content": ai_message.content, "sender_type": "ai", "created_at": ai_message.created_at.isoformat() if ai_message.created_at else None, "media_url": voice_media_url, "media_type": "audio/mpeg", "media_name": "ai_voice.mp3" }) logger.debug(f"📡 WebSocket updated with AI voice media_url") except Exception as ws_err: logger.warning(f"⚠️ WebSocket voice update failed: {ws_err}") except Exception as upload_err: logger.warning(f"⚠️ AI voice upload to Supabase failed: {upload_err}") # Send voice message to Telegram # Use dict return and reply_to_message_id voice_result = await telegram_service.send_voice( token=tenant.telegram_bot_token, chat_id=chat_id, audio_bytes=audio_bytes, reply_to_message_id=media_reply_id ) send_success = voice_result.get("success", False) if send_success: logger.info(f"🎤 Voice response sent to chat {chat_id}") # 📝 SEND EXTRACTED SENSITIVE DATA AS SEPARATE TEXT MESSAGE if extracted_items: # Format extracted items for text message text_parts = [] for item in extracted_items: item_type = item.get("type", "") value = item.get("value", "") if item_type == "link": text_parts.append(f"🔗 {value}") elif item_type == "card": text_parts.append(f"💳 {value}") elif item_type == "email": text_parts.append(f"📧 {value}") elif item_type == "iban": text_parts.append(f"🏦 {value}") else: text_parts.append(value) if text_parts: extracted_text = "\n".join(text_parts) logger.info(f"📝 Sending {len(extracted_items)} extracted items as text") await send_telegram_message( bot_token=tenant.telegram_bot_token, chat_id=chat_id, text=extracted_text, reply_to_message_id=media_reply_id ) else: # Fallback to text if voice fails logger.warning("⚠️ Voice send failed, falling back to text") send_success = await send_telegram_message( bot_token=tenant.telegram_bot_token, chat_id=chat_id, text=ai_response["text"], reply_to_message_id=media_reply_id ) except Exception as voice_err: logger.error(f"❌ Voice generation failed: {voice_err}, falling back to text") send_success = await send_telegram_message( bot_token=tenant.telegram_bot_token, chat_id=chat_id, text=ai_response["text"], reply_to_message_id=media_reply_id ) else: # Standard text response send_success = await send_telegram_message( bot_token=tenant.telegram_bot_token, chat_id=chat_id, text=ai_response["text"], reply_to_message_id=media_reply_id ) elif channel == 'linkedin': from app.services.linkedin_service import linkedin_service if lead.linkedin_urn: li_config = tenant.linkedin_config or {} send_success = await linkedin_service.send_message( recipient_urn=lead.linkedin_urn, text=ai_response["text"], cookies=li_config ) else: logger.error("LinkedIn URN missing for lead, cannot send AI response") elif channel == 'whatsapp': # Assuming WhatsApp service is available from app.services.meta_whatsapp import whatsapp_cloud_service # Need tenant object for Cloud API # tenant is already available in scope try: await whatsapp_cloud_service.send_text_message( tenant=tenant, to_phone=lead.telegram_id, # Re-using ID field text=ai_response["text"] ) send_success = True except Exception as e: logger.error(f"WhatsApp Cloud send failed: {e}") send_success = False # Update Message Status if send_success: ai_message.status = MessageStatus.SENT logger.info( "✅ AI response sent successfully to Telegram", chat_id=chat_id, lead_id=str(lead.id) ) else: ai_message.status = MessageStatus.FAILED logger.error( "❌ Failed to send AI response to Telegram", chat_id=chat_id, lead_id=str(lead.id) ) session.add(ai_message) await session.commit() except Exception as e: logger.error(f"❌ Exception during message sending: {e}") ai_message.status = MessageStatus.FAILED session.add(ai_message) await session.commit() # --- ASYNC BACKGROUND PROCESSING --- # Launch background task for: # 1. Answer Delay (if needed) - handled by AI response time technically # 2. Escalation Check # 3. Deep Analysis (Psychotype, Heat, Summary) asyncio.create_task( process_background_ai_tasks( lead_id=lead.id, conversation_id=conversation.id, tenant_id=tenant.id, user_message_text=user_text or "", channel=channel ) ) logger.info( "🚀 Background AI analysis tasks launched", lead_id=str(lead.id), conversation_id=str(conversation.id) ) logger.info( "AI response sent to Telegram", chat_id=chat_id, lead_id=str(lead.id) ) except Exception as e: logger.error( "Background AI processing failed", lead_id=str(lead_id), error=str(e), exc_info=True ) # Set error status try: lead = await session.get(Lead, lead_id) if lead: lead.processing_status = "error" session.add(lead) await session.commit() except: pass async def process_background_ai_tasks( lead_id: UUID, conversation_id: UUID, tenant_id: UUID, user_message_text: str, channel: str ): """ Background worker to handle: 1. Smart Escalation Check 2. Deep Lead Analysis (Psychotype, Heat, Summary) 3. Real-time Frontend Updates """ from app.core.database import async_session_maker from app.models.lead import Lead, Message from app.models.tenant import Tenant from app.services.ai_core import get_ai_core from app.services.escalation_service import escalation_service from app.services.notification_service import get_notification_service from app.api.websocket_chat import notify_lead_updated from sqlalchemy import select logger.info( "🚀 Starting background AI tasks", lead_id=str(lead_id), conversation_id=str(conversation_id) ) async with async_session_maker() as session: try: lead = await session.get(Lead, lead_id) tenant = await session.get(Tenant, tenant_id) if not lead or not tenant: logger.warning(f"Background task aborted: Lead/Tenant not found") return # RE-FETCH Conversation History (including the AI response we just sent) stmt = select(Message).where(Message.conversation_id == conversation_id).order_by(Message.created_at) result = await session.execute(stmt) conversation_history = result.scalars().all() # 1. ESCALATION CHECK try: # Build context for escalation esc_history = [] for msg in conversation_history[-10:]: esc_history.append({"sender_type": msg.sender_type, "content": msg.content}) # Get last AI response last_ai_response = "" if conversation_history: last_msg = conversation_history[-1] if last_msg.sender_type == 'ai': last_ai_response = last_msg.content escalation_result = await escalation_service.analyze_message_smart( user_message=user_message_text, ai_response=last_ai_response, conversation_history=esc_history, heat_score=lead.heat_score or 0, business_type=getattr(tenant, 'business_type', ''), current_stage=None ) if escalation_result.should_escalate: logger.info(f"🚨 Escalation triggered in background: {escalation_result.reason}") lead.needs_attention = True lead.escalation_reason = escalation_result.reason session.add(lead) await session.commit() # Notify Manager using EscalationService directly await escalation_service.send_escalation_notification( lead_id=str(lead.id), lead_name=lead.name or "Unknown", reason=escalation_result.reason, urgency=escalation_result.urgency, details=escalation_result.details, last_message=user_message_text, tenant_id=str(tenant.id), channel=channel ) except Exception as e: logger.error(f"Background escalation check failed: {e}") # 2. DEEP LEAD ANALYSIS (Psychotype, Heat, Summary) try: # Set status to analyzing lead.processing_status = "analyzing" session.add(lead) await session.commit() ai_core = get_ai_core() analysis = await ai_core.analyze_lead( session=session, lead=lead, conversation_history=conversation_history, tenant=tenant ) logger.info( "✅ Background analysis complete", lead_id=str(lead.id), heat_score=analysis.get('heat_score'), summary_generated=analysis.get('summary_generated') ) # Refresh lead to get latest data after internal commits in analyze_lead await session.refresh(lead) # 3. WEBSOCKET UPDATE try: await notify_lead_updated(str(lead.id), { "id": str(lead.id), "ai_summary_json": lead.ai_summary_json, "qualification_data": lead.qualification_data, # Added! "qualification_complete": lead.qualification_complete, # Added! "heat_score": lead.heat_score, "heat_level": lead.heat_level.value if lead.heat_level and hasattr(lead.heat_level, 'value') else str(lead.heat_level), "psychotype": lead.psychotype.value if lead.psychotype and hasattr(lead.psychotype, 'value') else str(lead.psychotype), "name": lead.name, "processing_status": "idle", # Explicitly set idle for UI "needs_attention": lead.needs_attention, "current_stage_id": str(lead.current_stage_id) if lead.current_stage_id else None }) except Exception as ws_err: logger.warning(f"WebSocket update failed: {ws_err}") except Exception as e: logger.error(f"Background lead analysis failed: {e}") # Finally set status back to idle lead.processing_status = "idle" session.add(lead) await session.commit() logger.info(f"✅ All background tasks completed for lead {lead_id}") except Exception as e: logger.error(f"CRITICAL: Background task crash: {e}", exc_info=True) # Try to reset status if possible try: if lead: lead.processing_status = "idle" session.add(lead) await session.commit() except: pass
from fastapi import APIRouter, Request, HTTPException, Depends, BackgroundTasks, Header
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import func
from sqlmodel import select
from typing import Dict, Any, Optional
from datetime import datetime
from uuid import UUID
import httpx
import hmac
import hashlib
import asyncio
from app.core.database import get_session
from app.models.tenant import Tenant
from app.models.lead import Lead, Conversation, Message, LeadStatus, Psychotype, MessageStatus
from app.services.ai_core import get_ai_core
from app.services.email import get_email_service
from app.services.subscription_manager import SubscriptionManager
from app.core.config import settings
from app.core.logging import get_logger
from app.api.telegram_webhook import transcribe_telegram_voice, analyze_telegram_image, analyze_telegram_document
logger = get_logger(__name__)
def _extract_topic_from_conversation(conversation_history, user_message: str) -> str:
"""
Extract topic from conversation for booking notes.
Returns topic string like "автоматизация, продажи"
"""
topic_keywords = []
keywords_to_find = [
"автоматизация", "продажи", "консультация", "внедрение",
"аудит", "ai", "бот", "crm", "интеграция", "помощь",
"партнер", "цена", "стоимость", "демо", "обучение",
"вопрос", "услуга", "тариф", "подписка"
]
# Check last 10 user messages for keywords
user_messages = [msg.content.lower() for msg in conversation_history[-10:] if msg.sender_type == "user"]
user_messages.append(user_message.lower())
for msg in user_messages:
for keyword in keywords_to_find:
if keyword in msg and keyword not in topic_keywords:
topic_keywords.append(keyword)
if len(topic_keywords) >= 3:
break
return ", ".join(topic_keywords) if topic_keywords else "Консультация"
def _extract_booking_info_from_conversation(conversation_history, lead, user_text: str) -> dict:
"""
Extract booking info from conversation history.
Returns dict with: name, phone, topic for comprehensive notes.
Universal for any business type.
"""
import re
# Get best available name: AI-extracted > lead.name > "Клиент"
best_name = "Клиент"
# 1. Try AI-extracted name from summary (most reliable)
if lead and lead.ai_summary_json:
ai_name = lead.ai_summary_json.get('client_name')
if ai_name and isinstance(ai_name, str) and len(ai_name) >= 2:
best_name = ai_name
# 2. Fallback to lead.name if no AI name
if best_name == "Клиент" and lead and lead.name:
best_name = lead.name
info = {
"name": best_name,
"phone": lead.phone if lead and lead.phone else None,
"topic": None
}
# Get user messages
user_messages = [msg.content for msg in conversation_history if msg.sender_type == "user"]
# Patterns for phone extraction
phone_patterns = [
r'[\+]?[0-9]{10,15}', # International format
r'[\+]?996\s*\d{9}', # Kyrgyzstan
r'[\+]?7\s*\d{10}', # Russia
r'\d{3}[\s\-]?\d{3}[\s\-]?\d{4}', # 999-123-4567
]
# Extract phone if not already have
if not info["phone"]:
for msg in reversed(user_messages[-15:]):
for pattern in phone_patterns:
match = re.search(pattern, msg)
if match:
info["phone"] = match.group(0).strip()
break
if info["phone"]:
break