from pydantic import BaseModel from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy.ext.asyncio import AsyncSession from sqlmodel import select, func from typing import List, Optional from uuid import UUID from datetime import datetime from app.core.database import get_session from app.models.lead import Lead, Conversation, Message, LeadStatus, LeadHeat from app.models.tenant import Tenant from app.models import User from app.models.knowledge import LeadContentProgress from app.models.notification import Notification from app.models.order import Order, OrderItem from app.models.booking import Appointment from app.models.ai_training import AIFeedback from app.api.deps import get_current_user from pydantic import BaseModel router = APIRouter(prefix="/leads", tags=["Leads"]) class LeadResponse(BaseModel): """Lead response schema.""" id: str tenant_id: str name: Optional[str] name: Optional[str] telegram_id: Optional[str] whatsapp_id: Optional[str] email: Optional[str] linkedin_profile: Optional[str] linkedin_urn: Optional[str] status: str heat_score: int heat_level: str psychotype: str budget: Optional[str] authority: Optional[str] need: Optional[str] timeline: Optional[str] ai_summary_json: dict first_message_at: datetime last_message_at: datetime created_at: datetime current_stage_id: Optional[str] = None last_message: Optional[str] = None # Last message content for preview # Qualification Card Data qualification_data: dict = {} # User-defined fields: {"Имя": "Иван", "Телефон": "..."} qualification_complete: bool = False # All fields filled human_takeover: bool = False # AI mode status class ConversationResponse(BaseModel): """Conversation with messages.""" id: str channel: str is_active: bool human_takeover: bool started_at: datetime messages: List[dict] @router.get("", response_model=List[LeadResponse]) async def get_leads( status: Optional[LeadStatus] = None, heat_level: Optional[LeadHeat] = None, skip: int = Query(0, ge=0), limit: int = Query(50, ge=1, le=100), current_user: User = Depends(get_current_user), session = Depends(get_session) ): """ Get leads for authenticated user's tenant with optional filtering. Query params: - status: Filter by lead status - heat_level: Filter by heat level (hot/warm/cold/junk) - skip/limit: Pagination """ # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id # Build query stmt = select(Lead).where(Lead.tenant_id == tenant_id) if status: stmt = stmt.where(Lead.status == status) if heat_level: stmt = stmt.where(Lead.heat_level == heat_level) # Order by activity stmt = stmt.order_by(Lead.last_activity_at.desc()) stmt = stmt.offset(skip).limit(limit) result = await session.execute(stmt) leads = result.scalars().all() # Fetch last messages for all leads in one query lead_ids = [lead.id for lead in leads] # Get ACTIVE conversations for these leads conv_stmt = select(Conversation).where( Conversation.lead_id.in_(lead_ids), Conversation.is_active == True ) conv_result = await session.execute(conv_stmt) conversations = conv_result.scalars().all() conv_map = {c.lead_id: c.id for c in conversations} # Get last message for each conversation - OPTIMIZED: Single query instead of N+1 last_messages = {} if conv_map: # Get all conversation IDs conv_ids = list(conv_map.values()) # Bulk fetch last messages using window function from sqlalchemy import func, desc from sqlalchemy.orm import aliased # Subquery to get latest message per conversation subq = ( select( Message.conversation_id, Message.content, func.row_number().over( partition_by=Message.conversation_id, order_by=desc(Message.created_at) ).label('rn') ) .where(Message.conversation_id.in_(conv_ids)) .subquery() ) # Select only the first row (rn=1) for each conversation last_msg_stmt = select(subq.c.conversation_id, subq.c.content).where(subq.c.rn == 1) last_msg_result = await session.execute(last_msg_stmt) # Build reverse map: lead_id -> last_message conv_to_lead = {v: k for k, v in conv_map.items()} for conv_id, content in last_msg_result: lead_id = conv_to_lead.get(conv_id) if lead_id and content: last_messages[lead_id] = content[:100] return [ LeadResponse( id=str(lead.id), tenant_id=str(lead.tenant_id), name=lead.name, telegram_id=lead.telegram_id, whatsapp_id=lead.whatsapp_id, email=lead.email, linkedin_profile=lead.linkedin_profile, linkedin_urn=lead.linkedin_urn, status=lead.status.value, heat_score=lead.heat_score, heat_level=lead.heat_level.value, psychotype=lead.psychotype.value, budget=lead.budget, authority=lead.authority, need=lead.need, timeline=lead.timeline, ai_summary_json=lead.ai_summary_json or {}, first_message_at=lead.first_message_at, last_message_at=lead.last_message_at, created_at=lead.created_at, current_stage_id=str(lead.current_stage_id) if lead.current_stage_id else None, last_message=last_messages.get(lead.id), qualification_data=lead.qualification_data or {}, qualification_complete=lead.qualification_complete or False, human_takeover=next((c.human_takeover for c in conversations if c.lead_id == lead.id), False) ) for lead in leads ] @router.get("/{lead_id}", response_model=LeadResponse) async def get_lead( lead_id: UUID, current_user: User = Depends(get_current_user), session = Depends(get_session) ): """Get single lead details for authenticated user's tenant.""" # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id stmt = select(Lead).where( Lead.tenant_id == tenant_id, Lead.id == lead_id ) result = await session.execute(stmt) lead = result.scalar_one_or_none() if not lead: raise HTTPException(status_code=404, detail="Lead not found") # Get active conversation to check AI mode conv_stmt = select(Conversation).where( Conversation.lead_id == lead_id, Conversation.is_active == True ).limit(1) conv_result = await session.execute(conv_stmt) conversation = conv_result.scalar_one_or_none() human_takeover = conversation.human_takeover if conversation else False return LeadResponse( id=str(lead.id), tenant_id=str(lead.tenant_id), name=lead.name, telegram_id=lead.telegram_id, whatsapp_id=lead.whatsapp_id, email=lead.email, linkedin_profile=lead.linkedin_profile, linkedin_urn=lead.linkedin_urn, status=lead.status.value, heat_score=lead.heat_score, heat_level=lead.heat_level.value, psychotype=lead.psychotype.value, budget=lead.budget, authority=lead.authority, need=lead.need, timeline=lead.timeline, ai_summary_json=lead.ai_summary_json or {}, first_message_at=lead.first_message_at, last_message_at=lead.last_message_at, created_at=lead.created_at, current_stage_id=str(lead.current_stage_id) if lead.current_stage_id else None, qualification_data=lead.qualification_data or {}, qualification_complete=lead.qualification_complete or False, human_takeover=human_takeover ) @router.get("/{lead_id}/conversation", response_model=ConversationResponse) async def get_lead_conversation( lead_id: UUID, current_user: User = Depends(get_current_user), session = Depends(get_session) ): """Get lead's conversation with all messages for authenticated user's tenant.""" # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id # Get active conversation stmt = select(Conversation).where( Conversation.tenant_id == tenant_id, Conversation.lead_id == lead_id, Conversation.is_active == True ) result = await session.execute(stmt) conversation = result.scalar_one_or_none() if not conversation: raise HTTPException(status_code=404, detail="Conversation not found") # Get messages msg_stmt = select(Message).where( Message.conversation_id == conversation.id ).order_by(Message.created_at) msg_result = await session.execute(msg_stmt) messages = msg_result.scalars().all() return ConversationResponse( id=str(conversation.id), channel=conversation.channel, is_active=conversation.is_active, human_takeover=conversation.human_takeover, started_at=conversation.started_at, messages=[ { "id": str(msg.id), "sender_type": msg.sender_type, "content": msg.content, "created_at": msg.created_at.isoformat(), "media_url": msg.media_url, "media_type": msg.media_type, "media_name": msg.media_name, "tokens": { "prompt": msg.prompt_tokens, "completion": msg.completion_tokens } if msg.sender_type == "ai" else None } for msg in messages ] ) class TakeoverRequest(BaseModel): """Request to takeover conversation.""" manager_id: UUID @router.post("/{lead_id}/takeover") async def takeover_conversation( lead_id: UUID, request: TakeoverRequest, current_user: User = Depends(get_current_user), session = Depends(get_session) ): """ Human manager takes over the conversation. AI will stop responding. """ # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id # Get active conversation stmt = select(Conversation).where( Conversation.tenant_id == tenant_id, Conversation.lead_id == lead_id, Conversation.is_active == True ) result = await session.execute(stmt) conversation = result.scalar_one_or_none() if not conversation: raise HTTPException(status_code=404, detail="Conversation not found") # Mark as taken over conversation.human_takeover = True conversation.taken_over_by = request.manager_id conversation.taken_over_at = datetime.utcnow() session.add(conversation) await session.commit() return { "ok": True, "message": "Conversation taken over by human manager", "conversation_id": str(conversation.id) } class ToggleAIRequest(BaseModel): """Request to toggle AI autopilot mode.""" is_ai_active: bool @router.post("/{lead_id}/toggle-ai") async def toggle_ai_mode( lead_id: UUID, request: ToggleAIRequest, current_user: User = Depends(get_current_user), session = Depends(get_session) ): """ Toggle AI autopilot mode for a conversation. - is_ai_active=True: AI responds automatically (human_takeover=False) - is_ai_active=False: Human mode, AI sleeps (human_takeover=True) """ # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id # Get active conversation stmt = select(Conversation).where( Conversation.tenant_id == tenant_id, Conversation.lead_id == lead_id, Conversation.is_active == True ) result = await session.execute(stmt) conversation = result.scalar_one_or_none() if not conversation: raise HTTPException(status_code=404, detail="Conversation not found") # Toggle mode conversation.human_takeover = not request.is_ai_active if request.is_ai_active: # AI is now active, clear human takeover data conversation.taken_over_by = None conversation.taken_over_at = None else: # Human takes over conversation.taken_over_by = current_user.id conversation.taken_over_at = datetime.utcnow() session.add(conversation) await session.commit() await session.refresh(conversation) return { "ok": True, "is_ai_active": request.is_ai_active, "human_takeover": conversation.human_takeover, "message": "Автопилот ИИ" if request.is_ai_active else "Ручной режим", "conversation_id": str(conversation.id) } @router.post("/{lead_id}/analyze") async def force_analyze_lead( lead_id: UUID, current_user: User = Depends(get_current_user), session = Depends(get_session) ): """ **MANUAL ANALYSIS TRIGGER** for debugging AI pipeline (tenant-isolated). This endpoint: 1. Fetches Lead + Tenant + Conversation History 2. Calls AI Core synchronously (await) 3. Logs everything to console for debugging 4. Returns the generated summary or error details Use this to debug why 11-point summary isn't appearing in UI. """ # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id print(f"\n{'='*80}") print(f"🔍 MANUAL ANALYSIS TRIGGERED: Lead {lead_id} | Tenant {tenant_id}") print(f"{'='*80}\n") try: # 1. FETCH LEAD lead = await session.get(Lead, lead_id) if not lead or lead.tenant_id != tenant_id: raise HTTPException(status_code=404, detail="Lead not found") print(f"✅ Lead found: {lead.name or 'Unnamed'} (ID: {lead.id})") print(f" Current Heat: {lead.heat_score}, Psychotype: {lead.psychotype.value}") # 2. FETCH TENANT SETTINGS tenant = await session.get(Tenant, tenant_id) if not tenant: raise HTTPException(status_code=404, detail="Tenant not found") ai_settings = tenant.ai_settings or {} print(f"✅ Tenant settings loaded: {tenant.business_name or 'Unknown'}") print(f" AI Settings: {ai_settings.keys() if ai_settings else 'None'}") # 3. FETCH CONVERSATION HISTORY conv_stmt = select(Conversation).where( Conversation.tenant_id == tenant_id, Conversation.lead_id == lead_id, Conversation.is_active == True ) conv_result = await session.execute(conv_stmt) conversation = conv_result.scalar_one_or_none() if not conversation: raise HTTPException(status_code=404, detail="No active conversation found") # Get ALL messages (user, ai, human) msg_stmt = select(Message).where( Message.conversation_id == conversation.id ).order_by(Message.created_at) msg_result = await session.execute(msg_stmt) messages = list(msg_result.scalars().all()) print(f"✅ Conversation history loaded: {len(messages)} messages") for i, msg in enumerate(messages[:5], 1): # Show first 5 print(f" {i}. [{msg.sender_type.upper()}]: {msg.content[:60]}...") if len(messages) < 3: raise HTTPException( status_code=400, detail=f"Not enough messages to analyze. Need 3+, got {len(messages)}" ) # 4. CALL AI CORE (SYNCHRONOUSLY) print(f"\n🤖 Calling AI Core to analyze lead...") from app.services.ai_core import get_ai_core ai_core = get_ai_core() # Run analysis analysis_result = await ai_core.analyze_lead( session=session, lead=lead, conversation_history=messages, tenant=tenant ) print(f"\n✅ AI Core returned successfully!") print(f" Psychotype: {analysis_result.get('psychotype')}") print(f" Heat Score: {analysis_result.get('heat_score')}") print(f" Summary Generated: {analysis_result.get('summary_generated')}") # 5. LOG GENERATED SUMMARY (RAW JSON) await session.refresh(lead) # Reload to get updated ai_summary_json print(f"\n📊 RAW AI SUMMARY JSON (from database):") print(f"{'-'*80}") import json print(json.dumps(lead.ai_summary_json, indent=2, ensure_ascii=False)) print(f"{'-'*80}\n") # 6. VALIDATE STRUCTURE summary = lead.ai_summary_json or {} expected_fields = [ 'intent', 'budget', 'timeline', 'authority', 'pain_points', 'psychotype', 'heat_score', 'objections', 'hidden_signals', 'recommendation', 'draft_reply' ] missing_fields = [f for f in expected_fields if f not in summary] if missing_fields: print(f"⚠️ WARNING: Missing fields in summary: {missing_fields}") else: print(f"✅ All 11 fields present in summary!") # 7. RETURN RESULT return { "success": True, "message": "Analysis completed successfully", "lead_id": str(lead.id), "analysis": { "psychotype": lead.psychotype.value, "heat_score": lead.heat_score, "heat_level": lead.heat_level.value, "messages_analyzed": len(messages) }, "ai_summary_json": lead.ai_summary_json, "validation": { "all_fields_present": len(missing_fields) == 0, "missing_fields": missing_fields } } except HTTPException: raise except Exception as e: print(f"\n❌ CRITICAL ERROR during analysis:") print(f" Type: {type(e).__name__}") print(f" Message: {str(e)}") import traceback print(f"\n📄 Full traceback:") traceback.print_exc() raise HTTPException( status_code=500, detail={ "error_type": type(e).__name__, "error_message": str(e), "hint": "Check backend console logs for full traceback" } ) @router.get("/stats") async def get_lead_stats( current_user: User = Depends(get_current_user), session = Depends(get_session) ): """Get lead statistics for dashboard (tenant-isolated).""" # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id # Total leads total_stmt = select(func.count(Lead.id)).where(Lead.tenant_id == tenant_id) total_result = await session.execute(total_stmt) total_leads = total_result.scalar() # By heat level hot_stmt = select(func.count(Lead.id)).where( Lead.tenant_id == tenant_id, Lead.heat_level == LeadHeat.HOT ) hot_result = await session.execute(hot_stmt) hot_leads = hot_result.scalar() warm_stmt = select(func.count(Lead.id)).where( Lead.tenant_id == tenant_id, Lead.heat_level == LeadHeat.WARM ) warm_result = await session.execute(warm_stmt) warm_leads = warm_result.scalar() # By status qualified_stmt = select(func.count(Lead.id)).where( Lead.tenant_id == tenant_id, Lead.status == LeadStatus.QUALIFIED ) qualified_result = await session.execute(qualified_stmt) qualified_leads = qualified_result.scalar() return { "total_leads": total_leads, "hot_leads": hot_leads, "warm_leads": warm_leads, "qualified_leads": qualified_leads, "conversion_rate": (qualified_leads / total_leads * 100) if total_leads > 0 else 0 } class UpdateStageRequest(BaseModel): """Request to update lead's current stage.""" stage_id: UUID @router.patch("/{lead_id}/stage") async def update_lead_stage( lead_id: UUID, request: UpdateStageRequest, current_user: User = Depends(get_current_user), session = Depends(get_session) ): """ Update the current stage of a lead. Allows manual override by manager (tenant-isolated). """ # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id # Get lead stmt = select(Lead).where( Lead.tenant_id == tenant_id, Lead.id == lead_id ) result = await session.execute(stmt) lead = result.scalar_one_or_none() if not lead: raise HTTPException(status_code=404, detail="Lead not found") # Update stage lead.current_stage_id = request.stage_id lead.updated_at = datetime.utcnow() session.add(lead) await session.commit() await session.refresh(lead) return { "message": "Stage updated successfully", "lead_id": str(lead.id), "current_stage_id": str(lead.current_stage_id) if lead.current_stage_id else None } @router.delete("/{lead_id}") async def delete_lead( lead_id: UUID, clear_cache: bool = Query(False, description="Clear AI memory cache for tenant"), current_user: User = Depends(get_current_user), session = Depends(get_session) ): """ Delete a lead and all associated data (conversations, messages). Tenant-isolated - users can only delete their own leads. Optional: clear_cache=true to invalidate AI memory cache. OPTIMIZED: Uses bulk SQL DELETE for speed. """ from sqlalchemy import delete as sql_delete # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id # Get lead stmt = select(Lead).where( Lead.tenant_id == tenant_id, Lead.id == lead_id ) result = await session.execute(stmt) lead = result.scalar_one_or_none() if not lead: raise HTTPException(status_code=404, detail="Lead not found") lead_name = lead.name or "Unnamed" # Get conversation IDs for this lead (needed for message deletion) conv_stmt = select(Conversation.id).where(Conversation.lead_id == lead_id) conv_result = await session.execute(conv_stmt) conv_ids = [row[0] for row in conv_result.fetchall()] # Get order IDs for this lead (needed for order items deletion) order_stmt = select(Order.id).where(Order.lead_id == lead_id) order_result = await session.execute(order_stmt) order_ids = [row[0] for row in order_result.fetchall()] # BULK DELETE in correct order (foreign key dependencies) # 1. Delete order items first if order_ids: await session.execute(sql_delete(OrderItem).where(OrderItem.order_id.in_(order_ids))) # 2. Delete orders await session.execute(sql_delete(Order).where(Order.lead_id == lead_id)) # 3. Delete notifications await session.execute(sql_delete(Notification).where(Notification.lead_id == lead_id)) # 4. Delete appointments await session.execute(sql_delete(Appointment).where(Appointment.lead_id == lead_id)) # 5. Delete content progress await session.execute(sql_delete(LeadContentProgress).where(LeadContentProgress.lead_id == lead_id)) # 6. Delete AI feedback await session.execute(sql_delete(AIFeedback).where(AIFeedback.lead_id == lead_id)) # 7. Delete messages (requires conversation IDs) if conv_ids: await session.execute(sql_delete(Message).where(Message.conversation_id.in_(conv_ids))) # 8. Delete conversations await session.execute(sql_delete(Conversation).where(Conversation.lead_id == lead_id)) # 9. Finally delete lead await session.execute(sql_delete(Lead).where(Lead.id == lead_id)) await session.commit() # Optionally clear AI cache cache_cleared = False if clear_cache: try: from app.services.ai_memory_manager import get_memory_manager tenant = await session.get(Tenant, tenant_id) if tenant and tenant.ai_cache_key: await get_memory_manager().invalidate_memory(session, tenant) cache_cleared = True except Exception as e: print(f"⚠️ Failed to clear AI cache: {e}") return { "ok": True, "message": f"Lead '{lead_name}' and all associated data deleted successfully", "lead_id": str(lead_id), "cache_cleared": cache_cleared } @router.post("/{lead_id}/reset") async def reset_lead( lead_id: UUID, current_user: User = Depends(get_current_user), session = Depends(get_session) ): """ Reset a lead - clears conversation history and AI analysis. The lead record is preserved so new messages from the same contact will be treated as a fresh conversation. This is useful for testing different prompts with the same account. """ # Use authenticated user's tenant_id (prevents tenant isolation breach) tenant_id = current_user.tenant_id # Get lead stmt = select(Lead).where( Lead.tenant_id == tenant_id, Lead.id == lead_id ) result = await session.execute(stmt) lead = result.scalar_one_or_none() if not lead: raise HTTPException(status_code=404, detail="Lead not found") lead_name = lead.name or "Unnamed" messages_deleted = 0 conversations_deleted = 0 # 1. Cleanup AI Feedback related to this lead feedback_stmt = select(AIFeedback).where(AIFeedback.lead_id == lead_id) feedback_result = await session.execute(feedback_stmt) for feedback in feedback_result.scalars().all(): await session.delete(feedback) # 2. Cleanup Conversations and Messages conv_stmt = select(Conversation).where(Conversation.lead_id == lead_id) conv_result = await session.execute(conv_stmt) conversations = conv_result.scalars().all() for conv in conversations: # Delete messages for this conversation msg_stmt = select(Message).where(Message.conversation_id == conv.id) msg_result = await session.execute(msg_stmt) messages = msg_result.scalars().all() for msg in messages: await session.delete(msg) messages_deleted += 1 # Delete conversation await session.delete(conv) conversations_deleted += 1 # Reset lead to initial state lead.ai_summary_json = {} # Clear AI analysis lead.heat_score = 0 lead.heat_level = LeadHeat.COLD lead.status = LeadStatus.NEW lead.psychotype = lead.psychotype # Keep psychotype for now (will be re-analyzed) lead.first_message_at = datetime.utcnow() lead.last_message_at = datetime.utcnow() lead.updated_at = datetime.utcnow() session.add(lead) await session.commit() return { "ok": True, "message": f"Lead '{lead_name}' has been reset. Next message will start fresh.", "lead_id": str(lead_id), "messages_deleted": messages_deleted, "conversations_deleted": conversations_deleted }