""" Chats API - Send messages from UI to customers. """ from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form from sqlalchemy.ext.asyncio import AsyncSession from pydantic import BaseModel from uuid import UUID from datetime import datetime from typing import Optional from sqlmodel import select import re import time from app.core.database import get_session from app.core.logging import get_logger from app.models.tenant import Tenant from app.models.lead import Lead, Message, Conversation from app.models import User from app.api.deps import get_current_user from app.services.ai_core import get_ai_core from app.services.llm_client import get_llm_client from app.core.supabase import supabase_client from app.api.webhook import send_telegram_message # from app.api.meta_webhooks import send_meta_message # DEPRECATED from app.services.meta_whatsapp import whatsapp_cloud_service import httpx from app.api.websocket_chat import notify_new_message logger = get_logger(__name__) router = APIRouter(prefix="/chats", tags=["Chats"]) class SendMessageRequest(BaseModel): """Request to send message from manager to customer.""" lead_id: UUID conversation_id: UUID message: str class GenerateReplyRequest(BaseModel): """Request to generate AI reply and send it.""" conversation_id: UUID @router.post("/send", status_code=status.HTTP_201_CREATED) async def send_message( request: SendMessageRequest, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Send message from Platform UI to customer via Telegram. CRITICAL FEATURES: 1. Save message to DB with sender_type='human' 2. Send to Telegram Bot API (robust error handling) 3. Trigger AI analysis in background ALWAYS """ # 1. GET TENANT FROM USER tenant = await session.get(Tenant, current_user.tenant_id) if not tenant: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found for current user" ) print(f"👤 User {current_user.email} from tenant {tenant.id}") # 2. CHECK BOT TOKEN EXISTS (Only for Telegram) # if not tenant.telegram_bot_token or not tenant.telegram_bot_token.strip(): # # For WhatsApp we don't need bot token here # pass # 3. Validate lead exists and belongs to tenant lead = await session.get(Lead, request.lead_id) if not lead or lead.tenant_id != tenant.id: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Lead not found" ) # 4. Validate conversation exists conversation = await session.get(Conversation, request.conversation_id) if not conversation or conversation.tenant_id != tenant.id: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found" ) # 5. Validate lead has Contact ID (Telegram ID or Phone) if not lead.telegram_id: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Lead has no Contact ID (Telegram ID/Phone) - cannot send message." ) # 6. SAVE MESSAGE TO DB FIRST (Even if Telegram fails, we have record) human_message = Message( tenant_id=tenant.id, conversation_id=conversation.id, sender_type="human", # CRITICAL: Mark as human manager content=request.message ) session.add(human_message) # Update lead timestamps lead.last_message_at = datetime.utcnow() lead.last_activity_at = datetime.utcnow() session.add(lead) await session.commit() await session.refresh(human_message) print(f"💬 Human message saved: {human_message.id} for lead {lead.id}") # Notify WebSocket clients about new message await notify_new_message(str(lead.id), { "id": str(human_message.id), "content": human_message.content, "sender_type": "human", "created_at": human_message.created_at.isoformat(), "media_url": None, "media_type": None, "media_name": None, "conversation_id": str(conversation.id) }) # 7. SEND TO APPROPRIATE CHANNEL (ROBUST ERROR HANDLING) send_success = False send_error_detail = None # Determine channel from conversation channel = conversation.channel if hasattr(conversation, 'channel') and conversation.channel else 'telegram' try: if channel == 'whatsapp': # Send via Meta WhatsApp Cloud API (Official) try: await whatsapp_cloud_service.send_text_message( tenant=tenant, to_phone=lead.telegram_id, # Using telegram_id field for phone number text=request.message ) send_success = True except Exception as e: send_success = False send_error_detail = f"WhatsApp Cloud API error: {str(e)}" elif channel == 'instagram': # Instagram not yet implemented send_success = False send_error_detail = "Instagram integration not yet available" elif channel == 'linkedin': # SEND VIA LINKEDIN # Check if lead has valid URN if not lead.linkedin_urn: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Lead has no LinkedIn URN - cannot send message." ) from app.services.linkedin_service import linkedin_service # Get tenant cookies li_config = tenant.linkedin_config or {} send_success = await linkedin_service.send_message( recipient_urn=lead.linkedin_urn, text=request.message, cookies=li_config # Service will extract li_at/JSESSIONID ) if not send_success: send_error_detail = "LinkedIn Service returned error (Check logs/cookies)" else: # telegram (default) # Validate Telegram ID if not lead.telegram_id: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Lead has no Telegram ID - cannot send message." ) url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendMessage" payload = { "chat_id": lead.telegram_id, "text": request.message, "parse_mode": "Markdown" } print(f"📤 Sending to Telegram: chat_id={lead.telegram_id}") async with httpx.AsyncClient() as client: response = await client.post(url, json=payload, timeout=10.0) # Log full response for debugging print(f"📡 Telegram API Response: {response.status_code}") print(f"📡 Response Body: {response.text}") if response.status_code == 200: send_success = True print(f"✅ Message sent to Telegram: {lead.telegram_id}") else: # Parse Telegram error try: error_data = response.json() send_error_detail = error_data.get('description', response.text) except: send_error_detail = response.text print(f"⚠️ Telegram API Error ({response.status_code}): {send_error_detail}") except httpx.TimeoutException: send_error_detail = f"{channel.capitalize()} API timeout (10s)" print(f"❌ {channel} timeout: {send_error_detail}") except httpx.RequestError as e: send_error_detail = f"Network error: {str(e)}" print(f"❌ {channel} request error: {send_error_detail}") except Exception as e: send_error_detail = f"Unexpected error: {str(e)}" print(f"❌ {channel} send error: {send_error_detail}") import traceback traceback.print_exc() # TASK: AUTO-ANALYZE LEAD after human message # Update AI summary to capture new information from manager's interaction try: from app.services.ai_core import get_ai_core # Get all messages for analysis msg_stmt = select(Message).where( Message.conversation_id == conversation.id ).order_by(Message.created_at) msg_result = await session.execute(msg_stmt) all_messages = list(msg_result.scalars().all()) if len(all_messages) >= 3: # Need minimum messages for analysis logger.info( "🧠 Auto-analyzing lead after human message", lead_id=str(lead.id), messages_count=len(all_messages) ) # Set analyzing status lead.processing_status = "analyzing" session.add(lead) await session.commit() # Run analysis ai_core = get_ai_core() analysis = await ai_core.analyze_lead( session=session, lead=lead, conversation_history=all_messages, tenant=tenant ) logger.info( "✅ Analysis complete after human message", lead_id=str(lead.id), heat_score=analysis.get('heat_score') ) # Reset to idle lead.processing_status = "idle" session.add(lead) await session.commit() except Exception as analysis_error: logger.error( "❌ Auto-analysis failed (non-critical)", lead_id=str(lead.id), error=str(analysis_error), exc_info=True ) # Reset status on error try: lead.processing_status = "idle" session.add(lead) await session.commit() except: pass # IMPORTANT: Return response to UI return { "success": True, "message_id": str(human_message.id), "channel": channel, "sent": send_success, "error": send_error_detail if not send_success else None, "message": { "id": str(human_message.id), "content": human_message.content, "sender_type": "human", "created_at": human_message.created_at.isoformat() } } @router.post("/send-media", status_code=status.HTTP_201_CREATED) async def send_media_message( lead_id: UUID = Form(...), conversation_id: UUID = Form(...), message: str = Form(""), file: Optional[UploadFile] = File(None), audio: Optional[UploadFile] = File(None), session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Send MULTIMODAL message (File/Voice) + Text. """ # 1. Validation tenant = await session.get(Tenant, current_user.tenant_id) if not tenant: raise HTTPException(404, "Tenant not found") lead = await session.get(Lead, lead_id) if not lead or lead.tenant_id != tenant.id: raise HTTPException(404, "Lead not found") conversation = await session.get(Conversation, conversation_id) if not conversation or conversation.tenant_id != tenant.id: raise HTTPException(404, "Conversation not found") if not lead.telegram_id: raise HTTPException(400, "Lead has no Contact ID") # 2. Process Media media_url = None media_type = None media_name = None final_text = message or "" target_file = audio if audio else file if target_file: try: # Read file content_bytes = await target_file.read() media_type = target_file.content_type media_name = target_file.filename # A) Transcribe if audio if audio: try: logger.info("🎤 Transcribing voice message...") # Transcription transcript = await get_llm_client().transcribe_audio(content_bytes) if transcript: final_text = (final_text + "\n" if final_text else "") + f"🎤 [Голосовое]: {transcript}" except Exception as e: logger.error(f"Transcription error: {e}") final_text += " (Ошибка транскрипции)" # B) Upload to Supabase if supabase_client: bucket = "chat-attachments" ts = int(time.time()) safe_name = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', media_name) path = f"{tenant.id}/{conversation.id}/{ts}_{safe_name}" try: # Try uploading to 'chat-attachments' (must exist) supabase_client.storage.from_(bucket).upload( path=path, file=content_bytes, file_options={"content-type": media_type} ) media_url = supabase_client.storage.from_(bucket).get_public_url(path) except Exception as up_err: logger.error(f"Upload failed (check bucket '{bucket}'): {up_err}") pass except Exception as e: logger.error(f"File processing error: {e}") # 3. Create Message Record human_message = Message( tenant_id=tenant.id, conversation_id=conversation.id, sender_type="human", content=final_text, media_url=media_url, media_type=media_type, media_name=media_name ) session.add(human_message) lead.last_message_at = datetime.utcnow() lead.last_activity_at = datetime.utcnow() session.add(lead) await session.commit() await session.refresh(human_message) # Notify WebSocket clients about new media message await notify_new_message(str(lead.id), { "id": str(human_message.id), "content": human_message.content, "sender_type": "human", "created_at": human_message.created_at.isoformat(), "media_url": media_url, "media_type": media_type, "media_name": media_name, "conversation_id": str(conversation.id) }) # 4. Send to Channel (Telegram/WhatsApp) channel = conversation.channel or 'telegram' send_success = False error_detail = None try: if channel == 'telegram': async with httpx.AsyncClient(timeout=30.0) as client: # Check if we have media to send if target_file and content_bytes: # Determine media type and use appropriate Telegram API if audio and media_type and 'audio' in media_type.lower(): # Send as voice message url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendVoice" files = {"voice": (media_name or "voice.ogg", content_bytes, media_type)} data = {"chat_id": lead.telegram_id} if message: data["caption"] = message[:1024] res = await client.post(url, files=files, data=data) logger.info(f"📤 Sent voice to Telegram: {res.status_code}") elif media_type and 'image' in media_type.lower(): # Send as photo url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendPhoto" files = {"photo": (media_name or "photo.jpg", content_bytes, media_type)} data = {"chat_id": lead.telegram_id} if message: data["caption"] = message[:1024] res = await client.post(url, files=files, data=data) logger.info(f"📤 Sent photo to Telegram: {res.status_code}") else: # Send as document url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendDocument" files = {"document": (media_name or "file", content_bytes, media_type)} data = {"chat_id": lead.telegram_id} if message: data["caption"] = message[:1024] res = await client.post(url, files=files, data=data) logger.info(f"📤 Sent document to Telegram: {res.status_code}") send_success = res.status_code == 200 if not send_success: error_detail = res.text else: # No media, just text url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendMessage" payload = {"chat_id": lead.telegram_id, "text": final_text} res = await client.post(url, json=payload, timeout=10) send_success = res.status_code == 200 if not send_success: error_detail = res.text elif channel == 'whatsapp': await whatsapp_cloud_service.send_text_message(tenant, lead.telegram_id, final_text) send_success = True except Exception as e: error_detail = str(e) logger.error(f"Send error: {e}") # Return Result return { "success": True, "message_id": str(human_message.id), "sent": send_success, "media_url": media_url, "transcript": final_text if audio else None, "message": human_message } @router.post("/{lead_id}/generate_reply", status_code=status.HTTP_201_CREATED) async def generate_ai_reply( lead_id: UUID, request: GenerateReplyRequest, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Delegate to AI: Generate and SEND reply automatically. This endpoint allows a human manager to hand control back to the bot. The AI will: 1. Analyze conversation history 2. Generate contextually appropriate response 3. Send it to Telegram immediately """ # 1. GET TENANT FROM USER tenant = await session.get(Tenant, current_user.tenant_id) if not tenant: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found" ) print(f"🤖 AI Delegation request from {current_user.email} for lead {lead_id}") # 2. CHECK BOT TOKEN if not tenant.telegram_bot_token or not tenant.telegram_bot_token.strip(): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Telegram Bot not connected" ) # 3. Validate lead lead = await session.get(Lead, lead_id) if not lead or lead.tenant_id != tenant.id: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Lead not found" ) # 4. Validate conversation conversation = await session.get(Conversation, request.conversation_id) if not conversation or conversation.tenant_id != tenant.id: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found" ) # 5. Validate Telegram ID if not lead.telegram_id: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Lead has no Telegram ID" ) # 6. SET GENERATING STATUS lead.processing_status = "generating" session.add(lead) await session.commit() try: # 7. GET CONVERSATION HISTORY stmt = select(Message).where( Message.conversation_id == conversation.id ).order_by(Message.created_at) result = await session.execute(stmt) messages = list(result.scalars().all()) if len(messages) == 0: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="No messages in conversation" ) print(f"💬 Processing {len(messages)} messages for AI generation") # 8. GENERATE AI RESPONSE ai_core = get_ai_core() last_user_message = next( (msg.content for msg in reversed(messages) if msg.sender_type == "user"), "Продолжите диалог" ) ai_response = await ai_core.generate_sales_response( session=session, tenant=tenant, lead=lead, user_message=last_user_message, conversation_history=messages ) # 9. SAVE AI MESSAGE TO DB ai_message = Message( tenant_id=tenant.id, conversation_id=conversation.id, sender_type="ai", content=ai_response["text"], prompt_tokens=ai_response["prompt_tokens"], completion_tokens=ai_response["completion_tokens"], model_used="gemini-pro" ) session.add(ai_message) # Update lead timestamps lead.last_message_at = datetime.utcnow() lead.last_activity_at = datetime.utcnow() session.add(lead) await session.commit() await session.refresh(ai_message) print(f"🤖 AI message generated: {ai_message.id}") # 10. SEND TO TELEGRAM telegram_success = False telegram_error = None try: url = f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendMessage" payload = { "chat_id": lead.telegram_id, "text": ai_response["text"], "parse_mode": "Markdown" } async with httpx.AsyncClient() as client: response = await client.post(url, json=payload, timeout=10.0) if response.status_code == 200: telegram_success = True print(f"✅ AI reply sent to Telegram: {lead.telegram_id}") else: error_data = response.json() telegram_error = error_data.get('description', response.text) print(f"⚠️ Telegram error: {telegram_error}") except Exception as e: telegram_error = str(e) print(f"❌ Telegram send failed: {telegram_error}") # TASK: AUTO-ANALYZE LEAD after AI generation # Update AI summary with new context from generated message try: logger.info( "🧠 Auto-analyzing lead after AI generation", lead_id=str(lead.id) ) # Set analyzing status lead.processing_status = "analyzing" session.add(lead) await session.commit() # Re-fetch messages (now includes AI response) analysis_stmt = select(Message).where( Message.conversation_id == conversation.id ).order_by(Message.created_at) analysis_result = await session.execute(analysis_stmt) all_messages = list(analysis_result.scalars().all()) # Run analysis analysis = await ai_core.analyze_lead( session=session, lead=lead, conversation_history=all_messages, tenant=tenant ) logger.info( "✅ Analysis complete after AI generation", lead_id=str(lead.id), heat_score=analysis.get('heat_score') ) except Exception as analysis_error: logger.error( "❌ Auto-analysis failed (non-critical)", lead_id=str(lead.id), error=str(analysis_error), exc_info=True ) # 12. SET BACK TO IDLE lead.processing_status = "idle" session.add(lead) await session.commit() return { "success": True, "message_id": str(ai_message.id), "telegram_sent": telegram_success, "telegram_error": telegram_error, "ai_response": { "id": str(ai_message.id), "content": ai_message.content, "sender_type": "ai", "created_at": ai_message.created_at.isoformat(), "tokens_used": ai_response["total_tokens"] } } except HTTPException: raise except Exception as e: print(f"❌ AI generation failed: {e}") import traceback traceback.print_exc() # Set error status lead.processing_status = "error" session.add(lead) await session.commit() raise HTTPException( status_code=500, detail=f"AI generation failed: {str(e)}" ) @router.delete("/messages/{message_id}", status_code=status.HTTP_200_OK) async def delete_message( message_id: UUID, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Delete a message from chat. Only allows deletion of messages with sender_type='human' (manager's own messages). AI and user messages cannot be deleted. """ # 1. Get tenant from user tenant = await session.get(Tenant, current_user.tenant_id) if not tenant: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Tenant not found" ) # 2. Find message message = await session.get(Message, message_id) if not message: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Message not found" ) # 3. Check message belongs to tenant if message.tenant_id != tenant.id: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized to delete this message" ) # 4. Only allow deletion of human messages (manager's own messages) if message.sender_type != "human": raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Only your own messages can be deleted" ) # 5. Delete message await session.delete(message) await session.commit() logger.info( "🗑️ Message deleted", message_id=str(message_id), user_email=current_user.email, tenant_id=str(tenant.id) ) return { "success": True, "message_id": str(message_id), "deleted": True }